I would write the code to an external file instead and reread it again when you need it. It avoids this issues and is much faster if you add a lot of material multiple times. Something based on filecontents or VerbatimOut of fancyvrb, but which allows to have multiple environments which all write to the same file:
Code:
% codewrite.sty
\RequirePackage{fancyvrb}
\newcommand*\CodeOut{\FV@Environment{}{CodeOut}}
\newwrite\@codewrite
% Or to save an output handle:
%\let\@codewrite\FV@OutFile
\newcommand*\CodeOpenFile[1]{%
\immediate\openout\@codewrite #1\relax
\def\CodeOpen@File{#1}%
}
\def\FVB@CodeOut{%
\@bsphack
\begingroup
\FV@UseKeyValues
\FV@DefineWhiteSpace
\def\FV@Space{\space}%
\FV@DefineTabOut
\def\FV@ProcessLine{\immediate\write\@codewrite}%
\let\FV@FontScanPrep\relax
%% DG/SR modification begin - May. 18, 1998 (to avoid problems with ligatures)
\let\@noligs\relax
%% DG/SR modification end
\FV@Scan
}
\def\FVE@CodeOut{\endgroup\@esphack}
\newcommand*\ReadCode{\immediate\closeout\@codewrite\input{\CodeOpen@File}}
\DefineVerbatimEnvironment{CodeOut}{CodeOut}{}
Usage Example:
\documentclass{article}
\usepackage{codewrite}
\CodeOpenFile{\jobname.cod}
\begin{CodeOut}
Test
\end{CodeOut}
\begin{document}
\begin{CodeOut}
\begin{verbatim}
test%^&$%\relax
\end{verbatim}
\end{CodeOut}
\ReadCode
\end{document}
There might be a package which does this already.
Note that you can catch the content of a file to a macro using the catchfile package.
\myboxand then\test=\expandafter{\the\test \box\mybox}– Alain Matthes Mar 10 '11 at 7:53\verbmacros orverbatimenvironments? Or should the text completely be read verbatim? You should add these cases to you MWE. It should always show what doesn't works. – Martin Scharrer♦ Mar 10 '11 at 11:22filecontents, but which allows to have multiple environments which all write to the same file. – Martin Scharrer♦ Mar 10 '11 at 14:43