Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
3  
listings can be used as an float environment. So you have no page breaks. –  Marco Daniel Dec 8 '11 at 18:19
add comment

marked as duplicate by Marco Daniel, Aditya, Seamus, Torbjørn T., topskip Jun 13 '12 at 16:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

up vote 3 down vote accepted

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.

share|improve this answer
    
I will use the float. I already used up my \enlargethispage-space –  towi Dec 8 '11 at 20:07
add comment

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