1

How can I have the regular behaviour of some paragraphs placed together, without changing line number in the algorithm after one paragraph ends?

I want that line number changes only after a \; appears and having the paragraphs indented as usual.

The contents of \If, \For, \While, must follow the same rule: only numerate a line after \;.

So, next MWE would have six numbered lines (assuming that lines of the start and end of block are numbered): two lines for the start and end of \While block, two lines for its contents and two lines for the next paragraphs.

\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 Answers1

1

You can set the content inside its own block (like a fixed-width \parbox that is anchored at the [t]op):

enter image description here

\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}


Another, automated way of handling this is to change \nl so that it only prints a numbered line once and then deactivates itself. Additionally, let \; temporarily reactivate \nl before shutting it down again. The redefinition of these macros are done using a hook into the \begin part of the algorithm environment.

enter image description here

\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}

I'm not sure whether this may break other components of the algorithm structure.

Werner
  • 603,163