4

I'm relatively new to Latex and having a bad time using listings inside a beamer presentation. I know I have to use a [fragile] frame to get verbatim environment inside a frame, but for some reasons it didn't work (and I've read it prevents from using overlays, but unsure about that).

I've found a solution, which works, by defining a savebox outside the frame and using it after :

\newsavebox{\mybox}
\begin{lrbox}{\mybox}
\begin{lstlistings}
blah blah blah
\end{lstlistings}
\end{lrbox}

\begin{frame}
    \usebox\mybox
\end{frame}

The thing is I want to create an environment for this. Something like:

\begin{code}{\mybox}
blahblahblah
\end{code}

I tried with \newenvironment, but obviously it didn't work because of the way verbatim environment works (looking for the matching end environment pattern, which doesn't exists during expansion). Listings gives \lstnewenvironment, but the problem is that I want my box to be around the created environment, so it's not the right solution.

As I'm new, I don't really know how it works under the hood so I don't know where to start searching.

1
  • Welcome to TeX.SX!
    – egreg
    Feb 2, 2016 at 0:59

1 Answer 1

2

You can't put a lstlisting environment directly in an lrbox, but you can in a \vbox (a lower level object).

\documentclass{beamer}
\usepackage{listings}

\lstnewenvironment{code}[2][]
 {\lstset{#1}\global\setbox#2\vbox\bgroup}
 {\egroup}

\newsavebox{\mybox}

\begin{document}

\begin{code}[basicstyle=\ttfamily]{\mybox}
blahblahblah
\end{code}

\begin{frame}

\usebox{\mybox}

\end{frame}

\end{document}

I used the optional argument just to show how it's employed.

enter image description here

2
  • Thanks, it works, but the thing is you still have to \newsavebox every time with a different name... I saw that I can reuse the same name over and over again in the rest of my document, so the name changing part is not useful finally (except if I want to reuse the same verbatim multiple times). Is there a solution to not have to \newsavebox?
    – orion78fr
    Feb 2, 2016 at 1:16
  • Nevermind, adding the \newsavebox#2 in the beginning of the code environment seems to work...
    – orion78fr
    Feb 2, 2016 at 1:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .