Conflict between \captionof and mdframed

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:

1 Answer

I've searched in the caption package documentation, and found that the captionof command needs to be inside an environment for it to work. Adding enclosing braces ({}) around the listing, including the captionof command, seems to fix the problem.

• \captionof permanently sets \@captype, which the extra group (breaces) will correct. Without a readable copy of your code (no screenshots) there isn't much else to say. – John Kormylo Sep 30 '18 at 15:46