# incompatibility of xparse e- and t-type argument with subscriptcorrection option of newtxmath

It appears that the subscriptcorrection option for newtxmath is incompatible with e- and t-type arguments of xparse that use _. Using examples adapted from egreg's answers here and here, the following compiles as expected:

\documentclass{article}

\usepackage{xparse}
\usepackage{newtxmath}
\usepackage{xcolor}

\NewDocumentCommand{\MyMacro}{t_}{A\IfBooleanT{#1}{\MyMacroAux}}
\NewDocumentCommand{\MyMacroAux}{m}{_{\textcolor{red}{#1}}}
\NewDocumentCommand{\MyOtherMacro}{e_}{
\IfNoValueTF{#1}
{\mathbf{A}}
{A_{\textcolor{red}{#1}}}
}

\begin{document}
\textbf{t-type:} With a subscript: $\MyMacro_{\pi}$

Without any subscript: $\MyMacro$

\textbf{e-type:} With a subscript: $\MyOtherMacro_{\pi}$

Without any subscript: $\MyOtherMacro$
\end{document}


However with subscriptcorrection enabled, the same code compiles without error but the macros have no effect:

The following lines in newtxmath.sty that are enabled by the package option suggest this is a catcode issue:

\AtBeginDocument{\mathcode\_=\string"8000 \catcode\_=12\relax} \begingroup
\catcode\_=13
\gdef_{\expandafter\s@@b@}
\endgroup


I know that \catcode\_=13 makes _ an active character, but I've not been able to determine how this interacts with xparse's definition of e- or t-type commands. Is there a workaround to get the effect of subscriptcorrection while also having e- and t-type commands function as expected?

xparse requires that the token used in a t or e argument be identical to the one found when executing the command, which means its catcode and charcode have to both match.

The part of subscriptcorrection that makes your command not work is \AtBeginDocument{\catcode\_=12\relax}, which makes the underscore an other (catcode 12) character at \begin{document}, but in the preamble, where you define your command, the underscore is still catcode 7, and this is the meaning of _ that is fixed in your commands.

You can work around that by temporarily making the underscore catcode 12 while you define your commands:

\documentclass{article}

\usepackage{xparse}
\usepackage[subscriptcorrection]{newtxmath}
\usepackage{xcolor}

\begingroup
\catcode\_=12
\long\def\next#1{\endgroup#1}%
\next{%
\NewDocumentCommand{\MyMacro}{t_}{A\IfBooleanT{#1}{\MyMacroAux}}
\NewDocumentCommand{\MyMacroAux}{m}{_{\textcolor{red}{#1}}}
\NewDocumentCommand{\MyOtherMacro}{e_}{
\IfNoValueTF{#1}
{\mathbf{A}}
{A_{\textcolor{red}{#1}}}
}
}

\begin{document}
\textbf{t-type:} With a subscript: $\MyMacro_{\pi}$

Without any subscript: $\MyMacro$

\textbf{e-type:} With a subscript: $\MyOtherMacro_{\pi}$

Without any subscript: $\MyOtherMacro$
\end{document}