[Tex/LaTex] How to define a command to feed the contents of a list into an \ifcase construct

comma-separated listconditionalsmacros

It's common to use an \ifcase construct to redefine a command depending on the value of a counter. The following example illustrates this:

\documentclass{article}
\usepackage{xcolor}
\usepackage{etoolbox}

\newcommand\sectioncolor{}

\renewcommand\sectioncolor{%
  \ifcase\value{section} brown\or red\or blue\else olive\fi}
\pretocmd{\section}{\color{\sectioncolor}}{}{}

\begin{document}

\section{Section One}
\section{Section Two}
\section{Section Three}
\section{Section Four}

\end{document}

The above redefinition of \sectioncolor using \ifcase implies manually feeding the colors in the \ifcase construct. What I would like to achieve is to have a command, say \ColorList, having as argument a comma separated list of variable length containing the colors to be used, and then redefine \sectioncolor to use the colors of the list depending on the section counter. So for example, referring to my sample code, using

\ColorList{brown,red,blue,olive}

would be equivalent to

\renewcommand\sectioncolor{%
  \ifcase\value{section} brown\or red\or blue\else olive\fi}

and

\ColorList{yellow,magenta,cyan,orange,blue}

would be equivalent to

\renewcommand\sectioncolor{%
  \ifcase\value{section} yellow\or magenta\or cyan\or orange \else blue\fi}

but. of course, without having to manually feed the colors into the \ifcase. How can this be done?

Best Answer

This is similar to @egreg's solution and avoids \ifcase in favour of just cycling the list, but the coding is probably a bit simpler (unless you'be already loaded expl3 for other reasons)

\documentclass{article}
\usepackage{xcolor}
\def\ColorList#1{\def\xcolorlist{#1}}
\let\xsection\section
\def\section{\expandafter\xxcycle\xcolorlist,\xcolorlist\xsection}
\def\xxcycle#1,#2{%
  \ifx\relax#1\relax\else
   \color{#1}%
   \ifx\xcolorlist#2\else
    \xcycle#1,#2%
   \fi
  \fi}


\def\xcycle#1,#2\fi\fi#3\xcolorlist{\fi\fi\ColorList{#2#3#1}}



\ColorList{yellow,magenta,cyan,orange,blue,green!30,red!50!black}
%\ColorList{yellow}
%\ColorList{}

\begin{document}

\section{Title}
\section{Title}
\section{Title}
\section{Title}
\section{Title}
\section{Title}
\section{Title}
\section{Title}
\section{Title}

\end{document}