# Add colors that depend on chapters to the TOC

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?

-
Just a hint: when entering code in your question, you can indent it with four spaces to get a nice formatting. =) – Paulo Cereda May 19 '11 at 23:35
Which document class are you using? In your question you talk about changing the color for the chapter entries in the ToC, but your code refers to sections and subsections. Which sectional units must be affected? – Gonzalo Medina May 20 '11 at 0:44

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*\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

-
Thankyou very much for the answer! Is that any way to color just the number of the sub section (2.1,2.2)? I cannot find it in the tocloft documentation. Thankyou again! – Jake May 20 '11 at 11:48
Thanks to your answer I've learned how to use \ifcase :). – Grzegorz Wierzowiecki Feb 1 '12 at 18:42