Section should automatically start new page if the whole section does not fit on current page

I would like my sections to start on a new page if they do not fit on the current page. In other words: if a section fits on the current page print it, if it does not fit start printing it on the next page.

I would like this to be done automatically.

\usepackage{titlesec} seems to be the solution, but I can not get it to do the job.

• Should it be done with titlesec? how ?
• Is there a better approach?
-
this question is very similar but does not give automatic solutions –  danjjl Apr 4 '12 at 21:27
The whole section? –  egreg Apr 4 '12 at 21:28
Not sure I understand the question right, but yes (my sections are quite short (longest are 3 pages long)) –  danjjl Apr 4 '12 at 21:29
So your question is very unclear: three pages can't fit on a page, can they? –  egreg Apr 4 '12 at 21:31
Do you mean: If the next section can fit on the current page, just print it as-is. Otherwise, put in a page break and start the section on the new page. ? –  Mike Renfro Apr 4 '12 at 22:13

There is a simple solution that does require only a single pass ...

\documentclass{article}

\newcommand\mysection{\vfil\penalty-9999\vfilneg\section}

\usepackage{lipsum}

\begin{document}
\mysection{A} \lipsum[3]
\mysection{B} \lipsum[1-2]
\mysection{C} \lipsum[5]
\end{document}

-
1. Set \labels at the start and end of the section and check if they are on the same page. You'll need multiple runs and you have to mark the end of sections.
I am not very familiar with Latex macros. How would I check if both \labels are on the same page and insert a \newpage at the first label if they are not? don't hesitate sending me to some documentation –  danjjl Apr 10 '12 at 20:33