10

I am writing a document using the book class, and I use tocloft in order to customize the appearance of my ToC. So far, the package did a great job for most customizations, except for one thing: I am trying to highlight ToC entries for the book parts (created with \part) with a grey box. Is there any way to do that?

I found \colorbox and soul as solutions for highlighting text in general, but I do not have an idea how to apply them to the ToC entries for parts.

lockstep
  • 250,273
elsvene
  • 203

1 Answers1

7

Here's a solution using tikz and tocloft. It places hidden nodes in the tocloft formatting commands for part and then uses the overlay function of tikz to draw the box.

\documentclass{book}
\usepackage{tocloft}
\usepackage[svgnames]{xcolor}
\usepackage{tikz}
% command to make a hidden node
\newcommand*{\hnode}[1]{%
    \tikz[remember picture] \node[minimum size=0pt,inner sep=0pt,outer sep=5pt] (#1) {};}
% create a node at the beginning of the part entry
\renewcommand{\cftpartfont}{\hnode{P1}\bfseries\Large}
\renewcommand{\cftpartpagefont}{\bfseries}
% create a node at the end of the part page number and draw the gray box
\renewcommand{\cftpartafterpnum}{%
  \hnode{P2}\tikz[remember picture,overlay] 
  \draw (P1.north west)  [line width={25pt}, gray,opacity=.2] -- (P2.north east);}
\begin{document}
\tableofcontents

\part{First part}
\chapter{A chapter}
\section{A section}
\part{Second Part}
\chapter{Another chapter}
\end{document}

output of code

Note that you need to compile your document twice to have the overlay align correctly.

Alan Munn
  • 218,180