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

LaTeX 交叉引用:label、ref 与两遍编译规则

一条交叉引用就是写进旁置文件、由下一遍编译再读回来的一个键。仅凭这一件事就能解释 ??、\label 的摆放规则、重名标签的警告、cleveref 为什么必须最后加载,以及一条引用怎么能伸进你压根没编译的那份文档。

    一个 label 究竟存下了什么

    LaTeX 里的交叉引用不是指向文档某处的指针,而是旁置文件里的一行。当 TeX 读到 \label{eq:gauss} 时,它不会环顾四周去找你紧挨着的那个东西。它只读一个内部宏 \@currentlabel,把那个宏此刻装着的内容,用由你的键拼出来的控制序列名,写进本次编译正在生成的 .aux 文件里。之后每一个 \ref 都是在由这些行汇成的表里查一次。周围的文字从头到尾没有被再看第二眼——这就是为什么一条引用可以格式完好、按正确的样式印出一个数字,却命名了错误的对象。

    \@currentlabel 是由 \refstepcounter{<counter>} 写入的,而这是唯一会写它的推进计数器的命令。光秃秃的 \stepcounter 只挪数字、不碰标签;\addtocounter 也一样。你依赖的那些命令内部都会调用 \refstepcounter——\section、\caption、enumerate 里的 \item、\begin{equation}、\bibitem——而你手工搭出来的那些通常不会。正是这一处不对称,让用 \stepcounter 推进计数器的自制 \newenvironment{exercise} 里,\label{ex:one} 解析到了外层的节上。

    把文件读回来的过程同样机械。裸 LaTeX 每个标签写两个字段,编号和页码;加载 hyperref 之后同一行带五个字段,大致是 \newlabel{eq:gauss}{{4.2}{17}{}{equation.4.2}{}}。\ref 印第一个字段,\pageref 印第二个,\nameref 印第三个,第四个则是点击要用的 PDF destination。这就是引用可以「对一半」的原因:数字和链接取自同一条记录的不同槽位,于是一份过期的 .aux、一个少见的 \p@<counter> 前缀、或者一个撞车的锚点名,都能只挪动其中一个而不动另一个。

    \text{stored} = \mathtt{currentlabel}\ \text{at that instant} \Longleftarrow \mathtt{refstepcounter}_{\text{most recent}}
    \text{stored} = \mathtt{currentlabel}\ \text{at that instant} \Longleftarrow \mathtt{refstepcounter}_{\text{most recent}}
    一次编译收尾后的标签表就是纯文本:打开 main.aux 搜 \newlabel。每一处命中都按下一遍将会看到的样子,列出键、编号、页码和 destination。
    LaTeX 交叉引用:label、ref 与两遍编译规则 — 一个 label 究竟存下了什么
    渲染结果——由本页展示的源码排版而来。

    两遍编译,以及第一遍上那个 ??

    .aux 恰恰是由那个正在读它的编译过程写出来的。在 \begin{document} 处,LaTeX 会输入上一遍留下的 \jobname.aux,把它找到的每一行 \newlabel 变成一条定义;而在排正文的同时,它把新产生的行追加到同一个文件末尾。所以一篇新文档第一次编译时那张表是空的,每个 \ref 都展开成 ??,日志以 LaTeX Warning: There were undefined references. 收尾。第二次编译读的是第一次写下的东西。什么都没坏;那个 ?? 只是系统在告诉你,它问了一个还不存在的键。

    有两个细节让这条规则不像听起来那么显然。第一,LaTeX 重跑不是因为你要它重跑:它发现某个自己需要的标签缺失,或者某个存下的值变了,于是往日志里写 Rerun to get cross-references right.。latexmk 和多数编辑器解析的正是这个字符串,所以按一下按钮好像就解决了两遍的问题——它是在跑那两遍,而不是跳过它们。第二,那张表以 \jobname 为键。直接编译某个章节文件、给根文档改名,或者编译到那个装着 .aux 的目录之外,都会让你重新得到一张空表,而且没有任何有人会读的报错。

    凡是丢掉辅助文件的做法,都等于丢掉标签表。一条每次 checkout 只跑一遍引擎的 CI 流水线、一个只提交 .tex 从不提交 .aux 的仓库、最终编译前按下的那个 clean 按钮、以及把 \includeonly 收窄到某一章而它的同伴章节从没编译过——结果全都一样:正文正确,每个指针里都是 ??。当合作者报告他看到 ?? 而你看到数字,先问他的编译命令是什么,再去动源码。

    \mathtt{??} \xrightarrow{\;\text{pass 1: write .aux}\;} \{\,\mathtt{eq:gauss} \mapsto (4.2,\,17)\,\} \xrightarrow{\;\text{pass 2: read .aux}\;} (4.2)
    \mathtt{??} \xrightarrow{\;\text{pass 1: write .aux}\;} \{\,\mathtt{eq:gauss} \mapsto (4.2,\,17)\,\} \xrightarrow{\;\text{pass 2: read .aux}\;} (4.2)
    在共享分支上,辅助文件既不要进版本控制,也不要被清理顺手带走:别人那次编译留下的 .aux,会把你的引用解析到他的页码上。
    % ============================================================
    % The whole subject of this document is the reference machinery.
    % Compile it TWICE: pass 1 writes the label table, pass 2 reads it.
    % ============================================================
    \documentclass[11pt,a4paper]{article}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[a4paper,margin=2.5cm]{geometry}
    \usepackage{xcolor}                 % teal is not a base colour name
    \usepackage[colorlinks=true,linkcolor=blue,citecolor=teal]{hyperref}
    \usepackage{cleveref}                % after hyperref, never before it
    
    \begin{document}
    \tableofcontents
    
    \section{Gaussian integrals}\label{sec:gauss}
    \begin{equation}
      \label{eq:gauss}%             anywhere after \begin{equation} is correct
      \int_{-\infty}^{\infty} e^{-x^{2}}\,dx = \sqrt{\pi}
    \end{equation}
    One key, five macros, five different strings on the same line:
    \ref{eq:gauss}, \eqref{eq:gauss}, \pageref{eq:gauss}, \autoref{eq:gauss}
    and \cref{eq:gauss}.
    %  ref -> bare number      eqref -> number in parentheses
    %  pageref -> the page      autoref -> "Equation <n>"
    %  cref -> "equation (<n>)", lower case, and it is a link
    
    \section{A float, and where its label goes}
    \begin{figure}[htbp]
      \centering
      \rule{4cm}{2cm}
      \caption{The error curve.}%
      \label{fig:error}%        MUST follow \caption: that is what steps figure
    \end{figure}
    As discussed in \cref{fig:error}. Move the \verb|\label| one line up and the
    number it stores becomes the section's --- right format, no error, wrong
    object. That is the whole reason the ordering rule exists.
    
    \section{A list worth pointing at}
    \begin{enumerate}
      \item Set up the integral over the whole line. \label{itm:setup}
      \item Square it and pass to polar coordinates. \label{itm:polar}
    \end{enumerate}
    Step \ref{itm:setup} is fine, because \verb|\item| steps \verb|enumi| through
    \verb|\refstepcounter|. A \verb|\label| written on the
    \verb|\begin{enumerate}| line, before the first \verb|\item|, would name the
    section instead.
    
    % main.aux, when you open it after pass 1, is an ordinary text file:
    %   \newlabel{eq:gauss}{{1}{1}{}{equation.1}{}}
    %   \newlabel{fig:error}{{1}{1}{}{figure.1}{}}
    %   \newlabel{itm:polar}{{2}{1}{}{Hei.2}{}}   % Hei = hyperref's name for enumi
    % Pass 2 is nothing but the second time those lines get read.
    \end{document}

    label 站在哪里,决定了它命名的是谁

    因为 \label 只是读 \@currentlabel,它的位置是就它前面那条命令说的一句话,而不是就后面那条。在 equation 里,计数器在 \begin{equation} 处就被推进了,所以标签可以待在体内的任何位置,而团队习惯是把它放在最前面——那里它不会与所属的展示式被拆开。在 \section{...} 之后,而不是之前。在编号列表里,放在你想要的那个编号对应的 \item 的下一行,因为推进 enumi 的正是 \item。

    浮动体是这件事咬人的地方,因为那里的计数器是由 \caption 推进的。写 \caption{...}\label{fig:x} 是对的,\label{fig:x}\caption{...} 不是——后一种记下的是最后被推进的那个东西,通常是节号。不会有任何报错。数字以一个像样的格式印出来,图表目录里的那一条看着也合理,唯一的症状是 \cref{fig:x} 在一句讲插图的中间说出「section 2.1」。而临交付时你手动挪过的一个浮动体,会在一个上周还正确的文档里把这个 bug 复现一遍——这就是为什么这条顺序规则值得背下来而不是现查。

    同一套机制也给你一个故意的技巧。存进去的是 \p@<counter> 后面跟 \the<counter>,所以重定义前一个宏,就加上了一个只出现在引用里、别处都不出现的词头:有了 \renewcommand{\p@solution}{Solution~},标题排出来是 3,而 \ref{sol:quad} 排出来是 Solution 3。至于 \theH<counter>,也就是 hyperref 用来拼锚点名的那个宏,是同一个想法用到链接这一侧——也正因如此,当两个对象合法地印出同一个数字时,它是最精准的那把手术刀。

    \int_{-\infty}^{\infty} e^{-x^2} \, dx = \sqrt{\pi}
    \int_{-\infty}^{\infty} e^{-x^2} \, dx = \sqrt{\pi}
    当一条引用恰好错开一个编号对象时,先怀疑摆放,再怀疑编译:把 \label 挪到那条推进你想要的计数器的命令之后。
    e^{i\pi} + 1 = 0
    e^{i\pi} + 1 = 0

    ref、eqref、pageref:哪个宏给哪个字符串

    \ref 只排存下的那个数字,别的不加。\eqref 来自 amsmath,做同样的查找,然后把结果用数学样式的括号包起来——那才是给一条展示式命名在排版上正确的写法,也是它存在的理由。手工敲的 (\ref{eq:x}) 看着一样,其实不是:那对括号是正体的文本符号而不是数学符号,而且一旦 \p@equation 带了词头,你的括号就落到词头外面去了。

    \pageref 读的是页码字段而不是编号字段,所以它跟着当前生效的页码编码走——指向罗马数字前置页里某个标签的引用会排出 vii,而不是 7。\nameref 读标题字段,给你目标的节标题文字;它之所以有东西可读,只是因为写标签那一刻 hyperref(或单独的 nameref)填了这个字段,两者都没有时,你在第一次使用处就会收到 ! Undefined control sequence。

    还有两个补日常的缺口。\ref*{key} 印数字但把链接关掉,这正是当名词和标点都由你写、只让那几位数字来自机器时你想要的。\autoref 和 \cref 连名词一起给:\autoref 把它首字母大写,\cref 全小写而 \Cref 又大写回去,cleveref 另外还管复数和列表折叠。选定一个,通篇用它,因为一篇在「fig. 3」「Figure 3」和「3」之间来回换的论文,读起来像是三个人写的——而这通常还真是事实。

    \underbrace{4.2}_{\text{ref}}\quad \underbrace{(4.2)}_{\text{eqref}}\quad \underbrace{17}_{\text{pageref}}\quad \underbrace{\text{Equation }4.2}_{\text{autoref}}\quad \underbrace{\text{equation (4.2)}}_{\text{cref}}
    \underbrace{4.2}_{\text{ref}}\quad \underbrace{(4.2)}_{\text{eqref}}\quad \underbrace{17}_{\text{pageref}}\quad \underbrace{\text{Equation }4.2}_{\text{autoref}}\quad \underbrace{\text{equation (4.2)}}_{\text{cref}}
    行文里优先用带名词的形式;圆括号和方括号里优先用 \eqref。同一句话里混用,是拼贴文档的破绽。

    名字、重名,以及无声的改道

    在 TeX 看来,eq:、fig:、sec:、tab: 和 enu: 这些词头都只是装饰:一个键就是一个不透明的字符串。它们的价值体现在另外三处——可 grep、编辑器自动补全,以及一个自带类型的名字被接到错误种类的对象上时会一眼看出不对。文档一旦有了章节,还值得再加一条习惯:按单元加前缀,比如 ch04:eq:wave,因为一份被编进两份报告的共用附录,正是相同的键第一次碰头的地方。

    同一个键用了两次,编译会报 LaTeX Warning: Label `fig:setup' multiply defined.,随后做的事比这句措辞暗示的更不起眼。整条记录——编号、页码、标题和 destination 一起——被最后写入的那一条替换,于是前面那个对象通过这个名字再也够不着了,而它每一次被提及都带着后面那个对象的编号。较新的内核还会在结束时补一句 LaTeX Warning: There were multiply-defined labels.,你不必再翻一千行日志才知道。

    还有第二条警告长得类似,意思却不同:Package hyperref Warning: Destination with the same identifier (name{figure.2.1}) has been already used, duplicate ignored. 这根本不是重名的键——是两个不同的标签拼出了同一个锚点名,因为 \theH<counter> 撞了,常见原因是某个计数器归零而锚点没跟着归零、某条定理共用了计数器,或者 \phantomsection 重复出现。引用解析正常,正文文字正确,只是点击跳到了两个对象里较早的那一个。

    找第一种很便宜。在源码里搜 \label{,把结果交给 sort 加一个去重过滤器;refcheck 宏包会在编译过程中报告未定义、重复以及从未被引用的标签;而在文档内部,\@ifundefined{r@<key>}{not yet}{ok} 可以测某个键有没有解析成功,于是过期的 .aux 变成一个看得见的词,而不是两个问号。refcount 宏包则用 \getrefnumber{key} 更舒服地暴露同一张表。

    \{\,\mathtt{fig:setup} \mapsto 1.4\,\} \;\cup\; \{\,\mathtt{fig:setup} \mapsto 2.7\,\} \longrightarrow \{\,\mathtt{fig:setup} \mapsto 2.7\,\}
    \{\,\mathtt{fig:setup} \mapsto 1.4\,\} \;\cup\; \{\,\mathtt{fig:setup} \mapsto 2.7\,\} \longrightarrow \{\,\mathtt{fig:setup} \mapsto 2.7\,\}
    想要事实就去 grep .aux 而不是源码:\newlabel 那些行才是下一遍真正会读到的东西,重复的也算。
    \documentclass[12pt,a4paper]{report}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[margin=2.5cm]{geometry}
    \usepackage[colorlinks=true]{hyperref}
    
    \makeatletter
    % (A) A label stores \p@<counter> followed by \the<counter>. Redefine the
    %     first half and a word appears in every reference while the printed
    %     heading itself stays bare.
    \newcounter{solution}[chapter]
    \renewcommand{\thesolution}{\arabic{solution}}
    \renewcommand{\p@solution}{Solution~}
    \newenvironment{solution}
      {\par\medskip\noindent\refstepcounter{solution}%   <- refstepcounter, not stepcounter
       \textbf{\thesolution.}\ }
      {\par\medskip}
    
    % (B) hyperref builds the PDF destination name from \theH<counter>. Two
    %     objects whose \theH form collides produce
    %       Package hyperref Warning: Destination with the same identifier
    %       (name{figure.2.1}) has been already used, duplicate ignored.
    %     and the second one then has no anchor of its own to jump to.
    \newcommand{\isresolved}[2]{%
      \@ifundefined{r@#1}{#2}{resolved from the previous pass}}
    \makeatother
    
    \begin{document}
    \chapter{Inequalities}\label{ch:one}
    \begin{figure}[htbp]\centering
      \rule{3cm}{1.6cm}
      \caption{Two curves.}\label{fig:setup}
    \end{figure}
    The heading below prints a bare number while the reference to it does not,
    because \verb|\p@solution| only enters the stored form: see \ref{sol:first}.
    \begin{solution}\label{sol:first}
      Square both sides and compare term by term.
    \end{solution}
    
    \chapter{Applications}\label{ch:two}
    \begin{figure}[htbp]\centering
      \rule{3cm}{1.6cm}
      \caption{The same drawing, reused.}\label{fig:setup}  % key used twice
    \end{figure}
    Reference to \ref{fig:setup}. The key was written twice, so the run warns
    \emph{Label `fig:setup' multiply defined} and the \emph{later} line owns the
    number, the page, the title and the destination together: the first figure is
    now unreachable through that name.
    
    \section{A collided anchor, not a collided key}
    \setcounter{figure}{0}   % deliberate: restart the counter inside chapter 2
    \begin{figure}[htbp]\centering
      \rule{3cm}{1.6cm}
      \caption{Also numbered 2.1.}\label{fig:again}
    \end{figure}
    \ref{fig:again} resolves and is typeset, but its destination name is the one
    figure 2.1 already registered, so clicking it jumps upward. Distinct labels,
    distinct numbers in the text, one anchor shared -- and only a warning in the
    log says so.
    
    \section*{Asking from inside the document}
    \isresolved{eq:nowhere}{NOT RESOLVED --- compile again}\\
    \isresolved{fig:setup}{NOT RESOLVED --- compile again}
    \end{document}

    数字前面那个词,以及提供它的那个顺序

    LaTeX 本身没有词表。\ref 印数字,名词要么你亲手打,要么由某个宏包给。hyperref 的 \autoref 拿计数器名去拼一个控制序列来查——\<counter>autorefname——所以 \figureautorefname 是 Figure,\sectionautorefname 是 Section。内置计数器早就有了条目;你用 \newcounter 建的那个没有,而 \autoref{ex:one} 会一言不发地只印一个数字。修它只要一行,\newcommand*{\exerciseautorefname}{Exercise}。

    cleveref 留着自己的一张表,而且更宽:小写形式用 \crefname{exercise}{exercise}{exercises},大写形式用 \Crefname{exercise}{Exercise}{Exercises}——单数和复数,写两遍,因为这是两次互不相干的查找。它也是这一对里唯一理解复数与列表的:\cref{sec:a,sec:b,sec:c} 折成「sections 1, 2 and 3」,\crefrange{sec:a}{sec:c} 折成「sections 1 to 3」,换成 \autoref 你就得自己打两个句子的连接词。它的 capitalise 选项,是通篇写全称时那个得体的默认值。

    加载顺序不是礼仪,而它的失败方式正是人们不信这段话的原因。hyperref 在加载时会重定义 \ref、\cite、\label 和各节标题命令,所以它站在导言区末尾;cleveref 随后包装 hyperref 产出的那些版本,因此它在 hyperref 之下,而且两者之下都不许再放别的东西。顺序反过来,hyperref 会把自己的 \ref 盖在 cleveref 的包装上:数字仍然正确,词没了,链接不跳了,而且不发一条报错。规范的那条尾巴是 hyperref 然后 cleveref。

    \{\,a,b,c\,\} \longmapsto \text{sections 1, 2 and 3} \qquad a \le k \le b \longmapsto \text{sections 1 to 3}
    \{\,a,b,c\,\} \longmapsto \text{sections 1, 2 and 3} \qquad a \le k \le b \longmapsto \text{sections 1 to 3}
    一篇文档只在 \autoref 和 \cref 之间选一次:它们大写规则不同,而且只有一个会变复数,混着用读起来就像一段话里挤了三个作者。

    跨文件、跨文档的引用

    一个多文件工程在编译过程中并不只有一张标签表,但最终会有一张。每个被 \include 的单元写自己的 .aux,主文件用 \@input{ch04.aux} 这些行把它们汇拢,于是等到引用需要解析时,整本书共用同一个键空间。这恰恰是 \includeonly{chapters/04-wave} 可用的原因:被排除的单元从没被读过,它们的辅助文件却照样被读,所以你在干活的那一章里 \cref{eq:projection} 能解析——解析成上一次完整构建留下的数字。像样、过期、又没有任何标记,是这个集群能造出的最危险的组合。

    跨两份文档时,同一个想法被 xr 家族有意摆到台面上:\externaldocument{supplementary} 把 supplementary.aux 读进当前这张表,从此那边定义的键就在这边解析。它是只读的、也不带链接——那份文档必须已经编译过,它的 .aux 必须放在这次编译找得着的地方——而带前缀的写法 \externaldocument[supp:]{supplementary},正是让两个独立键空间不至于在双方都定义 fig:setup 的那一刻撞车的东西。要可点击的跳转就改用 xr-hyper,并且 在 hyperref 之前 加载,因为 hyperref 必须先看见它,才可能去转接外部的 destination 名。

    三个边界情况,值得在截止日期之前撞上它们之前先知道。一个 \subfile 子文件单独编译时,自己之外的东西一个都解析不了,因为同伴文件的辅助文件从没被拉进来——那是版面结构的性质,不是值得追的 bug。两份互相引用的文档需要在两边都放 xr,而且只有在各自编译两轮之后才收敛。而当那份文档的编号确实在漂,就把指针手写出来:一句硬编码的「见补充材料,公式 (S4)」,比一个别人每次重新构建都会悄悄变掉的机器数字诚实得多。

    % ============================================================
    % main.tex -- labels gathered from included units and from a
    %            document that is not part of this build at all
    % ============================================================
    \documentclass[12pt,a4paper]{book}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[margin=2.5cm]{geometry}
    
    % Cross-document referencing. Use xr-hyper rather than xr as soon as hyperref
    % is in the document, and load it BEFORE hyperref: hyperref notices it there
    % and routes the external destination names through the other file, which is
    % the difference between a resolving number and a clickable jump.
    \usepackage{xr-hyper}
    \usepackage[colorlinks=true]{hyperref}
    \usepackage{cleveref}
    
    % The prefixed form keeps the two key spaces apart, so both documents are free
    % to define fig:setup. Write \externaldocument{supplementary} with no optional
    % argument to import the foreign keys verbatim instead.
    \externaldocument[supp:]{supplementary}
    
    \begin{document}
    \mainmatter
    % chapters/04-wave.aux is written by that \include and pulled back into
    % main.aux through an \@input line, so the whole book keeps ONE label table.
    \include{chapters/01-basics}
    \include{chapters/04-wave}
    
    % \includeonly{chapters/04-wave}  % a fast single-chapter build: the excluded
                                      % files are never read (their counters do not
                                      % advance) but their .aux files still are, so
                                      % \ref into them prints the numbers from the
                                      % last FULL build. Plausible and stale.
    
    As \cref{eq:wave} shows --- and compare the notation in
    \ref{supp:eq:derivation} of the separate supplementary document, whose
    \texttt{.aux} must exist beside it for this to resolve at all.
    \end{document}
    
    % ============================================================
    % supplementary.tex -- a normal document; its .aux is the interface
    % ============================================================
    \documentclass[12pt,a4paper]{article}
    \usepackage{amsmath}
    \begin{document}
    \section{Derivation}
    \begin{equation}\label{eq:derivation}
      \lVert x\rVert_{2} = \Bigl(\sum_{i} x_{i}^{2}\Bigr)^{1/2}
    \end{equation}
    Nothing here knows it is being referenced from elsewhere: the exported table
    is a side effect of compiling it.
    \end{document}

    参考文献是同一台机器,只是多了一个程序

    \cite{key} 与 \bibitem{key} 这一对,就是 label-ref 那份契约换了个写入者。\bibitem 通过 \refstepcounter 推进列表计数器,并发出一行 \newlabel,所以 \ref{knuth1984} 真的会排出一个你压根没打算加标签的条目序号。区别在上游:.aux 还会为每个 \cite 收进一行 \citation{key},而那些行正是 BibTeX 要读的——连同同一个文件里的 \bibdata 与 \bibstyle 记录——据此从 .bib 数据里挑出条目,并写出后面某一遍 LaTeX 会输入的 .bbl。

    就是这多出来的程序,让遍序不再是口味问题:latex、bibtex、latex、latex。在第一遍 LaTeX 之前跑 bibtex,它回你 I couldn't open file name "main.aux",因为装着引用清单的那个文件还不存在。之后只跑一遍 LaTeX,则每条引用都印成 [?],日志里有 LaTeX Warning: Citation `knuth1984' undefined.,因为 .bbl 到达得太晚、没赶上被读。latexmk 和 arara 不是在给这件事提速;它们是把这条依赖编码下来,让各遍按正确的顺序发生。

    biblatex 把挑选这一步从 bibtex 挪到 biber,形状完全没变——一遍负责发出请求清单,后面几遍负责消费结果——所以当期刊要求用它时,本节说的东西一概不变。变的是条目由书目数据来定键,而不是由你写的某个 \bibitem 定键,而排出来的数字是一个排序结果而不是计数器。调试的直觉倒是一样:一条引用解析不出来,先打开 .aux,看看那个键到底有没有被要过。

    % Equation with a number and label:
    \begin{equation}
      \label{eq:gaussian}
      \int_{-\infty}^{\infty} e^{-x^2} \, dx = \sqrt{\pi}
    \end{equation}
    
    % Inline reference (hyperref makes it a link):
    Combining \eqref{eq:gaussian} with \eqref{eq:laplace} …
    
    % Bibliography, minimal BibTeX workflow:
    %  1. \cite{knuth1984}  in the text
    %  2. a .bib file with the entries
    %  3. \bibliographystyle{plain} \bibliography{refs}
    %  4. run latex → bibtex → latex → latex

    本课速查

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

    小节 关键代码
    \text{stored} = \mathtt{currentlabel}\ \text{at that instant} \Longleftarrow \mathtt{refstepcounter}_{\text{most recent}}
    \documentclass[11pt,a4paper]{article}
    \int_{-\infty}^{\infty} e^{-x^2} \, dx = \sqrt{\pi}
    \underbrace{4.2}_{\text{ref}}\quad \underbrace{(4.2)}_{\text{eqref}}\quad \underbrace{17}_{\text{pageref}}\quad \underbrace{\text{Equation }4.2}_{\text{autoref}}\quad \underbrace{\text{equation (4.2)}}_{\text{cref}}
    \documentclass[12pt,a4paper]{report}
    \{\,a,b,c\,\} \longmapsto \text{sections 1, 2 and 3} \qquad a \le k \le b \longmapsto \text{sections 1 to 3}

    常见错误

    • 每个指针都排成 ??,日志以 LaTeX Warning: There were undefined references. 收尾。改动后的文档只编译了一遍;或者那个 .aux 被删了、或者压根没写出来——因为你直接编译的是子文件、\jobname 是另一个,或者它躺在本次编译看不见的目录里。编译两遍,或者让 latexmk 去响应 Rerun to get cross-references right.——不要靠手打数字来「修」。
    • LaTeX Warning: Label `fig:setup' multiply defined. 键出现了两次,通常是一段被复制粘贴的图块,或者一个共享章节被编进了两份报告。后写的那一次一并拿走编号、页码、标题和 destination,于是第一个对象悄悄不再是一个可跳转的目标。按单元给键划命名空间,然后在源码里搜重复的 \label{ 字符串;refcheck 会替你把它们报出来。
    • \cref{fig:setup} 排出「section 2.1」,而整个过程什么都没说。标签站在 \caption 之前,而 \caption 才是推进 figure 的那条命令,所以写下标签的那一刻 \@currentlabel 里装的还是节号。浮动体内部的顺序是 \caption{...}\label{fig:setup},永远如此。
    • \autoref{ex:quad} 只排出「2.1」,前面没有词;你自己的计数器在 cleveref 那里得到同样的待遇。没有任何东西为你的计数器命名:给 hyperref 定义 \newcommand*{\exerciseautorefname}{Exercise},给 cleveref 定义 \crefname 加 \Crefname。\autoref 也永远不会说「Figures 1 and 2」——那是 cleveref 的活。
    • 引用排出正确的数字却不能点击,唯一的线索是 \cref 开始表现得像 \ref。cleveref 在 hyperref 之前加载了,于是 hyperref 事后补丁了 \ref,把 cleveref 的包装丢到一边。顺序是:其余所有宏包,然后 hyperref,然后 cleveref——如果你用 xr-hyper,它在 hyperref 之上。
    • LaTeX Warning: Citation `knuth1984' undefined.,外加一节空空的文献表,虽然这次构建干净利落地结束了。bibtex 在第一遍 LaTeX 之前跑了,所以没有 \citation 行可读;或者它跑了,而 LaTeX 之后没再跑两遍。latex、bibtex、latex、latex;当输出看着没变时,去比 .aux 和 .bbl 的时间戳,而不是重读你的源码。

    关于本课的常见问题

    为什么我的 LaTeX 文档第一次编译时交叉引用全是 ??
    因为标签表正是由消费它的那一遍编译写出来的。第一遍为每个 \label 往 .aux 里写一行 \newlabel,同时读的是更早某一遍留下的表——对一篇新文档来说那张表是空的,于是每次查找都落空、都印 ??。第二遍读第一遍刚写下的那个文件,数字就出现了。编译两遍,或者让 latexmk 检出 "Rerun to get cross-references right." 并替你把后面几遍跑掉。
    LaTeX 里 \ref、\eqref、\pageref 和 \autoref 有什么区别?
    它们读同一个键,印的是那条记录下不同的字段。\ref 只印存下的数字;\eqref(amsmath)把那个数字包进数学样式的括号里,那才是一条展示式的正确形式;\pageref 印标签写下时所在的页码而不是编号;\autoref(hyperref)在数字前面加上为该计数器登记的那个词,比如 "Equation 4.2",而且它本身还是个链接。\nameref 则印目标的标题,而不是任何数字。
    一篇有很多交叉引用的 LaTeX 文档应该编译几遍?
    标签要稳定,最少两遍;而文档还在改变形状时更多也属正常:第二遍上挪了位的数字得在第三遍重新读一次。有 BibTeX 时固定的循环是 latex、bibtex、latex、latex。latexmk 全都替你管——它一直重跑,直到没有任何 .aux、.bbl 或 .toc 报告变化为止,这也是几页以上的文档都该拿它当构建命令的原因。
    我能引用另一个 LaTeX 文档里定义的标签吗?
    能,用 xr 宏包:\externaldocument{supplementary} 会把 supplementary.aux 读进你的标签表,那边定义的键随后就在这边解析。它是只读的、也不可点击,而且那份文档必须已经编译过,它的 .aux 就在旁边。用 \externaldocument[supp:]{supplementary} 给导入进来的键加上前缀,两份文档就都可以定义 fig:setup。要可点击地跳到另一个 PDF,改成在 hyperref 之前加载 xr-hyper。
    为什么 \autoref 只印一个数字,而不是 "Exercise 2.1"?
    因为 \autoref 是靠着查 \<counter>autorefname 来拼那个词的,而你用 \newcounter 建的计数器没有这么一条定义——hyperref 会退回到裸数字,并且不报警。补上一句 \newcommand*{\exerciseautorefname}{Exercise} 即可。如果你改用 cleveref,等价写法是 \crefname{exercise}{exercise}{exercises} 再加 \Crefname{exercise}{Exercise}{Exercises},顺带买到 \autoref 造不出来的复数形式与区间。
    图里的 \label 真的必须放在 \caption 之后吗?
    必须,而且理由是机制性的而不是风格性的。\label 存的是 \refstepcounter 最近一次写进 \@currentlabel 的东西,而在浮动体里推进 figure 计数器的正是 \caption。标签放前面,它存下的就是最后那个节号:构建干净,数字格式正确,而引用命名了错误的对象。在 equation 里你倒是有得选,因为计数器在 \begin{equation} 处就推进了。
    怎么让 LaTeX 引用排出我自己选定的、背后没有计数器的数字?
    展示式用 amsmath 的 \tag{3.7},写在 equation 内部:印出的数字就成了 3.7,\eqref 也会把它复现出来。别的东西,则在标签之前立刻手工设置 \@currentlabel——\makeatletter\def\@currentlabel{S4}\makeatother\label{eq:hand} 让 \ref{eq:hand} 排出 S4。两种都是逃出编号而不是编号的一部分:那个对象没有被计数,所以它不出现在图表目录里,hyperref 也没有真正的 destination 可给它。

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

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

    KaTeX 错误
    试一个例子

    继续读

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