[NTG-context] Macros which scan subscripts/superscripts in ConTeXt
Aditya Mahajan
adityam at umich.edu
Fri Jun 26 03:47:46 CEST 2020
On Thu, 25 Jun 2020, Jairo A. del Rio wrote:
> Hi, list! I've seen the following in Stack Exchange:
>
> https://tex.stackexchange.com/questions/503208/define-macro-that-scans-ahead-for-super-and-or-subscript-absorbs-them-and-mo
>
> The answer is:
>
> \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}
>
> Such a macro contextually defines a behavior for a subscript and a
> superscript even if they aren't displayed in a specific order, so
>
> \mymacro_{a}^{b}
>
> \mymacro^{b}_{a}
>
>
> have the same output, even if the intended behavior is not the typical
> one (I could redefine it so subscripts change colors, for instance).
> Although I could just port the macro using xparse-generic because it
> works in ConTeXt too, how to define a macro like that the ConTeXt way,
> i.e., using only ConTeXt macros?
Return of the dodo :-)
% Must be outside \unprotect .. \protect so that _ has usual catcodes
\def\capturemathoplimits#1%
{\doifnextcharelse _%
{\docapturemathoplimitsA{#1}}
{\doifnextcharelse ^%
{\docapturemathoplimitsB{#1}}
{\redocapturemathoplimits{#1}}}}
\def\docapturemathoplimitsA#1#2#3%
{\doifnextcharelse ^%
{\dodocapturemathoplimitsA{#1}{#2}{#3}}
{\dodocapturemathoplimitsA{#1}{#2}{#3}\empty\empty}}
\def\dodocapturemathoplimitsA#1#2#3#4#5{#1{#5}{#3}}
\def\docapturemathoplimitsB#1#2#3%
{\doifnextcharelse _%
{\dodocapturemathoplimitsB{#1}{#2}{#3}}
{\dodocapturemathoplimitsB{#1}{#2}{#3}\empty\empty}}
\def\dodocapturemathoplimitsB#1#2#3#4#5{#1{#3}{#5}}
\def\redocapturemathoplimits#1{#1\empty\empty\empty\empty\empty}
% Usage:
\define\mymacro{\capturemathoplimits\domymacro}
\def\domymacro#1#2%
% #1 is supscript, #2 is subscript
{x^{\mathrm{foo}\doifsomething{#1}{,#1}}_{\mathrm{bar}\doifsomething{#2}{,#2}}}
\starttext
\startlines
$\mymacro$
$\mymacro^{\mathrm{extrasup}}$
$\mymacro_{\mathrm{extrasub}}$
$\mymacro^{\mathrm{extrasup}}_{\mathrm{extrasub}}$
$\mymacro_{\mathrm{extrasub}}^{\mathrm{extrasup}}$
\stoplines
\stoptext
Aditya
More information about the ntg-context
mailing list