如何才能将一些段落的常规行为放在一起,而不在一个段落结束后改变算法中的行号?
我希望仅在出现后行号才会改变\;
,并且段落会像往常一样缩进。
\If
、、、\For
的内容\While
必须遵循相同规则:只在 之后编号一行\;
。
因此,下一个 MWE 将有六行编号(假设块的开始和结束的行都已编号):两行用于\While
块的开始和结束,两行用于其内容,两行用于下一段。
\documentclass[oneside]{memoir}
\usepackage[linesnumbered]{algorithm2e}
\DontPrintSemicolon
\begin{document}
\begin{algorithm}[H]
\While{$i < n$}{
First line numbered...
First line continues in new paragraph...
first line ends.\;
Second line.\;
}
First line numbered...
First line continues in new paragraph...
first line ends.\;
Second line starts...
Second line continues in new paragraph...
second line ends.\;
\end{algorithm}
\end{document}
答案1
您可以将内容设置在自己的块内(例如固定宽度\parbox
的锚定在[t]
上文中):
\documentclass{article}
\usepackage[linesnumbered]{algorithm2e}
\DontPrintSemicolon
\begin{document}
\begin{algorithm}[H]
First line numbered\ldots
First line continues in new paragraph\ldots
first line ends.\;
Second line starts\ldots
Second line continues in new paragraph\ldots
second line ends.\;
\end{algorithm}
\begin{algorithm}[H]
\parbox[t]{\dimexpr\algowidth-2\algomargin}{First line numbered\ldots
First line continues in new paragraph\ldots
first line ends.}\;
\vspace{-\baselineskip}
\parbox[t]{\dimexpr\algowidth-2\algomargin}{Second line starts\ldots
Second line continues in new paragraph\ldots
second line ends.}\;
\vspace{-\baselineskip}
\end{algorithm}
\end{document}
处理此问题的另一种自动化方法是进行更改\nl
,使其仅打印一次n
编号l
的行,然后自行停用。此外,让它\;
暂时重新激活,然后再将其关闭。这些宏的重新定义是使用钩子插入铁件的一部分\nl
来完成的。\begin
algorithm
env
\documentclass{article}
\usepackage[linesnumbered]{algorithm2e}
\DontPrintSemicolon
\makeatletter
\AddToHook{env/algorithm/begin}{%
% At the start of algorithm, make \nl only print something once
\let\oldnl\nl
\def\nl{\oldnl\let\nl\relax}
\let\old@endalgoln\@endalgoln
% Update \; (or \@endalgoln) to do the same thing
\renewcommand{\@endalgoln}{%
\def\nl{\oldnl\let\nl\relax}%
\old@endalgoln
}
}
\makeatother
\begin{document}
\begin{algorithm}[H]
First line numbered\ldots
First line continues in new paragraph\ldots
first line ends.\;
Second line starts\ldots
Second line continues in new paragraph\ldots
second line ends.\;
\end{algorithm}
\end{document}
我不确定这是否会破坏算法结构的其他组件。