[Tex/LaTex] Add colors that depend on chapters to the TOC

colortable of contentstocloft

I'would like to add different colors in my TOC, depending on the chapter. I've a color for the header, section subsection of each chapter (red chapter one, blue chapter two etc…). With this code I can change colors of chapter name, section and subsection, but this style is the same of all the TOC:

\usepackage[svgnames]{xcolor}

\makeatletter

\let\stdl@section\l@section

\renewcommand*{\l@subsection}[2]{%
  \stdl@subsection{\it\bf\textcolor{DarkGreen}{#1}}{\it\bf\textcolor{DarkGreen}{#2}}}
\makeatother

I'm a newbie, I would to exprime like an "if chapter==1 \textcolor{DarkGreen}" "if chapter==2 \textcolor{Red}"… Any ideas?

Thankyou in advance.

Best Answer

You can try the following:

\documentclass{book}

\usepackage[svgnames]{xcolor}
\newcounter{chapcntr}
\setcounter{chapcntr}{-1}
\newcommand*\toccolor{%
    \ifcase\value{chapcntr}%
         \color{red}%----- 0 --
    \or  \color{blue}%---- 1 --
    \or  \color{green}%--- 2 --
    \or  \color{cyan}%---- 3 --
    \else \color{black}%-- default
    \fi}

\usepackage{tocloft}
\renewcommand*\cftchapfont{\stepcounter{chapcntr}\toccolor\bfseries}
\renewcommand*\cftchappagefont{\toccolor\bfseries}

\renewcommand*\cftsecfont{\toccolor}
\renewcommand{\cftsecleader}{\toccolor\cftdotfill{\cftsecdotsep}}
\renewcommand*\cftsecpagefont{\toccolor}

\begin{document}
\frontmatter
\tableofcontents
\mainmatter
  \chapter{First chapter}
  \section{A section}
  \section{Another section}
  \chapter{Second chapter}
  \section{A section}
  \section{Another section}
\appendix
  \chapter{First appendix}
  \section{A section}
  \section{Another section}
\backmatter
\end{document}

Resulting in

enter image description here

Related Question