4

In package algorithm2e you can have side comments aligned in four different ways, depending on the option used (see Section 11.4 of the package's manual).

In the following mwe, there are two copies of the same 3-line "algorithm". The comments in the first algorithm are aligned with the [r] option, which right-justifies the comments and changes the line. In the second algorithm, the comments are aligned with the [f] option, which is supposed to right-justify the side-comments without changing the line (which is why the \; is necessary in this case).

\documentclass{book}
\usepackage{algorithm2e}

\SetKwComment{commentSt}{! }{}

\begin{document}

% this is right
\begin{algorithm}
  \KwSty{Keywords} and words\commentSt*[r]{first comment}
  \KwSty{More keywords} other words\commentSt*[r]{second comment}
  Words first \KwSty{keywords later}\commentSt*[r]{third}
\end{algorithm}

% this doesn't look right
\begin{algorithm}
  \KwSty{Keywords} and words\commentSt*[f]{first comment}\;
  \KwSty{More keywords} other words\commentSt*[f]{second comment}\;
  Words first \KwSty{keywords later}\commentSt*[f]{third}
\end{algorithm}
\end{document}

This is what the output looks like, which doesn't look right to me: Misaligned comments in the second algorithm

Is this some sort of bug? I actually stumbled upon this while revisiting older LaTeX code which used to work correctly... Could this be a regression? I am now compiling this with XeLaTeX.

0

h- and f-comments are not supposed to be used on normal lines. They do not finish the current line, and putting the end-line marker \; after them will leave two competing stretching glues in that line. The result is a comment that is centered on the remaining available space. So only use l- or r-comments on normal lines.

The purpose of h- and f-comments is to put comments on lines with block elements that already add a linebreak on their own. Compare the output of these two if-then-else statements with a comment put in an optional ()-argument:

\documentclass{article}
\usepackage{algorithm2e}

\SetKwComment{commentSt}{! }{}

\begin{document}
\begin{algorithm}
  \eIf(\commentSt*[r]{if comment}){cond}
    {true part}
    {false part}
\end{algorithm}

\begin{algorithm}
  \eIf(\commentSt*[f]{if comment}){cond}
    {true part}
    {false part}
\end{algorithm}
\end{document}

enter image description here

The first r-comment appears correctly flushed to the right, but an extra linebreak is inserted afterwards which leads to an unwanted empty line in the algorithm. The usage of an f-comment is correct here to prevent the extra linebreak.

The same applies to the flush left equivalents l and h.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.