0

I would like to generate a label using a command that uses conditions:

\newcommand{\paperPrefix}[1][]{\ifthenelse{\equal{#1}{}}{\ifthenelse{\equal{\activePaper}{}}{}{\activePaper\_}}{#1\_}}

Basically it should return #1_ if called with the optional parameter, \activePaper_ if the macro activePaper is define (\def\activePaper{...}) and nothing ('') otherwise.

However when I use it:

\label{\paperPrefix[MyPrefix]{}image}

Instead of defining a label in the form

\label{MyPrefix_image}

It complains that:

! Missing \endcsname inserted.<to be read again>\let ...eco]{}}{{1}{1}{Introduction}{chapter.1}{}}

So I was wondering, how to solve this.

  • 1
    The argument of \label must be expandable. LaTeX macros with optional arguments are not expandable, \ifthenelse is not expandable. Also \_ is problematic. Therefore the interface has to be changed. For example, a macro performs the unexpandable stuff and defines a simple macro, which can be used later in \label. – Heiko Oberdiek May 20 '16 at 16:57
1

Apart from the fact that \ifthenelse does not work by expansion

\label{\paperPrefix[MyPrefix]{}image}

only has one argument (in [] ) so the {} before image is untouched and would form part of the label.

I think you want

\newcommand{\paperPrefix}[1]{\ifx\activePaper\defaultPaper\else#1_\fi}

together with

\newcommand\defaultPaper{}%or anything really
\newcommand\activePaper{}%same as above

then \paperPrefix{mypaper} (with {} not []) will expand to nothing by default or to mypaper_ if \activepaper has been redefined.

  • Thanks, it works fabulously. To make it semantically match my original command I modified it to this: \renewcommand{\paperPrefix}[1]{\ifx&#1&\ifx\activePaper\empty\else\activePaper_\fi\else#1_\fi} . I just wonder how to make it so that it can be both used in \label{} and directly to output text (for debugging). I had to modify it as \newcommand{\paperPrefix}[1]{\def\tst{#1}\ifx&#1&{\ifx\activePaper\empty\detokenize{}\else\activePaper\detokenize{_}\fi}\else\detokenize{#1_}\fi} to be able to see the output (because otherwise _ caused the missing $ issue. – erkil1452 May 23 '16 at 12:16

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.