I am outputting LaTeX from another source language, but one that only gives me things a source-token at a time. Thus, I may get a token corresponding to “begin superscript” and then I will later get one corresponding to “end superscript”.
I used to have
\newcommand{\mybeginsup}{\begin{math}{}\sp\bgroup\tt}
\newcommand{\myendsup}{\egroup\end{math}}
(The \tt is the way I want my superscripts to style, and I hope it’s irrelevant.)
The problem with this is that it doesn’t handle nested superscripts. My guess it that this causes a nesting of \begin{math} commands, and that it is this that causes the “Bad math environment delimiter.” error messages.
So, how should I do this?
I did try:
\usepackage{ifthen}
\newcounter{embeddedmaths}
\renewcommand{\mybeginsup}{%
\ifthenelse{\value{embeddedmaths} = 0}%
{\addtocounter{embeddedmaths}{1}\begin{math}}{}\sp\bgroup\tt}
\renewcommand{\myendsup}{%
\egroup\addtocounter{embeddedmaths}{-1}%
\ifthenelse{\value{embeddedmaths} = 0}{\end{math}}{}}
to try to count the number of times I had entered math mode, but this gives
! Missing } inserted.
<inserted text>
So now I’m stuck.



\newcounter{embeddedmaths}somewhere. – Bruno Le Floch Jan 23 '12 at 1:29\newcounter. I’ll update. – Michael Norrish Jan 23 '12 at 2:31