I stumbled upon the solution from this question: How to highlight sections of my code in algorithm?
and incorporated it into the following MWE which shows two flaws:
\documentclass{article}
\usepackage[linesnumbered,lined,ruled,commentsnumbered]{algorithm2e}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{fit,calc}
\newcommand*{\tikzmk}[1]{\tikz[remember picture,overlay,] \node (#1) {};\ignorespaces}
%define a boxing command, argument = colour of box
\newcommand{\boxit}[1]{\tikz[remember picture,overlay]{\node[yshift=3pt,fill=#1,opacity=.25,fit={(A)($(B)+(.95\linewidth,.8\baselineskip)$)}] {};}\ignorespaces}
\begin{document}
\begin{algorithm}[h]
\caption{MWE}
a $\leftarrow$ b \;
\If{$x > 0$}{
\tikzmk{A}\If{$x > 0$}{
a $\leftarrow b$ \;
}\tikzmk{B}\boxit{cyan}
}
\end{algorithm}
\end{document}
- The solution inserts an additional line (line 6 in the image)
- The solution draws the box out of bounds (see right boundary)
As far as flaw 2 goes, I augmented the boxit command to also take the current indentation level as an argument, i.e.,
\documentclass{article}
\usepackage[linesnumbered,lined,ruled,commentsnumbered]{algorithm2e}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{fit,calc}
\newcommand*{\tikzmk}[1]{\tikz[remember picture,overlay,] \node (#1) {};\ignorespaces}
%define a boxing command, argument = colour of box
\newcommand{\boxit}[2]{\tikz[remember picture,overlay]{\node[yshift=3pt,fill=#1,opacity=.25,fit={(A)($(B)+(\dimexpr\algowidth-#2\algoskipindent,.8\baselineskip)$)}] {};}\ignorespaces}
\begin{document}
\begin{algorithm}[h]
\caption{MWE}
a $\leftarrow$ b \;
\If{$x > 0$}{
\tikzmk{A}\If{$x > 0$}{
a $\leftarrow b$ \;
}\tikzmk{B}\boxit{cyan}{2}
}
\end{algorithm}
\end{document}
Which is okay for me, but I can not remove flaw 1 with the additional line, any suggestions?