I have a listing of 6 lines. The listing box does not seem to fit on one page (it is on the bottom of the page) so the rest of the box is printed on the next page. There is nothing actually in the box on the next page. How can I avoid this? Can I tell the listing to put at least 3 lines on the next page?
4 Answers
use
\begin{lstlisting}[float,...]
then it cannot have a pagebreak inside
may be you can use the samepage
environment. A very small example
\begin{samepage}
\begin{verbatim}
line 1
line 2
line 3
line 4
line 5
line 6
\end{verbatim}
\end{samepage}
-
1Would you like to improve the answer perhaps showing how the
samepage
environment works? Sep 30, 2013 at 7:30 -
This solution does not work for me. I added \begin{samepage}...\end{samepage} around my lstlisting and there is still one orphan line on the next page. Oct 15, 2013 at 9:15
I had a similar problem where a the caption and maybe one line of code would appear at the end of one page and the rest of the code on the next one. What helped me was the needspace
package. Its not quite perfect, as I have to set the command in front of every \lstlisting
that is broken at the wrong place but its all right for a quick n dirty solution.
% preamble
\usepackage{needspace}
% document
\needspace{5\baselineskip} % reserve at least 5 lines, if there is not enough
% space, insert a page break
\begin{lstlisting}[...]
You could use the minipage
environment, which ensures that everything contained in itself is held together, and, if there is no more room for it, in its entirety, to fit, then it moves itself to the next page where it should have ample room to display (it's only six lines, so it shouldn't have to span multiple pages).
\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[colorinlistoftodos]{todonotes}
\begin{document}
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
\begin{minipage}{\textwidth}
line #1
line #2
line #3
line #4
line #5
line #6
\end{minipage}
\end{document}
basicstyle
smaller or, preferably, split up your code samples—nobody likes reading a page (or pages) full of code. (I mean, unless you're a textbook giving a solution.)