[Tex/LaTex] Using listings and subfigure together

listingssubcaptionsubfloatsverbatim

I am writing a document in which code listings and diagrams appear side-by-side frequently. I am using the listings package for the code and \includegraphics for the diagrams. I want to put them both on the same figure. I tried the subfigure package, but it does not allow verbatim environments inside the \subfigure{} argument.

The fancyvrb package has a workaround for this limitation: Using SaveVerbatim and \BUseVerbatim. However, I prefer to use only the listing package to get uniform styling for my code listings.

The subfigure manual includes some voodoo definition of a subfloat environment which can contain minipages with verbatim content. It is a clumsy solution. I also wonder why this solution was left out of the package itself.

Does anyone know a simple way to make these packages work together? Alt., is there a sub-figures package that is more verbatim-friendly?

Best Answer

Here's an example using the subcaption package which is included in the caption package bundle. (Note that the \rule command in my example is only a placeholder for \includegraphics.)

\documentclass{article}

\usepackage{listings}
\usepackage{caption,subcaption}

\begin{document}

\begin{figure}
  \begin{subfigure}[b]{.5\linewidth}
    \begin{lstlisting}
    for i:=maxint to 0 do
    begin
    { do nothing }
    end;
    \end{lstlisting}
    \caption{A listing}
  \end{subfigure}
  \begin{subfigure}[b]{.5\linewidth}
    \centering
    \rule{1.5cm}{1.5cm}
    \caption{A diagram}
  \end{subfigure}
  \caption{A listing and a diagram}
\end{figure}

\end{document}

EDIT: The subfigure entry of the TeX Catalogue OnLine states:

This package is now obsolescent: new users should use subfig or subcaption instead.

Related Question