[Tex/LaTex] Insert newpage before section but prevent pagebreak after part

macrospage-breakingpartssectioning

Maybe some of you can already guess what I'm trying to achieve; I want to redefine some commands with the following result: every \section should start on a new page except for sections which are placed directly after a \part.

MWE:

\documentclass[a4paper,10pt]{article}
\usepackage{lipsum}

\begin{document}

\part{Part one}
\section{First section}
\lipsum[1]

\section{Second section}
\lipsum[2]

\section{Third section}
\lipsum[1]


\part{Part two}
\section{First section}
\lipsum[3]

\section{Second section}
\lipsum[1]

\end{document}

In the above example, every \section should create a new page but not the "First sections", since they're located directly after a \part command.

I started with

\let\oldsection\section
\renewcommand\section{\newpage\oldsection}

but then I got stuck not finding an answer to the question on how to built up an exception (so that the \part sticks together with the following \section on one page).

I hope you know how to cope with my problem – you probably do; I never saw you being unable to solve a problem!

Best Answer

Use a conditional to turn off page breaks after a part:

\documentclass[a4paper,10pt]{article}

\usepackage{etoolbox}
\newtoggle{afterpart}
\pretocmd{\section}
  {\iftoggle{afterpart}
    {\global\togglefalse{afterpart}}% we're after a part
    {\clearpage}% we're not immediately after a part
  }{}{}
\pretocmd{\part}
  {\clearpage % do a page break
   \global\toggletrue{afterpart}% tell \section we're just after a part
  }
  {}{}

\usepackage{lipsum}

\begin{document}

\part{Part one}
\section{First section}
\lipsum[1]

\section{Second section}
\lipsum[2]

\section{Third section}
\lipsum[1]


\part{Part two}
\section{First section}
\lipsum[3]

\section{Second section}
\lipsum[1]

\end{document}

If you want to exclude some section from the mechanism, add

\newcommand{\sectionnobreak}{%
  \global\toggletrue{afterpart}%
  \section
}

to your preamble and use \sectionnobreak instead of \section. Alternatively, add

\newcommand{\NPB}{%
  \global\toggletrue{afterpart}%
}

to the preamble and type

\NPB\section{Title}

for the section you want to exclude from the automatic page break. The first section after \part will not need any adjustment in any case.

Related Question