3

I have some alignment problems in the algorithmic environment when I use the hyperref package. I like to have my comments left-aligned which I achieve by \renewcommand{\algorithmiccomment}[1]{\hfill(#1)} in the preamble.

It turns out that comments on lines before \ENDFOR or anline break (which I use to identify different blocks of code) are a bit misaligned.

Here is a MWE:

enter image description here

\documentclass{article}

\usepackage{algorithmic}
\renewcommand{\algorithmiccomment}[1]{\hfill(#1)}

\usepackage{hyperref}

\begin{document}

\begin{algorithmic}
\STATE foo
  \COMMENT{bar}
\FOR{foo}
  \STATE foo
    \COMMENT{bar}
  \STATE foo
    \COMMENT{bar}
\ENDFOR
\STATE foo
  \COMMENT{bar}
\STATE foo
  \COMMENT{bar} \\[0.5em]
\STATE foo
  \COMMENT{bar}
\RETURN foo
  \COMMENT{bar}
\end{algorithmic}

\end{document}

Please comment \usepackage{hyperref} to have the desired output:

enter image description here

My guess is some weird interaction between \end{list} which is used by algorithmic and hyperref, but I'm kind of stuck now. Do you have any suggestion?

Werner
  • 603,163

2 Answers2

3

For your comment, use

\renewcommand{\algorithmiccomment}[1]{\hfill(#1)\ignorespaces}

which gobbles any spaces after \COMMENT, effectively being the same as inserting % after each one. See What is the use of percent signs (%) at the end of lines?

Werner
  • 603,163
2

A work around is to comment out the end of line characters after the \COMMENT commands:

Sample output

\documentclass{article}

\usepackage{algorithmic}
\renewcommand{\algorithmiccomment}[1]{\hfill(#1)}

\usepackage{hyperref}

\begin{document}

\begin{algorithmic}
\STATE foo
  \COMMENT{bar}%
\FOR{foo}
  \STATE foo
    \COMMENT{bar}%
  \STATE foo
    \COMMENT{bar}%
\ENDFOR
\STATE foo
  \COMMENT{bar}%
\STATE foo
  \COMMENT{bar}\\[0.5em]
\STATE foo
  \COMMENT{bar}%
\RETURN foo
  \COMMENT{bar}
\end{algorithmic}

\end{document}

Exactly what in hyperref is causing an extra an extra box here is not clear to me. algothrimc does some quite heaving modification of \item commands in the custom list environment, which could be a source of the bad interaction.

Andrew Swann
  • 95,762