3

Consider the following MWE

\documentclass{article}
\usepackage[version=3]{mhchem}
\begin{document}
\begin{equation*}
  %   c_\ce{CO2} not working
  c_{\ce{CO2}} \quad c_\text{working}
\end{equation*}
\end{document}

which produce

enter image description here

Now: why do I have to embrace (all the puns intended) the \ce{CO2} macro with braces, while the \text{} macro doesn't need them? The commented text produces an error missing { inserted c_\ce{CO2}

  • The fact that \text works without the braces is purely incidental and should not be relied upon. See tex.stackexchange.com/a/160538/4427 – egreg Apr 18 '15 at 17:51
  • To explain what happens, the expansion of \text starts with {, which is then used for the subscript. – egreg Apr 18 '15 at 17:59
  • In the same way as \mathrm{}, as you explain in the question above? – Holene Apr 18 '15 at 18:00
  • Not completely the same, but basically so. I think I have already explained the behavior somewhere, and I'm trying to find it. – egreg Apr 18 '15 at 18:01
3

Let's see what amstext.sty says:

\DeclareRobustCommand{\text}{%
  \ifmmode\expandafter\text@\else\expandafter\mbox\fi}
\def\text@#1{{\mathchoice
  {\textdef@\displaystyle\f@size{#1}}%
  {\textdef@\textstyle\f@size{\firstchoice@false #1}}%
  {\textdef@\textstyle\sf@size{\firstchoice@false #1}}%
  {\textdef@\textstyle \ssf@size{\firstchoice@false #1}}%
  \check@mathfonts
  }%
}

If we are in math mode, when \text{xyz} is found, TeX follows the “true” branch and so is presented with \text@{xyz} (because the \else...\fi is discarded.

Then it substitutes \text@ with its definition, that is,

{\mathchoice{...}}

and these additional braces keep _ happy. We must recall that _ in math mode causes expansion of the following tokens.

I guess that the additional braces were introduced just for avoiding unscrutable errors that _\text{xyz} would produce otherwise.

Unfortunately, it allows that kind of “wrong” input. It's much similar to what happens with _\mathrm{xyz}, that I have roughly explained in https://tex.stackexchange.com/a/160538/4427

On the other hand, the definition of \ce has nothing of this kind:

\newcommand*{\ce}{%
  \ifx\protect\@typeset@protect
    \csname ce \expandafter\endcsname
  \else
    \ifx\protect\@unexpandable@protect
      \protect@unexpand@cmd@arg\ce
    \else
      \ifx\protect\string
        \protect@string@cmd@arg\ce
      \else
        \expandafter\protect@unknown@cmd@arg
        \csname ce \endcsname
      \fi
    \fi
  \fi
}

This will definitely make TeX unhappy upon seeing _\ce{...}.

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.