# How do I prevent LaTeX from putting \sections at the very end of the page?

Please take a look at the screenshot below. I am having a problem where LaTeX would put the \section at the very end of the page. So far I fixed it by using \newpage but I just learned that it was totally wrong.

I am using memoir document class together with listings package for code examples. The page in the screenshot was generated this way:

\section{Substitute (find and replace) "foo" with "bar" on each line}

\begin{lstlisting}
awk '{ sub(/foo/,"bar"); print }'
\end{lstlisting}

....

\section{Substitute "foo" with "bar" only on lines that contain "baz"}

\begin{lstlisting}
awk '/baz/ { gsub(/foo/, "bar") }; { print }'
\end{lstlisting}

...


Anyone knows how to make \sections always go on a new page if they are at very bottom?

-
I think you need a package needspace. –  xport Jun 3 '11 at 18:49
Somehow the lstlisting environment annuls the LaTeX mechanism that prevents page breaks after a \section command. –  lockstep Jun 3 '11 at 18:52

needspace package provides the \needspace and \Needspace macros for requesting a certain amount of space on the current page for the following materia.

\documentclass{article}
\usepackage[a4paper]{geometry}
\usepackage{needspace}
\usepackage{listings}
\lstset{frame=single}
\usepackage{lipsum}
\begin{document}
\lipsum[1-6]
\Needspace*{10\baselineskip}% you need a vertical space of 10 times \baselineskip for the following section.
\section{Something}
\begin{lstlisting}
hello world !
hello universe !
\end{lstlisting}
\end{document}

-
So should I add \Needspace before every \section? –  Peteris Krumins Jun 3 '11 at 19:05
Yes. Adjust the ... in \Needspace*{...\textheight}. You might use 0.3 for 1/3 of paper height. –  xport Jun 3 '11 at 19:08
The problem with this "solution" is that the "certain amount of space" needs to be set individually for every lstlisting environment and that it is easy to make wrong guesses about the amount of space actually needed. (In your example, \Needspace*{7\baselineskip} would have been sufficient, as you can easily test by setting \textheight 610pt in the preamble. –  lockstep Jun 3 '11 at 19:09
Manual adjustment per section should be done at the final release of your book. –  xport Jun 3 '11 at 19:15
@xport, @lockstep, but don't I again have the problem that I asked in my previous question? The problem was that I want to use the same text for different book formats (a4, letter, kindle, lulu, etc.), so if I do any adjustments for one format, the others break. –  Peteris Krumins Jun 3 '11 at 19:22