# Keeping environment on same page if possible

I have an environment for which I want a few things to happen:

1. If I can fit 2+ on the same page, then they both go on that page, with a certain amount of space between them (say one inch).

2. If two can't fit on the same page, then the second is bumped down onto the next page. And lastly,

3. If one environment is longer than a single page then it just overflows into the next page.

What I originally had looked like:

\newenvironment{env}{
\begin{minipage}{\textwidth}
}{
\end{minipage}
\vspace{1in}
}


But I ran into problems here with environments that were longer than one page, with the minipage simply continuing into the bottom margin and off the end of the page, then the next page starting with with the extra \vspace.

I also had troubles with the minipage messing up spacing within the environment — specifically space between text and the top of a table — but I imagine that I could solve that later if needed.

You can rely on needspace to calculate the remaining space on the current page and issue a \newpage if needed. The following wraps that into an environment called myenv:

\documentclass{article}

\usepackage{environ,needspace}
\newsavebox{\saveblock}

\NewEnviron{myenv}{%
\par
\begin{lrbox}{\saveblock}
\begin{minipage}{\linewidth}
\BODY
\end{minipage}
\end{lrbox}%
\Needspace{\dimexpr\ht\saveblock+\dp\saveblock}%
\BODY
}

\usepackage{lipsum}

\begin{document}

\begin{myenv}
\lipsum[1]
\end{myenv}

\begin{myenv}
\lipsum[2]
\end{myenv}

\begin{myenv}
\lipsum[3]
\end{myenv}

\begin{myenv}
\lipsum[4]
\end{myenv}

\begin{myenv}
\lipsum[5]
\end{myenv}

\end{document}

• This looks good, thanks! Feb 7 at 5:54