8

I want to use multiple fancyheader styles in my document. I've run into a problem that seems to be a bug to me. The code below doesn't compile with latex; it seems stuck in an infinite loop.

\documentclass{book}

\usepackage{lipsum}

\usepackage{fancyhdr}

\fancypagestyle{fancy}{%
  \fancyhf{}
  \fancyhead[C]{fancy \thepage}
  \fancyfoot{}
}

\fancypagestyle{tocstyle}{%
  \fancyhf{}
  \renewcommand{\headrulewidth}{0pt}
  \fancyfoot[C]{\footnotesize{TOC \thepage}}
}

\begin{document}

\frontmatter
\pagestyle{tocstyle}

\tableofcontents

\mainmatter
\pagestyle{fancy}

\chapter{Intro}

\lipsum

\end{document}

If I replace the fancyheader style fancy by anything else, e.g. fancy1, then everything does work as expected.

1 Answer 1

10

The package fancyhdr works essentially applying \pagestyle{fancy} everywhere (unless an already defined page style is declared). Thus, after

\fancypagestyle{foo}{...}

any declaration \pagestyle{foo} will really be translated into \pagestyle{fancy} with the values for the fields as stated in the previous definition of foo.

Therefore you can't say \fancypagestyle{fancy}{...}, but are free to use any other name you want, including those of other predefined styles.

I suggest you

\documentclass{book}

\usepackage{lipsum}

\usepackage{fancyhdr}

\fancypagestyle{main}{%
  \fancyhf{}
  \fancyhead[C]{fancy \thepage}
  \fancyfoot{}
}

\fancypagestyle{front}{%
  \fancyhf{}
  \renewcommand{\headrulewidth}{0pt}
  \fancyfoot[C]{\footnotesize{TOC \thepage}}
}

\begin{document}

\frontmatter
\pagestyle{front}

\tableofcontents

\mainmatter
\pagestyle{main}

\chapter{Intro}

\lipsum

\end{document}
2
  • 1
    Thanks, this clarifies the (to me) unexpected behaviour. I also found that when defining extra styles like this, switching back to \pagestyle{fancy} will use the settings of style foo last used, and not the default settings declared outside of any \fancypagestyle{foo}. Commented Feb 11, 2012 at 10:19
  • Thanks. This had me scratching my head for a while – it's not very clear in the documentation for fancyhdr. Commented Aug 19, 2015 at 9:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .