Goal: What I would like to do is to allow _ and ^ to be used to generate sub and superscripts in text mode only within a specific macro. I know that I can make _ and ^ active throughout the document, but that messes with other packages which assume that they will not be.
I've dug around a bit, and haven't found an example that implements something close to what I want.
I've been basing my code off of examples like https://texfaq.org/FAQ-actinarg This works for creating a command in which the argument is typeset with _ and ^ being active:
\documentclass{article}
\begin{document}
\begingroup
\catcode`_=\active%
\gdef_#1{\ensuremath{{}\sb{#1}}}%
\catcode`^=\active%
\gdef^#1{\ensuremath{{}\sp{#1}}}%
\endgroup
\def\subsup{%
\begingroup
\catcode_=\active \catcode^=\active
\Xsubsup
}
\def\Xsubsup#1{%
#1%
\endgroup
}
\subsup{foo_x bar^y baz}
% foo_a bar^b baz % this will cause an error because _ is not active.
Now, if I add the function that I want to embed this in:
\DeclareRobustCommand*\newMacro[2][\null]{
% other processing and formatting not directly relevant to this example
\subsup{#2}%
}
\newMacro{foo_x bar^y baz}
\end{document}
I get math mode errors:
ERROR: Missing $ inserted.
--- TeX said ---
<inserted text>
$
l.28 \newMacro{foo_x bar^y baz}
So I tried to embed the subsup macros into newMacro (I've repeated some of the code from above for ease of copying and pasting.):
\documentclass{article}
\begin{document}
\begingroup
\catcode`_=\active%
\gdef_#1{\ensuremath{{}\sb{#1}}}%
\catcode`^=\active%
\gdef^#1{\ensuremath{{}\sp{#1}}}%
\endgroup
\DeclareRobustCommand*\newMacro[2][\null]{
\def\subsup{%
\begingroup
\catcode_=\active \catcode^=\active
\Xsubsup
}
\def\Xsubsup#1{%
#1%
\endgroup
}
% other processing and formatting not directly relevant to this example
\subsup{#2}%
}
\subsup{foo_x bar^y baz} %this is undefined, and so fails because newMacro hasn't been called yet.
\newMacro{foo_x bar^y baz}
\subsup{foo_x bar^y baz} % this works because it comes after newMacro has been called.
\end{document}
This still doesn't work, but now I get the error:
ERROR: Use of \Xsubsup doesn't match its definition.
--- TeX said ---
\newMacro ...\Xsubsup #1{#1\endgroup } \subsup {
#2}
l.28 \newMacro{foo_x bar^y baz}
Why do the two subsup functions work only when not embedded in another macro? Why do I get errors that Xsubsup doesn't match its definition only when it is embedded within another macro? Is there anyway to get around this?
\supsubor other macros cannot change them. – egreg Feb 18 '13 at 20:56\foo{bar_{baz}}is doable but something like\foo{{baz_{bar}}}is much more tricky. – Joseph Wright Feb 18 '13 at 21:11