正确计算段落数是页眉/页脚

正确计算段落数是页眉/页脚

我想\usepackage{fancyhdr}在文档的页眉/页脚中列出段落编号。大多数情况下,这种方法都行得通,但是当新页面以段落开头时,上一页也会列出该编号。下面的屏幕截图显示第 8 页:列出了第 12-16 段,但实际上只有第 12-15 段出现在页面上。有什么办法可以解决这个问题吗?

在此处输入图片描述

这是 MWE:

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

% fancy headings as defined by the OP except we need to be more careful
% with plain headings
\usepackage{fancyhdr}
\fancypagestyle{plain}{% need to reset \firstpara on pages without headers
  \fancyhf{} % clear all header and footer fields
  \renewcommand{\headrulewidth}{0pt}
  \fancyfoot[C]{\bfseries \thepage}
  \xdef\firstpara{\lastpara}
}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[LE,RO]{\thepage}
\fancyhead[CO]{\rightmark}
\renewcommand{\sectionmark}[1]{%
   \markright{#1}%
   \def\firstpara{1}\def\lastpara{1}% reset counters each section
}
\fancyhead[CE]{\leftmark}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\fancyhead[LO,RE]{\thesection.\theparagraph}

\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}

相关内容