段階 4 · 構造と相互参照 29 / 48 ≈ 18 分で読める

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 を再定義すると読者には何も見えず、PDF ビューアの振る舞いには全部出ます。

    表記自身も再定義できるマクロです。\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] の後も番号は 2.4 でなく 4 と出ます。この任意引数にそんな評判があるのは、標準クラスが印字の部分を手作りでやっているからで、article.cls は \newcounter{subsection}[section] の直後に \renewcommand\thesubsection{\thesection.\arabic{subsection}} を持っていて、二行が一読されるのです。

    二行目——\setcounter{foo}{<value>}。Set と兄弟の \addtocounter は大域的です(カーネルが \global で包む)。だからグループの中で変えたカウンターはその後でも新しい値を保ち、通常のマクロと逆になります。第二引数は⟨integer expression⟩ なので、\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} は忘れられます。七から始まるリストを作る正しい方法は、同じセットアップ引数の中で \usecounter の後へ \setcounter を書くことです。

    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} が \@currentlabel を .aux へ書くので、素の \stepcounter で進めたカウンターは参照できません。後続の \label は前の \refstepcounter が残したものを記録し、\ref{ex:one} は章の番号か、前の練習問題か、?? を出します。標準の定理系環境が \refstepcounter を使う正確な理由がこれで、相互参照の課の「ラベルはカウンターの後」という規則にも機構があるわけです。

    \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> という名前のリストに住んでいて、親をステップするとそのリストを歩きます。カーネルは馴染みの階層を用意しています。footnote ではなく、equation、figure、table、各節レベルは section でリセットされ、subsection の親を迹って上へ行き、book 系クラスでは 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}{...} が第五章に "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)——そしてタイトルを \@currentlabelname へ入れると、\nameCref と PDF のブックマークがそれを運びます。環境を分割可能・不可能にしたいときの道具は \needspace{3\baselineskip} か minipage のラッパーで、カウンターの変更ではありません。

    これを文書でなくクラスやパッケージの中に書くなら、@ がカテゴリーコードで守られていることを思い出してください。定義を \makeatletter ... \makeatother で包み、環境が内部状態を書き込む必要があるなら、\exercise を手で再定義するより、モダンなカーネルが提供するフック(\AddToHook)を優先してください。

    \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} が文字列を複製せずにそれを伝えます。単語でなく書式——角括弧付きの番号、math mode 内の接頭辞——が欲しいなら、\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} が数えを再開するのはそれで、\pagenumbering の代わりに \setcounter{page}{1} を書くのが見かけ倒しなのも同じ理由です。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 行を読んでください。

    三つの失敗とその症状。物体の種類を間違えた参照は、ラベルが \refstepcounter の直後でない場所に立っていることで、あなたのカウンターをステップするコマンドの後へ移します。ページでは正しく \ref では間違った番号は、\thefoo と \p@foo が食い違っていること。パッケージか古いテンプレートがどちらかを再定義していないか確認してください。リセットされない番号付けは、親への関係が \newcounter{foo}[parent] で書かれているのに、その親が \stepcounter ではなく \setcounter で進められているケースです。手でセットした章は何もリセットしません。

    クラスを書いているときは、カウンターは先頭のほうで一度だけ、リセットの親と表記とともに宣言し、\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 はその後、リストのセットアップ引数の中へ置いてください。
    • \pagenumbering{...} の代わりに \thepage を手で再定義すること。\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}}、そして開始コードで \refstepcounter{exercise} を呼び \textbf{Exercise \theexercise.} を組版する \newenvironment。amsthm が足すのは共有カウンター、スタイル、任意の名前引数といった便宜で、魔法ではありません。
    list の中で 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 が二回印字します。

    ライブ playground:LaTeX を編集して即描画

    入力すると即座にプレビューが更新されます。わざと壊してエラーの見た目も確認しましょう。

    KaTeX エラー
    例を試す

    続けて読む

    同じ話題への三つの入口:記法そのもの、それを教える課、そして実際に使っている記事。