[Tex/LaTex] Caption and label on Minted code

captionslabelsminted

I want to add a caption and label on a Minted source code so I can reference it, similarly to what you can do to figures.

In Minted manual it says I can use the listing environment, which allows to use both caption and label, the problem is that listings creates a float and only allows to use one page. My source code is long and spans on two pages.

How can I add caption and label but still be able to use two pages?

Best Answer

You can define a non-floating environment which can break over pages and put the minted environment in that one. This is a documented feature:

8 FAQ and Troubleshooting

  • I need a listing environment that supports page breaks. The built-in listing environment is a standard float; it doesn’t support page breaks. You will probably want to define a new environment for long floats. [...]
    With the caption package, it is best to use minted’s newfloat package option. See
    https://tex.stackexchange.com/a/53540/10742

Loading minted.sty with newfloat option enables you to customize the listing environment, caption.sty offers \captionof for captions outside floating environments. Check their docs for further (plenty of) options.

Putting it together:

\documentclass{article}
\usepackage[newfloat]{minted}
\usepackage{caption}

\newenvironment{code}{\captionsetup{type=listing}}{}
\SetupFloatingEnvironment{listing}{name=Source Code}

\begin{document}
\begin{code}
\captionof{listing}{My C-Code}
\label{code:c-code}
\begin{minted}{c}
int main() {
printf("hello, world");
return 0;
}
\end{minted}
\end{code}

Reference to \ref{code:c-code}.  

\end{document}

enter image description here