4

I am more and more convinced that algorithm2e is badly designed, basically because it reinvents the wheel for quite a lot of things (e.g., captions). Alas, it's too late to switch. So here's my next question:

How do I get rid of the ugly margins of the following algorithm? (the margins to both sides of the caption, and the margin on the right of the algorithm)

\documentclass{scrartcl}
\usepackage[ruled]{algorithm2e}
\usepackage{lipsum}

\setlength{\algomargin}{0em}

\begin{document}
    \begin{algorithm}
        \caption{\lipsum[1]}
        \For{$x$}{$y$\tcp*[r]{$z$}}
    \end{algorithm}
    \lipsum[2]
\end{document}

enter image description here

2
  • Can you explain what would be a better version of algorithm2e?
    – projetmbc
    Commented Mar 6, 2023 at 22:00
  • 1
    @projetmbc Not setting spurious margins without an accessible way to change, using the same caption format as all other floats, not setting default [H] float specifier, separating algorithm and float would be some improvements I can think of. But – I have decided to use algorithm2e, so I'll have to live with it.
    – Bubaya
    Commented Mar 7, 2023 at 9:37

1 Answer 1

6

enter image description here

This answer requires etoolbox to be loaded so that \patchcmd can be used:

\documentclass{scrartcl}
\usepackage[ruled]{algorithm2e}
\usepackage{lipsum}

\usepackage{etoolbox} % For \patchcmd

\makeatletter
\patchcmd{\algocf@makecaption@ruled}{\hsize}{\textwidth}{}{} % Caption to stretch full text width
\patchcmd{\@algocf@start}{-1.5em}{0em}{}{} % For // to right margin
\makeatother

\SetAlCapHSkip{0pt} % Reset left skip of caption
\setlength{\algomargin}{0em}

\begin{document}
    \begin{algorithm}
        \caption{\lipsum[1]}
        \For{$x$}{$y$\tcp*[r]{$z$}}
    \end{algorithm}
    \lipsum[2]
\end{document}
1
  • 2
    The first two (possibly three) patches can be generalised via \SetAlCapHSkip{0pt}.
    – Werner
    Commented Feb 17, 2023 at 18:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .