[Tex/LaTex] Math inside \text

amsmath

Math inside \text looses the information that it is inside a subscript $X_{a+b,\text{\ensuremath{a+b}}}$.

\documentclass{article}
\usepackage{amsmath}
\begin{document}
  $X_{a+b,\text{\ensuremath{a+b}}}$
\end{document}

enter image description here

I'd like to find different ways to "fix" that.


Background: This is for my package mhchem. There is no striking use case I can think of, right now. It's more of a "make it consistent" feature.

If you use, for instance \ce{H2O} in text mode, then my package will typeset this correctly using the current text font, so it will also look nice in headlines and TOCs. It basically uses math mode with some \texts. I give the user the freedom to insert math anywhere they wish, and they could even write something like \ce{NO_{2n + $\sum_i x_i + y_i$} or something else. I had to choose such a weird example, because all the sensible expressions (n, 2n, 2n+1) already get a special treatment. However, I still want to allow any math expression there, no matter how weird and nested.

Best Answer

The \text macro indeed loses the information that it is being used in subscripts or superscripts.

Here is a possible patch, but probably using a different macro would be better. If you plan to use it in your package, the users should be warned about the difference with the standard \text command as defined by amsmath.

\documentclass{article}
\usepackage{amsmath}
\usepackage{xpatch}

\makeatletter
\newcommand{\remove@spaces}{%
  \thickmuskip=0mu
  \medmuskip=0mu
}
\xpatchcmd{\text@}
 {\textdef@\textstyle\sf@size}
 {\textdef@{\textstyle\remove@spaces}\sf@size}
 {}{}
\xpatchcmd{\text@}
 {\textdef@\textstyle\ssf@size}
 {\textdef@{\textstyle\remove@spaces}\ssf@size}
 {}{}
\makeatletter

\begin{document}

$X_{a+b<c\sin x,\text{text $a+b<c\sin x$}}$

$\displaystyle x+\text{text $a+b<c\sin x$}$

$x+\text{text $a+b<c\sin x$}$

\end{document}

enter image description here

If you want to define a new command, say \ttext, you can do (with \usepackage{amsmath}, of course)

\makeatletter
\newcommand{\remove@spaces}{%
  \thickmuskip=0mu
  \medmuskip=0mu
}
\DeclareRobustCommand{\ttext}{%
  \ifmmode\expandafter\ttext@\else\expandafter\mbox\fi}
\def\ttext@#1{{\mathchoice
  {\textdef@\displaystyle\f@size{#1}}%
  {\textdef@\textstyle\f@size{\firstchoice@false #1}}%
  {\textdef@{\textstyle\remove@spaces}\sf@size{\firstchoice@false #1}}%
  {\textdef@{\textstyle\remove@spaces}\ssf@size{\firstchoice@false #1}}%
  \check@mathfonts
  }%
}
\makeatother

This calls \mathchoice just once.

Related Question