1

Goal

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}
\addtokomafont{subsection}{\hl\mdseries\color{red}}

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

1 Answer 1

4

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
\addtokomafont{subsection}{\mdseries\color{red}}
\renewcommand\subsectionformat{\hl{\thesubsection\autodot}\enskip}

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

enter image description here

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:

enter image description here

3
  • 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. Apr 28, 2016 at 12:27
  • @hauptbenutzer Do not use \MakeUppercase in \addtokomafont or \setkomafont. You can change \sectionlinesformat instead. See my updated answer.
    – esdd
    Apr 28, 2016 at 12:50
  • Huh, why didn't I think of that. Thanks! Apr 28, 2016 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .