7

I'm working on a document which is divided into chapters. Each chapter is divided into 4 sections. I would like to create a command that defines a color depending on the number of the section.

I've been trying to do so using ifthen package :

\usepackage{ifthen}
...
\newcommand{\myColor}{%
    \ifthenelse{\thesection = 1}{DarkOrange}{%
        \ifthenelse{\thesection = 2}{DeepSkyBlue}{%
            \ifthenelse{\thesection = 3}{MediumSeaGreen}{%
            DimGray}%
        }%
    }%
}%

I use titlesec to customize my section titles.

I get the following error :

Use of \@undeclaredcolor doesn't match its definition \section{exploration}

pointing to the line of my first section.

How could I correct this ?

azetina
  • 28,884

2 Answers2

7

Your code can't work, because the argument of \color must be expandable, which \ifthenelse isn't.

Define four colors with a suffix dependent on the section number:

\documentclass{book}
\usepackage{titlesec}
\usepackage[svgnames]{xcolor}

\titleformat{\section}[hang]
 {\Large\bfseries\color{sectioncolor\arabic{section}}}
 {\thesection}
 {1em}
 {}

\colorlet{sectioncolor1}{DarkOrange}
\colorlet{sectioncolor2}{DeepSkyBlue}
\colorlet{sectioncolor3}{MediumSeaGreen}
\colorlet{sectioncolor4}{DimGray}

\begin{document}

\chapter{Title}

\section{First is DarkOrange}

\section{Second is DeepSkyBlue}

\section{Third is MediumSeaGreen}

\section{Fourth is DimGray}

\end{document}

enter image description here

egreg
  • 1,121,712
1

Since you're not providing a minimal working example (a complete LaTeX program that is very short yet illustrates the problem you're having) I don't know what your intentions are. But the following works.

\documentclass{article}

\usepackage[svgnames]{xcolor}
\usepackage{ifthen}
\usepackage{lipsum}

\newcommand{\myColor}{%
    \ifthenelse{\thesection = 1}{\color{DarkOrange}}{%
        \ifthenelse{\thesection = 2}{\color{DeepSkyBlue}}{%
            \ifthenelse{\thesection = 3}{\color{MediumSeaGreen}}{%
            \color{DimGray}}%
        }%
    }%
}%

%\def\couleur\expandafter\color{\myColor}

\begin{document}

{\myColor section 0}

\section{hello}

{\myColor
\lipsum[1-2]}

\section{howdy}

{\myColor \lipsum[3-4]}
\end{document}
JPi
  • 13,595
  • Your code works well. But if I define a function using myColor : \newcommand{\myFunction}[1]{% {\bfseries{\myColor} #1}} and if I call the function in differents sections, the color used is always the same – user60498 Aug 10 '14 at 16:34
  • Remove the curly brackets around \myColor. They limit the scope of your command. – JPi Aug 11 '14 at 08:45
  • Thank for your code. But how can we refresh color of each section by chapter? – GAVD Jun 03 '19 at 07:50