[Tex/LaTex] How to put a curly brace inside an algorithm to group code lines

algorithm2ealgorithmsbraces

I am using the algorithmic package (or even algorithm2e is fine). Is it possible to use curly braces to group some lines in the algorithm so as to be able to put an explanation to the right?

Best Answer

Here is an example using the infamous \tikzmark macro applied to the example from How to typeset gotos and labels using LaTeX pseudocode environments?.

enter image description here

Usage:

  • Mark the horizontal position with: \tikzmark{right}. Here I used the end of the header procedure Euclid(a,b) as the right` node. Hence the horizontal position of the brace.
  • Mark the top of the brace with: \tikzmark{top}.
  • Mark the bottom of the brace with \tikzmark{bottom}.
  • Call \AddNote{<top node>}{<bottom node>}{<right node>}{<text>}.

These node names top, bottom, and right are arbitrary so if you have multiple places in the same algorithm where you want to place such notes, you can use different node names. Just pass them to the \AddNote macro.

Notes:

  • This does require two runs. First one to determine the locations, and the second to do the drawing.

Further Enhancements:

  • The macro \AddNote could accept additional formatting parameters for the text of the node, and line color selection. Currently this is hard coded to used red and text width=2.5cm.

References:

Here are a few similar applications using \tikzmark:

Code:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing,calc}
\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}

\newcommand*{\AddNote}[4]{%
    \begin{tikzpicture}[overlay, remember picture]
        \draw [decoration={brace,amplitude=0.5em},decorate,ultra thick,red]
            ($(#3)!(#1.north)!($(#3)-(0,1)$)$) --  
            ($(#3)!(#2.south)!($(#3)-(0,1)$)$)
                node [align=center, text width=2.5cm, pos=0.5, anchor=west] {#4};
    \end{tikzpicture}
}%

\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\usepackage{algorithm}% http://ctan.org/pkg/algorithm
\begin{document}
\algnewcommand{\algorithmicgoto}{\textbf{go to}}%
\algnewcommand{\Goto}[1]{\algorithmicgoto~\ref{#1}}%
\begin{algorithm}
  \caption{Euclid’s algorithm}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\tikzmark{right}\Comment{The g.c.d. of a and b}
    \State $r\gets a\bmod b$
    \While{$r\not=0$} \tikzmark{top}\Comment{We have the answer if r is 0} \label{marker}
      \State $a\gets b$
      \State $b\gets r$
      \State $r\gets a\bmod b$
    \EndWhile \tikzmark{bottom}
    \State \textbf{return} $b$\Comment{The gcd is b}
    \State \Goto{marker}
  \EndProcedure
\end{algorithmic}
\AddNote{top}{bottom}{right}{We loop here until $r=0$.}
\end{algorithm}
\end{document}