12

enter image description here

\documentclass{article}
\usepackage[ruled]{algorithm2e} % http://www.ctan.org/pkg/algorithm2e
\usepackage{xcolor} % http://www.ctan.org/tex-archive/macros/latex/contrib/xcolor

\def\HiLi{\leavevmode\rlap{\hbox to \hsize{\color{yellow!50}\leaders\hrule height .8\baselineskip depth .5ex\hfill}}}

\begin{document}
\begin{algorithm}[h]
 \caption{Evolutionary algorithm}
 initialize population \;
 \HiLi\For( \emph{Evolutionary loop}){$g := 1$ to $G_{max}$}
 {
    \HiLi do things \;
    evolve population \;
 }
 celebrate \;
\end{algorithm}

\end{document}

The code gives me the image below. How can i fill up the highlight to the left margin like in the 1st picture and remove the whitespace between highlights ?

enter image description here

11

I would do this using TikZ. The idea is to use TikZ to mark the top and bottom of the region to be marked, and then use a boxing macro which uses the fit library to make a node that fits the marked nodes, with the width calculated automatically.

Because this uses the [remember picture] functionality of TikZ, two compilations will be needed to get the boxes in their correct position.

\documentclass{article}
\usepackage[ruled]{algorithm2e} % http://www.ctan.org/pkg/algorithm2e
\usepackage{xcolor} % http://www.ctan.org/tex-archive/macros/latex/contrib/xcolor
\usepackage{tikz}
\usetikzlibrary{fit,calc}
%define a marking command
\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}
%define some colours according to algorithm parts (or any other method you like)
\colorlet{pink}{red!40}
\colorlet{blue}{cyan!60}

\begin{document}
\begin{algorithm}[h]
 \caption{Evolutionary algorithm}
 initialize population \;
 \tikzmk{A}\For( \emph{Evolutionary loop}){$g := 1$ to $G_{max}$}
 {
    do things \;
    evolve population \;
 }\tikzmk{B}
 \boxit{pink}
 celebrate \;
 \tikzmk{A}\For( \emph{Evolutionary loop}){$g := 1$ to $G_{max}$}
 {
    do things \;
    evolve population \;
 }\tikzmk{B}
 \boxit{blue}
\end{algorithm}
\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.