我想知道是否有办法自动替换
\AAA (...) \BBB
其中\CCC
,(...)
代表由空格和 组成的序列\par
,例如\par \par\par
。
(我正在寻找使用 LaTeX 的解决方案,而不是使用编辑器的正则表达式替换功能)
下面是一个可以玩的示例。
\documentclass{article}
\def\AAA{A}
\def\BBB{B}
\def\CCC{C}
\begin{document}
% C
\AAA\BBB
% C
\AAA \BBB
% C
\AAA \par \BBB
% C
\AAA
\BBB
% C
\AAA \par \par\par \BBB
\end{document}
答案1
回答所问的问题,您可以定义\AAA
提前扫描\BBB
并替换为\CCC
\documentclass{article}
\def\AAA{A}
\def\BBB{B}
\def\CCC{C}
\long\def\AAA#1\BBB{\CCC}
\begin{document}
% C
\AAA\BBB
% C
\AAA \BBB
% C
\AAA \par \BBB
% C
\AAA
\BBB
% C
\AAA \par \par\par \BBB
\end{document}
或者,如果您想检查是否只有\par
空格,请更慢地执行:
\documentclass{article}
\def\AAA{A}
\def\BBB{B}
\def\CCC{C}
\makeatletter
\let\oldAAA\AAA
\def\AAA{\@ifnextchar\BBB
{\CCC\@gobble}{\@ifnextchar\par{\expandafter\AAA\@gobble}\oldAAA}}
\begin{document}
% C
\AAA\BBB
% C
\AAA \BBB
% C
\AAA \par \BBB
% C
\AAA
\BBB
% C
\AAA \par \par\par \BBB
%A1B
\AAA 1\BBB
\end{document}
答案2
您可以使用\peek_regex_remove_once:nTF
\documentclass{article}
\ExplSyntaxOn
\NewDocumentCommand{\AAA}{}
{
\peek_regex_remove_once:nTF { (\s|\c{par})*? \c{BBB} } { \CCC } { A }
}
\ExplSyntaxOff
\newcommand{\BBB}{B}
\newcommand{\CCC}{C}
\begin{document}
% A
\AAA xxx
% C
\AAA\BBB
% C
\expandafter\AAA\space \BBB
% C
\AAA \par \BBB
% C
\AAA
\BBB
% C
\AAA \par \par\par \BBB
\end{document}
宏将向前扫描,直到找到与正则表达式不匹配的内容,即任意数量的空格和\par
标记后跟\BBB
。如果找到匹配项,它将输出\CCC
,忽略与正则表达式匹配的标记;否则A
后面跟有标记,就像没有扫描任何内容一样。
答案3
创建了一个可以执行该任务的tokcycle
环境\nospace...\endnospace
。注意事项:它不会筛选出行尾宏空格\
,并且它将筛选出theorem
环境之后的空格和语法\begin
,无论下一个\begin
是 a{theorem}
还是任何其他环境。
如果在下一个 之前出现除、
\par
和之外的任何其他字符,则所有收集到的标记都会与取消资格的标记一起转储到流中。\
\begin
\documentclass{article}
\usepackage{tokcycle}
\newenvironment{theorem}{Theo\ignorespaces}{rem}
\def\comparitor{theorem}
\newif\ifeligible
\newtoks\stuff
\def\dumpit{\eligiblefalse\addcytoks[1]{\the\stuff}\stuff{}}
\def\clearit{\eligiblefalse\stuff{}}
\long\def\addstuff#1{\stuff\expandafter{\the\stuff#1}}
\tokcycleenvironment\nospace
{\dumpit\addcytoks{##1}}
{\def\tmp{##1}\ifx\tmp\comparitor\global\eligibletrue\fi\addcytoks{##1}}
{\tctestifcon{\ifeligible}%
{\tctestifx{\par##1}%
{\addstuff{##1}}%
{\tctestifx{\ ##1}%
{\addstuff{##1}}%
{\tctestifx{\begin##1}%
{\clearit}%
{\dumpit}%
\addcytoks{##1}%
}%
}%
}
{\addcytoks{##1}}%
}
{\ifeligible\addstuff{##1}\else\addcytoks{##1}\fi}
\begin{document}
\nospace
\begin{theorem}
\end{theorem}
\begin{theorem}
\end{theorem}
\par\ \ \par
\begin{theorem}
\end{theorem} \begin{theorem}
\end{theorem} \begin{theorem}
\end{theorem}
abc
\begin{theorem}
\end{theorem}
abc\begin{theorem}
\end{theorem}
Failure mode: line-ending explicit spaces
\begin{theorem}
\end{theorem}\ \ \
\begin{theorem}
\end{theorem}
\endnospace
\end{document}