[Tex/LaTex] Remove horizontal spacing on the right with algorithm2e

algorithm2espacing

Is there a way to remove the space on the right side of an algorithm with algorithm2e? I found \algomargin in the documentation but it does not help.
Example:

\documentclass[]{article}
\usepackage[ruled,linesnumbered]{algorithm2e}
\begin{document}
\begin{algorithm}[H]
    first line \tcp*{comment}
    long text line long text line long text line long text line long text line long text line long text line\;
\end{algorithm}
\end{document}

which produces:

2e

Note the extra horizontal space on the right of the comment (compared to the line width).

Best Answer

The right margin is left open in case you want to number your algorithm lines on the right (using \setRightLinesNumbers). However, the most common setting (or default) is to have the numbers on the left (\setLeftLinesNumbers) with the margin on the right left open. To remove this gap on the right hand side of the algorithm, you need to patch the initial settings when starting the algorithm, all of which is handled by \algocf@start:

\usepackage{etoolbox}

\makeatletter
% Remove right hand margin in algorithm
\patchcmd{\@algocf@start}% <cmd>
  {-1.5em}% <search>
  {0pt}% <replace>
  {}{}% <success><failure>
\makeatother

Line numbers on the right are placed within a 1.5em margin that is removed from the available algorithm space specifically for that reason. The above patch replaces this reduction with 0pt.

enter image description here

\documentclass{article}

\usepackage[ruled,linesnumbered]{algorithm2e}
\usepackage{etoolbox}

\makeatletter
% Remove right hand margin in algorithm
\patchcmd{\@algocf@start}% <cmd>
  {-1.5em}% <search>
  {0pt}% <replace>
  {}{}% <success><failure>
\makeatother

\begin{document}

\begin{algorithm}
  first line\tcp*{comment}
  long text line long text line long text line long text line 
    long text line long text line long text line\;
\end{algorithm}

\end{document}
Related Question