Counters & lengths

LaTeX has two kinds of register — a place to remember a value. A counter holds an integer; a length holds a dimension. Chapter, figure, and equation numbers are counted with counters; margins and box widths are measured with lengths. This page covers the programming basics of defining and manipulating your own counters and lengths. Units themselves and the space commands like \hspace/\vspace live on a separate page (linked below); here we focus on the machinery of counting, measuring, and remembering.

Counters — integer registers

A counter is a container that remembers one integer. As LaTeX reads through your document, it steps chapter when a chapter begins, figure when you place a figure, and prints those numbers into the heading or caption. These are the predefined standard counters, and you can also create your own.

You create a new counter with **\newcounter{foo}. Its value right after creation is 0. The name is letters only (no backslash) and must not already exist. The key extra is the optional parent: \newcounter{foo}[⟨parent⟩]** makes foo subordinate to parent, so that **every time parent is stepped, foo is automatically reset to 0**. That is exactly why the subsection number restarts whenever the section changes.

Three commands change the value. **\setcounter{foo}{3} assigns** foo the value 3; **\addtocounter{foo}{2} adds 2 to the current value (pass a negative number to subtract); and \stepcounter{foo}** adds just 1. \stepcounter has an important side effect: it resets to 0 every counter registered as a child of it. Note that the assignments made by \setcounter and \addtocounter are global — they do not revert when you leave a group ({ } or an environment).

Its close relative **\refstepcounter{foo} does the same stepping-and-resetting, but additionally makes foo the current reference target**. So a \label{…} placed right after it will point to the printed value of foo (its \thefoo, below), and \ref will recall that number. This is precisely the command LaTeX uses internally when it steps section, equation, or figure — which is why attaching a \label to a heading or equation references the right number. Reach for \stepcounter to merely advance a number internally, and \refstepcounter to create a referenceable “numbered thing.”

latex
\newcounter{trial}            % trial を作成(初期値 0)
\setcounter{trial}{5}         % trial = 5
\addtocounter{trial}{-2}      % trial = 3
\stepcounter{trial}           % trial = 4(子カウンタがあれば 0 に)

Getting the number out — \value

\value{foo} extracts a counter’s contents as a number that TeX can compute with. You can use it wherever LaTeX expects an integer** — in the value slot of \setcounter/\addtocounter, in an \ifnum test, even in a dimension calculation (as in \value{foo}\parindent). For instance, to bring bar into line with foo:

latex
\setcounter{bar}{\value{foo}}        % bar に foo の現在値を代入
\addtocounter{bar}{\value{foo}}      % bar に foo の値をさらに加える

Here is a common beginner’s stumble: **\value is not for display**. To actually *print* a number into the text, use a display command like \arabic (next section) or \thefoo. Think of it this way: \value gives the raw number for arithmetic, while the display commands give a string for humans to read — keep the two apart and the confusion disappears.

Printing a counter — \the and the format commands

Every counter comes with a family of display commands that turn its value into a printed string. You choose the notation:

CommandOutputRange / notes
\arabicArabic numerals (1, 2, 3 …)The usual choice; negatives allowed
\romanLowercase Roman (i, ii, iii …)Below 1 prints nothing
\RomanUppercase Roman (I, II, III …)Below 1 prints nothing
\alphLowercase letters (a, b, c …)1–26; out of range errors
\AlphUppercase letters (A, B, C …)1–26; out of range errors
\fnsymbolFootnote symbols (∗ † ‡ § ¶ ‖ …)1–9; for math mode

\alph/\Alph map to the 26 letters, so a value below 1 or above 26 raises a “Counter too large” error. \fnsymbol** emits nine footnote symbols in order — asterisk, dagger, double dagger, section sign, paragraph sign, parallel bars, double asterisk, double dagger, double-double dagger — with a valid range of 1–9. Because it runs in math mode, wrap it as $\fnsymbol{footnote}$ in text, or reach it through \thefootnote.

These commands take a counter name as their argument (as in \arabic{page}). But the number you actually see in print is emitted by a dedicated macro that every counter gets automatically: **\thefoo**. section has \thesection, figure has \thefigure, and so on. **Redefining this \the… with \renewcommand changes the entire number format.** To set section numbers in Roman numerals, for example, one line does it:

latex
\renewcommand{\thesection}{\Roman{section}}   % 1, 2, 3 → I, II, III
% 図番号を「節.通し番号」に:図 2.3 のように
\renewcommand{\thefigure}{\thesection.\arabic{figure}}

As in the second example, weaving another counter’s display into a \the… definition produces compound numbers like “2.3.” This works because the figure counter is set up with the section counter as its parent (its reset trigger) — showing that the appearance of a number and the linkage of when it resets to 0 are decided independently.

