I'd like to output LaTeX code to a file, with the caveat that all backslashes are doubled (ie, \
is replaced with \\
). This output will be consumed by another program.
I've adapted egreg's answer from Removing a backslash from a character sequence. It works when the resulting string is typeset, but I've been unable to write it to a file.
Here's a MWE with my attempts:
\documentclass{article}
\usepackage{xstring, etextools}
\begin{document}
%% Doubles all backslashes in the input argument
%% Adapted from: https://tex.stackexchange.com/a/42337/90126 (egreg)
\begingroup\lccode`\|=`\\
\lowercase{\endgroup\def\DoubleBackslashes#1{\StrSubstitute{#1}{|}{||}}}
\def\TestContents{Here are my contents: \UndefinedMacro and \\}
%% Prepare the output file
\newwrite\testfile
\immediate\openout\testfile=\jobname.TESTFILE
%% (1) This produces the expected output:
{\tt \DoubleBackslashes{\detokenize\expandafter{\TestContents}}}
%% (2) However, this doesn't:
%\immediate\write\testfile{\DoubleBackslashes{\detokenize\expandafter{\TestContents}}}
%% (3) We are able to write the un-doubled macro (as expected):
\immediate\write\testfile{\unexpanded\expandafter{\TestContents}}
%% (4) Using a intermediate macro doesn't work:
%\edef\TestContentsProtected{\expandnext\DoubleBackslashes{\detokenize\expandafter{\TestContents}}}
%\immediate\write\testfile{\unexpanded\expandafter{\TestContentsProtected}}
\immediate\closeout\testfile
\end{document}
- What am I missing here?
- How can this be fixed?