如何保留由 newwrite 命令创建的新 latex 文件中的所有注释?

如何保留由 newwrite 命令创建的新 latex 文件中的所有注释?
\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

相关内容