[Tex/LaTex] Preventing page break after the first or before the last list item

listspage-breakingwidows-orphans

Is there a way to globally prevent all lists from having a page break inserted between the first and second items or between the last and second-last item? I'm fine with page breaks that are after the second item and before the second-last item, but I do not want the first item or the last item to be alone.

I know that I can use "\nopagebreak\@nobreaktrue" to prevent a page break at a specific location, but I don't want to have to insert it manually, nor do I know how to insert it automatically via macros.

(I've searched everywhere for many hours but couldn't find a solution, and I'm a beginner in LaTeX so I can't figure out how to solve it myself.)

Best Answer

I've adjusted \pagetest so that if you reduce the rule to 6.31in you get all 5 items on one page.

\documentclass{article}

\newcommand{\pagecheck}[1]% #1 = legnth to end of page
{\ifvmode\vspace{-\parskip}\else\newline\fi% check for blank line between items
\rule{0pt}{#1}\vspace{-#1}}

\newlength{\pagetest}
\setlength{\pagetest}{0.55in}% adjustable

\makeatletter
\newcommand{\newaux}[2]% #1 = label, #2 = text
{\expandafter\gdef\csname AUX@#1\endcsname{#2}}

\newcommand{\getaux}[1]% #1 = label
{\@ifundefined{AUX@#1}{0}{\csname AUX@#1\endcsname}}

\newcommand{\writeaux}[2]% #1 = label, #2 = text
{\@bsphack
\write\@auxout{\string\newaux{#1}{#2}}%
\@esphack}
\makeatother

\newcounter{items}%
\newcount\itemtest
\newcount\itemno

\let\OLDitemize\itemize%
\let\endOLDitemize\enditemize%
\let\OLDitem=\item%

\renewenvironment{itemize}%
{\pagecheck{\pagetest}%
\stepcounter{items}%
\global\itemtest=\getaux{item\arabic{items}}
\global\advance\itemtest by -1
\global\itemno=0
\begin{OLDitemize}}%
{\end{OLDitemize}%
\writeaux{item\arabic{items}}{\the\itemno}}

\def\item{%
\global\advance\itemno by 1
\ifnum\itemno=\itemtest \pagecheck{\pagetest}\fi%
\OLDitem}

\begin{document}

\noindent\rule{\textwidth}{6.32in}% adjustable

\begin{itemize}
\item first
\item second
\item third
\item fourth
\item fifth
\end{itemize}

\end{document}
Related Question