[Tex/LaTex] Defining a New \pagestyle Using Fancyhdr


Using the fancyhdr package, the code below does exactly what I want for my headers and footers. I use the empty pagestyle, redefine the plain pagestyle, and define a fancy pagestyle.

There is something about the way you define the fancy pagestyle that bothers me (no brackets indicating the beginning and end of the definition). So, as an experiment, I used \fancypagestyle to define a MyFancy pagestyle that is identical to the fancy pagestyle. From this answer, I thought I was on the right track.

However, in the \frontmatter section below, if you comment out \pagestyle{fancy} and uncomment \pagestyle{MyFancy}, the results are different. In the \mainmatter, you no longer get the chapter information where it was expected to be in the footer (i.e., it was expected to be on all non-empty pages that were not the first page of a chapter). No doubt I am missing something obvious, but I am stumped.

Question: What changed are needed to my code so I can use the MyFancy pagestyle as a replacement for the fancy pagestyle?


\title{Some Book Name}
\author{Henry A. Smith}

\fancyfoot[RO, LE] {Page \thepage}
\makeatletter\fancyfoot[CE,CO]{\if@mainmatter \leftmark\fi}\makeatother

    \fancyfoot[RO, LE] {Page \thepage}}

    \fancyfoot[RO, LE] {Page \thepage}%
    \makeatletter\fancyfoot[CE,CO]{\if@mainmatter \leftmark\fi}\makeatother}


Copyright 2018, Henry A. Smith
\pagestyle{fancy}    % COMMENT THIS OUT
%\pagestyle{MyFancy} % UNCOMMENT THIS

\chapter{The First Chapter}
\chapter{The Second Chapter}

\chapter{BackMatter Chapter}


Best Answer

unrelated to fancyhdr

{\makeatletter\fancyfoot[CE,CO]{\if@mainmatter \leftmark\fi}\makeatother} 

can not work, move the \make... out of the argument and just have one \makeatletter and one \makeatother around all the definitions that need @ in your preamble.

The reason it can not work is the same as the reason \verb does not work in an argument of another command. As you have it the argument is scanned while @ is not a letter so the argument is the same as

{\makeatletter\fancyfoot[CE,CO]{\if @mainmatter \leftmark\fi}\makeatother}

the \makeatletter is not executed until this argument is used and by then it is too late catcode changes have no effect on already tokenised text, they just affect the tokens that are created when characters are read from a file.