Post by Andrei Alexandrescu (See Website For Email)I am trying to use the listings environment inside a macro, and this
How about working around this:
How about using the verbatimwrite-environment for writing your listing
verbatim to an external file?
Afterwards you can use \input or \lstinputlisting for repeated inclusion.
If you want repeated inclusion also of text which surrounds the listing, use the
verbatimwrite-environment for creating an external file which also contains the
lstlisting-environment. Use \input for importing it into your document.
If you only want the listing to be repeated, but no surrounding text, use the
verbatimwrite-environment for creating an external file which only contains
the listing but no surrounding lstlisting-environment.
Use \lstinputlisting for importing it into your document.
You can put the call to \input/lstinputlisting into a macro if you like.
You can also use Scott Pakin's attachfile-package for attaching the external file
with the code-listing to the pdf. This way you can have nicely formatted listings
with line-numbers etc when reading the pdf.
But for testing/compiling/playing around, the user can extract the listing to
hard-disk without the need of manually removing the formatting or the
line-numbers as might be the case when using some pdf-viewer's fancy
edit-copy-edit-paste-features.
Ulrich
\documentclass{article}
\usepackage{verbatim, listings}
%Define the verbatimwrite-environment:
\makeatletter
\@ifdefinable\***@out{%
\newwrite\***@out
}%
\newcommand*\verbatimwrite[1]{%
\@bsphack
\immediate\openout\***@out#1\relax
\let\do\@makeother\dospecials
\catcode`\^^M\active
\***@startline
\***@addtoline
\***@finish
\def\***@processline{%
\immediate\write\***@out{\the\***@line}%
}%
\***@start
}%
% This is the ending-part of the environment:
\@ifundefined{endverbatimwrite}%
{\def\endverbatimwrite{%
\immediate\closeout\***@out
\@esphack
}%
}%
{{\def\***@a{endverbatimwrite}\@notdefinable}}%
\makeatother
% Use the verbatim-environment for creating an external file
% which contains your listing:
\begin{verbatimwrite}{surround.tex}
some surrounding text
\begin{lstlisting}
some code ^@#&$§+-\/{}[]
\end{lstlisting}
some more surrounding text
\end{verbatimwrite}
\begin{verbatimwrite}{purelist.tex}
some code ^@#&$§+-\/{}[]
\end{verbatimwrite}
\newcommand*\othersurround{%
some surrounding text
\lstinputlisting{purelist.tex}
some more surrounding text
}%
\begin{document}
\textbf{The listing with text which surrounds it:}
\input{surround.tex}
\input{surround.tex}
\textbf{The pure listing:}
\lstinputlisting{purelist.tex}
\input{surround.tex}
\textbf{Again the listing with text which surrounds it:}
\othersurround
\othersurround
\end{document}