I want to put a box around lines of code and to add comments inside the box.
This is what I want it to achieve:
This is the example of code I am using for the algorithm.
\documentclass{article}
\usepackage[margin=1in]{geometry}% http://ctan.org/pkg/geometry
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\usepackage{algorithm}% http://ctan.org/pkg/algorithm
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\usepackage{subcaption}% http://ctan.org/pkg/subcaption
\captionsetup{compatibility=false}
\DeclareCaptionSubType*{algorithm}
\renewcommand\thesubalgorithm{\thetable\alph{subalgorithm}}
\DeclareCaptionLabelFormat{alglabel}{Alg.~#2}
\begin{document}
\begin{table}%
\begin{subalgorithm}{.5\textwidth}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$}%\Comment{The g.c.d. of a and b}
\State $r\gets a\bmod b$
\While{$r\not=0$}%\Comment{We have the answer if r is 0}
\State $a\gets b$
\State $b\gets r$
\State $r\gets a\bmod b$
\EndWhile
\State \textbf{return} $b$%\Comment{The gcd is b}
\EndProcedure
\end{algorithmic}
\caption{Euclid’s algorithm}\label{algo1}
\end{subalgorithm}%
\begin{subalgorithm}{.5\textwidth}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$}%\Comment{The g.c.d. of a and b}
\State $r\gets a\bmod b$
\While{$r\not=0$}%\Comment{We have the answer if r is 0}
\State $a\gets b$
\State $b\gets r$
\State $r\gets a\bmod b$
\EndWhile
\State \textbf{return} $b$%\Comment{The gcd is b}
\EndProcedure
\end{algorithmic}
\caption{Euclid’s algorithm}\label{algo2}
\end{subalgorithm}
\captionsetup{labelformat=alglabel}
\caption{Two algorithms}%
\label{tab:1}%
\end{table}
\end{document}
Best Answer
Here's some code to get you started. The idea is to use the ubiquitous
\tikzmark
to place some marks at the appropriate locations, and then to draw the boxes with the text; I used thefit
library for this purpose:The \Textbox command has two optional arguments and three mandatory ones:
where
<length1>
specifies the additional width of the box (default=2.5cm
);<length2>
controls the width of the box where the text will be typeset (default=2cm
);<name1>
and<name2>
are previously set marks that will be used to draw the box, and<text>
is the text that will be typeset (adjust the settings according to your needs).Remark:
Since
\tikzmark
is being used and some coordinate calculations are involved, the code needs three runs to produce the correct output.