[Tex/LaTex] latex fancyhdr: is possible to use leftmark and rightmark alternatively

fancyhdrheader-footer

I'm using this code to customize the header layout:

\pagestyle{fancy}
\fancyhead{}
\fancyfoot{}
\lhead{\nouppercase{\rightmark}}
\rhead{\thepage}

I would like to have the section name in the top left of every page, in the form of “1.1 section”, and this is possible using \rightmark. But, like mentioned in the fancyhdr documentation, "on the first page of a chapter (or a section in article style) the \rightmark will be empty". So, when \rightmark is empty I would like have printed the chapter name like “Chapter 1. Intro” instead of the section name, and this is possible using \leftmark. So my question is: can I use such an "else condition" in order to use \leftmark if \rightmark is empty, and to use \rightmark otherwise? Something like:

empty(\rightmark) ? \leftmark : \rightmark

Thanks in advance.

Best Answer

You can test if the \rightmark is empty by fully expanding it; the command \rightorleftmark will do what you want (uncomment the \section line to see the difference).

\documentclass{book}

\usepackage{fancyhdr}
\pagestyle{fancy}

\fancyhf{}
\lhead{\nouppercase{\rightorleftmark}}
\rhead{\thepage}

\makeatletter
\newcommand{\rightorleftmark}{%
  \begingroup\protected@edef\x{\rightmark}%
  \ifx\x\@empty
    \endgroup\leftmark
  \else
    \endgroup\rightmark
  \fi}
\makeatother

\begin{document}
\mainmatter
\chapter{A}
%\section{B}
abc\newpage
def\newpage
\end{document}