# Problem with mdframed, lstlisting and subfig

I'm trying to understand why the following code does not compile.

\documentclass[12pt]{article}
\usepackage[svgnames]{xcolor}
\usepackage{filecontents}
\usepackage{tikz}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{listings}
\lstnewenvironment{lstframed}
{
\mdframed[backgroundcolor=LightSlateGray!10] }
{
\endmdframed
}

\usepackage{subfig}
\begin{document}

\begin{figure}[H]
\centering
\subfloat[A]{
B
} \\
\subfloat[C]{
\begin{lstframed}
D
\end{lstframed}
}
\caption{E}
\end{figure}
\end{document}


If I do not use mdframed, then everything is fine, but I'm using a fancy frame in my real document, so I really need it.

• May be you should switch to a better tool. Migrate to tcolorbox that has listings support.
– user11232
May 26 '14 at 15:34

The problem is that you are trying to put verbatim material in the argument of a command (\subfloat) and this has severe limitations, as you've experienced. One option would be to previously box the listing material:

\documentclass[12pt]{article}
\usepackage[svgnames]{xcolor}
\usepackage{filecontents}
\usepackage{tikz}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{listings}
\usepackage{subfig}

\lstnewenvironment{lstframed}
{
\mdframed[backgroundcolor=LightSlateGray!50]
}
{
\endmdframed
}

\newsavebox\mybox

\begin{document}

\begin{lrbox}{\mybox}
\begin{minipage}{\linewidth}
\begin{lstframed}
Some test code
\end{lstframed}
\end{minipage}
\end{lrbox}

\begin{figure}[H]
\centering
\subfloat[Caption for the first subfloat]{%
\rule{5cm}{2cm}%
} \par
\subfloat[Caption for the second subfloat]{%
\usebox\mybox%
}
\caption{E}
\end{figure}

\end{document}


Another approach here would be to use the tcolorbox package instead, since it offers out of the box support for the listings package. In any case, since you are going to place verbatim material inside the argument of \subfloat you'll need the previous boxing:

\documentclass[12pt]{article}
\usepackage[svgnames]{xcolor}
\usepackage{filecontents}
\usepackage{tikz}
\usepackage{tcolorbox}
\tcbuselibrary{listings}
\usepackage{subfig}

\newtcblisting{lstframed}{
colback=LightGray!50,
listing only
}

\newsavebox\mybox

\begin{document}

\begin{lrbox}{\mybox}
\begin{minipage}{\linewidth}
\begin{lstframed}
Some test code
\end{lstframed}
\end{minipage}
\end{lrbox}

\begin{figure}[H]
\centering
\subfloat[Caption for the first subfloat]{%
\rule{5cm}{2cm}%
} \par
\subfloat[Caption for the second subfloat]{%
\usebox\mybox%
}
\caption{E}
\end{figure}

\end{document}