TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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}

awk '{ sub(/foo/,"bar"); print }'


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

awk '/baz/ { gsub(/foo/, "bar") }; { print }'


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

enter image description here

share|improve this question
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
up vote 4 down vote accepted

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

\Needspace*{10\baselineskip}% you need a vertical space of 10 times \baselineskip for the following section.
        hello world !
        hello universe !
share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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