我使用 listings latex 包将环境主体写入/读取到文件中。但是,如果环境中某些单词之间有两个空格,则会在开头添加一个额外的换行符(我将其设为红色,以便在本例中看得更清楚)。我该如何防止这种情况发生?
\documentclass{article}
\usepackage{listings}
\usepackage{color}
\makeatletter
\lst@RequireAspects{writefile}
\lstnewenvironment{testenv}{%
\lstset{aboveskip=0pt,belowskip=0pt,backgroundcolor=\color{red}}%
\lst@BeginWriteFile{\jobname.tst}%
}{%
\lst@EndWriteFile% closes output file
% do something
\input{\jobname.tst}
% do something
}%
\makeatother
\begin{document}
Something wrong begins.
\begin{testenv}
This is a text with two spaces between some words.
\end{testenv}
And it ends.
\begin{testenv}
This is a text with only one space between all words.
\end{testenv}
\end{document}
输出:
答案1
这似乎是 中的某种形式的错误listings
。我现在实际上记得我在使用捆绑包listings
中的 WriteFile 功能时遇到了同样的问题ydoc
。我的解决方法是将其排版输出捕获在一个框内,然后该框永远不会排版。例如,可以使用\begin{lrbox}{0} .. \end{lrbox}
临时框 #0 或 来完成此操作\@tempboxa
,或者使用\setbox
等。
\documentclass{article}
\usepackage{listings}
\usepackage{color}
\makeatletter
\lst@RequireAspects{writefile}
\lstnewenvironment{testenv}{%
\lstset{aboveskip=0pt,belowskip=0pt,backgroundcolor=\color{red}}%
\setbox\@tempboxa\hbox\bgroup
\lst@BeginWriteFile{\jobname.tst}%
}{%
\lst@EndWriteFile% closes output file
\egroup
% do something
\input{\jobname.tst}%
% do something
}%
\makeatother
\begin{document}
11111111111111111111111
\begin{testenv}
text text text text text text text text text text text text text text text text
\end{testenv}
22222222222222222222222
11111111111111111111111
\begin{testenv}
text text text text text text text text text text text text text text text text
\end{testenv}
22222222222222222222222
\end{document}