[Tex/LaTex] Problem defining a new lstlisting environment

environmentslistings

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.

Best Answer

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

Related Question