我正在使用算法2e伪代码包。我有一些很长的行需要换行。有没有办法缩进以下(断行)行和/或在第一行做个标记来表示发生了换行(类似于listings 包解决方案)
我找到了类似的问题对于 listings 包,这个问题之前已经回答过了,但我正在明确寻找一个算法2e解决方案。
答案1
以下最小示例定义
\nosemic
:删除行尾(EOL)字符的打印(通常为;
);\dosemic
:恢复打印 EOL 字符;\pushline
:缩进行1em
(典型缩进);由algorithm2e
提供\Indp
;\popline
\pushline
:删除(undent?)的缩进;由algorithm2e
as提供\Indm
\documentclass{article}
\usepackage{algorithm2e}% http://ctan.org/pkg/algorithm2e
\makeatletter
\newcommand{\nosemic}{\renewcommand{\@endalgocfline}{\relax}}% Drop semi-colon ;
\newcommand{\dosemic}{\renewcommand{\@endalgocfline}{\algocf@endline}}% Reinstate semi-colon ;
\newcommand{\pushline}{\Indp}% Indent
\newcommand{\popline}{\Indm\dosemic}% Undent
\makeatother
\begin{document}
\begin{algorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\While{not at end of this document}{
read current\;
\eIf{understand}{
go to next section\;
\nosemic this is a very long statement that has to be\;
\pushline\dosemic wrapped over two lines\;
\popline current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\caption{How to write algorithms}
\end{algorithm}
\end{document}
由于我不熟悉你的algorithm2e
设置,我不确定您想如何组合这四个命令。因此,我将它们分开,以便最大限度地(但手动)使用。
答案2
事实上,有一个更简单的解决方案:使用经典的\hangafter
和\hangindent
。这适用于algorithm2e
。
笔记:
\skiptext
是新块算法中文本缩进的长度;因此我选择这个缩进的 1/2;无需重新定义内部宏,因为
\algocf@endline
几乎所有的都可以重新定义algorithm2e
。用于\SetEndCharOfAlgoLine
重新定义行尾
\hangafter
请参阅下面的使用and的示例\hangindent
:
\documentclass{article}
\usepackage{algorithm2e}% http://ctan.org/pkg/algorithm2e
%
\newcommand{\nosemic}{\SetEndCharOfAlgoLine{\relax}}% Drop semi-colon ;
\newcommand{\dosemic}{\SetEndCharOfAlgoLine{\string;}}% Reinstate
\newcommand{\pushline}{\Indp}% Indent
\newcommand{\popline}{\Indm\dosemic}% Undent
%
\begin{document}
\begin{algorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\While{not at end of this document}{
read current\;
\eIf{understand}{
go to next section\;
\nosemic this is a very long statement that has to be\;
\pushline\dosemic wrapped over two lines\;
\popline current section becomes this one\;
\hangindent=.5\skiptext\hangafter=1
this is a very long statement that should be indented automatically on the next
lines if this statement is longer than one line\;
Following lines should be indented normally\;
}{
go back to the beginning of current section\;
}
}
\caption{How to write algorithms}
\end{algorithm}
\end{document}
答案3
\Indp
并且\Indm
可以在包中用于algorithm2e
缩进和删除缩进。我已经测试过了。