I'm using the minted package to generate highlighted code snippets. Because I want all minted environments to be wrapped with mdframed, I added the following to the preamble.
\usepackage{mdframed}
\BeforeBeginEnvironment{minted}{\begin{mdframed}}
\AfterEndEnvironment{minted}{\end{mdframed}}
I also want to caption the listings. Since I have listings that are more than one page long, I don't make them into a float; instead, I add a caption and a label with \captionof{listing}{...}\label{...} after the \end{minted} closure. The problem is that when I do that, the mdframed environment doesn't spread nicely across pages as it usually does. Instead, I get the whole listing crammed (truncated, actually) into a single page.
I've identified that either the caption package or the \captionof command are the culprit.
Do you know any solutions?
Edit: I've identified the source of the problem more precisely: it's the \captionof command from the previous minted environment that messes up the next one. If I just add a caption to the last one, for example, it doesn't happen.
Edit: I got it to work if I put the caption below, but if I put it above the listing it still messes up.
Without \captionof:
With \captionof:

