Defina una macro que busque superíndices y/o subíndices, los "absorba" y mueva su argumento.

Defina una macro que busque superíndices y/o subíndices, los "absorba" y mueva su argumento.

Tengo muchas macros matemáticas que ya tienen un superíndice y/o subíndice por definición, es decir, algo como

\newcommand*{\mymathsym}{x^{\text{foo}}_{\text{bar}}}

En el cuerpo del texto, estos símbolos frecuentemente necesitan un sup-/subíndice adicional. Esto significa que el autor debe recordar colocar el símbolo principal entre un par de llaves {}; de lo contrario, se producirá un error de doble índice/subíndice.

\begin{equation}
  {\mymathsym}^{\text{extra}}
\end{equation}

El superíndice adicional se convierte en superíndice secundario y se sitúa ligeramente más alto y más pequeño: superíndice adicional esto tiene dos inconvenientes: a) En el campo de aplicación especial, ambos superíndices se encuentran en el mismo nivel jerárquico desde el punto de vista conceptual. En otras palabras, ambos superíndices deberían imprimirse como una lista "foo, extra" y el orden opuesto "extra, foo" sería igualmente bueno. b) Si el sup- y el subíndice primario están muy desequilibrados en longitud, el superíndice secundario se separa mucho, por ejemplo

\newcommand*{\mymathsymlong}{x^{\text{foo}}_{\text{very long foobar}}}

y

\begin{equation}
{\mymathsymlong}^{\text{extra}}
\end{equation}

rendimientos superíndice muy separado

Como solución alternativa, actualmente uso la siguiente definición que toma un argumento opcional y lo agrega al superíndice interno:

\newcommand*{\mymathsymext}[1][]{x^{\text{foo}\if!#1!\else, #1\fi}_{\text{very long foobar}}}

(Nb, sé que la condición \if!#1!no es la forma correcta de probar un argumento vacío, porque falla si el argumento se expande a a !. Pero creo que entiendes lo que hace la macro).

Se utiliza como

\begin{equation}
\mymathsymext \qquad\text{vs.}\qquad \mymathsymext[\text{extra}]
\end{equation}

y produce ingrese la descripción de la imagen aquí Sin embargo, esto tiene dos inconvenientes importantes: a) \newcommandsólo admite un único argumento opcional. Por lo tanto, necesito decidir en el momento del diseño si eventualmente podría ser necesario un superíndice adicional o un subíndice adicional. No puedo apoyar a ambos. b) El usuario debe recordar una sintaxis inusual para colocar sup-/subíndices adicionales.

Pregunta:

¿Cómo se define una macro \mymathsymsuperque

  • escanea hacia adelante, si va seguido de un carácter de subíndice ^<tok> y/o un carácter de subíndice _<tok>, cada uno seguido de un token adicional <tok>
  • "los absorbe", y
  • ¿mueve <tok> al final de su sup-/subíndice interno separado por una coma?

MWE completo:

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}

\newcommand*{\mymathsym}{x^{\text{foo}}_{\text{bar}}}

\newcommand*{\mymathsymlong}{x^{\text{foo}}_{\text{very long foobar}}}

\newcommand*{\mymathsymext}[1][]{x^{\text{foo}\if!#1!\else, #1\fi}_{\text{very long foobar}}}

\begin{document}

Here, the author must know that \verb#\mymathsym# has already a super- and subscript and must remember to put the main symbol into a pair of \{\}-braces, otherwise a double sup-/subscript error occurs.
The extra superscript becomes a secondary superscript and it set slightly higher and smaller:
\begin{equation}
{\mymathsym}^{\text{extra}}
\end{equation}

If the primary sup- and subscript are very unbalanced in their length, the secondary subscript is set very far apart:
\begin{equation}
{\mymathsymlong}^{\text{extra}}
\end{equation}

This extended macro takes an optional argument and ``absorbs'' the extra superscript into the primary superscript:
\begin{equation}
\mymathsymext \qquad\text{vs.}\qquad \mymathsymext[\text{extra}]
\end{equation}
Still, the author must remember this ``unusual'' syntax and it only supports either an extra super- or subscript, bot not both.

\paragraph{Question:}
How does one define a macro \verb#\mymathsymsuper# that
\begin{itemize}
  \item scans ahead if it followed by a superscript character $\verb!^!\langle \mathit{token}_\text{sup}\rangle$ and/or subscript character $\verb!_!\langle \mathit{token}_\text{sub}\rangle$ each followed by an    additional token $\mathit{token}_\text{sup}$ and $\mathit{token}_\text{sub}$ resp.
  \item ``absorbs them'', and
  \item moves $\mathit{token}_\text{sup}$ and/or $\mathit{token}_\text{sub}$ to end of its internal sup-/subscript separated by a comma?
\end{itemize}

\end{document}

Respuesta1

Es muy fácil con xparse:

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\NewDocumentCommand{\mymathsym}{e{^_}}{%
  x^{\mathrm{foo}\IfValueT{#1}{,#1}}_{\mathrm{bar}\IfValueT{#2}{,#2}}%
}

\begin{document}

\begin{gather}
\mymathsym \\
\mymathsym^{\mathrm{extrasup}} \\
\mymathsym_{\mathrm{extrasub}} \\
\mymathsym^{\mathrm{extrasup}}_{\mathrm{extrasub}} \\
\mymathsym_{\mathrm{extrasub}}^{\mathrm{extrasup}}   
\end{gather}

\end{document}

ingrese la descripción de la imagen aquí

Con e{^_}la macro busca ^o _(en cualquier orden) y asigna #1al superíndice, #2al subíndice. Puede probar la presencia con \IfValueT(o \IfValueTFsi desea realizar alguna acción con un subíndice/superíndice ausente).

información relacionada