[Tex/LaTex] \newenvironment fails with special listings environment

environmentslistings

I want to use the showexpl, but define a new environment with predefined settings. But all I get is an emergency stop.

\documentclass{scrbook}
\RequirePackage{showexpl}
\lstdefinestyle{demoLatexStyle}{
    basicstyle=\small\ttfamily, % Standardschrift
    numbers=none,               % Ort der Zeilennummern
    frame=none,
}
\begin{document}
\newenvironment{showdemo}[1][]{\LTXexample[style=demoLatexStyle,#1]}{\endLTXexample}

\begin{LTXexample}[style=demoLatexStyle]
\LaTeX{} \LaTeX{}
\end{LTXexample}

\begin{showdemo}    
\LaTeX{} \LaTeX{}
\end{showdemo}

\end{document}

\openout3 = `testdemo.tmp'. Package Listings Warning: Text dropped
after begin of listing on input line 24. ! Emergency stop. <>
testdemo.tex
*
* (job aborted, no legal \end found)

Any hint what I am doing wrong?

Best Answer

Section 4.16 of the listings package specifies that to define new environments you need to use the following with syntax similar to LaTeX's \newenvironment.

\lstnewenvironment
    {<name>}[<number>][<optional default arg>]
    {<starting code>}
    {<ending code>}

So, if you replace the \newenvironment with the following:

\lstnewenvironment{showdemo}[1][]{%
    \lstset{style=demoLatexStyle,#1}}{}%

you get the desired result:

enter image description here


Update

You could also use LTXinputExample and add the necessary code in separate files, or use the filecontents package. Since you asked for an environment below I have defined showdemoEnv, but I think the macro version showdemo is probably better in this case:

\documentclass{scrbook}
\RequirePackage{showexpl}
\lstdefinestyle{demoLatexStyle}{
    basicstyle=\small\ttfamily, % Standardschrift
    numbers=none,               % Ort der Zeilennummern
    frame=none,
}

\newcommand{\TempFileName}{\jobname.filecontents.tmp}%
\usepackage{filecontents}
\begin{filecontents*}{\TempFileName}
\LaTeX{} \LaTeX{}
\end{filecontents*}

\newenvironment{showdemoEnv}[2][]{% Environment version
    \LTXinputExample[style=demoLatexStyle,#1]{#2}%
}{%
  % Add any end environemnt code here.
}%

\newcommand{\showdemo}[2][]{% Macro version
    \LTXinputExample[style=demoLatexStyle,#1]{#2}%
}%


\begin{document}

\begin{LTXexample}[style=demoLatexStyle]
\LaTeX{} \LaTeX{}
\end{LTXexample}

\begin{showdemoEnv}{\TempFileName}    
\end{showdemoEnv}

\showdemo{\TempFileName}
\immediate\write18{rm \TempFileName}% Remove file
\end{document}

Note that the starred version filecontents* was used. This prevents the header comments that filecontents would normally add to the file.

enter image description here

Related Question