Standard counters and numbering depth

LaTeX predefines and automatically drives a set of counters. You can manipulate these freely too — renumbering chapters partway, making appendix figures read A.1, and so on:

  • Sectioning: part, chapter, section, subsection, subsubsection, paragraph, subparagraph (availability depends on the class)
  • Floats & equations: figure, table, equation
  • Footnotes: footnote, mpfootnote (footnotes inside a minipage)
  • Lists: enumi, enumii, enumiii, enumiv (the four nesting levels of enumerate)
  • Page: page
  • Control: secnumdepth (how deep sectioning is numbered) and tocdepth (how deep entries reach the table of contents)

The last two are a different breed — integer switches that govern how “deep” numbering and listing go. Each sectioning command has a level number (section is 1, subsection is 2, …), and a level is numbered when it is less than or equal to secnumdepth. The default is around 2, so \setcounter{secnumdepth}{1} drops numbers below the section level, and \setcounter{tocdepth}{1} trims the table of contents to sections. A neat illustration that counters are not only for tallying but also serve as configuration values that steer typesetting.

Lengths — dimension registers

The other kind, a length, is a register that remembers one dimension like 12pt or 2cm. Where a counter is an integer, a length holds a dimension with a unit, and may carry stretch and shrink (plus/minus). If you reuse the same dimension throughout a document, naming a length beats hard-coding the number — it is far easier to maintain.

You declare a new length with **\newlength{\mylen}. Unlike a counter, the argument is a command name with a backslash** (\mylen), and the initial value is 0pt. Two commands do the basic work: **\setlength{\mylen}{2em} (assign) and \addtolength{\mylen}{-3pt} (add; a negative value subtracts). Once made, the length can stand in anywhere a dimension is expected**, as in \hspace{\mylen}.

You can also compute with existing lengths such as \textwidth (the body width) and \baselineskip (the leading). Prefix a factor to scale them — 0.8\textwidth is 80% of the body width — and add or subtract lengths directly. For richer arithmetic, and division in particular, load the **calc package**: then an expression like \setlength{\x}{\textwidth/3} (a third of the body width), dividing a dimension by an integer, works as written.

One caveat with calc: to scale a dimension by a real factor you write it differently from integer division, inserting \real{} (e.g. \widthof{word} * \real{0.68}). And expressions must be type-consistent: 2cm + 4 (a bare integer added to a dimension) is illegal, whereas 2cm + 4pt — both sides dimensions — is fine.

document.tex
\usepackage{calc}
\newlength{\thirdcol}
\setlength{\thirdcol}{\textwidth/3}     % 本文幅の 1/3
\addtolength{\thirdcol}{-1em}            % そこから 1em 引く

Measuring typeset material — \settowidth and friends

The most powerful length operations measure the result of actual typesetting and store it in a length. **\settowidth{\mylen}{text} typesets the given text internally and puts its width** into \mylen. Likewise **\settoheight measures the height above the baseline and \settodepth the depth** below it (each targets a length you declared earlier with \newlength).

This shines when you want a dimension that fits its contents — “a rule exactly as wide as this heading word,” or “a label width matched to the longest entry.” The example below measures a word’s width and lays a rule of the same length beneath it:

document.tex
\newlength{\wd}
\settowidth{\wd}{重要}        % 「重要」の組版幅を測る
\noindent 重要\par
\rule{\wd}{0.4pt}            % 同じ幅の罫線

The same “typeset and measure” idea carries over to the calc package’s **\widthof{text}/\heightof/\depthof**, mentioned earlier. The difference: \settowidth is a command that assigns the result to a length, whereas \widthof can be dropped straight into an expression as a value.

Putting it together — a custom counter and a measured length

Finally, a small example using both. We create a custom counter question, format its display as “Q1.”, “Q2.”, …, and define a simple command \question that steps and prints the number each time it is called. Because it uses \refstepcounter, you can \label each question and \ref it later:

document.tex
\newcounter{question}
\renewcommand{\thequestion}{Q\arabic{question}}
\newcommand{\question}{\refstepcounter{question}\par\noindent\textbf{\thequestion.}\ }
\begin{document}
\question 最初の問い。\label{q:first}
\question 次の問い。
問い~\ref{q:first} を参照。   % → 問い Q1 を参照
\end{document}

Defining \thequestion with \renewcommand concentrates the number format (Q + Arabic numeral) in one place, easy to change later. The same instinct pays off for lengths: build dimensions relative to the body width (\textwidth), or set them by measuring contents with \settowidth, and your document keeps its proportions when the paper size or margins change. Rather than hard-coding fixed values, give them names and manage them in one place — that is the knack of using counters and lengths as programming tools.