# How to automatically protect all the commands passed in an argument?

I need to write to an auxfile some mathematical formulas.

The following MWE does not work:

\documentclass{article}
\usepackage{amsmath}
\newwrite\filehandle

\begin{document}

\immediate\openout\filehandle=\jobname.test
\addToFile{$\sum_{k=1}^n k$}
\immediate\closeout\filehandle

\input{\jobname.test}

\end{document}


Is there a way to automatically protect all the commands used in the argument #1 of \addToFile?

I won't be the user of this file: that's why I am looking for an automatic solution.

PS: The problem here comes from the package amsmath.

• \unexpanded{ whatever ...} Jul 17 at 12:19
• Can you make it an answer so I can accept it? Thanks. Otherwise, I'll do it. Jul 23 at 20:47

you can surround the argument with \unexpanded{....}

With expl3 no expansion is done unless explicitly requested with \iow_now:Nx; using \iow_now:Nn will do nothing to the input.

\documentclass{article}

\ExplSyntaxOn

\iow_new:N \g_colas_filehandle_iow

\NewDocumentCommand{\openFile}{m}
{
\iow_open:Nn \g_colas_filehandle_iow { #1 }
}
\NewDocumentCommand{\closeFile}{}
{
\iow_close:N \g_colas_filehandle_iow
}

{
\iow_now:Nn \g_colas_filehandle_iow { #1 }
}

\ExplSyntaxOff

\begin{document}

\openFile{\jobname.test}
\addToFile{$\sum_{k=1}^n k$}
\closeFile

\input{\jobname.test}

\end{document}



The contents of the \jobname.test file will be

$\sum _{k=1}^n k$