MATH-499 · Lesson 10 of 12 · 22 min

Typesetting with LaTeX and managing references

Almost all research mathematics is typeset with LaTeX, and an honors thesis almost certainly will be too. LaTeX produces beautiful mathematics, handles numbering and cross-references automatically, manages bibliographies and is the format in which papers are submitted to the arXiv and to journals. It also has a reputation for being hard to learn, mostly undeserved: a small core of commands covers most needs, and the rest can be looked up. This lesson explains how LaTeX works, gives a thesis template, describes good habits for mathematical typesetting, and shows how to manage references so that the bibliography is accurate and consistent with no manual effort.

TeX and LaTeX

In 1977 Donald Knuth, dissatisfied with the typesetting of the second edition of his book The Art of Computer Programming, set out to write his own typesetting system. The result, TeX, appeared in 1978 and was rewritten as TeX82; it is famous for its stability, and its version numbers converge to \(\pi\), currently 3.141592653. TeX's algorithms for breaking paragraphs into lines and for spacing mathematical formulas remain the standard against which other systems are measured. In 1984 Leslie Lamport released LaTeX, a set of macros on top of TeX that lets authors describe the logical structure of a document, such as sections, theorems and lists, rather than its visual formatting. The current version, LaTeX2e, dates from 1994 and is maintained by the LaTeX Project team. The American Mathematical Society's packages amsmath, amssymb and amsthm provide the extended mathematical facilities that nearly every mathematics document uses.

A LaTeX document is a plain text file with markup. You write the source, run it through a LaTeX engine such as pdfLaTeX, XeLaTeX or LuaLaTeX, and obtain a PDF. Online editors such as Overleaf, launched in 2012 under the name WriteLaTeX, run the engine in the cloud and support collaboration, which many supervisors and students find convenient. Local installations such as TeX Live work offline and integrate with editors and version control.

The compile cycle

LaTeX processes a document in passes. The first pass typesets the text and writes labels and citations to an auxiliary file; it cannot yet know the number of a theorem that appears later, or the entries of the bibliography. A bibliography tool then reads the citations and the reference database and writes the formatted bibliography. Further passes of LaTeX read the auxiliary data and resolve every cross-reference. Tools such as latexmk run this sequence automatically until nothing changes.

A flow diagram: thesis.tex goes into a first pdflatex run, which writes an aux file; refs.bib and the aux data go into biber or bibtex, which builds a bbl file; two further pdflatex runs resolve references and produce thesis.pdf.
How a LaTeX document with a bibliography is compiled

A thesis template

The source below is a minimal but complete skeleton for a mathematics thesis. It loads the standard mathematical packages, defines theorem environments that share one numbering sequence within each chapter, uses biblatex for references and hyperref for clickable links. In the source, inline mathematics is enclosed in a backslash followed by an opening parenthesis and closed by a backslash followed by a closing parenthesis, and displayed mathematics uses the equation environment or the corresponding square-bracket delimiters; these are the modern LaTeX forms and are preferred over older notations based on dollar signs.

A minimal thesis skeleton in LaTeX (listing)
\documentclass[12pt]{report}
\usepackage{amsmath, amssymb, amsthm}
\usepackage[backend=biber, style=alphabetic]{biblatex}
\addbibresource{refs.bib}
\usepackage{hyperref}

\newtheorem{theorem}{Theorem}[chapter]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{corollary}[theorem]{Corollary}
\theoremstyle{definition}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{example}[theorem]{Example}

\newcommand{\reps}{r}          % one place to change notation

\title{Sums of Consecutive Integers}
\author{Amara N.\\ Supervisor: Dr. M. Okafor}
\date{April 2027}

\begin{document}
\maketitle
\begin{abstract}
We prove that the number \(\reps(n)\) of ways to write a positive integer \(n\)
as a sum of consecutive positive integers equals the number of odd divisors of \(n\) ...
\end{abstract}
\tableofcontents

\chapter{Introduction}\label{ch:intro}
\begin{definition}\label{def:rep}
A \emph{representation} of a positive integer \(n\) is a sequence of one or more
consecutive positive integers whose sum is \(n\).
\end{definition}

\begin{theorem}[Sylvester; Mason]\label{thm:main}
For every positive integer \(n\), \(\reps(n)\) equals the number of odd divisors of \(n\).
\end{theorem}

\begin{proof}
A representation with \(k\) terms starting at \(a\) satisfies
\begin{equation}\label{eq:factor}
  2n = k(2a + k - 1).
\end{equation}
Exactly one factor in \eqref{eq:factor} is odd ... see \cite{Pong2007}.
\end{proof}

\printbibliography
\end{document}

Several features of the template are good habits. Theorem-like environments share a counter, so Lemma 1.2 follows Theorem 1.1 and readers can find results by number. Every result has a label with a prefix indicating its kind, thm, def, eq or ch, so references are easy to manage. A macro for the main notation means that if the notation changes, one line changes. The proof environment from amsthm adds the end-of-proof symbol automatically.

Typesetting mathematics well

LaTeX makes good typography easy, but only if you use its facilities rather than fighting them. A few rules cover most cases.

