[Tex/LaTex] How to ensure that a listing is not going to be split

listingspage-breaking

How can I ensure that a listing is not going to be split? If it is going to be split I want that the entire listing to move to the following page, effectively moving everything at pass. I mean any text that comes after the listing must remain after the listing.

Best Answer

You can wrap the lstlisting environment in a minipage environment to disallow page breaks:

 \begin{minipage}{\textwidth}
 \begin{lstlisting}
   content
 \end{lstlisting}
 \end{minipage}

However, this might lead to large white space at the page before the listing when it doesn't fit there. It would be better style to turn the listing into a float with a caption plus label and reference it in the text using \ref like a figure or table. This can be done using:

 \begin{lstlisting}[float,caption=<Caption text>,label=<label>]
   content
 \end{lstlisting}

and then using \ref{<label>} in the text.

This of course will allow the text written in the .tex file after the listing to appear before it in the final document, what you don't won't. As states, the better style would be to adjust your document for this instead.

Related Question