# Captioning an mdframed box without making unbreakable

I would like to a have a caption below my mdframed box (outside the border if possible) which sometimes span across multiple pages. I managed to create a caption several ways but the pagebreaks are unfriendly. How can I do that without making the box unbreakable at pagebreaks?

The listings package is not an alternative, because I already use it inside somewhere in the mdframed box, and nesting them doesn't seem like a good idea.

Associated thread: use this inside \lstnewenvironment

The following might be what the after:

\documentclass{article}
\usepackage[a6paper]{geometry}% Just for this example
\usepackage{lipsum,mdframed}% http://ctan.org/pkg/{lipsum,mdframed}
\newmdenv[linecolor=red,frametitle=Infobox]{infoboxmd}
\makeatletter
\def\@noargument{noargument}
\newenvironment{infobox}[1][noargument]
{\gdef\@opt@arg{#1}% Caption optional argument
\infoboxmd}
{\endinfoboxmd\par\nobreak%
\ifx\@opt@arg\@noargument\else\centering\@opt@arg\par\fi}%
\begin{document}

\begin{infobox}[This is a caption]
\lipsum[1-2]
\end{infobox}

Some text.

\end{document}

• I'm rather curious about why you always change the test for no optional argument. ;-) The \gdef can be, more simply, \def. – egreg Sep 28 '13 at 19:25
• @egreg: I don't know. Testing it with \relax would be simpler. You're right, it could be \def. – Werner Sep 28 '13 at 19:29
• @Werner: Thanks for the quick reply. To be honest, I don't fully understand the underlying logic, so if you can point in a direction to gain that knowledge, I will follow. One more thing: is there a way to keep at least one line with the caption? It's pretty bad-looking alone. (I should have asked this - I'll edit the question.) – masu Sep 28 '13 at 22:15
• @Werner: UPDATE2: I tried to use it in \lstnewenvironment with less luck. (It works with \BeforeBeginEnvironment, but it's useless that way, because the lst environment has the caption text.) :( – masu Sep 28 '13 at 23:39
• One could exploit aftersingleframe and afterlastframe – egreg Sep 29 '13 at 0:01