# Correct counting of paragraph number is header/footer

I want to \usepackage{fancyhdr} to list paragraph numbers in the header/footer of a document. Most of the time this works fine but when a new page starts with a paragraph, the number is also listed on the previous page. In the below screenshot this shows on page 8: paragraphs 12-16 are listed but only paragraphs 12-15 actually appear on the page. Any ideas on how to fix this problem?

This is the MWE:

\documentclass{book}
\usepackage{lipsum}
\setlipsumdefault{1}
\usepackage{titlesec}

% fancy headings as defined by the OP except we need to be more careful
\usepackage{fancyhdr}
\fancypagestyle{plain}{% need to reset \firstpara on pages without headers
\fancyhf{} % clear all header and footer fields
\fancyfoot[C]{\bfseries \thepage}
\xdef\firstpara{\lastpara}
}
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\sectionmark}[1]{%
\markright{#1}%
\def\firstpara{1}\def\lastpara{1}% reset counters each section
}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}

\newcommand{\sectionbreak}{\clearpage\thispagestyle{plain}}
\renewcommand\thesection{\arabic{section}}

% now the macros for tracking the paragraph numbers
\def\firstpara{1}%    set to 1 by default
\def\lastpara{1}% set to 1 by default
\def\setparagraph#1-#2-#3|{%
% if \firstpara=0 => new page => set \firstpara
\ifnum\firstpara=0\def\firstpara{#1}\fi%
% if #2=0 => only #1 is meaningful to set \lastpara to this
% otherwise use #2
\ifnum#2=0\def\lastpara{#1}\else\def\lastpara{#2}\fi%
}
\def\paragraph#1{\textbf{#1}\space%
\setparagraph#1-0-|%
}
\def\theparagraph{%
% if \firstpara=\lastpara print only \firstpara otherwise print a range
\ifnum\firstpara=\lastpara\firstpara\else\firstpara--\lastpara\fi
% reset firstpara and lastpara
\xdef\firstpara{\lastpara}%
%\let\lastpara\relax%
}

% back to the MWe
\begin{document}

\null
\pagestyle{empty}

\newpage

\newpage

\pagestyle{fancy}

\chapter{A Chapter}

\section{First Section}

\paragraph{1}\lipsum

\paragraph{2}\lipsum

\paragraph{3-5}\lipsum

\paragraph{6}\lipsum

\paragraph{7-17}\lipsum

\paragraph{18}\lipsum

\section{Second Section}

\paragraph{1}\lipsum

\paragraph{2}\lipsum

\paragraph{3}\lipsum

\paragraph{4}\lipsum

\paragraph{5}\lipsum

\paragraph{6}\lipsum

\paragraph{7}\lipsum

\paragraph{8}\lipsum

\paragraph{9}\lipsum

\paragraph{10}\lipsum

\paragraph{11}\lipsum

\paragraph{12}\lipsum

\paragraph{13}\lipsum

\paragraph{14}\lipsum

\paragraph{15}\lipsum

Just another paragraph withou number.

\paragraph{16}\lipsum

\paragraph{17}\lipsum

\paragraph{18}\lipsum

\paragraph{19}\lipsum

\paragraph{20}\lipsum

\end{document}

• Don't use fancyhdr for this. Look instead at titleps. You can do it with the former, but the latter will be a whole lot easier. (Or if you are using KOMA or Memoir, you may be able to use their facilities instead.) – cfr Dec 8 '15 at 0:32
• – cfr Dec 8 '15 at 0:37