# Algorithm2e: framed environment shifts line numbers

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}


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.

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.

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

\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.

• 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? May 19 at 23:07