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

LaTeX 计数器:newcounter 与自定义编号环境

LaTeX 印出的每一个号码都出自同一台三段式机器:一个整数寄存器、一个决定它长什么样的宏,外加一份在它步进时要归零的计数器清单。弄懂这台机器,newtheorem、newpage、enumerate 和你自己写的习题环境就不再是四段互不相干的民间传说。

    每个号码背后的三个对象

    LaTeX 的计数器不是一个宏。\newcounter{foo} 创建一个名叫 \c@foo 的整数寄存器(所以 \value{foo}——它字面上就是 \csname c@foo\endcsname——是一个 TeX 的 \count),并同时创建四个同伴宏,各自回答不同的问题。\thefoo 是印刷表示,标题或环境显示的就是它。\p@foo 是一个参考前缀,只在 \label 往 .aux 写值时被粘到 \thefoo 前面。\theHfoo 是 hyperref 用来命名 PDF 锚点的目标表示。而 \cl@foo 是复位清单:每当 foo 步进就要回到零的那些计数器。

    把前两个混为一谈,是「我的编号不对、却又看不出哪里不对」这类报告的大半来源。重定义 \thefoo 会同时改掉页面和参考;重定义 \p@foo 只改 \ref 说的话;重定义 \theHfoo 对读者看到的东西毫无影响,却决定阅读器里发生的一切。

    这些表示法本身也是可供你重定义的宏:\arabic、\roman、\Roman、\alph、\Asbuk 与 \asbuk(后两个是西里尔字母,由 babel 提供)是标准的那一组,再加上排符号序列的 \fnsymbol。其中任何一个都能掺进字面文字,所以 \renewcommand{\theexercise}{(\alph{exercise})} 合法;而 \thepage、\thechapter、\thesection 也只是和其它任何计数器无异的计数器。

    有一条约束值得背下来,因为它会静悄悄地弄坏文档:内核要求 \thefoo 与 \p@foo 必须以这样的方式定义——让 \edef\bar{\thefoo} 能抓到当下那一刻的值。\arabic{} 及其同伴保证做到这一点,而由晚展开的宏搭出来的定义做不到——这就是为什么建立在一个会重定义计数器的包之上的 \thefoo,可能印出全文最后一个值而不是当前值。

    n_{\text{print}} = (n_{\text{parent}},\ n_{\text{raw}}) \qquad (2,4) \mapsto 2.4
    n_{\text{print}} = (n_{\text{parent}},\ n_{\text{raw}}) \qquad (2,4) \mapsto 2.4

    三行契约:newcounter、setcounter、usecounter

    第一行——\newcounter{foo}[parent]。它声明寄存器;如果你给了可选参数,它还会通过内部的 \@addtoreset 把 foo 加进父级的复位清单。可选参数做的只有这件事。它不改 \thefoo:\newcounter{exercise}[section] 之后号码仍然印成 4,而不是 2.4。这个可选参数之所以有那样的名声,是因为标准文档类把打印那一半手工补上了——article.cls 里在 \newcounter{subsection}[section] 之后紧跟一句 \renewcommand\thesubsection{\thesection.\arabic{subsection}}——于是两行读起来像一行。

    第二行——\setcounter{foo}{<value>}。它和它的兄弟 \addtocounter 是全局的(内核把它们包在 \global 里),所以在一个组里改动的计数器出来之后仍保留新值,这一点和普通宏相反。第二个参数是一个整数表达式,这就是 \setcounter{chapter}{\value{chapter}+1} 与 \addtocounter{page}{-2} 都合法的原因,也是为什么不能在期望表达式的地方写 \stepcounter、或者在大括号里留一个多余空格:参数按数字来读,任何它解析不了的记号都会静悄悄地终止整个表达式。

    第三行——\usecounter{foo}。这是 list 环境的计数器接口,而 enumerate 就是用它搭起来的。写在设置参数里——\begin{list}{\label}{\usecounter{enumi}}——它声明 \item 应当步进 foo,并且列表内部的 \label 指的就是那个计数器。它背后那行内核源码是 \def\usecounter#1{\@nmbrlisttrue\def\@listctr{#1}\setcounter{#1}\z@}——请注意最后一段:\usecounter 会把计数器归零。所以在列表之前写的 \setcounter{exercise}{6} 会被忘掉;要让列表从七开始,正确写法是把 \setcounter 写在同一个设置参数里、写在 \usecounter 之后。

    v = 4 \;\Longrightarrow\; \mathrm{iv},\ \mathrm{d},\ \mathrm{IV},\ 4
    v = 4 \;\Longrightarrow\; \mathrm{iv},\ \mathrm{d},\ \mathrm{IV},\ 4
    \documentclass[11pt,a4paper]{article}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[a4paper,margin=2.5cm]{geometry}
    
    % ---- 1. the counter exists, and it resets with its parent.
    %      Note: this is ONLY the reset. \newcounter does not touch the printed form.
    \newcounter{exercise}[section]
    
    % ---- 2. how the number is printed on the page.
    \renewcommand{\theexercise}{\thesection.\arabic{exercise}}
    
    % ---- 3. a solution counter whose heading is short but whose \ref is full:
    %      \p@<counter> is prefixed to \the<counter> only when \label is written.
    \newcounter{solution}
    \renewcommand{\thesolution}{\arabic{solution}}
    \makeatletter
    \renewcommand{\p@solution}{Solution \thesection.}   % \ref -> "Solution 1.3"
    \makeatother
    \newenvironment{solution}
      {\par\smallskip\noindent\refstepcounter{solution}%
       \textbf{Solution \thesolution.}\ }
      {\par\medskip}
    
    % ---- a hand-built numbered environment: three lines of machinery
    \newenvironment{exercise}
      {\par\medskip\noindent
       \refstepcounter{exercise}%            <- makes \label work
       \textbf{Exercise \theexercise.}\itshape\space}
      {\par\medskip}
    
    \begin{document}
    \section{First-order equations}\label{sec:one}
    
    \begin{exercise}
      Solve $x^{2} + 2bx + c = 0$ and verify the roots. \label{ex:quad}
    \end{exercise}
    Reference to \textbf{\ref{ex:quad}} works only because the environment called
    \verb|\refstepcounter|, not \verb|\stepcounter|.
    
    \begin{solution}
      Complete the square: $(x+b)^{2} = b^{2} - c$. \label{sol:quad}
    \end{solution}
    The heading reads \thesolution{} while \verb|\ref{sol:quad}| reads
    \ref{sol:quad}, because \verb|\p@solution| adds the prefix that only the
    reference sees.
    
    \subsection{A list that reuses a counter}
    A \texttt{list} environment counts with any counter you hand it, through
    \verb|\usecounter| --- which \emph{resets that counter to zero} when the list
    begins, so a preceding \verb|\setcounter| has to be repeated inside the setup:
    \begin{list}{\textbf{\theexercise.}}{\usecounter{exercise}\setcounter{exercise}{6}%
      \setlength{\leftmargin}{3.2em}\setlength{\labelwidth}{2.6em}}
      \item continues from 7, because \verb|\item| steps the list counter.
      \item and 8 here.
    \end{list}
    
    \section{Second section}
    \begin{exercise}
      The counter restarted: this is \ref{ex:quad} again? No ---
      this new exercise is \arabic{exercise} in section \thesection.
    \end{exercise}
    
    \subsection*{Skipping and setting}
    \setcounter{exercise}{10}
    Now manually at \theexercise.
    \addtocounter{exercise}{-3}
    And after a negative step, \theexercise.
    \end{document}

    stepcounter 与 refstepcounter 之别

    \stepcounter{foo} 做两件事:让寄存器加一,并把 foo 复位清单上的每个计数器归零。\refstepcounter{foo} 在那两件事之外多做一件,而那多出的一件正是「能用的环境」与「只好看的环境」之间的距离。它保存 \@currentlabel——也就是字符串 \p@foo\thefoo,在那一刻展开——同时记下 \@currentHref 与 \@currentcounter,即目标名和计数器的身份。

    因为 \label{name} 写进 .aux 的正是 \@currentlabel,一个只用裸 \stepcounter 步进的计数器无法被引用:在那之后的 \label 记录的是上一个 \refstepcounter 留下的东西,于是 \ref{ex:one} 印出章节号、或者上一道习题、或者 ??。这正是标准定理类环境使用 \refstepcounter 的确切原因,也是交叉引用那一课里「label 要站在计数器之后」这条规则背后的机制。

    当你想让一个数字前进、却不想让它变成可引用的,就该刻意选用 \stepcounter:页脚里用的滚动计数、循环计数器,或者一个只为占位而共享计数器的不编号环境。这条区分也解释了 \item 的行为——列表机制正是在那里调用 \refstepcounter\@listctr——所以 enumerate 内部的 \label 拿到的是 enumi,而 itemize 里的 \label 什么都拿不到,因为 itemize 从不设置 \@nmbrlisttrue。

    stepcounter and refstepcounter: only the second one stores the string that a later label records your environment steps a counter \stepcounter{exercise} increment only \refstepcounter{exercise} increment + remember c@exercise += 1 \@elt{part} of \cl@exercise children go back to zero \@currentlabel := \p@exercise\theexercise \@currentHref := \theHexercise \@currentcounter := exercise \label{ex:quad} writes the strings above, not a pointer to the object with \stepcounter: \@currentlabel is stale \ref{ex:quad} prints the previous section number - no error, no warning with \refstepcounter: the pair works \ref prints 2.4, \autoref and \cref find the noun, the link finds the page
    只有 refstepcounter 这一支会填 \@currentlabel,而也只有那个字符串才是稍后的 \label 写进 .aux 的内容。

    复位层级,以及给计数器换一个父级

    复位关系住在名叫 \cl@<parent> 的清单里,步进父级就是走一遍那张表。内核安排了大家熟悉的那套层级——equation、figure、table 以及每一个分节层级都随 section 复位,section 又随它自己的父级复位,一路向上直到书类文档家族里的 chapter。你可以用内部的 \@addtoreset{child}{parent} 往清单里加、用 \@removefromreset{child}{parent} 从中移除,或者用自 2018 版起已进入内核的用户级那一对:\counterwithin{child}{parent} 与 \counterwithout{child}{parent}。在更旧的安装上,这两条来自 chngcntr 包。

    两者的差别不止名字,而且那个差别正是人们踩的地方:\counterwithin 两半都做——它既登记复位、又把 \thechild 重定义成 \theparent.arabic(child)——而 \newcounter{child}[parent] 只做复位。所以把 \newcounter{exercise}[chapter] 改写成 \newcounter{exercise} 加 \counterwithin{exercise}{chapter} 不是化妆性重构:后者才是同样把两段式号码一并交给你的那个版本。

    还有第三种关系,是共享而非嵌套:两个环境排在同一个序号里。amsthm 用 \newtheorem{lemma}[theorem]{Lemma} 表达这件事;用裸计数器时,等价做法是让两者指向同一个寄存器、却印出不同的词,而内核自最新版本起通过计数器别名支持这一点。实践上,要么用一个计数器、改动的只是标题宏,要么接受两个序列各走各的、并在文中说明白。

    关于复位还有最后一处微妙:它们发生在父级被步进时,而不是被设置时。\setcounter{section}{3} 不会复位 cl@section 上挂着的那些计数器,所以一本手工跳节的文档会留着一堆过时的公式编号——这也正是多人合写的书里,一句手写的 \setcounter{chapter}{...} 会让第 5 章冒出 Theorem 4.7 的原因之一。

    c_{\text{child}} \leftarrow 0 \quad \text{whenever} \quad c_{\text{parent}} \leftarrow c_{\text{parent}} + 1
    c_{\text{child}} \leftarrow 0 \quad \text{whenever} \quad c_{\text{parent}} \leftarrow c_{\text{parent}} + 1
    Counter reset hierarchy: each parent keeps a cl@ list of children that stepcounter zeroes THE PARENT CHAIN IN A report CLASS DOCUMENT chapter \cl@chapter section \cl@section subsection \cl@subsection subsubsection no children CHILDREN THAT RESET WHEN section IS STEPPED figure \thefigure = 2.4 table \thetable = 2.3 equation \theequation = 2.7 exercise (yours) \theexercise = 2.1 \newcounter{exercise}[section] runs \@definecounter and then \@addtoreset only: the reset happens -> exercise goes to 0 the print form does NOT change: 4, not 2.4 \counterwithin{exercise}{section} does both halves of the job: \@addtoreset{exercise}{section} \theexercise := \thesection.\arabic{exercise} this single missing line is the most common reason a custom counter refuses to show the section prefix resets fire on \stepcounter{section}, not on \setcounter{section}{3} - hand-set parents leave their children running on
    复位是父级的属性:每个计数器都持有一份子级清单,stepcounter 会沿清单把它们逐个归零。

    亲手搭一个带编号的环境

    一个编号环境只有四行,而一旦你亲手写过一次,amsthm 身上的神秘感就蒸发了:\newenvironment{exercise}{\par\medskip\noindent\refstepcounter{exercise}\textbf{Exercise \theexercise.}\ }{\par\medskip}。其中 \refstepcounter 是参考机制,\theexercise 是可见的号码,两个 \par 则让这个环境不至于把外面的段落吞进去。想让相邻的习题共用一道空隙而不是两道,就把 \medskip 换成 \addvspace{\medskipamount}。

    两处改进在真实文档里是有意义的。要给习题一个可选标题,就带参数声明它——\newenvironment{exercise}[1]{...\textbf{Exercise \theexercise.\ifblank{#1}{}{ (#1)}}...}{...}(配 etoolbox 的 \ifblank,或内核自带的 \ifstrempty)——并且如果你希望 \nameCref 与 PDF 书签把这个标题带上,就把它写进 \@currentlabelname。要让环境可断或不可断,工具是 \needspace{3\baselineskip} 或一个 minipage 外壳,而不是去改计数器。

    如果你写的不是文档而是文档类或宏包,记得 @ 这些字母受类别码保护:把定义包进 \makeatletter ... \makeatother;如果环境需要写内部状态,优先用现代内核提供的钩子接口(\AddToHook),而不是手工重定义 \exercise。

    \documentclass[11pt,a4paper]{article}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[a4paper,margin=2.5cm]{geometry}
    
    % ---- 1. the counter exists, and it resets with its parent.
    %      Note: this is ONLY the reset. \newcounter does not touch the printed form.
    \newcounter{exercise}[section]
    
    % ---- 2. how the number is printed on the page.
    \renewcommand{\theexercise}{\thesection.\arabic{exercise}}
    
    % ---- 3. a solution counter whose heading is short but whose \ref is full:
    %      \p@<counter> is prefixed to \the<counter> only when \label is written.
    \newcounter{solution}
    \renewcommand{\thesolution}{\arabic{solution}}
    \makeatletter
    \renewcommand{\p@solution}{Solution \thesection.}   % \ref -> "Solution 1.3"
    \makeatother
    \newenvironment{solution}
      {\par\smallskip\noindent\refstepcounter{solution}%
       \textbf{Solution \thesolution.}\ }
      {\par\medskip}
    
    % ---- a hand-built numbered environment: three lines of machinery
    \newenvironment{exercise}
      {\par\medskip\noindent
       \refstepcounter{exercise}%            <- makes \label work
       \textbf{Exercise \theexercise.}\itshape\space}
      {\par\medskip}
    
    \begin{document}
    \section{First-order equations}\label{sec:one}
    
    \begin{exercise}
      Solve $x^{2} + 2bx + c = 0$ and verify the roots. \label{ex:quad}
    \end{exercise}
    Reference to \textbf{\ref{ex:quad}} works only because the environment called
    \verb|\refstepcounter|, not \verb|\stepcounter|.
    
    \begin{solution}
      Complete the square: $(x+b)^{2} = b^{2} - c$. \label{sol:quad}
    \end{solution}
    The heading reads \thesolution{} while \verb|\ref{sol:quad}| reads
    \ref{sol:quad}, because \verb|\p@solution| adds the prefix that only the
    reference sees.
    
    \subsection{A list that reuses a counter}
    A \texttt{list} environment counts with any counter you hand it, through
    \verb|\usecounter| --- which \emph{resets that counter to zero} when the list
    begins, so a preceding \verb|\setcounter| has to be repeated inside the setup:
    \begin{list}{\textbf{\theexercise.}}{\usecounter{exercise}\setcounter{exercise}{6}%
      \setlength{\leftmargin}{3.2em}\setlength{\labelwidth}{2.6em}}
      \item continues from 7, because \verb|\item| steps the list counter.
      \item and 8 here.
    \end{list}
    
    \section{Second section}
    \begin{exercise}
      The counter restarted: this is \ref{ex:quad} again? No ---
      this new exercise is \arabic{exercise} in section \thesection.
    \end{exercise}
    
    \subsection*{Skipping and setting}
    \setcounter{exercise}{10}
    Now manually at \theexercise.
    \addtocounter{exercise}{-3}
    And after a negative step, \theexercise.
    \end{document}

    让 hyperref 与 cleveref 认识你的新计数器

    一个新计数器在参考机制眼里并不存在,直到另外三个宏也到位。hyperref 的 \autoref 会去读 \<counter>autorefname,所以你得写 \newcommand*{\exerciseautorefname}{Exercise}——缺了它,\autoref{ex:one} 只印编号、不带名词。hyperref 的目标名读的是 \theHexercise,而这个宏内核现在会为每个计数器预先创建(自 2024 版起,\@definecounter 把 \theH<name> 定义成 \number\value{<name>});光板整数只在一个父级的范围内唯一,所以在 report 里你应该把它做成 \thechapter.\arabic{exercise},否则日志会被重复目标的警告灌满。

    cleveref 保留自己的两张表:\crefname{exercise}{exercise}{exercises} 给小写的单数与复数,\Crefname{exercise}{Exercise}{Exercises} 给大写的那一对。如果第二个环境应当复用第一个的词汇,\crefalias{subexercise}{exercise} 就把这件事说清楚、而无需把字符串抄两遍。如果你要的是一个格式而不是一个词——带括号的编号、数学模式里的前缀——\crefformat{exercise}{\textbf{#2#1#3}} 会给你 cleveref 负责替换的三个槽:前括、编号、后括。

    \p@ 前缀在这里体现价值。因为它只在参考字符串被组装时才生效,你可以让标题印一个短的、而 \ref 印一个完整的:\renewcommand{\thesolution}{\arabic{solution}} 配上 \renewcommand{\p@solution}{\thesection.},就得到读作 Solution 3 的标题和读作 Solution 2.3 的交叉引用。反向的把戏——把名词放进 \p@solution——让 \ref 自解释,代价是当你同时使用 \autoref 时名词会被印两遍;所以要挑定哪一层拥有名词,并留在那一层。

    \underbrace{3}_{\text{printed by the heading}} \ne \underbrace{\text{Solution }2.3}_{\text{stored for the reference}}
    \underbrace{3}_{\text{printed by the heading}} \ne \underbrace{\text{Solution }2.3}_{\text{stored for the reference}}
    顺序检查:在 cleveref 加载之前就把计数器与它的各种表示定义好,因为 cleveref 在自身加载过程中就会去读计数器清单。
    \documentclass[12pt,a4paper]{report}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[margin=2.5cm]{geometry}
    
    \newcounter{exercise}[chapter]
    \renewcommand{\theexercise}{\thechapter.\arabic{exercise}}
    
    \newenvironment{exercise}
      {\par\medskip\noindent
       \refstepcounter{exercise}%
       \textbf{Exercise \theexercise.}\ }
      {\par\medskip}
    
    % --- the machinery that has to be told about a new counter -------------
    \makeatletter
    % hyperref: \autoref builds its word from \<counter>autorefname
    \newcommand*{\exerciseautorefname}{Exercise}
    % hyperref: the destination name must be unique across the document
    \renewcommand{\theHexercise}{\thechapter.\arabic{exercise}}
    \makeatother
    
    \usepackage{hyperref}
    \hypersetup{colorlinks=true, linkcolor=blue}
    \usepackage[capitalise]{cleveref}
    % cleveref keeps its own tables: singular/plural, lower and upper case
    \crefname{exercise}{exercise}{exercises}
    \Crefname{exercise}{Exercise}{Exercises}
    
    \begin{document}
    \chapter{Linear algebra}
    \section{Systems}\label{sec:sys}
    
    \begin{exercise}\label{ex:one}
      Solve $Ax = b$ for $A$ invertible.
    \end{exercise}
    \begin{exercise}\label{ex:two}
      Solve the same system by row reduction.
    \end{exercise}
    
    All four reference styles at once: \ref{ex:one}, \theexercise,
    \autoref{ex:two}, \cref{ex:one,ex:two}, \Cref{ex:two},
    and \cpageref{ex:one}.
    
    \subsection*{Re-parenting a counter}
    \begin{verbatim}
    \counterwithin{exercise}{section}   % 2.3: reset with section, prefix included
    \counterwithout{exercise}{section}  % 7   : independent numbering again
    \end{verbatim}
    Both are kernel commands since the 2018 release; on an older installation the
    package \texttt{chngcntr} provides them. \verb|\newcounter{exercise}[chapter]|
    by contrast only ever does the reset half of that job.
    \end{document}

    页码也是计数器

    \thepage 在默认文档类里就是 \arabic{page},没有什么阻止你把它当作其它任何计数器来对待——只有一个危险的差别:page 是被输出例程步进的,所以 \setcounter{page} 是异步的。在第 7 页设置它,不会追溯性地给第 1 到 6 页重新编号;而在某个盒子或某个 mark 里设置它,可能落在你并不想去的地方。

    受支持的接口是 \pagenumbering{<style>},它同时干两件事:改掉 \thepage,并把计数器复位成一。这就是 \mainmatter 处那一句 \pagenumbering{arabic} 会重新起数的原因,也是为什么改用 \setcounter{page}{1} 来代替 \pagenumbering 是省错了地方:hyperref 以及每个要给页面目标命名的包都以编号方式为键,于是一份同一种样式里出现两个 1 页的文档就会产生重复目标。前置页用罗马、正文用阿拉伯——\pagenumbering{roman}、然后 \clearpage、然后 \pagenumbering{arabic}——正是让两片命名空间互不相犯的那个形状。

    剩下几个有特权的计数器是 enumi 到 enumiv:内核支持四层嵌套列表、不多不少,每层各有一个表示宏 \theenumi..\theenumiv 与一个标签宏 \labelenumi..\labelenumiv。第五层 enumerate 是一个错误,Too deeply nested,而不是静默溢出。把 \labelenumii 重定义成 \emph{(\theenumii)} 改的是印出来的标签,而 \theenumii 才是你对那一条目做 \ref 时拿到的东西——标签对参考值这一对,正是 \p@ 那套故事往下低一层的版本。

    调试一个不听话的计数器

    四个问题几乎能回答所有编号抱怨,而且你可以问日志、不必问源码。原始值是多少?\typeout{COUNT = \number\value{exercise}} 直接印那个整数,完全绕过 \the。印刷形式是什么?\typeout{\meaning\theexercise} 把定义摊给你看,缺失的父级前缀在那里一眼显形。复位清单上有什么?\typeout{\meaning\cl@chapter} 会以 \@elt {equation}\@elt {figure}... 列出各个子级。写进 aux 文件的是什么?打开 .aux,读那条 \newlabel。

    三种失败与它们的签名。引用印出了错误的对象类型,意味着 label 站在一个刚刚没有 \refstepcounter 跑过的地方——把它挪到步进你计数器的命令之后。页面上号码对、\ref 里错,意味着 \thefoo 与 \p@foo 不一致;查一查是不是某个包或一份旧模板重定义了其中之一。编号怎么也复不了位,意味着父子关系是用 \newcounter{foo}[parent] 表达的、而那份文档里的父级是被 \setcounter 而不是被 \stepcounter 改动的——手工设置的章不会复位任何东西。

    而当你在写的是一个文档类:更省事的做法是在靠近顶部一次性声明计数器,连同它的复位父级与表示法,并且在没有需要时不要去碰 \p@ 与 \theH 这两个宏。计数器系统是 LaTeX 里少数几个「无聊的解法恰好也是正确的解法」的地方之一。

    本课速查

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

    小节 关键代码
    n_{\text{print}} = (n_{\text{parent}},\ n_{\text{raw}}) \qquad (2,4) \mapsto 2.4
    \documentclass[11pt,a4paper]{article}
    c_{\text{child}} \leftarrow 0 \quad \text{whenever} \quad c_{\text{parent}} \leftarrow c_{\text{parent}} + 1
    \documentclass[12pt,a4paper]{report}

    常见错误

    • 以为 \newcounter{foo}[section] 就会让号码印成 2.1。可选参数只登记复位;你还是需要 \renewcommand{\thefoo}{\thesection.\arabic{foo}}——或者 \counterwithin{foo}{section},它两件事一起做。
    • 用 \stepcounter 搭编号环境。号码看着对,但 \label/\ref 抓到的是上一个计数器;凡是打算被引用的环境都必须调用 \refstepcounter。
    • 在使用 \usecounter{enumi} 的列表之前写 \setcounter{enumi}{4}。\usecounter 自己会把计数器归零,所以 \setcounter 要写在它之后、放在列表的设置参数里。
    • 手工重定义 \thepage 而不用 \pagenumbering{...}。\pagenumbering 还会把编号复位到 1,更重要的是它告诉 hyperref 页码目标住在哪一片命名空间里。
    • 指望 \autoref 或 \cref 认识你发明的计数器:给 hyperref 定义 \exerciseautorefname、给 cleveref 同时定义 \crefname 与 \Crefname,否则你拿到的是一个光板编号或一个 ??。
    • 用 \setcounter 复位父级、然后纳闷为什么子级还在往前走:复位是在 \stepcounter 时触发的,不在 \setcounter 时。

    关于本课的常见问题

    \stepcounter 和 \refstepcounter 有什么区别?
    \stepcounter 让寄存器加一并复位它的子级。\refstepcounter 做同样的事,另外还把当前的印刷形式存进 \@currentlabel(外加 \@currentHref 与 \@currentcounter),而那正是紧随其后的 \label 会记录的字符串。只要这个计数器将来会被 \ref 一次,它就必须由 \refstepcounter 步进。
    怎么让计数器在每节开始时归零?
    声明时写 \newcounter{foo}[section],或者事后写 \counterwithin{foo}{section}。2018 版加入的内核形式其实做两件事——\counterwithin 还会把 \thefoo 重定义成 \thesection.arabic(foo),让印出来的号码自带章节前缀;而 \newcounter 只登记复位。旧安装上加载 chngcntr 就能拿到同样的两条命令。
    不用 amsthm 能给自己的环境编号吗?
    能,四行就够:\newcounter{exercise}[section]、\renewcommand{\theexercise}{\thesection.\arabic{exercise}},再加一个 \newenvironment,它的起始代码调用 \refstepcounter{exercise} 并排出 \textbf{Exercise \theexercise.}。amsthm 添的是共享计数器、样式和可选的名字参数这些便利,不是魔法。
    列表里的 usecounter 到底做了什么?
    它是计数器三行契约的第三行:写在 \begin{list} 的设置参数里,声明 \item 步进哪一个计数器、内部的 \label 又指哪一个计数器。它的定义以 \setcounter{#1}\z@ 收尾,所以列表一开始时它也会把那个计数器归零。
    为什么我自己的计数器在 PDF 书签或链接里找不到?
    因为目标名是由 \theH<counter> 拼出来的,而默认值只是一个光板整数,会在各章之间相撞。请把它改得更具体,例如 \renewcommand{\theHexercise}{\thechapter.\arabic{exercise}},并在日志里盯着重复目标的警告。
    怎么让 \ref 印出与标题不同的字符串?
    用 \p@<counter> 前缀:它只在标签的值被写出时前置到 \the<counter> 上,所以 \thesolution 可以在页面上保持简短,而 \ref{sol:x} 出来时自带章节前缀。名词请交给一层负责,否则 \autoref 会把它印两遍。

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

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

    KaTeX 错误
    试一个例子

    继续读

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