To extract text from huge LaTeX-files in a safe and controllable manner, I am having LaTeX itself write to a textfile. To retain and adapt some formatting informations and structural elements I have given the file a new header where I redefine the commands for this special purpose. This works fine until I need commands with optional arguments.
Using newfile for convenience:
\documentclass{minimal}
\usepackage{newfile}
\newoutputstream{out}
\openoutputfile{out.text}{out}
\newcommand{\standardexample}[3]{#1:#2(#3)}
\newcommand{\optionalexample}[3][default]{#1:#2(#3)}
\begin{document}
text \standardexample{1}{2}{3} and \optionalexample[not default]{2}{3} or \optionalexample{2}{3}
\addtostream{out}{
text \standardexample{1}{2}{3} and \optionalexample[not default]{2}{3} or \optionalexample{2}{3}
}
\closeoutputstream{out}
\end{document}
I get
text 1:2(3) and not default:2(3) or default:2(3)
in the pdf as expected, but
text 1:2(3) and \optionalexample[not default]{2}{3} or \optionalexample{2}{3}
in the text-file with no errors in the log.
Testing without newfile, e.g.
\documentclass{minimal}
\newcommand{\standardexample}[3]{#1:#2(#3)}
\newcommand{\optionalexample}[3][default]{#1:#2(#3)}
\newwrite\tempfile
\begin{document}
\immediate\openout\tempfile=\jobname.tmp
\immediate\write\tempfile{text \standardexample{1}{2}{3} and \optionalexample[not default]{2}{3} or \optionalexample{2}{3}}
\immediate\closeout\tempfile
text \standardexample{1}{2}{3} and \optionalexample[not default]{2}{3} or \optionalexample{2}{3}
\end{document}
the typesetting is broken off by a couple of error messages (some of which are even included in the tmp-file), but I can't really make sense of them.
Both an expanation and a workaround would be great.
\protected@writeor the\immediatevariant defined in Writing\\to a file – egreg Jun 03 '15 at 21:02