# etoolbox not breaking page when needed

I have the following piece of code in the preamble, that should prevent chapter from beginning on different pages, but, by the same time, when I get to chapter 3 it has enough text to break a page and does not, how can I fix it?

\usepackage{etoolbox}
\makeatletter
\patchcmd{\chapter}{\if@openright\cleardoublepage\else\clearpage\fi}{}{}{}
\makeatother


Unfortunately, I can't build a MWE with the same specs as the original, so I'm letting a only view link to the overleaf project.

Project

As pointed in the coments bellow, LaTeX does not handle well with a whole bunch of text inside sections, so I changed from sections to enumerate environment, and then changed how the item appeared using the enumitem package.

• In your code you have \subsection{A whole bunch of text}. LaTeX doesn't allow page breaks in section titles. You should make your document into something like \subsection{Title} A whole bunch of text. – Phelype Oleinik Oct 12 '19 at 15:32
• and how can I mantain the format of a Law text, with Art and § symbols? – liuzp Oct 12 '19 at 16:47
• where exactly @JohnKormylo? – liuzp Oct 12 '19 at 21:34
• Oops, you DON"T want it to break a page normally. This looks like a job for needspace. – John Kormylo Oct 13 '19 at 15:47

I put some of the instructions into the MWE itself.

BTW, etoolkit is just an code editor. \patchcmd replaces some of the existing code with something else.

\documentclass{book}
\usepackage{needspace}

\def\chapterspace{184.87657pt}% reserving a length register seemed a bit wasteful

\usepackage{etoolbox}
\makeatletter
\patchcmd{\chapter}{\if@openright\cleardoublepage\else\clearpage\fi}{\needspace{\chapterspace}}{}{}
\makeatother

\usepackage{lipsum}% MWE only

\begin{document}

First you must find out how much space you need.
Unless you use long chapter titles, the following should do.

\setbox0=\vbox{\chapter{\strut}\strut\newline\strut}%
\def\chapterspace{\the\ht0}%
%\hrule
%\usebox0
%\hrule
Then copy \chapterspace{} into the definition of \verb|\chapterspace| and remove this code.

\noindent\rule{\textwidth}{15\baselineskip}% worst case

\lipsum[1]

\chapter{Test}
\lipsum[2]

\end{document}