[Tex/LaTex] A line in the lstlisting environment cannot start with “\end{frame}” in a beamer presentation

beamerlistings

I'm making a presentation about LaTeX using the beamer package (v3.10). I'm using the listings (v1.4) package to print pieces of latex source code and highlight the keywords.

It seems that the following minimal example can't compile :

\documentclass{beamer}
\usepackage[english,french]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{listings}
\lstset{language=[LaTeX]tex}

\begin{document}

\begin{frame}[fragile]
\begin{lstlisting}
\begin{frame}
\titlepage
\end{frame}
\end{lstlisting}
\end{frame}

\end{document}

Using latexmk with the latexila editor, I got this error :

Missing } inserted

Whereas, using pdftex with the latexila editor, I got a more verbose output :

\begin{lstlisting} on input line 1 ended by \end{beamer@framepauses}.
Extra }, or forgotten \endgroup
\begin{lstlisting} on input line 1 ended by \end{beamer@frameslide}.
Undefined control sequence
Package Listings Error: Extra \endlstlisting
\begin{beamer@framepauses} on input line 17 ended by \end{lstlisting}.
Extra }, or forgotten \endgroup
\begin{beamer@framepauses} on input line 17 ended by \end{document}.
You can't use `\end' in internal vertical mode
\begin{beamer@framepauses} on input line 17 ended by \end{document}.

After some research, It seems that even with the [fragile] option passed on to \frame, there is a problem with the last line of the quoted code : \end{frame}.

One workaround is to indent from at least one space this line :

\begin{lstlisting}
\begin{frame}
\titlepage
 \end{frame}
\end{lstlisting}

My conclusion is : a line in the lstlisting environment cannot start with \end{frame}.
Did I do something wrong ?

Best Answer

beamer does a lot of leg work when setting the frame environment, since it might have to parse the contents more than once in order to take seemingly single slides and break them into number of frames. As a safe bet, you can box the contents of your listing outside the frame and then include the pre-typeset box:

enter image description here

\documentclass{beamer}% http://ctan.org/pkg/beamer
\usepackage{listings}% http://ctan.org/pkg/listings
\lstset{language=[LaTeX]tex}
\newsavebox{\codebox}% For storing listings

\begin{document}

\begin{lrbox}{\codebox}
\begin{lstlisting}
\begin{frame}
\titlepage
\end{frame}
\end{lstlisting}
\end{lrbox}

\begin{frame}
\usebox{\codebox}
\end{frame}

\end{document}​