0

I want to have a box in my algorithm, and for that I'm using framed environment. However, it also shifts line numbers:

\documentclass{article}
\usepackage[vlined,ruled,linesnumbered]{algorithm2e}
\usepackage{framed}

\begin{document}
\begin{algorithm}
    aaa
    \begin{framed}
    bbb
    \end{framed}
\end{algorithm}
\end{document}

enter image description here

How can I vertically align line numbers? \Indm shifts the code, not the line numbers. \DecMargin doesn't apply to individual lines. I don't mind using another package/environment instead of framed if you can recommend one: my only requirement is to have a box around a block of code. I don't mind hardcoding the indentations if required.

1 Answer 1

2

The package algorithm2e uses \llap put the line numbers in a box of width zero, with the numbers plus their space from the algorithm, sticking out to the left of this box. This code patch adds more space to the left.

a

\documentclass{article}
\usepackage[vlined,ruled,linesnumbered]{algorithm2e}
\usepackage{framed}


%*****************************************% added <<<<<<<<<<<<
\usepackage{etoolbox}

\newlength{\nummargin} % move line numbers to the margin
\setlength{\nummargin}{2ex}

\makeatletter
\patchcmd{\algocf@printnl}{\kern\skiplinenumber}{\kern\dimexpr\skiplinenumber +\nummargin+1ex }{}{}
\makeatother
%*****************************************

\begin{document}    

\begin{algorithm}
    aaa
    {\parindent-\nummargin\begin{framed}% changed <<<<
            bbb 
                
            ccc
    \end{framed}}
    ddd
\end{algorithm}

\end{document}

Used with algorithm2e.sty 2017/07/18 v5.2

UPDATE after follow-up up question

The command \patchcmd (package etoolbox) allows to change a portion of a macro command.

\patchcmd{<command to patch>}{<code to be replaced>}{<new code>}{<message if success>}{<message if failure>}

The macro \algocf@printnl (line #1644 of algorithm2e.sty) generates the line numbers. The patch used in this example adds more space between the line number and the text by changing the \kern. \kern is a TeX primitive used to insert a non-breakable space.

5
  • Thank you very much! If possible, can you please explain what happens in line \patchcmd{...}? Or where I should look to undrestand what's going on there?
    – Dmitry
    May 19, 2022 at 23:07
  • @Dmitry Thank you for your feedback!. Please see the updated answer. May 20, 2022 at 13:01
  • THank you very much for the update!
    – Dmitry
    May 20, 2022 at 19:15
  • By any chance, do you know how to handle nested boxes?
    – Dmitry
    Oct 1, 2022 at 8:16
  • 1
    @Dmitry To help other readers please ask a new question. Oct 1, 2022 at 13:05

You must log in to answer this question.

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