# Fancyhdr and \thesection command

I have a problem with \thechapter implementation in fancyhdr package. As you can see in the photo I attached at the bottom of the post, the section number (RO) and its title (LO) don't match at the header: it should say "Propietats bàsiques de la divisibilitat" and then "1.3", or "Equacions diofantines lineals" and then "1.4". If I had to choose, I would prefer the latter (I think it's more complex to achieve, though). My pagestyle{fancy} config is the following:

% Header
\pagestyle{fancy}
\fancyfoot[RO, LE]{\thepage}
\fancyfoot[CO, CE]{}
\renewcommand{\chaptermark}[1]{\markboth{ #1}{}}
\renewcommand{\sectionmark}[1]{\markright{ #1}}


If it can be of any help, I am working on a book, twoside environment.

\documentclass[a4paper,12pt,twoside]{book}


• You should never use \thesection in your header or footer. That kind of running information must be communicated via marks. It could happen that the information is used, but then the text that produces this information is pushed to the next page. That is not the case here, because here there is another problem: if there is more than one section on the page, \thesection has the value of the last section on the page (or one pushed over to the next page). So you must get it from the \firstmark or something similar. I'll try to make a working solution for you. Mar 2 at 14:01

As I stated in my comment, the section number \thesection must be communicated through a mark (for \thechapter this isn't necessary as chapters always start at a new page). But normal LaTeX doesn't have an extra mark for this section number, so I use the extramarks package with the \extramarks command and \firstrightxmark and \firstleftxmark.

\documentclass{book}

\usepackage{fancyhdr}
\usepackage{extramarks}
\usepackage{lipsum}

\pagestyle{fancy}
\fancyfoot[RO, LE]{\thepage}
\fancyfoot[CO, CE]{}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\extramarks{\thesection}{#1}}

\begin{document}
\chapter{First Chapter}

\lipsum

\newpage

\section{First section}

\lipsum[1]

\section{Second section}

\lipsum[2]

\end{document}

• Maybe \renewcommand{\chaptermark}[1]{\markboth{#1}{}\extramarks{}{}} to reset the extramarks when a new chapter starts? Additionally you could mention \lastrightxmark and \lastleftxmark because the OP seems to prefer them.
– esdd
Mar 2 at 15:20
• @esdd You are right Mar 2 at 21:34

A workaround which redefines \sectionmark to use only the left header of odd pages:

\renewcommand{\sectionmark}[1]{\markright{#1\hfill \thesection}}


### MWE

\documentclass[a4paper,12pt,twoside]{book}
\usepackage{lipsum}
\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{\thechapter\hfill #1}{}}
\renewcommand{\sectionmark}[1]{\markright{#1\hfill \thesection}}
\fancyhf{}