# Drawing a rectangle box around code fragment

How to produce the effect of drawing a rectangle box surrounded the code, and put it in the figure? (Any methods including non-tikz-pgf method that helps is welcome)

-
Take a look at fancyvrb package –  JLDiaz Feb 25 '13 at 12:29
or listings?? –  Harish Kumar Feb 25 '13 at 12:30
or the verbatimbox package –  Steven B. Segletes Feb 25 '13 at 12:56

An example of verbatimbox usage:

\documentclass{article}
\usepackage{verbatimbox}
\begin{document}
\verbfilebox{codefrag}
\begin{tabular}{cc}
\boxbottomsep = 3em
\end{tabular}
\end{document}


where codefrag.tex is

{invoke ... operation = "bf" ...
outputVariable = "FlightConf">
<compensationHandler cost="g">
<invoke ... operation = "cancelF" />
</compensationHandler>
</invoke>


Alternately, if you wish to auto-number the code fragments, here I define the \numblock command, so that each code block is sequentially numbered. Once that is done, a code frag is placed as follows, quite simply:

\verbfilebox{codefrag}
\numblock{\fbox{\theverbbox}}


Here is an example where \numblock is defined.

\documentclass{article}
\usepackage{verbatimbox}
\begin{document}
\newlength\maxblocklabelsize
\newlength\blockindent
\setlength\maxblocklabelsize{-0.4in}
\setlength\blockindent{0.2in}
\newcommand\blocklabel[1]{[\textit{\alph{#1}}]}
\newcounter{blocknum}
\setcounter{blocknum}{0}
\newlength\codeblockwidth
\newlength\parindentsave
\newcommand\numblock[1]{
\setlength\codeblockwidth{\textwidth}
\setlength\parindentsave{\parindent}
\parindent 0in
\vspace{\abovecaptionskip}
\begin{tabular}{@{\hspace{\blockindent}} l @{} r @{}}
{\tt
\begin{tabular*}{\codeblockwidth}{@{} l @{}}
#1
\end{tabular*}%
}
& \makebox[\maxblocklabelsize]{\hfill\blocklabel{blocknum}}\\
\end{tabular}
\vspace{\belowcaptionskip}
\setlength{\parindent}{\parindentsave}
}

\verbfilebox{codefrag}
\numblock{\fbox{\theverbbox}}
\end{document}

-

If I'm not mistaken, the question has been edited to emphasize the notion of putting the code listing into a "figure." The verbatimbox package can do it, because it's output is a box, which can easily be stuffed into a figure environment or, as I prefer, into the \bxfigure command of the boxhandler package.

\documentclass{article}
\usepackage{boxhandler}
\usepackage{verbatimbox}
\begin{document}
\verbfilebox{codefrag}
\bxfigure{My caption goes here}{\fbox{\theverbbox}}
\end{document}


In this case, the boxed code fragment constitutes the entire figure (minus the caption). However, that need not be the case. The second argument of \bxfigure can be tweaked to make \theverbbox part of a tabular environment, etc.

-