2015-02-28 Math examples in TeX, part I

I’m currently coauthoring an introductory book on LaTeX. (Yes, yet another one. But apparently there are not that many of them in Polish!) Of course, one of the must-haves is a chapter on typesetting equations. What I wanted, however, is a way to enter them with preservation of the DRY principle. It’s probably a solved problem, but I quite enjoyed hacking it together myself.

\documentclass{article}
\makeatletter
\def\mathdemo{%
  \bgroup
  \let\do\@makeother\dospecials
  \@mathdemo
}
\def\@mathdemo`#1`{%
  \egroup
  \par\smallskip\noindent
  \makebox[0.48\textwidth]{\texttt{#1}}\hfill
  \framebox[0.48\textwidth]{$\scantokens{#1}$}\par\smallskip
}
\makeatother

\begin{document}
\mathdemo`E=mc^2`
\end{document}

It is probably self-explanatory for more seasoned TeX hackers, but let me explain it for the beginners here. We start with enabling the internal “@-commands” (\makeatletter). With that done, we define the \mathdemo command. It starts a group and makes all special characters no longer special locally in that group. (It does that by making the \do command turn its argument into an “other” category, and firing the \dospecials, which runs \do on all the special characters.) Finally, we start the \@mathdemo internal command.

What it does is that it interprets anything between the backticks as its argument (backtick is rather unlikely to happen in math examples). It starts by ending the group, which is important: now that all the category codes of the characters in the argument are fixed (as “non-specials”), we no longer need that. We start a new, unindented paragraph with a small skip above, put our argument in a fixed-width font in a box, and then the real fun begins. We use eTeX’s \scantokens to reinterpret the argument with the category codes now in effect. (This was something impossible to do in Knuth’s vanilla TeX.) This way, all the special characters (like the caret) get reinterpreted with their usual meaning. Finally, we turn off the “letterness” of the at-sign.

A side-effect of our playing with catcodes, by the way, is the impossibility of putting a space between \mathdemo and the first backtick: when reading the backtick-delimited argument to \@mathdemo, space is no longer of category 10 (a space character), so it is not ignored after a command.

Also, I have to admit that the production code I use is a bit more complicated: it allows for multiline code on the left, for instance, and it has a \dmathdemo variant for demonstrating displayed math. This, however, is another subject for another post.

CategoryEnglish, CategoryBlog, CategoryTeX, CategoryLaTeX