[Tex/LaTex] Display different colors in the table of contents

colortable of contents

I wonder if there is a way in a table of contents to display only chapters with different colors, such as in the sample below:

enter image description here

Best Answer

Using a patch for \@chapter to provide this automatically, with some colour switching according to the chapter number, having a 'table' of colours defined in \currentchaptitlecolor. The sequence of colours is of course completely arbitrary and can be changed at will.

The patch does work for \mainmatter - chapter content only (yet).

\documentclass{book}

\usepackage[x11names,named]{xcolor}
\usepackage{xpatch}
\makeatletter

\xpatchcmd{\@chapter}{%
  \addcontentsline{toc}{chapter}%
  {\protect\numberline{\thechapter}#1}%
}{%
 \addcontentsline{toc}{chapter}%
 {\color{\currentchaptitlecolor}\protect\numberline{\thechapter}#1}%
}{}{}


\newcommand{\currentchaptitlecolor}{%
  \ifcase\value{chapter}
  \or
  red% First chapter
  \or
  blue% Second chapter
  \or
  green% Third chapter
  \or
  yellow% etc.
  \or
  brown%
  \fi
}


\makeatother

\begin{document}
\tableofcontents
\chapter{First chapter}
\section{Some section}


\chapter{Second chapter}
\section{Some section}

\end{document}

enter image description here

Related Question