[Tex/LaTex] Align comments in algorithm with package algorithm2e

algorithm2ecommentshorizontal alignment

I am using the package algorithm2e.
When using comments like this

\documentclass[11pt,a4paper,twoside,openright]{book}
\usepackage[algochapter,linesnumbered,ruled,lined,boxed]{algorithm2e}
\begin{document}
\begin{algorithm}
    \tcp{not aligned comment}
    \If(\tcp*[h]{comment next to if}){constraint}{ 
         c  \tcp*[l]{bla}
         $d = \min \{c,e\}$ \tcp*[l]{minimum}
    }      

\end{algorithm}
\end{document}

the result is

// not aligned comment
if constraint then // comment next to if 
   c; // bla
   d = min{c,e}; // minimum
end

I would like to have the comments aligned, that is

// not aligned comment
if constraint then       // comment next to if
   c;                    // bla
   d = min{c,e};         // minimum
end

I only found an answer for the package algorithmicx: Algpseudocode (algorithmicx) package comments.

Best Answer

This flushes them right, padded to the longest comment, so the // line up. It takes a couple of runs to get the measuring. I added some $ to avoid errors that were generated when I tried your MWE.

enter image description here

\documentclass{article}
\usepackage{algorithm2e}

\makeatletter
\newdimen\commentwd
\let\oldtcp\tcp
\def\tcp*[#1]#2{% only support one style for simplicity
\setbox0\hbox{#2}%
\ifdim\wd\z@>\commentwd\global\commentwd\wd\z@\fi
\oldtcp*[r]{\leavevmode\hbox to \commentwd{\box0\hfill}}}

\let\oldalgorithm\algorithm
\def\algorithm{\oldalgorithm
\global\commentwd\z@
\expandafter\ifx\csname commentwd@\romannumeral\csname c@\algocf@float\endcsname\endcsname\relax\else
\global\commentwd\csname commentwd@\romannumeral\csname c@\algocf@float\endcsname\endcsname
\fi
}
\let\oldendalgorithm\endalgorithm
\def\endalgorithm{\oldendalgorithm
\immediate\write\@auxout{\gdef\expandafter\string\csname commentwd@\romannumeral\csname c@\algocf@float\endcsname\endcsname{%
\the\commentwd}}}

\begin{document}
\begin{algorithm}
    c  \tcp*[l]{bla}
    $d = \min \{c,e\}$ \tcp*[l]{minimum}
\end{algorithm}
\end{document}