Algorithm2e - 禁用特定行的行号

Algorithm2e - 禁用特定行的行号

Algorithm2e 包有特定的选项,可以禁用/隐藏整个文档或算法的行号,然后为特定行启用/显示行号。我想做相反的事情。我的意思是,为整个文档启用行号,然后为特定行禁用行号。(A类似主题的问题已经被问过了,但是针对的是不同的目标。

为了进一步说明,我需要手动换行和适当的缩进。因此,我找到了@Werner 的回答非常好这里。但问题是,手动创建的行会被编号,这对我来说是不可取的。下面是直接从 Werner 的回答中摘录的示例,启用了行号:

\documentclass{article}
\usepackage[linesnumbered]{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}

带编号的换行

如您所见,第 7 行是换行的行,但它被编号了。我想要的是这一行不被编号,而下一行(第 8 行)被编号为 7。

答案1

当你加载时algorithm2e使用linesnumbered,它会\nl在每个段落分隔符处执行(取自algorithm2e.sty):

%
% line numbering
%
\newcommand{\LinesNumbered}{%
  \setboolean{algocf@linesnumbered}{true}%
  \renewcommand{\algocf@linesnumbered}{\everypar={\nl}}}%

所以,\nl这是我们感兴趣调整的事情。

您可以使用以下命令删除单行的行号\nonl

\let\oldnl\nl% Store \nl in \oldnl
\newcommand{\nonl}{\renewcommand{\nl}{\let\nl\oldnl}}% Remove line number for one line

这是一个显示输出的最小示例:

在此处输入图片描述

\documentclass{article}
\usepackage[linesnumbered]{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
\let\oldnl\nl% Store \nl in \oldnl
\newcommand{\nonl}{\renewcommand{\nl}{\let\nl\oldnl}}% Remove line number for one line
\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\nonl 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}

\nonl重新定义\nl一种用法。这种用法只是重新定义自身以使用原始形式(在狡猾的 (La)TeX 技巧)。

相关内容