Use the right commands for operators and functions: \sin, \log, \gcd and \max are typeset upright with correct spacing, and \operatorname defines new ones. Writing sin x without the backslash produces the italic product of three variables. Use \ldots and \cdots appropriately: \(1, 2, \ldots, n\) for lists and \(1 + 2 + \cdots + n\) between operators. Use \mid for divides, giving \(d \mid n\), rather than a vertical bar, which has the wrong spacing. Use \text inside formulas for words.

Use environments for multi-line displays: align for aligned chains of equations, cases for piecewise definitions, and never build alignments with spaces. Put punctuation at the end of displayed equations as part of the sentence. Size delimiters with \big, \Big and their relatives when needed, and keep parentheses matched.

Do not number every equation; number only those you refer to, and refer to them with \eqref, which adds parentheses. Do not hard-code numbers: write Theorem~\ref{thm:main}, with a tie that prevents a line break, never Theorem 2.1, which will be wrong as soon as you add a result.

Figures and tables

Figures are included with the graphicx package and placed in a figure environment with a caption and label. Vector formats such as PDF give crisp output; plots produced by Python's plotting libraries or by SageMath can be saved directly as PDF. Diagrams can also be drawn within LaTeX using the TikZ package created by Till Tantau, which produces typographically consistent figures, though it has a learning curve. Tables use the tabular environment, preferably with the booktabs package, which provides clean horizontal rules and discourages vertical ones.

Managing references

Bibliographies are managed with a database of references in BibTeX format, a plain text file of entries, and a tool that formats the cited entries. BibTeX itself was written by Oren Patashnik with Leslie Lamport in 1985; the newer biblatex package with the biber backend offers more flexibility and better handling of Unicode names. Either way, you never format a reference by hand: you cite by key and the tool does the rest, consistently.

BibTeX entries for two references of the model thesis (listing)
@article{Mason1912,
  author  = {Mason, Thomas E.},
  title   = {On the representation of an integer as the sum of consecutive integers},
  journal = {American Mathematical Monthly},
  volume  = {19},
  number  = {3},
  pages   = {46--50},
  year    = {1912},
}

@article{Pong2007,
  author  = {Pong, Wai Yan},
  title   = {Sums of consecutive integers},
  journal = {College Mathematics Journal},
  volume  = {38},
  number  = {2},
  pages   = {119--123},
  year    = {2007},
  eprint  = {math/0701149},
  archivePrefix = {arXiv},
}

Good sources of BibTeX entries are MathSciNet and zbMATH Open, both of which export entries for every item they index, and the arXiv, which provides entries for preprints. These are far more reliable than entries copied from other people's files or generated by guesswork. Even so, check each entry against the document: titles sometimes lose capitalization, accented names are mangled, and preprint entries must be updated when the paper is published. Reference managers such as Zotero and JabRef store entries, attach PDFs and export BibTeX files, and are worth setting up at the start of the project.

A bibliography in a thesis should include every work cited and nothing else, which the tools enforce automatically. Cite page numbers or theorem numbers when quoting a specific result from a long work, for example \cite[Theorem 3.2]{key}. Software used substantially should also be cited, with version numbers.

Checking a document automatically

As a thesis grows to hundreds of labels and dozens of citations, small inconsistencies creep in: a reference to a label that was renamed, a citation key with a typo, a bibliography entry missing its year. LaTeX reports some of these as warnings in its log file, which is worth reading. A short script can check more systematically. The program below parses a fragment of LaTeX source and a BibTeX database and reports undefined references and citations, unused labels and incomplete entries.

Checking labels, references, citations and bibliography entries in LaTeX source
import re

tex = r"""
\begin{theorem}\label{thm:main} ... \end{theorem}
\begin{lemma}\label{lem:parity} ... \end{lemma}
By Lemma~\ref{lem:parity} and Theorem~\ref{thm:main}, see also \cite{Pong2007, Mason1912}.
Corollary~\ref{cor:lengths} follows from \eqref{eq:factor}; compare \cite[Thm. 2]{Sylvester1882}.
\begin{equation}\label{eq:factor} 2n = k(2a + k - 1) \end{equation}
\begin{example}\label{ex:fifteen} ... \end{example}
"""
bib = """
@article{Mason1912, author = {Mason, Thomas E.}, title = {On the representation of an integer
  as the sum of consecutive integers}, journal = {American Mathematical Monthly}, year = {1912}, volume = {19}}
@article{Pong2007, author = {Pong, Wai Yan}, title = {Sums of consecutive integers},
  journal = {College Mathematics Journal}, volume = {38}}
"""

labels = set(re.findall(r'\\label\{([^\}]*)\}', tex))
refs = set(re.findall(r'\\ref\{([^\}]*)\}', tex)) | set(re.findall(r'\\eqref\{([^\}]*)\}', tex))
cites = {k.strip() for group in re.findall(r'\\cite(?:\[[^\]]*\])?\{([^\}]*)\}', tex) for k in group.split(',')}
entries = dict(re.findall(r'@\w+\{(\w+),(.*?)\}\s*(?=@|\Z)', bib, re.S))

