I am very surprised that simply adding an optional argument to the definition of my command changes the spacing in formulas in combination with \mathcolor. Why does this happen? How can this be fixed?
MWE:
\documentclass{article}
\usepackage{xcolor}
%MINIMAL EXAMPLE:
\newcommand{\optionalSub}[2][a]{_{#2}}
\newcommand{\noOptionalSub}[1]{_{#1}}
%other example:
\newcommand{\coloredSubscript}[2][red]{_{\mathcolor{#1}{#2}}}
\begin{document}
%MINIMAL EXAMPLE:
$a^b\optionalSub{c}$ %correct spacing
$\mathcolor{blue}{a^b}\optionalSub{c}$ % very wrong spacing
$\mathcolor{blue}{a^b}\noOptionalSub{c}$ %correct spacing
%other example:
$a^b\coloredSubscript{c}$ %correct spacing
$\mathcolor{blue}{a^b}\coloredSubscript{c}$ %very wrong spacing
\end{document}
To summarize: \mathcolor alone does not influence the spacing (which I appreciate a lot) and adding optional arguments usually also does not change the spacing (as I appreciate a lot). But somehow using both of them directly next to each other changes the spacing? Why?


_or^which has to be there via expansion, the lookahead and test for optional argument stops that so \mathcolor does not see the_– David Carlisle Nov 16 '23 at 00:27\mathcolor{blue}{a}^{\mathcolor{blue}{b}}\coloredSubscript? (tl;dr: What you want isn't supported by\mathcolor, which requires an explicit^or_after it to work. Use something else.) – user202729 Nov 16 '23 at 03:34