Math inside \text

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.


Same approach as egreg's answer. But in a form that much better fits into my brain. (I created it to see if my understanding of egreg's solution was correct.)

\documentclass{article}
\usepackage{amsmath}

\newcommand\ttext[1]{\mathchoice%
  {\text{#1}}%
  {\text{#1}}%
  {\thickmuskip=0mu\medmuskip=0mu\text{#1}}%
  {\thickmuskip=0mu\medmuskip=0mu\text{#1}}}

\begin{document}

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

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

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

\end{document}

enter image description here

Tags:

Amsmath