TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 17 down vote accepted

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


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>]

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.

share|improve this answer
thanks @Martin, i use the minipage advice and i'm taking special care adjusting the document to avoid the existence of lstlisting environment greater than a certain number of lines, so the white spaces never going very large – mjsr May 18 '11 at 11:10
+1 for the float option! – Trefex Apr 22 '14 at 16:32

\begin{framed} \begin{lstlisting} or \lstinputlisting{...} \end{lstlisting} \end{framed}

share|improve this answer
Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. To start to make this a usable answer, you should make it into a complete compilable document including, explain what it does. In particular, your code snippet won't compile in a standard document, so you need to include about which packages are needed. – Andrew Swann Dec 2 '13 at 19:19
...there's only no need to use framed specifically. What about minipage? – Werner Dec 2 '13 at 19:26

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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