
\documentclass[12pt,a4paper,oneside]{book}
\begin{document}
\newwrite\copyfile
\immediate\openout\copyfile=Theorem.tex
\immediate\write\copyfile{hello %this is comment 1
%this is comment 2
}
\immediate\closeout\copyfile
\end{document}
Der obige Code erstellt Theorem.tex
eine Datei. Aber alle Kommentare (das ist Kommentar 1, das ist Kommentar 2) verschwinden. Wie behält man alle Kommentare %this is comment 1, %this is comment 2
?
Antwort1
\documentclass[12pt,a4paper,oneside]{book}
\begin{document}
\newwrite\copyfile
\immediate\openout\copyfile=Theorem.tex
{\catcode`\%=12
\immediate\write\copyfile{hello %this is comment 1
%this is comment 2
}
}
\immediate\closeout\copyfile
\end{document}
Wenn Sie den Catcode 12 verwenden %
, geht sein Kommentarstatus verloren (vielleicht möchten Sie auch Zeilenumbrüche beibehalten?)
Das Obige macht
hello %this is comment 1 %this is comment 2
\documentclass[12pt,a4paper,oneside]{book}
\begin{document}
\newwrite\copyfile
\immediate\openout\copyfile=Theorem.tex
{\catcode`\%=12
\endlinechar=`\^^J%
\immediate\write\copyfile{hello %this is comment 1
%this is comment 2
}%
}%
\immediate\closeout\copyfile
\end{document}
produziert
hello %this is comment 1
%this is comment 2
Antwort2
Ein komplizierteres Beispiel, das alle Sonderzeichen zulässt. Dies funktioniert mit Plain LuaTeX und LuaLaTeX, mit einigen Änderungen auch mit anderen Engines. Die Implementierung ähnelt der filecontents
Umgebung des LaTeX-Kernels.
\catcode`@=11
\newwrite\file
\immediate\openout\file=xxx.zzz\relax
\newif\if@firstline
\def\@makeother#1{\catcode`#112\relax}
\begingroup
\obeylines%
\gdef\verbatimwrite#1#2{%
\begingroup%
\let\do\@makeother \dospecials%
\expandafter\edef\expandafter\E\expandafter{%
\expandafter\csstring\expandafter\\\expandafter%
\scantextokens\expandafter{\csstring#2}}%
\edef\reserved@b{\def\noexpand\reserved@b####1\E####2\E####3\relax}%
\reserved@b{%
\ifx\relax##3\relax%
\if@firstline%
\wlog{Wrong input `##1' discarded.}%
\@firstlinefalse%
\else\immediate\write#1{##1}%
\fi%
\else%
\let^^M\endgroup%
\if@firstline%
\errhelp{The verbatim writing command must not end on the same line.}%
\errmessage{Writing nothing}%
\else%
\ifx\relax##1\relax%
\else%
\wlog{Writing text `##1' before%
\E\space as last line.}%
\immediate\write#1{##1}%
\fi%
\ifx\relax##2\relax%
\else%
\wlog{Ignoring text `##2' after \E.}%
\fi%
\fi%
\fi%
^^M}%
\@firstlinetrue%
\obeylines%
\edef^^M##1^^M{\noexpand\reserved@b##1\E\E\relax}%
^^M}%
\endgroup
Let's test:
\verbatimwrite\file\endverbatimwrite This is deleted!
%12