# Section title with background color and line breaks in KOMA

I want my subsection title to have a colored background with support for line breaks. There are a few questions about spanning that background to the margins - that's not what I want to achieve, however.

After some research I found that the soul package comes pretty close to what I need, but I can't, unfortunately, seem to use its \hl command in KOMA's \addtokomafont.

Here's an MWE

\documentclass[a5paper,pagesize]{scrbook}
\usepackage{xcolor,soul}
\sethlcolor{black}

\begin{document}
\subsection{A very peculiar title which will hopefully break into the next line}
\end{document}


You can redefine \sectionlinesformat (needs KOMA-Script Version 3.19 or newer) and \subsectionformat.

\documentclass[a5paper]{scrbook}[2015/10/03]
\usepackage{xcolor,soul}
\sethlcolor{black}

\makeatletter
\renewcommand\sectionlinesformat[4]{%
\ifstr{#1}{subsection}% only subsections should be changed
{\@hangfrom{\hskip#2 #3}{\hl{#4}}}% subsection level
{\@hangfrom{\hskip#2 #3}{#4}}% other section levels
}
\makeatother
\renewcommand\subsectionformat{\hl{\thesubsection\autodot}\enskip}

\begin{document}
\subsection{A very peculiar title which will hopefully break into the next line}
\end{document}


Note that \hl has some limitations. See the documentation of package soul.

If you really want to use \MakeUppercase for the subsections you have to change the redefinition of \sectionlinesformat to

\renewcommand\sectionlinesformat[4]{%
\ifstr{#1}{subsection}% only subsections should be changed
{\@hangfrom{\hskip#2 #3}{\hl{\MakeUppercase{#4}}}}% subsection level
{\@hangfrom{\hskip#2 #3}{#4}}% other section levels
}


Result:

• Thanks! That worked for me for the most part. Ran into some weird error with \MakeUppercase in \addtokomafont (possibly related to this), though. Anyway, since I'm auto-generating the TeX code, I can uppercase the text before writing the .tex file. – hauptbenutzer Apr 28 '16 at 12:27
• @hauptbenutzer Do not use \MakeUppercase in \addtokomafont or \setkomafont. You can change \sectionlinesformat instead. See my updated answer. – esdd Apr 28 '16 at 12:50
• Huh, why didn't I think of that. Thanks! – hauptbenutzer Apr 28 '16 at 12:55