When I put a long code in my file using a floating lstlisting, it is forced to be in only one page at the end of the chapter, and then some of the code is truncated and outside of the page. If I remove the float option, the code is "split" even though it would fit on a single page. It looks ugly.

What I want:

  • place the listing at the top or bottom of some page close to the place in the TeX-code
  • if the listing is to long for one page, continue on the next page, but don't split the code if it could fit on one page

Here's a minimal example to play around with. Notice that if the float-option is removed, it is placed 'correctly', but split. Also, the code will not continue on another page if you add as many linies to it that it would need a page break, but instead gets truncated. Furthermore, if one line is deleted from the listing it will behave as expected. Also, changing lipsum[1] to lipsum[1-3] shows what I would expect.



\begin{lstlisting}[frame=single, float=htb]
Long listing start.

Long listing end.

  • 1
    floats are not broken across the pages. If you want to break, don't use float. For caption you may use captionof macro from either caption ot capt-of packages.
    – user11232
    Nov 21, 2014 at 1:21
  • @HarishKumar (+) Yes... but then the question will be: how can it be forced to fit on a page in the case that it will fit (even if that means putting it on the next page and continuing the text on this one)? At least, I take it that's the motivation to use floats although you are obviously right about their limitations.
    – cfr
    Nov 21, 2014 at 2:01
  • @cfr: Probably \afterpage?
    – user11232
    Nov 21, 2014 at 2:27
  • @HarishKumar That was what I wondered although I think that will put it on the next page even if there's room on this one, won't it? I guess the only way to prevent that, though, would be to use one of those needs-space things to figure out if there is room?
    – cfr
    Nov 21, 2014 at 2:30
  • I changed the title; the behavior you get is not stupid at all: floats are never split, by design. What you want is a different feature; but the specifications you give are too loose.
    – egreg
    Nov 21, 2014 at 11:27

2 Answers 2


Do not use the float option. A caption is also possible without it:

\begin{lstlisting}[frame=single, caption=foo]
Long listing start.
  • If I don't use the float option the lstlisting will be split over pages, and I don't want that. Nov 21, 2014 at 11:36

Add the exclamation mark ! in the float option to give the float placement a higher priority, so

\begin{lstlisting}[frame=single, float=!htb]

Some restrictions on the float placement are ignored when including !.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .