This question shows how to prevent a long listing from being split across several pages when the code is written directly into the tex file. I want to achieve the same effect when including code in separate files using \lstinputlisting like so:

\lstinputlisting[label=lst:mylist,caption=A Caption]{code/parametrised.xml}

How do I modify the listing environment definition given in the above question to do so?


Any help would be greatly appreciated!

Edit: The question has been rephrased for clarity - The answers here relate to preventing a listing from being split across pages by ensuring it's treated like a unbreakable float. Howvever, this also means that listings longer than a page will not be paginated and will run off the bottom of the page.


declare the listing to a float, then it will be automatically be set in a box:

  • Just checked it - this will sometimes misplace the lstinputlisting, namely: put it after the paragraph that is immediately after it in the code. – Patryk Jan 13 '14 at 1:53

Instead of using the \lstnewenvironment to define a new environment, define a new environment using the regular \newenvironment:

  {\minipage{\linewidth}% \begin{filecode}[#1]
  {\endminipage}% \end{filecode}

Now you use

\begin{filecode}[label=lst:mylist,caption=A Caption]
  • Thank you. That works, but the code is no longer paginated, and now runs off the page as if it were a float. Is there a way to avoid that, other than this: tex.stackexchange.com/questions/14522/… ? – danH Sep 7 '11 at 8:05
  • Yes, but I thought you were actually interested in a solution that typesets your code without breaking (or splitting) it. Am I understanding your request incorrectly? – Werner Sep 7 '11 at 8:09
  • Sorry I've not been clear. I have long code listings, which are split across several pages by the listings environment as desired. However, other floats are appearing in between these pages, so I end up with [code page 1of2][page of floats][code page 2of2]. I now see the question I referenced originally was talking about a different issue. Should I just mark this as solved and repost? – danH Sep 7 '11 at 13:08
  • @danH: I do think there will be different techniques involved in (1) splitting listings across pages (without restriction); and (2) splitting listings across pages without being interrupted by a float. I suggest finishing this question off by adequately rephrasing it (so there's a clear distinction between the requirements), and then repost. – Werner Sep 7 '11 at 19:49

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.