Problem creating a lstnewenvironment that starts/ends another environment
Asked Answered
T

2

10

I am currently using Beamer and the listing package to pretty-print code into Beamer blocks. So what I'm doing looks like :

\begin{block}{}
\begin{lstlisting}
int foobar(void) { return 0; }
\end{lstlisting}
\end{block}

Now, I find it cumbersome to start the block and lstlisting environments everytime. I'd like to have a simple codeblock environment that just does it:

\begin{codeblock}
int foobar(void) { return 0; }
\end{codeblock}

So, I tried something like :

\lstnewenvironment{codeblock}
{\begin{block}{}}
{\end{block}}

But unfortunately, the Beamer document no longer compiles, with the following error:

! Missing } inserted.
<inserted text> 
                }
l.178 \end{frame}

? 

Is there some way to do this ?

In Problem with creating a newenvironment in LaTeX, Andreas Grech had the same problem, but it could solve it since there was another way to enter/exit the enclosing environment. But in the case of the block Beamer environment, it seems there is no other way than doing \begin{block}...\end{block}.

Trommel answered 4/3, 2011 at 8:45 Comment(2)
Has this issue been resolved?Appellative
For the record, there is the same problem with \begin{tabular}{...} and \end{tabular}, but problem is solved using the TeX style \tabular{...} and \endtabular. I have no idea why (I thought both forms were strictly equivalent). Unfortunately, this does not seem to be applicable to beamer's block environment.Ergograph
R
0

I had the same problem and could not find a solution for it. My workaround was to use the \lstinputlisting command and have the code in a separate file. That's great if you have real code you want to include. Not so for small examples.

Another workaround is to put the code snipplet into a variable before starting the {frame} environment and then reference it. How to do this is explained in latex-beamer docs. It would also allow you to employ your custom environment/command.

Romanaromanas answered 4/3, 2011 at 10:0 Comment(0)
G
0

I "solved" this by using the fancyvrb package's \VerbatimOut(See write environmnet body verbatim to a file) to create a temporary file which then can be included with lstinputlisting:

\usepackage{fancyvrb}
\usepackage{listings}

\newenvironment{blocklisting}[1]
{\begingroup\lstset{#1}\VerbatimOut{blocklisting-tmp.txt}}
{\endVerbatimOut\begin{block}{Code}\lstinputlisting{blocklisting-tmp.txt}\end{block}\endgroup}

For some reason i could not make the environment-argument optional, though.

Used like this:

\begin{document}
\begin{frame}[fragile]
\frametitle{Whatever}
\begin{blocklisting}{language=Java, basicstyle=\Huge}
Code
\end{blocklisting}

\begin{blocklisting}{}
Code 2
\end{blocklisting}
\end{frame}
\end{document}

Not the optimal solution, but it works, i guess.

Generalize answered 25/11, 2015 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.