4

I would like to define a command which creates an index with a certain name, when i pass the name, and doesn't create any index if there is no name passed.

My first idea was to write it like that:

\newcommand{\kw}[1][]{\emph{#2}\index{#1}}

but the compiler gets stuch when I pass an empty optional argument. How can I build an if-then structure like the following?

\newcommand{\kw}[1][]{
 if(#1 is not empty)
  \emph{#2}\index{#1}}
 else
  \emph{#2}
}
5

If you don't want to use xparse (why not?), you can use some traditional tricks, for example:

\newcommand{\kw}[2][]{%
  \emph{#2}%
  \if&#1&\else
    \index{#1}%
  \fi
}

xparse's \IfValueT is safer in some cases. A safer implementation without LaTeX3 is:

\usepackage{etoolbox}
\newcommand{\kw}[2][]{%
  \emph{#2}%
  \ifstrempty{#1}{}{\index{#1}}%
}
  • Why the {a} in the second example? Shouldn't it be {}? – clemens Oct 20 '13 at 10:25
  • @cgnieder: Sorry, it's a typo. – Leo Liu Oct 20 '13 at 10:45
3

You can use the xparse package from the LaTeX3 project.

\usepackage{xparse}
\NewDocumentCommand\kw{o}{%
  \IfNoValueTF{#1}{%
    % #1 is empty.
  }{%
    % #1 has a value.
  }%
}

To recreate your example command:

\NewDocumentCommand\kw{om}{%
  \IfNoValueTF{#1}{%
    \emph{#2}%
  }{%
    \emph{#2}\index{#1}%
  }%
}
  • 6
    More simply, \emph{#2}\IfValueT{#1}{\index{#1}}. Be careful with spurious spaces; in your example macro you have three of them. – egreg Oct 20 '13 at 9:05
  • @egreg I wasn't aware that there is a \IfValueT; it's not mentioned in the xparse documentation. – ChrisS Oct 20 '13 at 21:25
  • Yes, it is, on page 7; note that the entry in the margin is \IfValueTF with T and F in italics and underlined in red. This means that \IfValueT, \IfValueF and \IfValueTF are available. – egreg Oct 20 '13 at 21:47
  • @egreg Thanks for pointing that out; I'd seen the underlining but didn't know what it meant. – ChrisS Oct 21 '13 at 1:13
  • I upvoted your answer and edited it in order it does what's advertised; I won't do the same next time. – egreg Oct 21 '13 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.