latexbeamer

How can I include a listing inside a beamer in latex?


I'm using the listings package for Latex to insert a python code snippet inside a beamer. Here's the (although reduced to the bare minimum for the bug to happen) code :


\documentclass{beamer}
\usepackage{graphicx, listings, tikz, subcaption, amsmath} 
\usetheme{Copenhagen}
\setbeamertemplate{footline}[frame number]


\begin{document}

\maketitle

\begin{frame}{My frame}
    \begin{lstlisting}
        Why 
            doesn't 
        this work ??
    \end{lstlisting}
\end{frame}

\end{document}

The result is a compilation timeout, and I don't get why.


Solution

  • If your frame contains fragile content like listings, use the fragile frame option:

    \documentclass{beamer}
    
    \usepackage{
      %graphicx, 
      listings, 
      tikz, 
      subcaption, 
      %amsmath
    } 
    \usetheme{Copenhagen}
    \setbeamertemplate{footline}[frame number]
    
    \begin{document}
    
    \maketitle
    
    \begin{frame}[fragile]
      \frametitle{My frame}
        \begin{lstlisting}
    Why 
        doesn't 
    this work ??
        \end{lstlisting}
    \end{frame}
    
    \end{document}