8

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?

  • 1
    A solution is described in minted docs. 8 FAQ and Troubleshooting, I need a listing environment that supports page breaks. It has a link to this answer. – Arash Esbati Jul 7 '15 at 7:44
  • Thank you @ArashEsbati, it works now but the caption shows like this: Listing 1: MY_LABEL. Is there a way to change from Listing 1 to Source Code 1? – Anthony Gaudino Jul 7 '15 at 15:16
  • See my answer below. – Arash Esbati Jul 7 '15 at 18:20
11

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.