6

Possible Duplicate:
How to prevent lstlisting from splitting code between pages?

I have a rather long listing on a page that has 3-4 lines on the following page. Just before the listing is one 7-line paragraph.

I'd like to have the listing start 2cm earlier (move it upwards) so that the whole listing fits on the page. The paragraph must then lose its last 3-4 lines to the next page -- but: without having the paragraph justification being interrupted.

I guess I have to introduce a sort of "minipage" around the listing or something and lat that be moved around independently from the running text -- not unlike an image. But how?

1
  • 3
    listings can be used as an float environment. So you have no page breaks. Commented Dec 8, 2011 at 18:19

1 Answer 1

3

Using the float option for lstlisting (or for \lstset), your listings will be treated as floating, and won't be split across pages, objects:

\documentclass{article}
\usepackage{listings}
\usepackage{lipsum}

\begin{document}

\lipsum[1-4]
\begin{lstlisting}[float]
for i:=maxint to 0 do
begin
j:=square(root(i));
end;
for i:=maxint to 0 do
begin
j:=square(root(i));
end;
for i:=maxint to 0 do
begin
j:=square(root(i));
end;
\end{lstlisting}
\lipsum[1]

\end{document}

you can use something like float=ht to specify the float placement. Another option would be to use \enlargethispage* to, in this case, enlarge the \textheight for the page:

\documentclass{article}
\usepackage{listings}
\usepackage{lipsum}

\begin{document}

\lipsum[1-4]\enlargethispage*{3\baselineskip}
\begin{lstlisting}
for i:=maxint to 0 do
begin
j:=square(root(i));
end;
for i:=maxint to 0 do
begin
j:=square(root(i));
end;
f    or i:=maxint to 0 do
begin
j:=square(root(i));
end;
\end{lstlisting}
\lipsum[1]

\end{document}

Notice, however, that this can result in the last lines of text being too close to the footer.

1
  • I will use the float. I already used up my \enlargethispage-space
    – towi
    Commented Dec 8, 2011 at 20:07

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