I currently have the following way of inserting code in my report, as I do not typically want pagebreaks for my code examples.



Code here...

   \caption{This is an example of code}


However I now have an example that is more than one page, and I can't get pagebreaking to work. Is there a better way of approaching this? I still want to have figure numbers as I refer to them in the report.

  • 2
    Welcome to TeX.SX! Using a figure seems the wrong approach, but you could use \captionof{figure}{My caption}. In order to give you real advice please post some more code (MWE). – TeXnician May 9 '17 at 14:46

Welcome to TeX.SX!

Yes, I would indeed say there is a better way of achieving this. Well, at least in my humble opinion.

For starters, as has been mentioned by TeXnician, using a figure to contain a listing isn't really very proper. I would recommend using dedicated listings environments for that. After all, a figure is not the same thing as a listing.

Besides the philosophical question of whether or not one should use figure environments to contain listings, there is also a practical issue: A figure environment is a float and cannot break across pages. So I would recommend a different approach:

  • Use a listings float for short code listings which should not break across pages.
  • Create a new environment for long code listings which can break across pages. See page 32 of the minted package documentation, which also refers to this question.

Short Example for Showcasing the Principles

As said, we create a new environment called longlisting which will break across pages and can be captioned and labelled. It will also show up in the \listoflistings.

% Create a new environment for breaking code listings across pages.


\section{Let Us Make Some Listings}

        ... input a lot of code here ...
        ... It will break across pages ...
    \caption[Long Code Example]{A long code example which will break across pages.}

        ... input short code here ...
        ... This code will not break across pages ...
    \caption[Short Code Example]{A shorter code example which will not break across pages.}

Result When Filled in With of Code

page1 page2 page3

Closing Remarks

Apologies if I have misunderstood your intent. If you truly do want to list your listings as figures, you can make the following changes in my code:

Instead of




And for the non-breakable environments, just use figure as you have been doing. But as said, I would really not recommend this.

  • 1
    Thanks a lot you saved my life – David Alvarez Jul 9 '19 at 13:44

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.