1

I want to show some program code line by line. I have the following code:

\documentclass[10pt,english]{beamer}

\usepackage{listings} \lstset{ language=C, basicstyle=\ttfamily }

\begin{document} \begin{frame}[fragile] \frametitle{Slides with code} \begin{itemize} \item <1-> A piece of code \item[] <2-> \begin{lstlisting}[caption=,belowskip=-5pt] int main(void) \end{lstlisting} \item[] <3-> \begin{lstlisting}[caption=,belowskip=-5pt] { \end{lstlisting} \item[] <4-> \begin{lstlisting}[caption=,belowskip=-5pt] int i; \end{lstlisting} \end{itemize} \end{frame}

\end{document}

Now this is error-prone a painstaking. Is there another way to produce these slides?

  • You still have to \pause on each line, but it's better than having to restart the listing every time. – Teepeemm Sep 27 '21 at 15:54

1 Answers1

1

You can use mathescape to insert appropriate \pauses within the code, resulting in an easier way to negotiate the code reveal:

enter image description here

\documentclass{beamer}

\usepackage{listings} \lstset{ language=C, basicstyle=\ttfamily }

\begin{document}

\begin{frame}[fragile] \frametitle{Slides with code}

\begin{lstlisting}[caption=,mathescape] int main(void) $\pause${ $\pause$ int i; $\pause$} \end{lstlisting}

\end{frame}

\end{document}

Werner
  • 603,163
  • Thanks, I needed the pause. Is this better that using escapeinside=|| and then use |\pause|? – Jesse op den Brouw Sep 27 '21 at 15:58
  • You could probably move mathescape up to the lstset. Then it would be basically the same as escapeinside=$$ (although $$ may break things). So my guess is "better" would boil down to: does your code otherwise use the character | or $? – Teepeemm Sep 27 '21 at 16:05
  • That would be problematic if the code uses $, indeed. Better is to set the escape characters on a per listing basis, or use mathescape when is can be used. – Jesse op den Brouw Sep 27 '21 at 16:14
  • @JesseopdenBrouw: True. You'd have to use whatever suits your needs specifically. Not sure whether C uses $. Regardless, you can adjust this on a lstlisting basis, if needed. – Werner Sep 27 '21 at 16:15