I'm trying to write math in a code listing, like so :
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin[mathescape]{lstlisting}
$\infty$
\end{lstlisting}
\end{document}
I get the following error :
! Display math should end with $$.
<to be read again>
\infty
l.10 $\infty
$
?
Best Answer
It is an argument to
listings
not to\begin
The reason that you get that error is that TeX allows you to omit the braces around mandatory arguments, and if so takes the first token. so
is
Now
\begin
essentially does\begingroup\csname[\endcsname
so this isso
\[
starts display math andmathescape]{lstlisting}
gets typeset as characters in display math mode, then the single$
is met but TeX wants a double$$
to end display math so issues a primitive error.Basically error detection in a macro processing language is usually more by luck than design.