Get the LaTeX chapter name and section name on the document header

Wow, this was a tough LaTeX problem, and it would really help if I knew a lot more about LaTeX.

My goal for a LaTeX PDF that I created recently was to get the header of my pages to look something like this:

Section Name (Chapter Name)

where “Section Name” and “Chapter Name” are left-aligned in the header of the page, and would be dynamically replaced by the actual values of the current section and chapter names, respectively.

I was driven by the fact that this was a very complicated technical document, and I wanted the users to be able to look at the header of their current page and easily identify the chapter and section they were currently in. This may seem like overkill, but I found it to be exceptionally useful, and the readers really liked it.

Solution

To enable this capability, all I had to do (hah!) was use the following code segment at the beginning of my LaTeX document. (Of course it took me 30 minutes to figure this out, and I was yelling and screaming the entire time.)

  \lhead{\nouppercase{\rightmark} (\nouppercase{\leftmark})}
  \chead{}
  \rhead{}
  \lfoot{\today}
  \cfoot{}
  \rfoot{\thepage}
  \renewcommand{\headrulewidth}{0.4pt}
  \renewcommand{\footrulewidth}{0.4pt}

  \renewcommand{\chaptermark}[1]{%
  \markboth{#1}{}}

As I wrote, I wish I knew more about LaTeX so I could explain this well, but alas, I do not. I can tell you that the important pieces are the \rightmark (section), \leftmark (chapter), and \renewcommand{\chaptermark} commands, and that I generated my LaTeX PDF document with the pdflatex command.

The \renewcommand{\chaptermark} portion of the code is especially important in getting the "Chapter" and chapter number out of the chapter text that appears in the header. If that doesn't make any sense, try commenting out these two lines of code, and then see what the resulting output looks like.

I forgot to mention it, but you can find out a lot more about this subject by reading the "fancyhdr" document, fancyhdr.pdf. It is available by searching at the tug.org web site.