When I try to write an input given by a user in a token list to a file, it turns # into ##, so if a users wants to write \def\hello#1{Hello #1!}, instead of writing:
\def\hello#1{Hello #1!}
as expected I get:
\def \hello ##1{Hello ##1!}
Any idea how to make it work? Ideally I'd like to avoid asking the user to change their input.
MWE
\documentclass{article}
\newtoks\mytokens
\newwrite\myWrite
\NewDocumentCommand{\writeInFile}{m}{%
\mytokens={#1}% We put the input in a token list (that token list might actually be populated by another script before)
\immediate\openout\myWrite myfile.tex\relax% We open the output file
\immediate\write\myWrite{\the\mytokens}% We write to the output file
\immediate\closeout\myWrite% We close the file
}
\begin{document}
%% I don't want to change the syntax in this part of the document:
\writeInFile{\def\hello#1{Hello #1!}}
\input{myfile.tex}
\hello{Alice}
\hello{Bob}
\end{document}
\scantokens/\tl_rescan? I'm surprised that it seems to handle properly&inalignwithout a need for\tl_rescanas you proposed here https://tex.stackexchange.com/a/619983/116348 – tobiasBora Mar 20 '23 at 14:16\scantokns/tl_rescanto also handle other characters (it might not make a difference for LaTeX documents, but it does in non-latex code) here, without success https://tex.stackexchange.com/questions/680240/put-in-a-latex3-string-the-exact-input-string-to-write-in-a-file – tobiasBora Mar 21 '23 at 09:05