3

I'm trying to define a command such that if it's given one argument, it outputs \textbf{#1}\index{#1}, and if given two arguments it does \textbf{#1}\index{#2}. Essentially, I'd like by default it to index to the input, but if given an optional argument index to that instead. It'd also be nice if when given one argument it could automatically capitalize it (so \myIndex{word} would run \textbf{word}\index{Word}), but I haven't looked into this much.

From this answer, it seems like the package xifthen will give me what I want. Unfortunately, I'm not at all familiar with ifthenelse, so writing the following has been giving me errors:

\newcommand{\Def}[2][]{\textbf{#2}\index{%\ifthenelse{\isempty{#1}{#2}{#1}%}}

The specific errors I'm getting are file ended while scanning use of \@xargdef, and then various undefined control sequence errors from whenever I used \Def in my code already.

  • \ifthenelse{\isempty{#1}{\index{#2}}{\index{#1}} – egreg Oct 6 '16 at 20:44
5

LaTeX has a shortcut for this

enter image description here

\documentclass{article}

\makeatletter
\newcommand\Def{\@dblarg\Defx}
\newcommand\Defx[2][]{\textbf{#2}[index #1]}
\makeatother
\begin{document}

\Def{aaa}

\Def[bb]{aaa}


\end{document}
2
\documentclass{article}    
\newcommand\Def[2][]{\textbf{#2}\ifx\relax#1\relax \index{#2}\else\index{#1}\fi}
\usepackage{imakeidx}
\makeindex
\begin{document}

\Def{foo}
\Def[bar]{baz}

\printindex
\end{document}
1

You don't want to index \ifthenelse. The conditional should call \index, not conversely:

\newcommand{\Def}[2][]{%
  \ifthenelse{\isempty{#1}}{\index{#2}}{\index{#1}}%
  \textbf{#2}%
}

If you are keen on using xparse, you can do

\usepackage{xparse}

\NewDocumentCommand{\Def}{om}{%
  \IfNoValueTF{#1}{\index{#2}}{\index{#1}}%
  \textbf{#2}%
}

which is more robust than the \isempty test.

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.