print("undefined references:", sorted(refs - labels))
print("labels never referenced:", sorted(labels - refs))
print("citations missing from the database:", sorted(cites - set(entries)))
required = ['author', 'title', 'journal', 'year', 'volume']
for key, body in sorted(entries.items()):
    fields = set(re.findall(r'(\w+)\s*=', body))
    missing = [f for f in required if f not in fields]
    if missing:
        print(f"entry {key} is missing: {', '.join(missing)}")
Output
undefined references: ['cor:lengths']
labels never referenced: ['ex:fifteen']
citations missing from the database: ['Sylvester1882']
entry Pong2007 is missing: year

The script finds that the corollary label is referenced but never defined, that the example label is never referenced, that Sylvester's paper is cited but missing from the database, and that the Pong entry lacks a year. Each would otherwise produce a question mark in the PDF or an incomplete reference, exactly the kind of blemish that makes examiners wonder what else is careless.

Version control and backups

Keep the thesis under version control with Git, or at least in a synchronized folder with history, and commit after every working session with a short message. Version control lets you see what changed between drafts, recover deleted material and work on experiments in branches without fear. Keep at least two backups in different places. Every year some student loses weeks of work to a failed laptop or an overwritten file; with these habits it will not be you.

Worked problem

Typesetting a displayed derivation

Typeset the derivation of \(2n = k(2a + k - 1)\) from the sum of \(k\) consecutive integers starting at \(a\), aligned at the equals signs.

Show solution
  1. Use the align environment from amsmath, with an ampersand before each equals sign and a double backslash at each line end, and suppress numbers on lines not referred to with \notag.
  2. The rendered result should look like this:
  3. \[\begin{aligned} n &= a + (a + 1) + \cdots + (a + k - 1) \\ &= ka + (0 + 1 + \cdots + (k - 1)) \\ &= ka + \frac{k(k - 1)}{2}, \end{aligned}\]
  4. and multiplying by 2 gives \(2n = k(2a + k - 1)\), which receives an equation number and a label because the proof refers to it.

Answer: Alignment at the relation symbols, punctuation at the end, numbers only where needed and \cdots between operators: these small choices make a derivation easy to follow.

Common mistakes

  • MistakeHard-coding theorem and equation numbers in the text.

    InsteadUse \label and \ref (or \eqref) so numbers update automatically.

  • MistakeWriting function names without backslashes, such as sin x or log n.

    InsteadUse \sin, \log and \operatorname for correct upright typesetting.

  • MistakeCopying BibTeX entries from unverified sources.

    InsteadExport entries from MathSciNet, zbMATH Open or the arXiv and check them against the document.

  • MistakeIgnoring warnings in the LaTeX log.

    InsteadRead the log; undefined references and citations are reported there.

  • MistakeKeeping the only copy of the thesis on one laptop.

    InsteadUse version control and at least two backups in different places.

Summary and key terms

  • TeX was created by Donald Knuth from 1977 to 1978; LaTeX by Leslie Lamport in 1984, with LaTeX2e the current version since 1994.
  • LaTeX documents compile in passes: labels and citations are written to an auxiliary file and resolved in later runs, automated by tools such as latexmk.
  • A thesis template loads amsmath, amssymb and amsthm, defines shared-counter theorem environments and uses labels and macros consistently.
  • Good typesetting uses proper operators, ellipses, alignment environments, punctuated displays and automatic references.
  • References live in a BibTeX database exported from reviewing databases, formatted by BibTeX or biblatex with biber, and checked against the sources.
  • Automated checks, version control and backups protect the thesis from inconsistencies and loss.
LaTeX
A document preparation system built on TeX that separates logical structure from formatting.
amsthm
The American Mathematical Society package for theorem and proof environments.
BibTeX
A format and tool for bibliographic databases used with LaTeX.
biblatex
A modern LaTeX package for bibliographies, usually used with the biber backend.
cross-reference
A reference by label to a numbered item, resolved automatically.
version control
Software such as Git that records the history of changes to files.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why does a LaTeX document with references need more than one compilation pass?

    Show answer

    The first pass records labels and citations; the bibliography tool and later passes then insert the numbers and references that were unknown during the first pass.

  2. Write the LaTeX source for the formula \(d \mid n\) and for \(\gcd(a, b) = 1\).

    Show answer

    Write d \mid n and \gcd(a, b) = 1, each between the inline mathematics delimiters.

  3. Run the checking script. Which problems does it report?

    Show answer

    An undefined reference, cor:lengths; unused label ex:fifteen; missing citation Sylvester1882; the Pong2007 entry is missing year.

  4. Where should you obtain a BibTeX entry for a published paper?

    Show answer

    Export it from MathSciNet or zbMATH Open (or from the publisher), then check it against the paper itself.

  5. Why use a macro such as \reps for the main notation?

    Show answer

    If the notation changes, only the macro definition needs editing, and the notation is guaranteed to be consistent throughout.

  6. What does the tie in Theorem~\ref{thm:main} do?

    Show answer

    It is a non-breaking space, preventing a line break between the word Theorem and its number.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz