4

I am trying to define a command with xparse that takes an optional argument but no mandatory argument. The optional argument is a number, which works fine with a single digit but not with more. The command is as follows:

\usepackage{xparse}
\usepackage{xspace}

\NewDocumentCommand \HL { o } {\IfNoValueTF #1 {\emph{HL}\xspace}{\emph{HL} {#1}\xspace}}

\HL
(\HL[1])
(\HL[10])

I want the following result:

HL

(HL 1)

(HL 10)

But I get this:

HL

(HL 1)

(HLHL 10)

  • \IfNoValueTF{#1}: you're missing the braces. – egreg Nov 22 '13 at 16:12
6

As #1 is potentially more than one token you should always handle it in braces. Thus you need

\IfNoValueTF {#1}

which prevents the second or later tokens of #1 being misunderstood as one the the true/false branches. In your case, \HL[10] is only testing 1 and treating the 0 as the true branch for the conditional, leading to the odd output.

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.