[Tex/LaTex] Difficult with fancyhdr and table of contents

fancyhdrtable of contents

Premise: I'm new with fancyhdr.
I defined the following fancy style:

\lhead{}
\chead{\slshape\leftmark}
\rhead{}
\lfoot{}
\cfoot{\thepage}
\rfoot{}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}

which correctly draw the chapter number and name, top line, the bottom line, and the page number, in all the page except the first of each chapter.

So, I redefined the plain style in the following way:

\fancypagestyle{plain}{
\lhead{}
\chead{}
\rhead{}
\lfoot{}
\cfoot{\thepage}
\rfoot{}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0.4pt}}

which correctly draw the top line, the bottom line, and the page number in the first page of each chapter (note: the plain style miss the chapter number and name of the fancy style)

Now, I have a problem with the table of contents.
The first page of the toc has the plain style (without the chapter number and name), but the following pages have the fancy style (with chapter number and name).
How can I apply the plain style to ALL the page of the toc?

Best Answer

Since you're using the book class, I presume that everything in the front matter is intended to be under the plain pagestyle:

\documentclass[a4paper,oneside]{book}
\usepackage{fancyhdr}
\usepackage{etoolbox}
\usepackage{lipsum} % just for the example

\pagestyle{fancy}
\fancypagestyle{main}{%
  \fancyhf{}%
  \fancyhead[C]{\slshape\leftmark}%
  \fancyfoot[C]{\thepage}%
  \renewcommand{\headrulewidth}{0.4pt}%
  \renewcommand{\footrulewidth}{0.4pt}%
}
\fancypagestyle{plain}{%
  \fancyhf{}%
  \fancyfoot[C]{\thepage}%
  \renewcommand{\headrulewidth}{0pt}%
  \renewcommand{\footrulewidth}{0.4pt}%
}

\appto\frontmatter{\pagestyle{plain}}
\appto\mainmatter{\pagestyle{main}}

\begin{document}

\frontmatter
\tableofcontents

\mainmatter

%%% fill with some mock text
\def\testsec{\section{B}\lipsum}
\def\test{\chapter{A}
  \testsec
  \testsec
  \testsec
  \testsec
  \testsec
  \testsec
  \testsec
  \testsec
  \testsec
  \testsec
}
\test
\test
\test
\test
\test
\test
\test
\test
\end{document}

However, I'd recommend against the footrule.