[Tex/LaTex] LaTeX – Multiple pages on a code listing inside a beamer frame

beamerlistings

I'm trying to put some Python code on a beamer slide. I would like to take one big file and print it with lstinputlisting.

I've tried to set the frame fragile with:

\begin{frame} [fragile]
    \lstinputlisting{my_big_file.py}     
\end{frame}

It compiles ok, but LaTeX seems to ignore me =(

Am I missing something?

Best Answer

Usually the allowframebreaks option allows that overlong content creates several frames. However, this seems not to work with \lstinputlisting. My suggestion is therefore to use a loop to include only e.g. 10 lines of code per slide. If this should really be done for a presentation is an own question, I only answer the technical part.

Here I use \foreach from pgffor to loop in steps of 10 from the first to the last page (120 in this example). Then \only<+> is used to create a new slide as part of the frame. I also added a subtitle to show the current line number. This requires some manually expanding because the loop variable isn't accessible otherwise.

\documentclass{beamer}
\usepackage{listings}
\usepackage{pgffor}
\begin{document}

\begin{frame}{My code}
    \lstset{language=python,basicstyle=\sffamily\small}%
    \foreach \n in {1,11,...,120} {%
       \only<+>{%
            \edef\m{\the\numexpr\n+9\relax}%
            \edef\thesubtitle{{Lines \n--\m\ / 120}}%
            \expandafter\framesubtitle\thesubtitle
            \lstinputlisting[firstline=\n,lastline=\m]{my_big_file.py}%
       }%
    }
\end{frame}

\end{document}

This code creates 12 slides. You only need to adjust the title text and the maximum line number. Note that the fragile option is not required here because the frame doesn't actually include verbatim material directly.