阶段 4 · 结构与交叉引用 32 / 48 ≈ 16 分钟读完

LaTeX 页眉页脚:fancyhdr 六格、页码与章首页样式

页面这套家具是输出例行程序搭起来的,位置不在你敲字的地方:所以页眉只能靠标记取信息,headheight 必须在使用之前先声明,章的首页也永远留着另一套样式。这一课把从纸顶到纸底的那条纵向叠层一个槽一个槽拆开,顺带说清 twoside 版式下奇偶页镜像、空白页与页码落点的规矩。

    一页是若干条带的叠层,只有中间那条是你的正文

    从纸的顶端往下数,\textheight 之上还压着三条长度,外加 TeX 自己塞进去的那一条。先是没法取消的 1 英寸——它是 TeX 原语层的固定偏移,「上边距」在 LaTeX 手册里从来不等于你尺子量出的那个数,原因就在这里;接着是 \voffset 加 \topmargin,两者把你送到页眉盒的顶边;然后是 \headheight,即这个盒子被声明出来的高度;再往下是 \headsep,也就是页眉底线与第一条正文基线之间的空隙。正文底下先轮到 \skip\footins 和脚注插入物,最后是 \footskip——它量到页脚第一行的基线为止,而不是页脚的顶端。

    最常写错的恰恰是 \headheight 和 \footskip 这两个数。\headheight 表达的不是「我想留多大地方」,而是输出例行程序直接采信的一句声明。页眉内容比声明值高时,TeX 不会把页面重切一遍,它让页眉压到正文上,然后在日志里知会你一声。\footskip 给小了,页脚就被推进脚注区;脚注一多,碰撞就在那里显形。

    整套尺寸都交给 geometry 去算,让它顺手把 \textheight 维持一致:\usepackage[a4paper,top=2.5cm,bottom=2.8cm,headheight=15pt,headsep=14pt,footskip=26pt]{geometry}。等类把页面算完之后再用 \setlength 手工调,是可行的,早年的类就是这么伺候出来的;代价是你必须在同一次改动里把 \textheight、\vsize 和上边距一起修好,而这道算术题正是 geometry 存在的理由。

    V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
    V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
    Page geometry: the vertical band stack that carries a header and a footer, and the headwidth a header rule is drawn to THE VERTICAL STACK, TOP OF THE PAPER TO BOTTOM 1in + \voffset + \topmargin (TeX adds the inch itself) \headheight - declared, not measured \headsep \textheight a footnote mark sits in the line; \skip\footins footnote rule, then the notes (an insertion: it is part of the page, not the text) \footskip - measured to the BASELINE of this line the bottom margin that is left over; a footer taller than \footskip reaches into it, and a footer with two lines needs \footskip raised as well headheight headsep textheight footskip HORIZONTAL: THE RULE SPANS headwidth text block = \textwidth \headwidth (fancyheadoffset extends it) L offset R offset the rule is an \hbox to\headwidth, so changing \textwidth without reloading geometry leaves a short rule HOW TO SET IT \usepackage[a4paper,top=2.5cm,bottom=2.8cm, headheight=15pt,headsep=14pt,footskip=26pt]{geometry} geometry keeps textheight consistent with the bands you asked for. \setlength{\headheight}{15pt} % legal, but recompute textheight yourself fancyhdr prints the value it measured - use exactly that number, then recompile: a taller band moves every page break below it, and can raise a new requirement TeX always starts the text 1 inch plus \voffset plus \topmargin below the top edge of the paper, which is why a hand-set \topmargin looks wrong and why geometry's top= is measured from the text block, not the header.
    从纸边到纸边的整条叠层:headheight 与 footskip 是声明,不是愿望。

    样式模型:pagestyle 管全局,thispagestyle 管一页

    页面家具在 LaTeX 里是两份状态。\pagestyle{X} 定下从此刻起每一页用什么样式,\thispagestyle{Y} 只覆盖当前这一页,而且这一页一输出它就作废。内置样式四个:empty(什么都不放)、plain(页码居中放在页脚,标准类的默认值)、headings(两行由标记拼成、不带横线的运行标题)与 myheadings(同样的架子,内容换成你自己写的 \markboth)。

    由此挤出的冲突,就是关于首页提问最多的那一个。凡是开启一个单元的指令都会自己来一句 \thispagestyle:\maketitle 用 plain,\chapter 用 plain,\part 与 \tableofcontents 同样如此,\cleardoublepage 则给它可能插进来的那张空白反页设 empty。所以 \thispagestyle{empty} 必须写在 \maketitle 之后,写在前面只会让后一句赢;而要让每一章第一页都不出现页码,正确做法不是和逐页调用对打,而是把它点名的那个样式改掉——这正是 \fancypagestyle{plain}{...} 的用途。

    自己排标题页、把它裹进 titlepage 环境时,规则一模一样:紧跟在 \begin{titlepage} 后面写 \thispagestyle{empty}。该环境收尾时就把这一页送出去了,而家具是在那一刻按它最后读到的那句调用定下来的。

    就算还没上 fancyhdr,headings 这个样式也值得先看一眼,因为它把运行标题的原料摊开了给你看:偶数页读 \leftmark,奇数页读 \rightmark,除标记之外一无所有。后面几节要拆的机制,全都从这里长出来。

    fancyhdr:六个槽位,以及「三段并排」这个模型

    fancyhdr 把页眉与页脚各换成一排三个盒子,于是有了六个槽位:\fancyhead[L]、\fancyhead[C]、\fancyhead[R],以及 \fancyfoot[L]、[C]、[R]。每次配置都从 \fancyhf{} 起手,它把六个槽一次清空;省掉这一句,你就继承了上一个定义留下的残局。整排是由一个 \hbox 排出来的,所以中间槽空着不改变任何东西,而左槽一旦超宽就会把中间那个挤离轴线——它的心智模型是「三段并排」,不是「三个能各自定位的独立盒子」。

    双面文档里每个槽都翻倍,选择参数决定哪一面拿到什么:E 偶数页、O 奇数页、L 左手页、R 右手页、C 两面都要。\fancyhead[LE,RO]{\thepage} 是经典的外侧页码;\fancyhead[RE]{\leftmark}\fancyhead[LO]{\rightmark} 是经典的镜像运行标题,反页放章名、正页放节名。别写了 \fancyhead[L] 就以为它指「左页」,它指的就是槽位的左边——镜像页眉调不出想要的效果,多数是卡在这一个区别上。

    实现细节里有三条会在普通文档里露头。空槽仍然是个盒子:fancyhdr 会往里补一个 \strut 等价物好让整排有高度,这就是「页眉什么都不放」依然需要一个非零 \headheight 的原因。页眉底下那条线是 \headrule,它按 \headwidth 画,而不是按 \textwidth;粗细由 \headrulewidth 给出,设成 0pt 线就没了,再配一句 \renewcommand{\footrulewidth}{0.4pt} 页脚上方就多出对称的那条。而 \headwidth 可以用 \fancyheadoffset 朝切口方向外扩——想让横线铺满整个版面宽度、让页眉伸进边注盒,走的就是这条路。

    要给那条线染色,别拿 \textcolor 去包它,而是把线本身重定义掉,因为它本来就是 \hbox to\headwidth{\leaders\hrule ...} 这么个东西:\renewcommand{\headrule}{\hbox to\headwidth{\color{accent}\leaders\hrule height \headrulewidth\hfill}}。想要双线也是同一招,在盒子里放两条高度不同的 \hrule 即可。

    w_{\text{rule}} = \text{headwidth} = \text{textwidth} + l_{\text{offset}} + r_{\text{offset}}
    w_{\text{rule}} = \text{headwidth} = \text{textwidth} + l_{\text{offset}} + r_{\text{offset}}
    fancyhdr slot model: three boxes per row, doubled by page selector for even and odd pages of a twoside document EVEN (LEFT-HAND) PAGE LE \leftmark CE RE \thepage \headrule, drawn to \headwidth LF CF \today RF ODD (RIGHT-HAND) PAGE LO \rightmark CO RO same row, mirrored content LF CO RF \thepage THE SELECTOR ARGUMENT E even O odd L lefthand R righthand C both [LE,RO] -> folio at the outer top of a twoside book [RE,LO] -> chapter on the verso, section on the recto [L] alone fills the LEFT SLOT on every page, which in a twoside layout is not "left page" - the usual misread \fancyhf{} clears all six; do it before you fill any MECHANICS THAT SHOW UP AS BUGS An empty slot is still a box: fancyhdr keeps a strut in it, so \headheight must be non-zero even with no content. The row is one \hbox, so a wide left box pushes the centre box off the middle of the page - the classic crooked header. \headrulewidth 0pt removes the rule; \footrulewidth adds one. \nouppercase undoes the \MakeUppercase the class put into the mark - the standard classes, not fancyhdr, do that. \fancypagestyle{plain}{...} restyles chapter first pages.
    每页六个具名槽位,双面文档再翻一倍:选择字母决定哪一面的哪个槽填什么。
    \documentclass[11pt,a4paper]{article}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    % headheight must be big enough for what the header holds; geometry then
    % keeps \textheight consistent with the rest of the page.
    \usepackage[a4paper,top=2.5cm,bottom=2.8cm,left=3cm,right=3cm,
                headheight=15pt,headsep=14pt,footskip=26pt]{geometry}
    \usepackage{xcolor}
    \usepackage{lastpage}       % \pageref{LastPage} for "of 12"
    \usepackage{fancyhdr}
    
    \pagestyle{fancy}
    \fancyhf{}                                % clear all six slots first
    \fancyhead[L]{\small\nouppercase{\leftmark}}
    \fancyhead[R]{\small\itshape A. Student}
    \fancyfoot[C]{\small\thepage\ of \pageref{LastPage}}
    
    \renewcommand{\headrulewidth}{0.4pt}
    \renewcommand{\footrulewidth}{0pt}
    \renewcommand{\headrule}{%
      \hbox to\headwidth{\color{blue!60!black}\leaders\hrule height \headrulewidth\hfill}}
    \setlength{\headwidth}{\textwidth}
    
    \title{Headers and footers, concretely}
    \author{A. Student}
    
    \begin{document}
    \maketitle                      % \maketitle issues its own \thispagestyle{plain}
    \thispagestyle{empty}           % so the override goes AFTER it, never before
    
    \section{Definitions}
    Because the section title is put into the left mark by the class, the header of
    this page reads \emph{Definitions}. A running head has to be produced from a
    mark, not from the heading command itself: the header is typeset when the page
    is shipped out, long after the heading was seen.
    
    \begin{equation}
      \label{eq:cauchy}
      \int_{\gamma} f(z)\,dz = 0
    \end{equation}
    Equation \eqref{eq:cauchy} is unaffected by any of the above, which is the point:
    page furniture and content are laid out by different mechanisms.
    
    \section{Further remarks}
    A two-line header needs a larger \verb|headheight|: ask geometry for
    \verb|headheight=26pt| instead of ignoring the warning, and recompile, because
    the taller band moves every page break below it.
    \end{document}

    headheight 太小的警告,以及该拿它怎么办

    那条警告的原话大致是 Package fancyhdr Warning: \headheight is too small (12.0 pt),后面附上它实测到的页眉尺寸和一个建议值。它不是装饰性提示。fancyhdr 会算出你那个页眉盒的自然高度,再与被声明的 \headheight 比一比;若声明值更小,它没法把页眉塞进去——页面早就切好了,于是盒子溢出到第一行正文上,而日志是唯一留下证据的地方。

    修要修在声明的源头,顺序照你排版面的方式来。用 geometry 就补一个 headheight=15pt(或警告里打出来的那个值);用裸的 \setlength 就在导言区写 \setlength{\headheight}{15pt},同时记住改它不会自动重算 \textheight,正文因此会往下多占一截。然后重新编译:页眉高度一动,紧邻 \textheight 的材料跟着动,断页就移;断页一移标记就变,页眉宽度也可能再变,于是警告带着一个新数字回来。

    起因永远是四种之一。页眉里出现 \frac 或任何近似行间公式的材料,其高度远超一行正文——把式子压成 \scriptstyle,或者塞进 \mbox{} 再加一个 \footnotesize。两行的页眉,需要的高度大致翻倍,所以论文里那种叠两层的页眉常常一上来就声明 26pt 以上。页眉里放了 \includegraphics 的刊徽。以及类在 12pt 下把 \headheight 设得偏小,标准类就常干这件事。

    相关而且同样真实的:若 geometry 这类宏包在 fancyhdr 读过之后又改文本块,fancyhdr 还会为 headwidth 报警,说它被覆写了;页脚加上 \footskip 掉出页面之外时,又会报页脚线一类的碰撞。两样都是同一个药方:先载 geometry 并把所有取值一次定死,再载 fancyhdr,之后两个长度都不再手工去碰。

    标记:页眉是怎么知道你读到哪儿了

    页眉没法问「我在哪一节」——轮到它被排版时,那条文题命令早就过去了,页面也已经被输出例行程序切完。机制叫标记:\markboth{left text}{right text} 在被调用的位置往垂直表里塞一张便条,输出例行程序在送出这一页时把页上的便条读出来。标准类替你调好了——\section 发出 \sectionmark{...},而后者就是 \markboth{...}{...}——运行标题的文字正是这么来的。

    取用这一半才是糊的地方,内核文档对此说得非常死:\leftmark 给出这一页上最后一个左标记,\rightmark 给出第一个右标记。这种不对称是故意的——翻进某章的那一面显示章名,进入某节的那一面显示节名——也正是页眉看起来有时「落后一节」有时又「抢先一节」的原因,取决于你用的哪个槽。同族还有 \topmark(页面顶部时刻的标记)、\firstmark 与 \botmark。

    2020 年的标记更新之后,LaTeX 会为每个标记类分别保存首值与末值,缺的那几种组合就此补齐。\markboth 与 \markright 所用的类名叫 2e-left、2e-right 和 2e-right-nonempty,通用读取器则是 \TopMark{class}、\FirstMark{class} 与 \LastMark{class}——于是 \LastMark{2e-right} 给你页面上最后那一节,而「你正在阅读 X」式页眉要的恰恰是它。自定义标记走 \NewMarkClass{status} 加 \InsertMark{status}{text};手册里还有一句要紧提醒:读标记只在输出例行程序内部才有意义,而且单面文档下标准类只设右标记,所以 \leftmark 空着是设计如此。

    标记带来的两个常见麻烦,都是一行能修的。大小写:标准类在写入标记时就套了 \MakeUppercase,fancyhdr 提供 \nouppercase 让你在槽里把它撤掉,所以惯用写法长成 \fancyhead[RE]{\nouppercase{\leftmark}}。带重音或带数学的文题:标记存的是排版后的形态,所以标题里有 \texorpdfstring 或 \footnote 时就得用上短的可选参数——\section[Plain form]{Pretty form}——否则页眉里会多出你根本不想要的零件。

    \text{leftmark} = \text{last left mark on the page}, \qquad \text{rightmark} = \text{first right mark on the page}
    \text{leftmark} = \text{last left mark on the page}, \qquad \text{rightmark} = \text{first right mark on the page}
    How a running head is produced: a mark is dropped into the vertical list where the heading is typeset and read back by the output routine when the page is cut STEP 1 - THE HEADING DROPS A MARK INTO THE TEXT \section{Modules} the class runs \sectionmark{Modules} \markboth{Modules}{Modules} left class -> even pages right class -> odd pages the mark is not typeset: it is a note left in the vertical list STEP 2 - THE PAGE IS CUT, AND THE ROUTINE READS THE NOTES material collected for this page: mark: "Modules" (first on page) mark: "Ideals" (last on page) \topmark what was current at the top \FirstMark{class} \LastMark{class} \leftmark = LAST left, \rightmark = FIRST right the kernel documents that asymmetry; it is not a bug STEP 3 - THE SLOTS CONSUME THE VALUES \fancyhead[RE]{\nouppercase{\leftmark}} \fancyhead[LO]{\nouppercase{\rightmark}} the header box is built inside the output routine, which is why only marks can drive it - not a counter and not "the last \section" \FirstMark{2e-left} \LastMark{2e-right} THREE CASES THAT LOOK LIKE BROKEN HEADERS unnumbered heading \section*{Acknowledgements} sets no mark at all, so the head still shows the previous section. fix: \markboth{...}{...} by hand, then \addcontentsline for the TOC heading at the very top of a page a section that begins the page is both the first and the last mark - so \rightmark reads the NEW title while \leftmark-style reading of the previous one is what you expected. try \TopMark{2e-right} chapter opening page \chapter issues \thispagestyle{plain}, so no header appears however correct the mark is. fix once for the whole document: \fancypagestyle{plain}{\fancyhf{} \fancyfoot[C]{\thepage}\renewcommand... Why marks rather than state The header of page 40 is typeset after page 40 is full and while the rest of the document is still unread, so it can only ask what notes the material on that page left behind. That is also why a header change alters pagination, and pagination is why the marks resolve differently on the next run - compile twice before trusting a running head.
    标记在文题被排版的那一刻落下;页眉要等页面被切出时才组装,并按槽位去读首个或末个标记。
    \documentclass[11pt,a4paper]{report}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[a4paper,margin=2.5cm,headheight=26pt,headsep=16pt]{geometry}
    \usepackage{fancyhdr}
    
    \pagestyle{fancy}
    \fancyhf{}
    \fancyhead[L]{%
      \begin{minipage}[t]{.55\headwidth}\raggedright\footnotesize
        \firstleftmark\\[1pt]
        \footnotesize\itshape second line of the header, from a mark of its own
      \end{minipage}%
    }%
    \fancyhead[R]{\footnotesize\thepage}
    \renewcommand{\headrulewidth}{0.4pt}
    
    \makeatletter
    % Two-sided behaviour of \markboth: left part -> even pages, right -> odd.
    % \leftmark reads the LAST left mark of the page, \rightmark the FIRST right mark.
    \newcommand{\firstleftmark}{\FirstMark{2e-left}}
    \makeatother
    
    \begin{document}
    \chapter{Marked material}\label{ch:one}
    
    \section*{A section that is not numbered}
    % Unnumbered headings set no mark, so the running head must be written by hand:
    \markboth{Appendix: unnumbered material}{}
    \addcontentsline{toc}{section}{Unnumbered material}
    The header on the following pages now reads from the mark we set manually.
    
    \section{Numbered from here}
    \subsection{Deeper}
    Because \verb|\rightmark| is the \emph{first} right mark on the page, a page
    that starts with a new section shows that section in the header even when the
    rest of the page belongs to the next one - the asymmetry behind the
    "my header is one heading behind" complaint.
    
    \begin{equation}
      \label{eq:star}
      \sum_{d\mid n} \varphi(d) = n
    \end{equation}
    Equation \eqref{eq:star} has nothing to do with page furniture, but its number
    comes from the same two-pass mechanism, which is why adding a header line that
    changes \verb|\headheight| can move it to another page.
    \end{document}

    双面文档:镜像、空白页与页码落点

    twoside 文档不是同一页左右翻印:边距本身就要互换,这正是 geometry 里 inner= 与 outer= 要表达的东西,页眉跟着一起换。标准类里 book 默认双面、article 默认单面,于是同一段页眉代码在两个模板里表现迥异——「在 article 里好使,换成学位论文就崩」,最常见的解释就是这一条。

    章的开局是另一处结构差异。设了 openright(book 的默认值),\chapter 会跑一遍 \cleardoublepage;若结果是本章起始落在反页,就补进一张空页,而那张页上 \thispagestyle{empty} 早已生效,所以不带页码。印成书这是对的,在 PDF 里审阅却像 bug,去掉它的开关是 openany。另外注意,这样插入的空白页照样消耗一个页号:手工编号时,计数与印出来的页码会各说各话。

    值得遵守的落点惯例:专著里页码走外侧上方或外侧下方,双面印刷时两页都居中是大忌,居中的页码会掉进订口。运行标题反页放章名、正页放节名,用小加大或斜体,绝不把两者塞进同一页。真要付印,先问印厂第 1 页算不算正页;页码出现在反的那一侧,十有八九是前部差了一张空白页。

    最后,双面文档的奇偶问题有一个正确答案,它不是对 \thepage 做算术:要紧的是物理页序,稳妥的问法是 oddpage 宏包的 \checkoddpage 加 \ifoddpage,它比的是位置而非印出来的数字,代价是要跑两遍。绝不要靠读 \value{page} 判奇偶——前置部分用罗马数字、又用 \includeonly 做局部构建时,印出的页号与物理页号就是两回事。

    \documentclass[12pt,a4paper,twoside]{book}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[margin=2.6cm,marginparwidth=2.2cm,headheight=16pt]{geometry}
    \usepackage{fancyhdr}
    
    \pagestyle{fancy}
    \fancyhf{}
    % E = even pages, O = odd pages; L/R = left/right slot of that page.
    \fancyhead[LE,RO]{\small\thepage}                       % folio outside
    \fancyhead[RE]{\small\nouppercase{\leftmark}}           % chapter, verso
    \fancyhead[LO]{\small\nouppercase{\rightmark}}          % section, recto
    \fancyfoot[C]{\small\itshape Draft of \today}
    
    \renewcommand{\headrulewidth}{0.4pt}
    \fancyheadoffset[L]{0pt}          % keep the rule exactly at \textwidth
    
    % The style used by \chapter, \part and the TOC: they call \thispagestyle{plain},
    % so redefining plain is how you decorate first pages without touching every call.
    \fancypagestyle{plain}{%
      \fancyhf{}%
      \fancyfoot[C]{\small\thepage}%
      \renewcommand{\headrulewidth}{0pt}%
    }
    
    \begin{document}
    
    \frontmatter                       % roman page numbers, and it resets to i
    \title{A Thesis}
    \author{A. Candidate}
    \date{}
    \maketitle
    \thispagestyle{empty}
    \tableofcontents                   % own \thispagestyle{plain}
    \listoffigures
    
    \mainmatter                        % arabic again, restarting at 1
    \chapter{Rings}
    A chapter opens on a recto here and its first page uses the plain style redefined
    above; later pages use the fancy style, and \verb|\leftmark| carries the chapter
    title on the even pages.
    
    \section{Modules}
    \verb|\rightmark| carries the section title on the odd pages. A section that
    begins at the very top of a page is the classic reason a running head appears
    one section behind, because marks are resolved by the output routine for the
    page as a whole.
    
    \cleardoublepage                   % \thispagestyle{empty} on the blank verso
    \chapter{Fields}
    Both marks are set with \verb|\markboth| by the class: the book class issues
    \verb|\chaptermark| and \verb|\sectionmark|, so the header text is the title
    \emph{as typeset}, uppercase and all, unless \verb|\nouppercase| intercepts it.
    \end{document}

    页码编号、前置部分,与你不想看见的那个数

    页码是个计数器,而 \pagenumbering{style} 在换表示法的同时把它归零——所以 book 系的 \frontmatter 与 \mainmatter 不是花饰:前者切到罗马数字,后者切回阿拉伯数字并重新起算。在 article 里手搓一遍就是 \pagenumbering{roman}、然后 \clearpage、然后 \pagenumbering{arabic}。反过来用 \setcounter{page}{1} 再配一个重定义的 \thepage,就是 PDF 重复锚点的诞生现场。

    把标题页的页码抹掉是两行的活:整段前置部分都不想要,就在 \maketitle 之前写 \pagestyle{empty};只去那一页,就紧跟在 \maketitle 之后写 \thispagestyle{empty}——难点全部集中在先后次序上。若首页必须素净、页码又要从次页起算为 1,更稳的写法是把计数器显式提前一格:在 \maketitle 之前 \setcounter{page}{0},于是下一页自然就是 1。

    要印「第 3 页,共 12 页」就得知道末页,而一遍编译不可能知道:lastpage 宏包提供 \pageref{LastPage},两遍即收敛;基于 zref-useri 的 zref-lastpage 则是能在 \includeonly 局部构建与多作用域文档里活下来的那个变体。两者和本课其余机制同属一类:这个值只有上一遍编译才给得出。

    至于重启与偏移:\addtocounter{page}{-1} 是补偿「不该被计数的那一页」(比如整页插图)的老实话,它管用,却让打印编号与物理编号失去同步,于是链接和评审意见齐刷刷错一页。另一条路是 \thispagestyle{empty} 加上不去碰计数器——物理编号原样保住,页面上也不印码,而评审人期待的几乎总是这一种。

    现成配方,以及它们出事的方式

    常用配置:\pagestyle{fancy}\fancyhf{}\fancyhead[R]{\small\thepage}\fancyhead[L]{\small\nouppercase{\leftmark}},再在 geometry 选项里带上 headheight=15pt。不要页眉横线:\renewcommand{\headrulewidth}{0pt}——不是 \headrule{},更不是把 \headheight 删掉。左页章名、右页节名、页码靠外:就是槽位那节的三行 \fancyhead[LE,RO]/[RE]/[LO]。每章首页另有样式:用 \fancypagestyle 重定义 plain,而不是在每一条 \chapter 之后再补一句 \thispagestyle。

    最出人意料的一种失败是「什么都没出现」。按可能性排序的原因:\pagestyle{fancy} 压根没写,或者写在了 \usepackage{fancyhdr} 之前;\chapter、\maketitle、\tableofcontents 发出的 \thispagestyle{plain},恰好在你盯着看的那一页上盖过了它;内容放错了页选择器的槽——双面文档里写 \fancyhead[L] 填的是每一页的左槽,镜像版式随后又把它藏了起来;或者页眉其实全在,只因 \headheight 是 0,那个盒子被丢掉了。

    第二种:页眉显示的是错的标题。这是标记问题,不是家具问题——带着首/末那条不对称去读 \leftmark 与 \rightmark,在不编号的文题之后用 \markboth{}{} 自己补一笔,还要记得章的起始页用的是 plain,所以标记再正确那里也不会冒出页眉。

    第三种:日志里满是关于脆弱命令的警告。页眉里的 \footnote、\marginpar 或行间公式,等于在输出例行程序内部做页面插入,这是不允许的;\marginpar 进页眉会直接失败,含 \ref 的页眉需要两遍编译,而用 \mbox{} 把它按在一行内属于正当用法。若你真的需要掌控章首页的家具,titlesec 自带一套页样式接口(\newpagestyle)——先把 \pagestyleset{fancyhdr} 设上,你刚学过的那套词汇就还能继续用。

    h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}
    h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}

    本课速查

    每节抽一行关键代码:点小节名跳到对应位置,代码一键复制。

    小节 关键代码
    V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
    \documentclass[11pt,a4paper]{article}
    \documentclass[11pt,a4paper]{report}
    \documentclass[12pt,a4paper,twoside]{book}
    h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}

    常见错误

    • 把 \thispagestyle{empty} 写在 \maketitle 或 \chapter{...} 之前。这两条命令自己会发出 \thispagestyle{plain},而它来得更晚所以它说了算。覆盖要写在它们之后,或者干脆用 \fancypagestyle 把 plain 重定义掉。
    • 把 \headheight is too small 当成耳旁风。页眉盒不会被压扁,页面也不会被重切——内容就是直接压在第一行正文上,而日志是唯一说过这件事的地方。
    • 用 \setlength 改 \headheight,却指望文本块跟着一起挪。要么让 geometry 重算整页,要么接受 \textheight 已经和这张纸对不上。
    • 在双面的 book 文档里写 \fancyhead[L]{...},然后把结果称作「左页」。L 选中的是左槽;页选择器是 E、O、代表左手页的 L 和代表右手页的 R,如 \fancyhead[LE,RO] 那样写。
    • 指望 \leftmark 在单面的 article 里正常干活:标准类在单面下只维护右标记,而且 \leftmark 是页面上最后一个左标记、\rightmark 是第一个右标记。
    • 用 \setcounter{page}{1} 而不是 \pagenumbering{arabic} 来重启页码。于是两页都印着「1」,PDF 锚点互相撞车,hyperref 跟着报页面名重复。
    • 往页眉里塞 \marginpar、\footnote 或者行间公式。输出例行程序内部不允许页面插入,结果要么什么都没印出来,要么这一遍直接停住。

    关于本课的常见问题

    LaTeX 怎么把页码放到右上角?
    载入 fancyhdr,写 \pagestyle{fancy},用 \fancyhf{} 清空六个槽,再来一句 \fancyhead[R]{\thepage};双面文档想让它待在外侧就写 \fancyhead[LE,RO]{\thepage}。记得在 geometry 选项里声明 headheight,否则 fancyhdr 一边报警,页眉一边压到第一行正文上。
    为什么我每章的第一页没有页眉?
    因为 \chapter 会调用 \thispagestyle{plain},而 plain 是与 fancy 不同的另一套样式。只处理一次的场合,在 \chapter 命令之后紧跟一句 \thispagestyle{fancy};想一次管住所有章首页、目录和图清单,就用 \fancypagestyle{plain}{...} 把这个样式重定义掉。
    fancyhdr 那条 headheight 警告到底是什么意思?
    fancyhdr 量了你定义的页眉的自然高度,它比类声明的 \headheight 更高。TeX 不重切页面就没法把这条带子撑高,于是页眉溢出到第一行正文上。把 geometry 选项里的 headheight= 设成警告建议的值,再编一遍:高度一变断页就移,可能又暴露出一个更大的需求。
    怎么让页眉显示当前节的标题?
    类会把每个文题写进标记:奇数页用 \rightmark,偶数页用 \leftmark,被类转成大写就再套一层 \nouppercase。记住内核文档写明的不对称——\leftmark 是页面上最后一个左标记,\rightmark 是第一个右标记——要另一种组合就用 \LastMark{2e-right} 或 \FirstMark{2e-left}。
    页脚里怎么打出「第 3 页 共 12 页」?
    载入 lastpage 宏包,在某个页脚槽里写 \thepage\ of \pageref{LastPage}。总数要到最后一页输出完才知道,所以必须两遍编译;多文件项目里用了 \includeonly 的话,换成 zref-lastpage,它按文档作用域分别记录这个值。
    该用 fancyhdr、titlesec 的页样式,还是 KOMA-Script 的选项?
    标准类就用 fancyhdr:六个槽位、文档齐全,各家编辑器教程讲的也是这套词汇。titlesec 与 titleboth 给你同一个模型,另加与文题绑定的钩子,而且 \pagestyleset{fancyhdr} 之后能直接看懂 fancyhdr 写法。KOMA-Script 的类自带开关(headings=plainflat,管页面尺寸的 typearea),把它们和手工设定的长度混着用,就是绝大多数 KOMA 版面之争的起点。

    实时演示:直接编辑 LaTeX,立刻看渲染结果

    预览随输入实时更新——不妨故意写坏一次,看看报错长什么样。

    KaTeX 错误
    试一个例子

    继续读

    同一个东西的三个入口:记法本身、讲它的那一课、以及真正用它写东西的一篇文章。