
考慮以下 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}
哪個產生
現在:為什麼我必須用\ce{CO2}
大括號來擁抱(所有雙關語)宏,而\text{}
宏不需要它們?註釋文字產生錯誤missing { inserted c_\ce{CO2}
答案1
我們來看看怎麼amstext.sty
說的:
\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
}%
}
如果我們處於數學模式,當\text{xyz}
找到 時,TeX 會遵循「true」分支,因此會出現\text@{xyz}
(因為\else...\fi
被丟棄。
然後用它的定義代替\text@
,即
{\mathchoice{...}}
這些額外的括號保持_
快樂。我們必須記住,_
在數學模式下會導致以下標記的擴展。
我猜想引入額外的大括號只是為了避免_\text{xyz}
否則會產生難以理解的錯誤。
不幸的是,它允許那種「錯誤」的輸入。這與 發生的情況非常相似_\mathrm{xyz}
,我已在中粗略地解釋過https://tex.stackexchange.com/a/160538/4427
另一方面, 的定義\ce
沒有這種類型:
\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
}
這肯定會讓 TeX 看到不高興_\ce{...}
。