3

The other day I had a problem in creating an example that contained text and listings, I asked about that here: lstlisting in a box? David Carlisle found a very good solution for it, and after toying with his solution I ended up with another problem. It seems that this solution does accept listings but it does not accept figures.

Below is an example of what I want. It basically is the solution David provided earlier with a figure added. As such it will fail. While I know the figure is maybe not really required here, I have other situations where I do want to use figures in examples, and this provides a working example.

I have no clue how to resolve this. Any pointers and ideas are welcome.

As a side remark I intend to use the final solution later as a newenvironment to serve as a template for all examples I got in my document.

Thank you for reading this.

\documentclass{article}
\usepackage{color,listings}
\definecolor{lightgray}{rgb}{.7,.7,.7}
\newsavebox\lstbox
\begin{document}

\begin{lrbox}{\lstbox}\begin{minipage}{\textwidth}
An example text

\begin{lstlisting}[frame=single,language=XML,caption=A Fibonaci example\label{code:fibonaci}]
   <xml></xml>
\end{lstlisting}   

\begin{figure}[htb]
\begin{verbatim}
  1 1 2 3 5 8 13 21 34 55 89
\end{verbatim}
\caption{\label{code:fibonaci:output}Output of the Fibonaci example}
\end{figure}
  Some more text
\end{minipage}\end{lrbox}  

\colorbox{lightgray}{\usebox\lstbox}


\end{document}
2
  • The whole point about figure is that it is a floating environment that can move so it has to be at the top level.You should use the box to get the background inside the figure Apr 17, 2013 at 9:13
  • You can also just use \captionof{figure}{My text}, supported by the capt-of or caption package and get rid of the figure-environment. That way nothing floats and you still get a caption as desired.
    – Martin H
    Apr 17, 2013 at 9:19

1 Answer 1

2

Use the caption or capt-of package and do everything in an outer figure environment. I've added some spacing to make the frame around the lstlisting inside the grey background.

\documentclass{article}
\usepackage{color,listings,caption,calc}
\definecolor{lightgray}{rgb}{.7,.7,.7}
\newsavebox\lstbox
\begin{document}

\begin{figure}[htb]
\begin{lrbox}{\lstbox}\begin{minipage}{\textwidth-2\fboxsep-2pt}
An example text

\begin{lstlisting}[frame=single,language=XML,caption=A Fibonacci example\label{code:fibonacci}]
   <xml></xml>
\end{lstlisting}

\begin{verbatim}
  1 1 2 3 5 8 13 21 34 55 89
\end{verbatim}
\captionof{figure}{\label{code:fibonacci:output}Output of the Fibonacci example}
  Some more text
\end{minipage}\end{lrbox}

\colorbox{lightgray}{\kern1pt\usebox\lstbox\kern1pt}
\end{figure}

\end{document}

enter image description here

By the way, it's Fibonacci, not Fibonaci.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .