I'm defining a wrapper environment for filecontents
so that I can modify its behaviour.
Everything works fine for most of the test cases. For example, I define an environment testenv
which takes one mandatory argument and writes its value to the console:
\newenvironment{testenv}[1]{%
\typeout{Argument = #1}%
\filec@ntents{\jobname.pfc}%
}{}
so when I call
\begin{testenv}{hello}
hi
\end{testenv}
LaTeX prints Argument = hello
to the console and writes a file called \jobname.pfc
which contains
hi
This works for environments without arguments, and with mandatory arguments. For environments with optional arguments it works as long as the optional argument is present, otherwise it fails.
The code below illustrates all the cases. The last one will throw a Missing \begin{document}
error:
\documentclass{book}
\usepackage{filecontents}
\makeatletter
\newenvironment{testenv}{%
\filec@ntents{\jobname.pfc}%
}{}
% The environment works without arguments
\begin{testenv}
hi
\end{testenv}
\renewenvironment{testenv}[1]{%
\typeout{Argument = #1}%
\filec@ntents{\jobname.pfc}%
}{}
% and with mandatory arguments
\begin{testenv}{hello}
hi
\end{testenv}
\renewenvironment{testenv}[1][abcde]{%
\typeout{Argument = #1}%
\filec@ntents{\jobname.pfc}%
}{}
% and it works with optional arguments
% only if the argument is given
\begin{testenv}[hello]
hi
\end{testenv}
% otherwise it fails :/
\begin{testenv}
hi
\end{testenv}
\begin{document}
\end{document}
The actual use of the argument is for some text to be typeset after the contents of the environment, so the catcode will not be of much importance.