[Tex/LaTex] Can not use float placement options with algorithm2e

algorithm2efloatspositioning

I am using algorihtm2e and I am formatting a new command to align comments in the algorithms like in the answer of Align comments in algorithm with package algorithm2e.
Now when I try to use positions options like this

\documentclass[11pt,a4paper,twoside,openright]{book}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[algochapter,linesnumbered,ruled,lined,boxed]{algorithm2e}
\usepackage{etoolbox}

\makeatletter
\newdimen\commentwd
\let\oldtcp\tcp
\def\mytcp*[#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{#2\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}[ht]
      bla
   \end{algorithm}
\end{document}

The result is that [ht] is written in the first line of the algorithm.
When I don't use that, it works. Does anyone have an idea how I can align the comments and use positioning?

Best Answer

Your redefinition of algorithm is causing the problem. Use the following instead:

\def\algorithm{%
\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%
\oldalgorithm
}

Since the environment algorithm takes an optional argument as part of its definition, it "checks ahead" to see if you follow \algorithm with [ or not. You've placed the older definition \oldalgorithm at the start of the newly redefined \algorithm, meaning it is literally followed by \global, which is not [. Placing \oldalgorithm at the end of \algorithm allows scanning to pick up [ in the input stream correctly.

Related Question