Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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
            $
? 
share|improve this question

1 Answer 1

up vote 12 down vote accepted

It is an argument to listings not to \begin

                  %%%%%%%%%%%%
\begin{lstlisting}[mathescape]
$\infty$
\end{lstlisting}

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

\begin[mathescape]{lstlisting}$\infty$

is

\begin{[}mathescape]{lstlisting}$\infty$

Now \begin essentially does \begingroup\csname[\endcsname so this is

\begingroup\[mathescape]{lstlisting}$\infty$

so \[ starts display math and mathescape]{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.

share|improve this answer
    
Thanks ! You must admit the error message wasn't really helpful... –  otibom Apr 9 '13 at 8:48
    
@otibom actually the reason you get that error is quite funny (if it is not your document:-) I'll put a breakdown in the answer. –  David Carlisle Apr 9 '13 at 8:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.