1

I'd like to create a custom command with an optional parameter, which could be used in math mode as a sub- or superscript. However, the following code:

\documentclass[pdftex,11pt]{report}

\usepackage{xparse}

\NewDocumentCommand{\MyCmd}{o}{\IfNoValueTF{#1}{X}{X_\mathrm{{#1}}}}

\begin{document}

$\MyCmd$

$Q_{\MyCmd}$

$Q_{\MyCmd[Y]}$

$Q_\MyCmd$  % <-- fails

$Q_\MyCmd[Y]$  % <-- fails

\end{document}

produces the following errors:
Missing { inserted. $Q_\MyCmd
Missing } inserted. $Q_\MyCmd$
Missing { inserted. $Q_\MyCmd
Missing } inserted. $Q_\MyCmd[Y]$

I.e., it seems I need to wrap my command call in braces whenever I'd like to use it in a sub- or superscipt.

How to properly define such a command so that it wouldn't be necessary to insert extra braces?

2 Answers2

6

It is possible to define the command so that braces are not needed by relying on the low level detail that _ scans for an argument in a way that is not at all like the scanning for a macro argument, so you just need a \bgroup before looking for the optional argument:

\documentclass[pdftex,11pt]{report}

\usepackage{xparse}

\NewDocumentCommand\MyCmd{}{\bgroup\MyCmdx}
\NewDocumentCommand{\MyCmdx}{o}{\IfNoValueTF{#1}{X}{X_\mathrm{#1}}\egroup}

\begin{document}

$\MyCmd$

$Q_{\MyCmd}$

$Q_{\MyCmd[Y]}$

$Q_\MyCmd$  % <-- fails

$Q_\MyCmd[Y]$  % <-- fails

\end{document}

However this will fail if used in conjunction with one of the many packages that redefine _ to be active character taking a normal argument.

The fact that X_\mathrm{b} or X_\frac12 work is an accident of the implementation and really it is just a mis-feature of the language that they do not give errors. The documented supported markup would be X_{\mathrm{b}} or X_{\frac{1}{2}}.

So the response to a missing { inserted error should be to add the missing { not to re-code the macro so the error is not given:-)

David Carlisle
  • 757,742
0

Based on the link provided barbara beeton:

in my case the answer would be:

There is no such way to avoid using braces. On the other hand, it is a good "coding" practice to always include them when using sub- and superscripts (as it will save me from head scratching when something goes wrong).

  • It is possible to write the command so braces are not needed but I would never do that, the fact that X_\frac12 with no braces gives no error and a subscript half is an accident of the implementation and a mis-feature in latex, not something to be emulated. (I would write X_{\mathrm{#1}}` for similar reasons. – David Carlisle Oct 17 '19 at 11:10