[Tex/LaTex] Prevent caption to appear on separate page

captionsenvironmentsmintedpage-breaking

I'm using a custom listing environment which does not float taken from
Code spanning over two pages with minted, inside listing with caption.
The caption is done with the caption package.

The problem is that under certain circumstances the caption is on another page than the complete listing. Is there any way to prevent this behavior?

Update Here is the minimal example. Just to clarify again: It is allowed to have pagebreaks in the code, but not between code and caption. So in the example the caption should either be also on page 1 or on page 2 there should be some lines of code.

Best Answer

Things you can try:

  • Wrap the part of the environment that shouldn't experience a break in a minipage environment. Use \vspace{-\baselineskip}s at will.
  • Include the needspace package and then use \needspace{20\baselineskip} before the caption, where 20 is the number of lines your caption is long.
  • Plaster your code or macros with \nopagebreak[4]s all over the place (although you mentioned that this doesn't work so just sayin').
  • Use manual \pagebreaks
  • STFTeX.SE and see if you can find something that can be applied to your problem as well.