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?