# Declare environment that does not “break”

Is there a way in LaTeX to declare a command or environment that will "refuse" to be broken across pages unless absolutely necessary?

Use case: I have a number of documentation items (all generated via Doxygen's XML) and several of them are just a handful of lines long. In some cases up to four of these items could fit on one (A4) page.

Now one such documentation item starts a new \section or \subsection (depending on the context) and it should not break between the (sub)section heading and the contents. That is, title and content must always be kept on the same page. The only exception to that rule would be that title and content combined would not fit a single page if they started on a new page.

I guess what I am looking for could be described as "vertical badness" value and I need a way to measure items vertically and let them flow onto the next page if necessary.

• Put the environment inside a box? – user156344 May 7 at 15:11
• @JouleV that even works with a section and subsection? – 0xC0000022L May 7 at 15:21
• Without code I can't test... Please add an example code – user156344 May 7 at 15:22
• latex always prevents a page break after a heading, although of course normally it would allow the text to break – David Carlisle May 7 at 15:54
• @Marijn I forgot the :) – Sveinung May 7 at 20:02

I don't think that there is a good answer to your request. As David Carlise said that a sectional heading and following text are always on the same page and JouleV suggested putting your text into a box. Consider the following (less any of my typos):

\documentclass{article}
\newcommand{\stuff}{Bunch of stuff \\ more stuff \\ yet more.}
\begin{document}
\mbox{}
\vspace{0.85\textheight} % move near bottom of page
\section{One}
\begin{minipage}{\textwidth}  % box some text
\stuff
\end{minipage}

\clearpage % next page

\mbox{}
\vspace{0.85\textheight}
\section{two}
\stuff

\end{document}


In section One the text is boxed and stays on the same page but in section Two the text is not boxed and continues on the following page. If you change the \vspace to o.86\textheight then section One starts on the second page and page 1 is empty.

In essence just use:

\section{...}

• I tried boxing the content, using a minipage just because that was easiest to get quickly. Alas, it really complicates things when the content is too big (vertically) to fit a page. What I am looking for is something that will keep together the content but fail gracefully if it can't. Thanks anyway for the answer and +1. – 0xC0000022L May 9 at 14:23