[Tex/LaTex] How to write verbatim code to a file with \immediate\write

external filesverbatim

I'm using the technique described in egreg's answer to Efficient way to write backslash to a file to write LaTeX code in an external file:

\newwrite\mywriter
\NewEnviron{writethis}
    {\immediate\write\mywriter{\unexpanded\expandafter{\BODY}}}
\begin{document}

\immediate\openout\mywriter=\jobname-later.tex
\begin{writethis}\textbf{abc}\end{writethis}
\immediate\closeout\mywriter

However, I cannot use it with verbatim text:

\begin{writethis}
\begin{verbatim}
  foo() {
  }
\end{verbatim}
\end{writethis}

The newlines are removed.

How to copy verbatim code with \immediate\write?

Best Answer

I wouldn't reinvent the wheel. ;-)

\documentclass{article}

\usepackage{fancyvrb}

\begin{document}

\begin{VerbatimOut}{\jobname-later.tex}
\begin{verbatim}
  foo() {
  }
\end{verbatim}
\end{VerbatimOut}

Something

\input{\jobname-later}

\end{document}

One can use the infrastructure of fancyvrb to define VerbatimOutAppend so that the file is closed only when we want to.

\documentclass{article}

\usepackage{fancyvrb}

\makeatletter
\newcommand{\OpenVerbatimOutAppend}[2]{%
  \expandafter\newwrite\csname martin@write@#1\endcsname
  \immediate\openout\csname martin@write@#1\endcsname=#2\relax
}
\newcommand{\CloseVerbatimOutAppend}[1]{%
  \immediate\closeout\csname martin@write@#1\endcsname
}
\def\VerbatimOutAppend{\FV@Environment{}{VerbatimOutAppend}}
\def\FVB@VerbatimOutAppend#1{%
  \@bsphack
  \begingroup
    \FV@UseKeyValues
    \FV@DefineWhiteSpace
    \def\FV@Space{\space}%
    \FV@DefineTabOut
    \expandafter\let\expandafter\FV@OutFile\csname martin@write@#1\endcsname
    \def\FV@ProcessLine{\immediate\write\FV@OutFile}%
    \let\FV@FontScanPrep\relax
    \let\@noligs\relax
    \FV@Scan}
\def\FVE@VerbatimOutAppend{\endgroup\@esphack}
\DefineVerbatimEnvironment{VerbatimOutAppend}{VerbatimOutAppend}{}
\makeatother

\begin{document}

\OpenVerbatimOutAppend{default}{\jobname-later.tex}

\begin{VerbatimOutAppend}{default}
\begin{verbatim}
  foo() {
  }
\end{verbatim}
\end{VerbatimOutAppend}

Something

\begin{VerbatimOutAppend}{default}
\begin{verbatim}
  foo() {
  }
\end{verbatim}
\end{VerbatimOutAppend}

\CloseVerbatimOutAppend{default}

\input{\jobname-later}

\end{document}

Several output files can be active at the same time; to each we assign a symbolic name, in the example it is default. Here's the content of the output file:

\begin{verbatim}
  foo() {
  }
\end{verbatim}
\begin{verbatim}
  foo() {
  }
\end{verbatim}