[Tex/LaTex] \thispagestyle and \pagestyle with packages fancyhdr and extramarks causes confusion

fancyhdrheader-footer

I am writing a scientific article using the article class. I have encountered some issues with my page headings that I have defined through the packages "fancyhdr" and "extramarks". I have 3 pagestyles: (1) "ttlpage" is used for the first page of the document only, (2) "simple" is used for the table of contents only and (3) "main" is used for the rest of the article document. See my code below.

\documentclass[twoside]{article}

\usepackage{fancyhdr}
\usepackage{extramarks}

\setlength{\headheight}{14pt}

\fancypagestyle{ttlpage}{
  \fancyhf{}
  \fancyhead[L]{First page head}
}

\fancypagestyle{simple}{
  \fancyhf{}
  \fancyhead[LE, RO]{\thepage}
}

\fancypagestyle{main}{
  \fancyhf{}
  \fancyhead[LE, RO]{\thepage}
  \fancyhead[LO]{\firstleftmark}
  \fancyhead[RE]{\lastrightmark}
}

\begin{document}

\thispagestyle{ttlpage} % Causes problems.
%\pagestyle{ttlpage} % Works fine.
first page
\newpage

\pagestyle{empty} % With \thispagestyle above, causes missing \firstleftmark              and \lastrightmark
%\pagestyle{simple} % With \thispagestyle above, causes "CONTENTS" to be   printed instead of "INTRODUCTION",
\tableofcontents
\newpage

\pagestyle{main}
\section{Introduction}
\subsection{Foo}

\end{document}

If I use \thispagestyle{ttlpage} for the first page and then \pagestyle{simple} before \tableofcontents and \pagestyle{main} before the first section then \firstleftmark and \lastrightmark will print "Contents" in the headers of the following pages in the document, which is not what I want.
If I change \pagestyle{simple} to \pagestyle{empty} \fristleftmark and \lastrightmark will print nothing.

I managed to solve the problem by changing \thispagestyle{ttlpage} to \pagestyle{ttlpage}.
I don't see why this would solve the problem and I would really like to know why there is a difference.

Best Answer

As in John Kormylo's comment you need to issue some \pagestyle command before \begin{document}. Following the fancyhdr documentation this would be \pagestyle{fancy}, but any other of your defined styles would also do.

Below is an illustration with \pagestyle{fancy} showing a corrected header on the introduction page..

Sample output

\documentclass[twoside]{article}

\usepackage{fancyhdr}
\usepackage{extramarks}

\setlength{\headheight}{14pt}

\fancypagestyle{ttlpage}{
  \fancyhf{}
  \fancyhead[L]{First page head}
}

\fancypagestyle{simple}{
  \fancyhf{}
  \fancyhead[LE, RO]{\thepage}
}

\fancypagestyle{main}{
  \fancyhf{}
  \fancyhead[LE, RO]{\thepage}
  \fancyhead[LO]{\firstleftmark}
  \fancyhead[RE]{\lastrightmark}
}

\pagestyle{fancy}

\begin{document}

\thispagestyle{ttlpage}

first page
\newpage

\pagestyle{simple} 
\tableofcontents
\newpage

\pagestyle{main}
\section{Introduction}
\subsection{Foo}

\end{document}