如何保留newwrite指令所建立的新乳膠檔案中的所有註解?

如何保留newwrite指令所建立的新乳膠檔案中的所有註解?
\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}

以上程式碼製作Theorem.tex文件。但所有評論(這是評論 1,這是評論 2)都消失了。如何保留所有評論%this is comment 1, %this is comment 2

答案1

\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}

製作%catcode 12 將失去其註解狀態(您可能還想保留換行符?)

以上使得

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}

產生

hello %this is comment 1
%this is comment 2

答案2

一個更複雜的範例,允許所有特殊字元。這適用於 Plain LuaTeX 和 LuaLaTeX,經過一些更改,它也適用於其他引擎。實作與filecontentsLaTeX核心的環境類似。

\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

相關內容