[Tex/LaTex] unexpected behaviour of \addtokomafont

koma-script

Regarding the following two examples my question is: Is it a bug or is it a feature (or do I miss something)?

\documentclass{scrbook}
\usepackage{xcolor}
% \addtokomafont{sectioning}{\color{green}}
 \addtokomafont{chapter}{\color{green}}
 \addtokomafont{section}{\color{green}}
 \addtokomafont{subsection}{\color{green}}
 \addtokomafont{subsubsection}{\color{green}}

\setlength{\textheight}{13\baselineskip}
\begin{document}
\chapter{test}

AAA

\section{test}

\subsection{subtest}

AAA
\end{document}

Please compare the results [sorry, I can not upload images] of the examples.

\documentclass{scrbook}
\usepackage{xcolor}
 \addtokomafont{sectioning}{\color{green}}
% \addtokomafont{chapter}{\color{green}}
% \addtokomafont{section}{\color{green}}
% \addtokomafont{subsection}{\color{green}}
% \addtokomafont{subsubsection}{\color{green}}

\setlength{\textheight}{13\baselineskip}
\begin{document}
\chapter{test}

AAA

\section{test}

\subsection{subtest}

AAA
\end{document}

The former one shows a page break between \section and \subsection.

Best Answer

With an uptodate KOMA-Script (at least version 3.21, current is 3.22) I do not get a page break between \section and \subsection.

Even if I use

\addtokomafont{section}{\color{blue}}
\addtokomafont{subsection}{\color{red}}

the result is

enter image description here

So you have to update your KOMA-Script version.


Workaround for version 3.20 or older:

You can add \nobreak after the \color command:

\documentclass{scrbook}
\usepackage{xcolor}
\addtokomafont{sectioning}{\color{green}\nobreak}
\addtokomafont{section}{\color{blue}\nobreak}
\addtokomafont{subsection}{\color{red}\nobreak}

\setlength{\textheight}{13\baselineskip}
\begin{document}
\chapter{test}
\KOMAScriptVersion
\section{test}
\subsection{subtest}
AAA
\end{document}

or \leavevmode before \color (see also this question):

\documentclass{scrbook}
\usepackage{xcolor}
\addtokomafont{sectioning}{\leavevmode\color{green}}% see https://tex.stackexchange.com/a/314243/43317
\addtokomafont{section}{\leavevmode\color{blue}}
\addtokomafont{subsection}{\leavevmode\color{red}}

\setlength{\textheight}{13\baselineskip}
\begin{document}
\chapter{test}
\KOMAScriptVersion
\section{test}
\subsection{subtest}
AAA
\end{document}

Both results in

enter image description here