我正在尝试将包含标记的行写入外部文件,然后在另一个文档中再次读取它们。我面临两个问题:
(1)当我使用标记调用我的 \filewrite 命令时,有没有办法解决丑陋的 \unexpanded{} ?
(2)我的 \parsefile{} 命令中的循环只读取外部文件的第一行——因此循环本身一定有问题,但我无法弄清楚。
环境:在 Windows 上更新了 MikTeX
问候,维克
测试_写入.tex
\documentclass{article}
\usepackage{textcomp}
\newwrite\mywrite
\immediate\openout\mywrite=file.tex
\immediate\write\mywrite{Headline}
\newcommand{\filewrite}[1]{
\immediate\write\mywrite{#1}
}
\begin{document}
Hello World!
\filewrite{11 & 12}
\filewrite{\unexpanded{21 & 22\textdegree}}
\filewrite{31 & 32}
\immediate\closeout\mywrite
\end{document}
测试读取.tex
\documentclass{article}
\usepackage{textcomp}
\newwrite\myread
\immediate\openin\myread=file.tex
\newcommand{\fileparse}{
\loop
\unless\ifeof\myread
\immediate\read\myread to \fline
\fline\\
\repeat
}
\begin{document}
\immediate\read\myread to \fheader
\textbf{\fheader}\vspace{1cm}
\begin{tabular}{cc}
Col1 & Col2\\
\fileparse
\end{tabular}
\immediate\closein\myread
\end{document}
答案1
您不能在表格单元格中开始循环并在另一个单元格中结束循环。相反,您可以将所有行加载到标记变量中,并在循环结束时立即传递它。“丑陋”\unexpanded
可以放在 的定义中\filewrite
。
\documentclass{article}
\usepackage{textcomp}
\newwrite\mywrite
\newread\myread
\newcommand{\filewrite}[1]{%
\immediate\write\mywrite{\unexpanded{#1}}%
}
\newcommand{\fileparse}{%
\toks0={}%
\loop
\unless\ifeof\myread
\immediate\read\myread to \fline
\toks0=\expandafter{\the\toks\expandafter0\expandafter\space\fline\\}%
\repeat
\the\toks0
}
\begin{document}
\immediate\openout\mywrite=\jobname-out.tex
\immediate\write\mywrite{Headline}
Hello World!
\filewrite{11 & 12}
\filewrite{21 & 22\textdegree}
\filewrite{31 & 32}
\immediate\closeout\mywrite
\openin\myread=\jobname-out.tex
\read\myread to \fheader
\textbf{\fheader}\vspace{1cm}
\begin{tabular}{cc}
Col1 & Col2\\
\fileparse
\end{tabular}
\closein\myread
\end{document}
顺便说一句,\immediate
对于读取流不执行任何操作。
答案2
LaTeX 内核具有可扩展的循环(特别是不会进行范围受表格单元格限制的分配),但它们并不用于一般用途。
一行代码就可以将它们公开。(实际上它们的定义也几乎是一行代码)。还有其他选择,但为什么不使用可用的东西呢。我选择了一个包装器,否则语法可能看起来不熟悉。
\documentclass{article}
\usepackage{textcomp}
\newwrite\mywrite
\newread\myread
\newcommand{\filewrite}[1]{%
\immediate\write\mywrite{\unexpanded{#1}}%
}
\newcommand*\Unless {}% check it does not exist
\makeatletter
\long\def\Unless #1\repeat{\unless#1\@iwhilesw{\unless#1}\fi\fi}
\makeatother
% related:
% \long\def\SoLongAs #1\repeat{#1\@iwhilesw{#1}\fi\fi}
\newcommand{\fileparse}{%
\Unless\ifeof\myread
\read\myread to \fline
\fline\\%
\repeat
}
\begin{document}
\immediate\openout\mywrite=\jobname-out.tex
\immediate\write\mywrite{Headline}
Hello World!
\filewrite{11 & 12}
\filewrite{21 & 22\textdegree}
\filewrite{31 & 32}
\immediate\closeout\mywrite
\openin\myread=\jobname-out.tex
\read\myread to \fheader
\textbf{\fheader}\vspace{1cm}
\begin{tabular}{cc}
Col1 & Col2\\
\fileparse
\end{tabular}
\closein\myread
\end{document}