当我尝试将用户在标记列表中给出的输入写入文件时,它会变成#
,##
因此如果用户想要写入\def\hello#1{Hello #1!}
,而不是写入:
\def\hello#1{Hello #1!}
正如预期的那样我得到:
\def \hello ##1{Hello ##1!}
知道如何让它工作吗?理想情况下,我想避免要求用户更改他们的输入。
平均能量损失
\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}
答案1
这里我定义带有两个参数的命令,第一个是文件名。
#
您想更改阅读之前的类别代码。
\documentclass{article}
\newwrite\myWrite
\newtoks\mytokens
\newcommand{\writeInFile}{%
\begingroup\catcode`\#=12 \writeInFileAux
}
\newcommand{\writeInFileAux}[2]{% #1 = file name, #2 = what to write
\immediate\openout\myWrite #1\relax% We open the output file
\mytokens={#2}%
\immediate\write\myWrite{\the\mytokens}% We write to the output file
\immediate\closeout\myWrite% We close the file
\endgroup
}
\begin{document}
%% I don't want to change the syntax in this part of the document:
\writeInFile{\jobname-out}{\def\hello#1{Hello #1!}}
\input{\jobname-out}
\hello{Alice}
\hello{Bob}
\end{document}
这将是写出的文件
\def \hello #1{Hello #1!}
当然,您不能将其\writeInFile
作为另一个命令的参数。
您可以通过字符串替换来消除此限制。
\documentclass{article}
\ExplSyntaxOn
\iow_new:N \g_bora_write_iow
\str_new:N \l_bora_write_str
\NewDocumentCommand{\writeInFile}{mm}
{
% #1 = file name, #2 = what to write
\str_set:Nn \l_bora_write_str { #2 }
\str_replace_all:NnV \l_bora_write_str { ## } \c_hash_str
\iow_open:Nn \g_bora_write_iow { #1 }
\iow_now:NV \g_bora_write_iow \l_bora_write_str
\iow_close:N \g_bora_write_iow
}
\cs_generate_variant:Nn \iow_now:Nn { NV }
\cs_generate_variant:Nn \str_replace_all:Nnn { NnV }
\ExplSyntaxOff
\begin{document}
%% I don't want to change the syntax in this part of the document:
\textit{xx \writeInFile{\jobname-out}{\def\hello#1{Hello #1!}}}
\input{\jobname-out}
\hello{Alice}
\hello{Bob}
\end{document}
该\textit
位仅用于演示目的。