How to use patchcmd to insert \clearpage before \chapter to avoid breaking page

I want my document to not start new pages when there is a new chapter. My code is the following:

\documentclass{scrbook}
\usepackage{etoolbox}

\patchcmd{\chapter}{\clearpage}{}{}
\begin{document}

\chapter{Preliminary}
first chapter

\chapter{Discussion}
second chapter

final chapter
\end{document}


This code will start new pages for the first and second chapters but not for the third one.

Why is my \patchcmd not working?

-

With a KOMA-Script class you can use \RedeclareSectionCommand to set style=section for the chapter headings. So there is no need to patch anything.

\documentclass{scrbook}[2015/10/03]

\RedeclareSectionCommand[
style=section,
indent=0pt
]{chapter}

\begin{document}
\chapter{Preliminary}
first chapter
\chapter{Discussion}
second chapter
final chapter
\end{document}


-

Here is a solution. One need to patch \scr@startchapter

\documentclass{scrbook}
\usepackage{etoolbox}

\makeatletter
\if@openright
\patchcmd{\scr@startchapter}{\cleardoublepage}{}{}{}
\else
\patchcmd{\scr@startchapter}{\clearpage}{}{}{}
\fi
\makeatother
\begin{document}

\chapter{Preliminary}
first chapter

\chapter{Discussion}
second chapter

\end{document}

-

First, you have a syntax error in the \patchcmd line, because you're missing a brace pair:

\patchcmd{<macro>}{<search>}{<replace>}{<success>}{<failure>}


This has no consequences in this case, because the patch fails, so \begin that was absorbed as the fifth argument is delivered because of the failure.

Main reason: the \chapter macro has no \clearpage in its replacement text, which is

\scr@startchapter{chapter}


and it is \scr@startchapter that must be patched

% scrbook.cls, line 4030:
\newcommand*{\scr@startchapter}[1]{%
\if@openright\cleardoublepage\else\clearpage\fi
\scr@ifundefinedorrelax{#1pagestyle}{}{%
\ifstr{#1pagestyle}{}{}{%
\thispagestyle{\@nameuse{#1pagestyle}}%
}%
}%
\global\@topnum\z@
\@afterindentfalse
\expandafter\SecDef\csname @#1\expandafter\endcsname\csname @s#1\endcsname
}


Always check the meaning of a macro, before trying to patch it.

You probably want to remove both \cleardoublepage and \clearpage, so

\makeatletter
\patchcmd{\scr@startchapter}
{\if@openright\cleardoublepage\else\clearpage\fi}% search
{}% replace
{}{\ddt}
\makeatother


I find it convenient to add something like \ddt, which will warn about failure with Undefined control sequence \ddt. When I'm sure the patch succeeds, I remove it.

-