[Tex/LaTex] algorithm2e: too wide when in \item

algorithm2elists

Consider

\documentclass{article}
\usepackage[tworuled]{algorithm2e}%%% v5.1 or v5.2. Could not find v5.3 for download.
\usepackage{lipsum}
\begin{document}
\lipsum[1]
\begin{algorithm}[H]
  TEST1
\end{algorithm}
\begin{enumerate}
\item \lipsum[2]

  \begin{algorithm}[H]
    TEST2
  \end{algorithm}
\end{enumerate}
\begin{algorithm}[H]
  TEST3
\end{algorithm}
\end{document}

In the output

latex output

the horizontal lines around TEST2 are too long. If we had more text in TEST2, it would also go beyond the right border into the margin. Is there a possibility to let TEST2 end at the right text border more-or-less automatically?

Best Answer

This is because the algorithms are meant to float where there aren't any restrictions in terms of the width (it's usually \textwidth). If you want to have the algorithms inline (and not floating; by using the [H]ere float specifier), then you'll have to set it inside a minipage of pre-specified width - \linewidth in this case:

enter image description here

\documentclass{article}

\usepackage[tworuled]{algorithm2e}
\usepackage{lipsum}

\begin{document}

\lipsum[1]
\begin{algorithm}[H]
  TEST1
\end{algorithm}

\begin{enumerate}
  \item \lipsum[2]

  \begin{minipage}{\linewidth}%
  \begin{algorithm}[H]
    TEST2
  \end{algorithm}
  \end{minipage}
\end{enumerate}

\begin{algorithm}[H]
  TEST3
\end{algorithm}

\end{document}