2nd Course in Latex
2nd Course in Latex
Petri Laarne
Version 1.0
May 31, 2024
Contents
Contents 1
0 Introduction 5
0.1 What you need . . . . . . . . . . . . . . . . . . . . . . . . . . 5
0.2 About this version . . . . . . . . . . . . . . . . . . . . . . . . 6
0.3 See how it is made . . . . . . . . . . . . . . . . . . . . . . . . 6
1 Programming 7
1.1 How LATEX processes files . . . . . . . . . . . . . . . . . . . . 8
1.1.1 Splitting your source into multiple files . . . . . . . . . 10
1.2 Commands and environments . . . . . . . . . . . . . . . . . . 12
1.2.1 Defining commands . . . . . . . . . . . . . . . . . . . 12
1.2.2 Arguments to commands . . . . . . . . . . . . . . . . 14
1.2.3 Groups and scopes . . . . . . . . . . . . . . . . . . . . 15
1.2.4 Optional arguments . . . . . . . . . . . . . . . . . . . 17
1.2.5 Replacing existing commands . . . . . . . . . . . . . . 18
1.2.6 Defining environments . . . . . . . . . . . . . . . . . . 19
1.3 Diagnosing errors . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.4 Document structure . . . . . . . . . . . . . . . . . . . . . . . 23
1.4.1 Document classes . . . . . . . . . . . . . . . . . . . . . 25
1.4.2 Loading packages . . . . . . . . . . . . . . . . . . . . . 26
1.5 Creating your own style file . . . . . . . . . . . . . . . . . . . 28
1.6 Counters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.7 Further topics* . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.7.1 Control flow . . . . . . . . . . . . . . . . . . . . . . . . 32
1.7.2 Robustness . . . . . . . . . . . . . . . . . . . . . . . . 33
1.7.3 More on command and style definitions . . . . . . . . 34
2 Styling text 35
2.1 The not so minor characters . . . . . . . . . . . . . . . . . . . 35
2.1.1 Special characters . . . . . . . . . . . . . . . . . . . . 36
2.1.2 Dingbats and logos . . . . . . . . . . . . . . . . . . . . 37
2.2 Style and size . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1
2.2.1 Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.2.2 But what about underlining? . . . . . . . . . . . . . . 39
2.2.3 Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.2.4 Verbatim text . . . . . . . . . . . . . . . . . . . . . . . 40
2.3 Spaces, line breaks, and paragraphs . . . . . . . . . . . . . . . 42
2.4 Colour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.5 Footnotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.6 List structures . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.7 Sectioning commands . . . . . . . . . . . . . . . . . . . . . . 48
2.7.1 Customizing headings . . . . . . . . . . . . . . . . . . 50
4 Mathematics layout 75
4.1 Equation environments . . . . . . . . . . . . . . . . . . . . . . 75
4.1.1 Single numbered equation . . . . . . . . . . . . . . . . 76
4.1.2 Single equation on many lines . . . . . . . . . . . . . . 76
4.1.3 Many equations, many lines . . . . . . . . . . . . . . . 78
4.1.4 Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.1.5 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.2 Fonts and text in mathematics . . . . . . . . . . . . . . . . . 82
4.2.1 Explanatory text . . . . . . . . . . . . . . . . . . . . . 82
4.2.2 Mathematics fonts . . . . . . . . . . . . . . . . . . . . 83
4.2.3 Completely different typefaces . . . . . . . . . . . . . 86
4.2.4 Units of measure . . . . . . . . . . . . . . . . . . . . . 86
4.3 Mathematical symbols and whitespace . . . . . . . . . . . . . 87
4.3.1 Spacing . . . . . . . . . . . . . . . . . . . . . . . . . . 88
4.3.2 Operators and limits . . . . . . . . . . . . . . . . . . . 91
4.3.3 Fractions . . . . . . . . . . . . . . . . . . . . . . . . . 93
4.4 Size in mathematics . . . . . . . . . . . . . . . . . . . . . . . 93
4.5 Decorations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
2
4.5.1 Accents . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.5.2 Dots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
4.5.3 Braces and highlighting . . . . . . . . . . . . . . . . . 96
4.5.4 Arrows . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4.6 Theorem environments . . . . . . . . . . . . . . . . . . . . . . 98
3
8 Graphics with TikZ 149
8.1 Coordinates, nodes, and paths . . . . . . . . . . . . . . . . . . 150
8.1.1 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
8.1.2 Path options . . . . . . . . . . . . . . . . . . . . . . . 153
8.1.3 Absolute positioning* . . . . . . . . . . . . . . . . . . . 155
8.2 Special paths . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
8.3 Transformations . . . . . . . . . . . . . . . . . . . . . . . . . 159
8.4 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
8.5 Setting styles* . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
8.6 Some extensions . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.6.1 Commutative diagrams . . . . . . . . . . . . . . . . . 163
Index 192
Colophon 200
4
Chapter 0
Introduction
These notes were created for a course called Advanced LATEX, offered to PhD
students at University of Helsinki in spring 2024.1 They attempt to give a
somewhat unified view of what LATEX is, how it works, and how it should
be used in producing scientific literature. They are much larger than can be
covered in a two-week intensive course – my hope is that they can work as
a reference as well.
These notes owe a lot to The LATEX Companion [4] by Frank Mittelbach
and other LATEX team members. The third edition of the book is a treasure
trove for a serious LATEXnician, but at three kilograms (printed version) it is
not an investment for everybody. I have tried to distill some of the wisdom2
into these notes (which are still not what you’d call lightweight).
Of course, the authoritative reference for each package is the documen-
tation hosted on the Comprehensive TEX Archive Network (ctan.org).
5
Note to Overleaf users
As an exception, there are a few blocks like this that discuss Overleaf. I felt
that Overleaf is worth mentioning, since so many people use it nowadays,
and it has some differences to locally installed tools.
a The source code and latest PDF release for these notes are available
on GitHub: github.com/polsys/2nd-course-latex.
You are invited to see how I built these notes – I tried to follow my own
guidelines, but of course you can disagree with some choices. In the end,
there is no one true path to TEXnical enlightenment.
If you spot a typo or an error, you can send a pull request with the
correction, file a GitHub issue, or send me an email about it. You can find
my up-to-date contact information at petri.laarne.fi.
3
creativecommons.org/licenses/by/4.0/
6
Chapter 1
Programming
Warning
Even when using LATEX, the old TEX is still there. It is possible to use
plain-TEX commands in your documents, but this is highly discouraged.
These commands sidestep all the enhancements brought by LATEX, and might
cause hard-to-diagnose problems. You might need them when writing more
complicated packages, but then you are already solidly in the “you are free
to shoot your own foot” territory. Some such commands are noted in these
Warnings.
Unfortunately, many heritage templates and Stack Exchange answers
still mix TEX, LATEX, and pre-1994 LATEX. Examples of the latter include
the obsolete \bf and \it commands (e.g. writing {\bf bold} instead of
\textbf{bold}).
7
New in LATEX3
The “standard” LATEX version is 2ε, released in 1994. LATEX3 is a long-
running project (started already before 2ε, and reactivated around 2018) on
rewriting the internals of LATEX to be more extensible.
LATEX3 introduces new commands for defining commands and environ-
ments. We will only discuss the version 2ε methods (which are still valid)
here, but if you find yourself writing a package, you should consider learning
about the new methods.1
We will talk about some new features and accessibility improvements
brought by LATEX3 below, starting already in Section 1.4.
3. This means that all page number references point to the state of the
previous compilation.
1
www.latex-project.org/help/documentation/usrguide.pdf
8
Warning
Sometimes, a typo’ed command might end up messing the .aux file. In this
case, fixing the error and recompiling will not be enough, since the .aux file
feeds back incorrect data.
Usually, the .aux file from the recompilation is no longer erroneous, so
a second recompilation is enough.
Rarely, the state might be so messed that the .aux file gets re-corrupted
before the compilation halts. This manifests itself as weird compilation
errors even when you have reverted your code back to a known good state.
If this happens, delete the auxiliary files and recompile from scratch. Some
LATEX editors have even a handy button for this.
Since this is the only mechanism for creating forward references, the
.aux file is not the only one of its kind. Some other temporary files that
you can expect to see in your compilation folder:
.bbl The bibliography generated by the bibliography compiler. See below
and Section 5.2. Some publishers, in particular arXiv, require you to
submit this file together with your source code.
.log This is the raw compiler log. LATEX editors parse this into a more
readable form, but long, multi-line error messages can be easier to
read from the raw log.
9
These auxiliary files can also be read and written by other programs.
The prime example is the bibtex program. Processing a database of bib-
liographic entries is too complicated to do inside the TEX programming
environment. Therefore, a separate program is used.2 It works like this:
1. You write bibliographic data in a .bib file. See Section 5.2 for the
syntax.
4. When the bibtex program is invoked, it reads the .aux file. It creates
a combined list of all citations, and outputs the commands to typeset
a bibliography into the .bbl file.
5. When LATEX is run again, it reads the .bbl file and prints the bibli-
ography.
The LATEX compiler and bibtex are decoupled in the sense that you only
need to run bibtex when you need to update the bibliography.
In fact, arXiv does not run any bibliographic compilers at all. They
require you to submit the .bbl file created by your preferred compiler. (This
probably has to do with two facts: 1. There is more than one bibliography
compiler in wide use. 2. The bibliographic databases can contain a lot of
data, also including uncited works.)
Good practices
While it would sound reasonable to split even articles into section-specific
files, there are two reasons not to do so:
• Many journals prefer to have the submission in one .tex file for similar
logistical reasons.
2
The newer biber compiler used by biblatex package works in a similar way to that
described here.
10
As we see below, there can also be some complexity in setting up the editor.
Therefore my recommendation is: only split the document if you are
preparing a book. This advice might be extended to theses, and lecture
notes edited by a limited amount of people simultaneously. These very
notes are split into one file per chapter.3
When I started preparing this course, this was the piece of advice I got
the most from other TEXnicians. Consider yourself warned.
% Preamble
\includeonly{intro,discussion}
Gotcha!
\include only produces a warning if it cannot find the specified file. Also,
some packages work unreliably with \include.
Do not use \includeonly when preparing the final copy of your docu-
ment, since some of the .aux files could be outdated.
3
And suffer from some associated problems. The “main file detection” heuristics of my
editor do get confused by this chapter where several \documentclass commands appear.
4
Some environments do not allow \input inside them.
11
Good practices
If you separate chapter contents into their own files, I highly recommend
keeping the “main file” very short – consisting only of the preamble and
\include commands.
In either case, the included .tex file must not contain a preamble – there
already was one in the main file. Conversely, this means that the separated
files cannot be compiled on their own.
There might be some editor-specific support for setting the main file of
your project. This allows you to hit Compile while editing a chapter file,
and the main file gets compiled instead.
Good practices
When should you define your own commands? Generally, the less customiza-
tion you have, the easier your manuscript is for the journal publication pro-
cess and your coauthors. At the same time, good commands make the code
semantically meaningful.
I personally find \norm{...} easier to read than \left\|...\right\|,
and \Prob certainly better than \mathbb P, but others could find those an
overkill. This is a hard balance to strike.
There is just one strict rule: never repurpose the name of an existing
base LATEX command. It will cause endless trouble when the journal style
or some package tries to use the original command.
12
\newcommand{\hello}{Hello world!}
Hello world!
\hello
Here \newcommand takes two arguments: the first is the name of the
macro to define, and the second is what the macro expands to. In TEX
things are grouped with the {} braces. (The first set of braces is technically
unnecessary, but it looks cleaner in my opinion.)
Let us see another example where the command is used repeatedly, and
also expanded inside other commands:
\newcommand{\hello}{Hello world}
–Hello world, they whispered.
--\hello, they whispered.\\ –I said, HELLO WORLD!
--I said, \MakeUppercase{\hello}!
Since the macros are expanded recursively until there is nothing more
to expand, you can write things that are semantically very unclear, but
comprehensible to a computer:
\newcommand{\hi}{^\infty}
\newcommand{\underscore}{_} ∞
\newcommand{\lo}{\underscore{i=1}}
X
\[ \sum\lo\hi \] i=1
1. \sum\lo\hi
2. \sum\underscore{i=1}\hi
3. \sum_{i=1}\hi
4. \sum_{i=1}^\infty
So the end result is the same as if one had written the sum sensibly from
the beginning.
13
Warning
In plain TEX macros are defined with \def and \let. If you see code using
either, you have entered the “shoot your own foot” territory.5
The TEX compiler works in two basic modes: text mode and math mode.
Some commands (for example, \sqrt) are only usable in math mode.
How to define a command that works both in text and math mode? You
can use the \ensuremath command: in text mode it wraps its contents
inside $, and in math mode it does nothing:
\newcommand{\magic}{\ensuremath{\sqrt 2}}
√
The number 2 satisfies
The number \magic{} satisfies
\[ √ 2
\magic^2 = 2. 2 = 2.
\]
14
\[
\frac{1}{2}
= \frac 1 2 1 1 1
= \frac12. = = .
2 2 2
\]
Do note the last one – LATEX command names can only consist of letters,
so the number 1 is not interpreted as part of the command name but an
argument. There is no requirement to separate the name and a following
number. (I do find the last example hard to read, though.) Conversely,
whitespace won’t separate longer arguments; you really need the braces:
\[
\frac 12 34
1 12
\neq \frac {12} {34}. 34 6= .
\] 2 34
\newcommand{\magic}{314 159}
314159
\[ \frac \magic \pi \]
π
Gotcha!
Some built-in macros swallow the whitespace that follows them. If a word
space is actually needed, you can feed the command an empty group {}:
15
that change how all the following text is output. For example, the font-sizing
commands like \tiny and \Large affect the size of all text that follows them.
However, this effect only lasts until the group is closed with a }.
If you forget about this and just write \tiny without any scoping, you
will have tiny text until the end of document (or the next font size com-
mand).
There is one place where the braces do not delimit a group: in the defini-
tion of commands. In the following example, \mouse{Squeak} is expanded
into \tiny Squeak and not into {\tiny Squeak}. Therefore the effect per-
sists onto the following line.
\newcommand{\mouse}[1]{Mouse: \tiny#1.}
Mouse: Squeak.
\mouse{Squeak}\\ I: Oops.
I: Oops.
The scope can be introduced here by adding {} into the command definition:
\newcommand{\mouse}[1]{{Mouse: \tiny#1.}}
Mouse: Squeak.
\mouse{Squeak}\\ I: Alright.
I: Alright.
Scopes also affect things like \newcommand: the command \mouse defined
above only exists within the example block, and is not accessible beyond it.
16
1.2.4 Optional arguments
Some commands also have optional arguments. Instead of braces, these are
passed within brackets []. A basic example is the \sqrt command that
produces not only square roots, but general roots:
$\sqrt{7}$, √ √
3
$\sqrt[3]{7}$. 7, 7.
Gotcha!
Inside an optional argument, LATEX interprets the first ] it sees as the closing
bracket. This means that if you need to use [] inside an optional argument
(say, as an optional argument to an inner command), you need to wrap
things in braces. Quite often, you might need even two sets of braces.
Compare the two citations:
The first citation is shown correctly. In the second, the optional argument is
interpreted to be “Page [40” and the citation name then “m” (only a single
letter since it was not wrapped in braces). The remaining “aybe?]{TLC}”
is then normal body text.
Gotcha!
LATEX ignores whitespace between a command and its optional argument.
This might sometimes lead to surprising behaviour. Here the second list
item is interpreted as an optional argument that replaces the bullet symbol:
17
\begin{itemize} • Cookies
\item Cookies
\item [Maybe cake?] Maybe cake?
\item Drinks
\end{itemize} • Drinks
The syntax for optional arguments is not always clear: sometimes they
precede the real arguments, sometimes they follow them. Sometimes they
consist of just one thing, sometimes they can be a list of things (see the
discussion of \usepackage later in this chapter).
Again, the redefinition of a command lasts only for the current scope. Once
the scope is closed, \epsilon again means the old regular symbol. To rede-
fine a command within the entire document, you need to call \renewcommand
in the document preamble.
Here is an example of \newcommand and \renewcommand with arguments.
The two commands have matching syntax. Note that the new definition is
free to have a different number of arguments.
18
The \DeclareCommandCopy robustly copies the current definition of a
command.6 It is then possible to renew the definition, and still access
the previous version. Let us illustrate this by swapping the meanings of
\epsilon and \varepsilon:
\DeclareCommandCopy{\oldepsilon}{\epsilon}
\DeclareCommandCopy
Epsilon and varepsilon ε
{\oldvarepsilon}{\varepsilon}
\renewcommand{\epsilon}{\oldvarepsilon} Epsilon ε and varepsilon
\renewcommand{\varepsilon}{\oldepsilon}
New in LATEX3
This command is part of the LATEX3 programming interface. It requires a
relatively recent (2020 or later) LATEX version.
\begin{center}
\renewcommand{\epsilon}{\varepsilon}
Centered text and $\epsilon$ Centered text and ε
\end{center}
19
\newenvironment{cool}
{A mathmo enters the lab.\par}
{\par The mathmo leaves the lab.} A mathmo enters the lab.
A massive explosion occurs.
\begin{cool} The mathmo leaves the lab.
A massive explosion occurs.
\end{cool}
(If you’re wondering about the \par commands, they are used to ensure
that the first and last lines are their own paragraphs.)
There is also \renewenvironment that works like \renewcommand.
Since environments are groups, it is possible to change font characteris-
tics for the duration of the environment:
\newenvironment{mouse}{\tiny}{}
Note that here the end code is empty; the font properties are reset automat-
ically as the group ends.
Gotcha!
If the begin/end code of your environment spans multiple lines, you need
to be careful with line breaks. The extra whitespace might cause LATEX to
output an unintended empty space or even a paragraph break. To avoid
line breaks to be interpreted as line breaks, you can end each line in the
environment definition with % – the comment character shallows the line
break.
This same thing applies to empty lines before and after environment
usage – the usual paragraph-breaking rules apply. If you don’t want to start
a new paragraph after the environment ends, do not leave an empty line
between \end{...} and the following text. (For visual separation in the
code, I prefer a line containing just %.)
20
1.3 Diagnosing errors
Macro languages were popular in the 1980s, back when 640 kilobytes was
enough memory for anyone. An unfortunate consequence of TEX’s stability
is that the compiler still operates under this worldview. The source code is
read exactly once from top to bottom, and if the code is not correct, error
messages can be extremely cryptic.
21
Good practices
You should always check for warnings before submitting a document. It’s a
bit embarrassing to publish a document with [?] citations, after all.
Overfull and underfull hboxes are usually not worth fixing until the final
typesetting phase, since very small changes to the text or style can drastically
change the line breaking.
Errors, on the other hand, halt the compiler altogether. The compiler
can try to ignore errors and recover itself, but at that point it is guessing
what you tried to mean, and might get even more confused. Quite often the
internal state is so messed up, TEX can only spew more errors.
Good practices
Recompile often. It is much easier to locate an error when you have modified
only a small region of the code.
Always recompile after you modify a command definition or do a find-
and-replace operation. These are risky.
If your document takes a long time to compile, find a way to speed it up
(skip complicated TikZ pictures in draft mode, only include chapters you’re
working on, etc.). If recompilation breaks your flow, you won’t do it often
enough.
For some pointers for conditionally skipping parts of pictures, see
page 33.
22
Bad math environment delimiter
Conversely, do you have an extra $ inside a display math environment?
Misplaced alignment tab character &
Extra alignment tab has been changed to \cr
You have a bit too many & characters per line, or are using an equation
environment that does not support them at all.
Package amsmath Error: \begin{split} won’t work here.
You need to wrap the environment inside equation or one of its friends.
Missing character: There is no … in font nullfont!
If this happens inside a TikZ picture, you have very likely mistyped a com-
mand or option. Check the code line shown above the error message.
Good practices
I would advocate for starting every project from an empty .tex file. The
problem with “heritage” templates is that they accumulate a lot of unnec-
essary package dependencies and custom commands. I’ve seen files where
the same package is loaded three times.
By starting from an empty file and only adding the customizations you
need for the particular project, you help maintain your “code hygiene”.
23
1 \DocumentMetadata{}
2 \documentclass[a4paper]{article}
3
4 \fontencoding{OT1} % Read note below!
5 \usepackage[hidelinks]{hyperref}
6
7 \title{My first document}
8 \author{Firstname Lastname}
9 \date{\today}
10
11 \begin{document}
12
13 \maketitle
14
15 % Rest of content here...
16
17 \end{document}
We discuss the first line in a LATEX3 note below. On the second line,
we load a LATEX document class. The document class determines the ba-
sic layout of your document, and it is where several basic commands like
\maketitle are defined. We will look at some different document classes
and arguments in the next subsection.
Lines 1–10 are collectively known as the preamble. This is the best place
to define new commands and do other setup. Additional packages are also
loaded here; see Section 1.4.2.
New in LATEX3
What’s interesting in the above example is the one package that is not
loaded. The inputenc package used to be very important to load, since it
told LATEX about the encoding of non-English characters. Since 2018 LATEX
has followed the rest of the world and uses UTF-8 encoding by default.
What does this mean for you? If you create a new file in any reasonably
modern LATEX editor, you get the correct encoding and don’t need to load
inputenc.
However, if you modify a sufficiently aged file that contains non-English
characters, you might stumble upon legacy encodings like latin1 or cp1252.
In such files, the inputenc package must be loaded with the proper optional
argument.
24
LuaLaTeX or XeLaTeX compilers, this command might cause subtly worse
output. See page 62 for more explanation.
Trying to output any text before the \begin{document} line is an error.
When the compiler reaches that line, a lot of stuff happens behind the scenes
to prepare LATEX for actually outputting pages.
Similarly, the \end{document} line is necessary. At that point, a lot of
code is executed to make sure that everything is output properly. Any text
written below that line is ignored. (I do not recommend writing anything
there!)
New in LATEX3
An important part of the LATEX3 project is revising the PDF output to
include accessibility information: for example, tagging section headings as
headings and not just bold text in big font. Since this might cause issues
with some packages, the new behaviour is opt-in.
If you write \DocumentMetadata{} before the \documentclass decla-
ration, you opt in to these new features. This command also enables new
functionality in e.g. the hyperref package.
Good practices
Journals commonly define their own document classes, based on one of the
standard classes. The discussion below only applies to the documents where
you are in charge of the style. Always look at the journal instructions for
preparing the published version of your article.
article As the name suggests, this should be used for articles, short notes,
and such. The \maketitle command does not create a separate title
page, and the highest-level sectioning command is \section. There is
no page break between sections.
report This class is suitable for e.g. a thesis, lecture notes, or a longer
article. The present notes use this class. There is a separate title
page, and the highest-level sectioning command is \chapter. Each
chapter begins on a new page.
book This is the heaviest of all the classes. You get a lot of empty pages,
just like in a real printed book. If you find yourself using this class,
you have agreed to something monumental.
25
There is also a letter document class, which understandably sees little use
nowadays. But it is still there if you need it!
Options passed to document classes are interesting in that they are also
passed to all packages. If you pass a4paper to the document class, then you
don’t need to pass it again to the geometry package.
Some options are supported by all the basic document classes:
10pt, 11pt, 12pt Sets the body font size. Fonts for section headers, foot-
notes, etc. are scaled accordingly. The default is 10 points.
\usepackage[hidelinks]{hyperref}
26
Options can be passed to packages inside the brackets. Here we pass the
hidelinks option that suppresses the coloured boxes around clickable links.
Some packages also take options with a key=value notation.
In addition to the options passed explicitly, all the options passed to the
document class are also forwarded to the package.
Good practices
You should always load hyperref. It not only turns cross-references into
clickable links, but also adds section headers to the PDF table of contents
(usually found in the sidebar of any reader application). Your readers will
appreciate this navigation aid.
babel Support for languages other than English. See Section 3.1.
xcolor Support for setting text and symbols in colour. Replaces the old
color package included in early LATEX. See Section 2.4.
Gotcha!
Quite a few packages modify the standard LATEX commands and even the
commands defined by each other. This means that sometimes it is important
to load packages in the correct order, so that the modifications are applied
27
sensibly. The core packages are usually compatible with each other, but you
should always check the package documentation for possible conflicts.
For example, it is important to load ntheorem before hyperref, since the
former modifies the label commands that are also touched by the latter.
Otherwise, you might get non-functioning hyperlinks.
Good practices
As discussed above, it is best to keep an article in one file. The same can
be said also of a thesis.
You should only create a style file if you have multiple documents sharing
commands and packages. For example, a style file is useful for a personal
notes folder.
\usepackage{mystyle}
\NeedsTeXFormat{LaTeX2e}[2020/02/02]
\ProvidesPackage{mystyle}[2024/05/20 mystyle]
These tell TEX that the file requires LATEX released no later than 2 Febru-
ary 2020, and that the file contains the version of mystyle published on
20 May 2024. (Keeping the latter number up to date is relevant only for
package writers, but it is nice to keep in sync for your own reference.)
After this, you can do everything that you could do in document pream-
ble. Ideally, you would define your favourite commands here. One change
is that loading packages is done with \RequirePackage.
7
Or on TEX’s search path, but don’t ask me about that.
28
As a complete example, here is a heavily shortened version of the style
file for these notes.8
\NeedsTeXFormat{LaTeX2e}[2020/02/02]
\ProvidesPackage{latexcourse}[2024/03/05 latexcourse]
% A simple TODO command, available only when the 'draft' option is set
\DeclareOption{draft}{
\newcommand{\todo}[1]{\textcolor{red}{\textbf{[TODO: #1]}}}
}
\ProcessOptions\relax
\RequirePackage{mathtools}
\RequirePackage{csquotes}
\RequirePackage[finnish,french,english]{babel}
\RequirePackage[hidelinks]{hyperref}
In this example, you could also see how a simple boolean option can be
declared. It is enabled with \usepackage[draft]{latexcourse}. We do
not discuss further package development topics here.
1.6 Counters
LATEX keeps a lot of internal state in variables called counters.
29
the \setcounter command. One such example is seen in Väisälä’s topology
textbook:
\setcounter{chapter}{-1}
\chapter{Prerequisites}
\begin{enumerate}
\item Add one and step: 1. Add one and step:
\stepcounter{enumi}
\item Add seven and step: 3. Add seven and step:
\addtocounter{enumi}{7}
\item Minus one + step: 11. Minus one + step:
\addtocounter{enumi}{-1}
\item Same as above! 11. Same as above!
\end{enumerate}
Section~\arabic{section}\\
Section 6
Section~\alph{section}\\ Section f
Section~\Alph{section}\\ Section F
Section~\Roman{section}\\ Section VI
Section~\fnsymbol{section}
Section ‖
The last command \fnsymbol is used for footnote symbols. Note that the
letter-based styles can be capitalized by using \Roman instead of \roman etc.
To format numbers as natural-language strings, you can use the fmtcount
package. For example, its \ordinalstring command produces strings like
“first”, “second”, and so on. There are several capitalization variants, as
well as support for a few languages (including grammatical gender).9 The
package also provides commands for binary and hexadecimal number for-
matting.
To define your own counters, you can use \newcounter:
9
Unfortunately, Finnish is not yet among them.
30
\newcounter{fact}
\newcommand{\axiom}[1]{\stepcounter{fact}%
\textbf{Rule \thefact.} #1\par} Rule 1. Don’t use plain TEX.
Rule 2. See the above.
\axiom{Don't use plain \TeX.}
\axiom{See the above.}
If you want the counter to reset when another counter is stepped, you
can pass an optional argument (after the counter name!) to \newcounter.
An example use case is to reset the counter every time a new section is
started (in which case the optional argument would be [section]):
\newcounter{exc}[fact]
\renewcommand{\theexc}{\roman{exc}}
\newcommand{\except}[1]{\stepcounter{exc}% Rule 1. Don’t use plain TEX.
{\tiny Exception~\theexc. #1}\par} Exception i. Unless Don Knuth passes by.
Gotcha!
This only sees the effect of \stepcounter on the another counter; if you use
\setcounter to change it, the dependent counter is not reset.
\counterwithin{equation}{section}
31
This effect can be undone with the \counterwithout command:
\counterwithout{equation}{section}
You can also pass an optional formatting command. If you like your equa-
tions in Roman numbers within section (like 1.iv), then you’d set
\counterwithin[\Roman]{equation}{section}
% \counterwithin[\Roman]{equation}{section}
\renewcommand{\theequation}{\thesection.\Roman{equation}}
\counterwithin{equation}{section}
\renewcommand\theequation{\arabic{equation}}
32
\ifthenelse{\thepage>10}
{We're past page~10.}
{We haven't passed it yet.} We’re past page 10. Yet
\ifthenelse{\thepage>50} page 50 is still ahead.
{We're also past page~50.}
{Yet page~50 is still ahead.}
The syntax allows basic comparisons of counters with <, =, and >. There
is also the \isodd command that is useful with page numbers. Lengths (Sec-
tion 3.2.1) can be compared by wrapping the comparison inside \lengthtest.
See the package documentation for all expressions.
It is also possible to define and test boolean variables that have value
equal to true or false:
\newboolean{MyBool}
\ifthenelse{\boolean{MyBool}}
{It is true!}{It is false!}
It is false!
\setboolean{MyBool}{true} It is true!
\ifthenelse{\boolean{MyBool}}
{It is true!}{It is false!}
1 is I
\newcounter{mynumber} 2 is II
3 is III
\whiledo{\themynumber<6}{% 4 is IV
\stepcounter{mynumber} 5 is V
\arabic{mynumber} is \Roman{mynumber}\\}
6 is VI
1.7.2 Robustness
The design of TEX as a macro language poses some challenges. One is
controlling the time and place where macros are expanded.
33
Some commands like \section store their contents in the auxiliary file:
the section title is also used for setting the table of contents. Commands
like \ifthenelse cannot be used in this context. They are called fragile
commands.
The commands that expand to text are generally robust. Similarly, most
L TEX commands are nowadays robust.
A
It is very rare to see a robustness issue, but its telltale signs are very
confusing error messages caused by using a command inside a sectioning
command, figure caption, or table specification. If you really need to use a
command there, you can try prefixing its use with \protect.
34
Chapter 2
Styling text
Good practices
Stylish use of punctuation makes your text look so much more professional.
Some (but not nearly all) journals employ copy editors who have a keen eye
for these issues.
35
The double quotes “”, coded as `` ''
This effect is even more exaggerated with “double quotes”; if you use the "
symbol on your keyboard, you get ”not as nice” quotes.
Since LATEX is nowadays Unicode-native, you can write letters like åäö di-
rectly into your source code. If you can’t find the specific letter on your
keyboard, or the journal you’re submitting to uses age-old tools, the old
commands for producing accents are still there. These are useful for e.g.
author names in bibliographies. You can find the full list online;3 some
common examples are here:
Curriculum Vitæ
Curriculum Vit\ae\\
\r{A}bo Akademi\\ Åbo Akademi
Wac\l{}aw Sierpi\'{n}ski\\ Wacław Sierpiński
Bernt \O{}ksendal\\ Bernt Øksendal
Besan\c{c}on\\ Besançon
\v{S}koda\\
Dotless \i
Škoda
Dotless ı
TEX also does some typographical tweaks on its own. Look at the ‘ffi’
in ‘efficient’ – the letter shapes have been merged. This is called a ligature.
Ligatures improve legibility, but if you need to suppress them, you can
stick a \/ between the letters. This is sometimes practiced for English words
like ‘shelfful’, where there is a word boundary between the f’s.
Efficient\\ Efficient
Ef\/ficient\\ Efficient
Ef\/f\/icient Efficient
2
detexify.kirelabs.org/classify.html
3
en.wikibooks.org/wiki/LaTeX/#Special_Characters
36
2.1.2 Dingbats and logos
There are several packages providing symbol characters. One notable ex-
ample is fontawesome5, which packages the version 5 of the Font Awesome
symbol font.4 Once the package is loaded, symbols can be set with names
prefixed with \fa:
Reading suggestions
\faBook{} Reading suggestions\\ ē (Have a cup at hand)
\faCoffee{} (Have a cup at hand)\\
There are also brand logos
There are also brand logos like
like ȃ Git and z Linux,
\faGit*~Git and \faLinux~Linux,
but remember that they are trademarks.\\ but remember that they are
trademarks.
Font size commands are supported:
{\tiny\faPoop}~{\faPoop}~{\Large\faPoop} Font size commands are sup-
ported: ͠ ͠ ͠
Family The basic shape of the font. There are three families by default:
serif, sans serif, and typewriter. In these notes, the sans serif font is
used to highlight package names, and the typewriter font is used for
LATEX code.
Series This is the combination of weight and width of the font. Generally,
one only needs to care about the normal and bold series. Those into
4
As of May 2024, Font Awesome is in version 6.5, but there does not seem to be a
corresponding LATEX package yet.
37
graphical design know that this is only the tip of the iceberg; the
methods in Section 6.3 can create more series.
Shape Usual choices include upright, italic, and small capitals. Tech-
nically, small caps is not a shape variant but an independent style
altogether, but we are simplifying things here.
The following table shows the most common font commands. These
come in two forms: the first takes the text as its argument, and the second
applies the change to all the following text (until end of scope; see p. 15).
\textit{Super}charged\\ Supercharged
{\itshape Super}charged Supercharged
There are two important points to remember: First, you should keep
the semantics and the styling separate. For example, these notes define a
38
\pkg command to highlight package names; there are no \textsf commands
sprinkled around the code.5
Another is that you should not use \textit to emphasize text. It is
much better to use \emph: first, it is semantically meaningful, and second,
it supports nesting:
Underlined
\uline{Underlined}\\
\uuline{Doubly so}\\ Doubly so
\sout{Struck out}\\ Struck out
\uwave{Waves}\\ Waves
::::::
\dashuline{Dashes}\\ Dashes
\dotuline{Dots}
Dots
.. . . .
2.2.3 Size
Coming from any graphical word processor or layout program, you have seen
fonts being measured in points. LATEX does support it (see Section 6.3 where
we talk about font customization), but again it works against separating
content from presentation.
5
Moreover, this command adds an entry to the index. Thus the code is not only
semantically meaningful but also benefits the reader.
39
Instead, LATEX offers a range of sizes relative to the default document
font passed as the class option (Section 1.4.1). These are as follows:
It is possible to either embed the source code within your .tex file by using
the lstlisting environment, or to input the contents directly from a source
code file like above.
The package offers some support for making listings float like figures, or
alternatively you could define your own float environment (see Section 7.2.2).
Computer science journals typically have their own instructions for this.
40
The lstlisting environment is a special variant of the verbatim envi-
ronment. All contents inside this environment are printed verbatim in the
typewriter font: LATEX commands and special characters are printed as is.
(Except of course for the \end{verbatim}. It would be silly not to evaluate
that.)
\begin{verbatim}
Printed as is, including Printed as is, including
whitespace. whitespace.
\LaTeX & $math$ \LaTeX & $math$
\end{verbatim}
There is also the \verb command for short spans of verbatim text. This
command has a special syntax: it must be followed by a special character
(or a number, but not *). This special character ends the verbatim span.
Obviously, you need to choose a character that does not appear in the text!
There is also a starred form that makes the whitespace visible.
\verb+\LaTeX{}+ \\ \LaTeX{}
\verb|$1 + 1$| \\ $1 + 1$
\verb*|$1 + 1$| $1␣+␣1$
These notes use a lot of \verb|...| in the code (and the preceding was
coded as \verb+\verb|...|+, which in turn was coded as…).
The verbatim environment is a more lightweight way to display source
code, but it offers no customization at all. The fancyvrb package provides a
lot of that customization. However, the listings package additionally provides
automatic syntax highlighting for many common programming languages,
so it should be your first choice.
One neat use of verbatim environments is to comment out large blocks
of text. This example requires fancyvrb and its capitalized Verbatim envi-
ronment:
Some text.
\begin{Verbatim}[lastline=0]
You cannot see what's happening here.
Some text.
It's as if it didn't exist!
\end{Verbatim} Some more text.
Some more text.
41
This can be further simplified with the \DefineVerbatimEnvironment com-
mand, which creates a customized environment based on Verbatim:
\DefineVerbatimEnvironment
{CommentOut}{Verbatim}{lastline=0}
Good practices
I personally like to put every sentence on a new line. To me it is easier to
scan, and it also goes well with the version control system I use: the system
highlights changed lines, so there is a one-to-one correspondence between
changed lines and changed sentences.
Gotcha!
Be careful with line breaks in your macro definitions; you might accidentally
end up causing paragraph breaks. If your macro definition spreads over
42
many lines, you should tell TEX to ignore the line breaks by ending each
line with %.
\setlength\parindent{2em}
\setlength\parskip{0pt}
This is a long example
This is a long example paragraph. paragraph.
This too is a long example
This too is a long example paragraph. paragraph.
This paragraph is exceptional,
\noindent
This paragraph is exceptional, as it is not indented.
as it is not indented.
If you really need a manual line break without starting a new paragraph,
you can use either the \\ or the \\* command. The difference between the
two is that the starred form prevents a page break between the lines. (That
is, you probably need to use the latter.) These commands take an optional
argument for the space after the line break:
Yours sincerely,
Yours sincerely,\\*[8pt]
P.~Laarne\\* P. Laarne
\TeX nical assistant
TEXnical assistant
2.4 Colour
Due to historical and technical reasons, TEX does not natively support
colours. The xcolor package adds this support. Many other packages load
xcolor automatically and support the colour syntax (for example tikz).
Gotcha!
Be careful with the spelling: the color package is the original 90s implemen-
tation, and its use is discouraged.
Like with the font commands, there are two forms of the colour speci-
fication: \textcolor that colours only its (second) argument, and \color
43
that colours everything until the current scope ends. There are three basic
ways and several advanced ones to define colors:
By CMYK value This one is only for those into printing presses; the
optional argument is [cmyk] and syntax is similar to the RGB model.
The four parameters correspond to cyan, magenta, yellow and key
(black) inks on white paper.
By HSB value Here the keyword is [hsb] and the parameters are hue,
saturation, and brightness.
By HTML code This takes the six-letter hexadecimal string colour string,
such as \color[HTML]{2ABC4D}.
The package also offers a lot of ways to mix colours together. As you
probably learned in primary school, this generally procudes mainly shades
of greyish brown, so we do not talk about it here.6 The only exception is the
syntax \textcolor{blue!60}{...} which blends blue with 40 % white.
It is possible to define custom colour names with \definecolor. This
can be useful e.g. when creating TikZ pictures with recurring elements. Here
we follow the University of Helsinki style guide and define the brand colour
of the Faculty of Science:
6
Another reason is that the result depends on the specific colour model. Taking
averages of RGB values can yield a very different result to averaging equivalent HSB
values. There is no ‘correct’ way to do this; in fact, trying to understand what colour
really is leads you to a rabbit hole of mathematics, human perception, and questioning
the reality.
44
\definecolor{Sciency}{cmyk}{0,0.46,1,0}
\textcolor{Sciency}{Science!} Science!
Good practices
Never use colour as the sole means of indicating information. Many people
read papers in black-and-white prints or on ebook reader with grayscale
screen. Red-green colourblindness, the most common form of colour vision
deficiency, affects about 1 in 12 males.
Even then, pay attention to the colour contrast. Low-contrast text might
be impossible to read e.g. on screen in bright sunlight, or for a person with
a vision deficiency.
2.5 Footnotes
Footnotes are produced with the imaginatively named \footnote command.
The command itself needs no explanation, but we remark on a few points
on placement and styling of footnotes.
Gotcha!
Whitespace immediately preceding the footnote command is interpreted as
a word space as usual. If you put a footnote on a separate code line, the
line break is interpreted as a space. This causes separation between the
preceding word or punctuation.
The easy fix is to put a % before the whitespace, since it causes the
whitespace and line break to be swallowed.
An ugly space. a
An ugly space.
\footnote{First note!}\\
Tightly together.b
Tightly together.% a
\footnote{Second note!} First note!
b
Second note!
45
In these cases the footnote mark can be placed with \footnotemark and
the footnote text defined outside the environment with \footnotetext. Do
note that now you are responsible for keeping the footnote symbols and texts
in sync!
The optional argument to the \item command provides the content for
the “bullet symbol”:
46
♣ Club
\begin{itemize}
\item[$\clubsuit$] Club
\item[$\spadesuit$] Spade
♠ Spade
\item[$\heartsuit$] Heart
\item[$\diamondsuit$] Diamond
♥ Heart
\end{itemize}
♦ Diamond
List elements may contain multiple paragraphs, and lists can be nested.
As we discuss in Section 1.6, the running numbers can be accessed with the
enumi, enumii, and enumiii counters (corresponding to levels of nesting).
The enumitem package offers a lot of customization for the standard
environments. It adds an optional argument with key-value syntax to the
standard environments.
\begin{enumerate}
\item Default list 1. Default list
\item Nothing to see here
\end{enumerate} 2. Nothing to see here
You can also use the package to customize labels. Note that you need to
use a starred form of the counter command (these were defined on page 30).
\begin{enumerate}[noitemsep,
format=\bfseries,
label={Rule~\arabic*.}] Rule 1. Don’t use plain TEX.
\item Don't use plain \TeX. Rule 2. See the above.
\item See the above.
\end{enumerate}
Instead of repeating yourself at every list environment, you can use the
\setlist command to customize all of the lists:
47
\setlist[enumerate]{noitemsep}
\begin{enumerate}
\item Tightly\dots
1. Tightly…
\item \dots{}spaced. 2. …spaced.
\end{enumerate}
Some text
Some text
1. Same…
\begin{enumerate}
\item Same\dots 2. …here.
\item \dots{}here.
\end{enumerate}
\newlist{rules}{enumerate}{2}
\setlist[rules]{noitemsep,
format=\bfseries,
label*=\arabic*.}
\setlist[rules,1]{noitemsep,
Rule 1. Don’t use plain TEX.
label={Rule~\arabic*.}}
Rule 2. See the above.
\begin{rules} Rule 2.1. Unless Don Knuth
\item Don't use plain \TeX.
\item See the above.
passes by.
\begin{rules}
\item Unless Don Knuth passes by.
\end{rules}
\end{rules}
48
Good practices
Always use the standard sectioning commands. They are semantically mean-
ingful, they take care of numbering and cross-references, and they are used
to build a PDF navigation bar (when hyperref is loaded).
Gotcha!
If your section title contains mathematical symbols and you have hyperref
loaded (as you do, right?), you will probably get a warning. This is because
the PDF navigation bar format does not support mathematical symbols.
To solve this issue, you can use the \texorpdfstring command. It takes
two arguments: the first is the one to show in the document, and the second
is the (non-mathematical) alternative to show in PDF navigation.
This code displays “The φ4 measure” in the document but “The phi4 mea-
sure” in the navigation bar.
You can pass a shorter version of the section title as an optional argu-
ment. It will be used in the table of contents and page headers (if enabled).
\section{Introduction} % Section 1
\section{Methods} % Section 2
\section{Results} % Section 3
\appendix
49
Pages in the front matter are numbered with Roman numerals and chap-
ters are unnumbered. The \frontmatter command should appear immedi-
ately after \begin{document}. After \mainmatter, pages and chapters are
numbered usually. Appendix numbering can be enabled with the \appendix
command as before. Finally, bibliographies and other closing stuff can be
put after \backmatter.7
Gotcha!
If you use the memoir or koma-script document classes, this package is not
usable. The document classes provide their own mechanisms instead.
\usepackage{titlesec}
\titleformat*{\subsection}{\centering\Large\scshape}
The simple interface does not let you customize the layout of headings,
and it does not permit customization of chapter headings (which spread on
two lines by default). For these cases, there is the advanced interface. It uses
the unstarred \titleformat command, which takes up to seven parameters:
50
• Formatting code applied to the whole title. This might also include
some commands in vertical mode.
\titleformat{\chapter}[display]{\filcenter}
{--\emph{The \ordinalstring{chapter} \MakeLowercase{\chaptertitlename}}--}
{4pt}{\Large\scshape}
\titleformat{\section}[block]{\large}
{\bfseries\itshape Section~\thesection.}{4pt}
{\bfseries}
\titleformat{\subsection}[runin]{}{\itshape \thesubsection.}
{\wordsep}{\itshape}[.]
51
–The first chapter–
My chapter name
• Addition to the left margin. For the wrap shape, it gives the maximum
width of the heading.
In the following, we move the chapter heading closer to the top of page,
indent the framed section heading, and specify a wrapped subsection head-
ing:
\titleformat{\chapter}[display]{\filinner\sffamily}
{\bfseries\textcolor{gray}{\fontsize{60pt}{60pt}\selectfont\thechapter}}
{0pt}{}
\titlespacing{\chapter}{0pt}{12pt}{12pt}
\titleformat{\section}[frame]{\large}
{Section~\thesection}{8pt}
{\filcenter}
\titlespacing{\section}{5em}{4pt}{12pt}
\titleformat{\subsection}[wrap]{\bfseries}{\thesubsection.}{0.5em}{}
\titlespacing{\subsection}{5cm}{8pt}{\wordsep}
52
2
My chapter name
Section 2.1
My section name
Warning
Be careful with heading customization, especially with the run-in and wrap
styles. Long headings might break in surprising and suboptimal ways.
53
Chapter 3
Warning
The following discussion is TEXnical, and mostly for giving you an idea of
how things work. If you find yourself needing to manipulate boxes directly,
TEX lays out a line just like a human typesetter would do with metal
type. The basic unit is box, a rectangular piece of content. TEX alternates
between a horizontal mode, where the boxes are set in line, and a vertical
mode, where boxes are set on top of each other.1 Boxes are nested to produce
complicated layouts.
1
To be precise, there are two horizontal modes: the one where lines are broken auto-
matically, and the one where they are not. Similarly, there are two vertical modes that
differ in page breaking behaviour. Finally, there are the inline and display math modes,
bringing the total to six.
54
Technical side note
We can play an old-school typesetter with the \hbox and \vbox commands.
(These are low-level TEX commands – see below for LATEX versions!)
\vbox{\hbox{\hbox{Above1}\hbox{Above2}}\hbox{Below}}
Above1Above2
Below
Typography baseline
line depth
The height of each line is given by the baseline skip: the vertical distance
between baselines. It is visually pleasing when lines are spread evenly, but
1
TEX will happily give extra space when content like needs it, even though it
2
looks bad (just look at it!). Moreover, the baseline skip might vary between
pages, since TEX might try to squeeze one more line onto a page to get a
better layout.
Back to boxes. I can invent three reasons to create boxes manually:
• overriding hyphenation,
• drawing a frame around something,
• doing some placement tricks.
We will look at each of these use cases. You can create your own boxes with
the \mbox command, and framed boxes with the \fbox command. These
commands are both defined in LATEX.
\fbox{Framed!} Framed!
55
The \fboxsep length parameter determines the padding between the box
and the frame; by default it is 3 pt. There is also a \fboxrule parameter
for the width of the line (0.4 pt by default). We can use these parameters
to illustrate how TEX lays out words (ignoring hyphenation):
\setlength\fboxsep{0pt}
Some example text that
\fbox{Some} \fbox{example} \fbox{text}
\fbox{that} \fbox{forms} \fbox{a}
forms a complete example
\fbox{complete} \fbox{example} paragraph.
\fbox{paragraph}.
\framebox[4cm][c]{Centered}\\
Centered
\framebox[1.5\width][r]{Some legroom}\\ Some legroom
\framebox[1cm][l]{Overflowed it!}
Overflowed it!
56
The \totalheight command gives the height of the line: it is the sum of
\height (of the contents above baseline) and \depth (of the contents below
baseline). We will talk about baseline a bit later below.
What if you want to put multiple lines of content into a box, with au-
tomatic hyphenation? Enter paragraph boxes. The minipage environment
essentially creates a page within page. You need to tell it the width of the
box, and optionally whether the top, center, or bottom line is aligned with
the baseline:
Some text
\begin{minipage}[b]{2.7cm}
interrupted by a rambling
note, followed by
\end{minipage}
some
\begin{minipage}[t]{2cm}
more text, albeit not
very usefully set either.
\end{minipage}
interrupted by a
rambling note,
Some text followed by some more text,
albeit not
very use-
fully set
either.
Let us also show a more practical example of how this could be used:
\begin{minipage}[c]{5cm}
\textbf{Curriculum Vit\ae}\\
Cira the dog\\
Born 2009\\
Expert eater of everything
\end{minipage}
\hfill
\begin{minipage}[c]{4cm}
\includegraphics[bb=2.8cm 1.4cm 7cm 6cm, clip, width=\textwidth]
{pictures/TheDogs.jpg}
\end{minipage}
57
Curriculum Vitæ
Cira the dog
Born 2009
Expert eater of everything
There is a in here.
There is a phantom in here.
The \rule command creates a filled box, but it can also be used to create
a strut: an invisible “support beam” that takes up some vertical space. The
command takes the width and height of the rule, optionally preceded by the
position above baseline:
If we set the width to zero, then the space is reserved but no rule is drawn.
Here we reserve 0.5 cm below the baseline and 1 cm above it:
\fbox{\rule[-0.5cm]{0pt}{1.5cm}%
A lot of room!} A lot of room!
This can be used e.g. to create some vertical clearance inside a table cell.
58
3.1.1 Hyphenation
By default TEX hyphenates words according to a set of English rules. It is
very good at hyphenating general text, and can be trusted at it.2 Sometimes,
especially with technical compound words, it might still need some help.
To hint the possible breaking points, use the \- command. This disables
automatic hyphenation for the particular word, so it will only be broken at
the hinted points. Conversely, if a word should not be broken across lines,
it can be wrapped in an \mbox. Finally, to prevent a line break between two
words, the tilde ~ symbol produces a non-breaking space.
Compare these two passages (to illustrate the automatic hyphenation,
they are slightly different). The breaking override commands cause the lines
to be underfull, but at least for names the result is syntactically more correct.
Quantum electrochromo-
dynamics presented by
Quantum electro\-chromo\-dynamics
presented by P.~Laarne,
P. Laarne, based on
based on \mbox{Chatterjee}.\\ Chatterjee.
Good practices
If you add a hyphenation hint to a word, I suggest adding \- commands at
all reasonable hyphenation points. That might save you some effort when
the line breaking changes.
Let us then talk about the issues. An overfull hbox means that TEX
could not break the lines without overflowing into the margin. Conversely,
an underfull hbox results from a line having too little content, and thus
unacceptably large spaces between words. There are a few ways to fix these
issues:
• If the offending line is visually not too bad, just accept it.
59
• If the page layout causes suboptimal paragraph shaping, it could also
be tweaked, but this is an extreme action (see Section 3.3.2).
There is just one hard rule:
Warning
Only fix over-/underfull issues at the very end of publication process, when
you have applied the final style file and all the content fixes are done.
Since the TEX layout algorithm is global, adding just one letter can
change the breaking of a line, which can change the length of the paragraph,
which can change the page layout, which then propagates to the next pages.
Result: You fixed a typo, and all the fine-tuning you had done on the
following pages was just lost.
I have often seen a one-word change increase the length of a paper by
half a page. The LATEX Companion [4] production notes mention a 1 %
change to a typewriter font size that broke 50 already fine-tuned pages.
By default LATEX produces justified text that extends from the left to
right margin. It is possible to let the line lengths vary (as most word proces-
sors do by default). This is done by the \raggedright command, or more
locally inside a flushleft environment.
3.1.2 Language
The standard method for producing LATEX documents in a language other
than English, or even in multiple languages, is the babel package. It does
60
several things:
• Applies the language-specific hyphenation rules;
• Translates words produced by LATEX commands such as “Chapter”,
“References”, and dates produced by \today;
• Might do some typographical fine-tuning.
The list of languages is passed as an option when babel is loaded. The
last language on the list is taken to be the default language for the document.
In these notes, the magic command is
\usepackage[finnish,french,english]{babel}
The full list of languages (and regional variants!) can be found in the babel
documentation. Some European languages have undergone major orthogra-
phy revisions in the past decades; for modern German the language code is
ngerman and for Norwegian nynorsk it is norsk.
The currently active language is changed with \selectlanguage. The
otherlanguage environment can be used for a short passage in a different
language. Below there are two visible changes: obviously the language is
different, but do note also the small space before ! in the French version.
The hyphenation rules are also changed, but the effect might be neg-
ligibly small. Overall, the hyphenation algorithm of TEX is optimized for
English, so the long Finnish words might need your help.
Pitkähköjen yhdyssanamuo-
Pitkähköjen yhdyssanamuotojen tavutus
oikeinkirjoitussääntöjen mukaisesti\\ tojen tavutus oikeinkirjoi-
tussääntöjen mukaisesti
\begin{otherlanguage}{finnish}
Pitkähköjen yhdyssanamuotojen tavutus Pitkähköjen yhdyssanamuoto-
oikeinkirjoitussääntöjen mukaisesti
\end{otherlanguage}
jen tavutus oikeinkirjoitus-
sääntöjen mukaisesti
61
Finally, since non-English languages also contain non-English characters,
we need to talk about font encodings.
Gotcha!
This here is the most important place where the traditional pdfTeX compiler
and the Unicode-native LuaTeX and XeTeX compilers differ. You should
always use the fontenc package with pdfTeX, unless your document only
contains the basic English characters. On the other hand, you should not
use fontenc with LuaLaTeX or XeLaTeX, since they use a better internal
encoding by default.
Since 2018, LATEX has accepted Unicode input by default. However, this
only applies to the input: characters are then transformed into an internal
representation and further into individual glyphs from a font file.3 When
TEX and LATEX were developed, they had to solve the problem of having
many (mathematical) glyphs, but Unicode was back then far from a univer-
sal standard.
There are several of these internal representations. The original OT1
encoding only has 128 characters. Characters like ‘ä’ need to be composed
of ¨a set on top of each other. The T1 encoding is a more recent encoding
that supports Western European languages. Cyrillic and Greek characters
still need further encodings.
The basic use is:
\usepackage[T1]{fontenc}
The LuaTeX and XeTeX engines use Unicode for their internal represen-
tation, so this command is no longer necessary. Furthermore, it might cause
missing/incorrect characters or bad hyphenation, so it should be removed
altogether.
Good practices
Unfortunately, most journals (and coauthors) still use pdfLaTeX in their
production process, so you might just need to accept the minor issues with
newer compilers.
3
To be precise, several characters can be combined into one glyph: see the ffi ligature
in ‘efficient’.
62
3.2 Units of measure and whitespace
TEX supports specifying distances in a variety of units. The most useful are:
cm Centimetres
63
Left\hfill center\hfill right
There are also the \hrulefill and \dotfill commands that fill the
space with something:
The same general ideas work for vertical spacing. One can request exact
vertical space with \vspace or a stretch space with \vfill (below, the latter
does nothing since the “page” streches according to the example content):
Something
\vspace{1cm}
Something
Something else
Something else
\vfill
Bottom of the page
Bottom of the page
64
Vertical space at page boundaries is eliminated. If you need to suppress
that, for instance when designing a title page, you can use \vspace* (see
the example on page 73).
Instead of manual spacing commands within text, you should use the
semantically more meaningful \smallskip, \medskip, and \bigskip com-
mands.
However, there is a significant catch. Remember that TEX alternates
between the horizontal and vertical mode. Using vertical commands in the
horizontal mode might cause some surprises.
{\color{blue}\rule{\textwidth}{1pt}}
65
The text width is \the\textwidth.
Here's a line of that width: The text width is 143.9978pt.
Here’s a line of that width:
{\color{blue}\rule{\textwidth}{1pt}}
And of half that width:
And of half that width:
{\color{blue}\rule{0.5\textwidth}{1pt}}
Out of the box, the only calculation possible with lengths is multipli-
cation, like 0.5\textwidth used above. The calc package has traditionally
been used when a complete expression language is needed.
New in LATEX3
LATEX3 now also provides similar functionality through the \dimeval and
\inteval commands:
Be warned that the syntax does have some peculiar corner cases.
\newlength\Mylen
\setlength\Mylen{1.75em}
My space.
My\hspace{\Mylen}space.
66
There are the useful \settowidth, \settoheight, and \settodepth
commands that measure a piece of text and store its size in the variable:
\settowidth\Mylen{Hello world!}
inner The width of the inner margin. In oneside document mode, this
corresponds to the left margin.
outer The width of the outer margin. In oneside document mode, this
corresponds to the right margin.
lines Alternatively to the above, the desired text height in lines (in the
current default font).
67
Header area
1
Hello! This is a footnote.
Footer area
68
headsep Distance between the header and text area.
Remark
University of Helsinki doctoral theses are printed on B5 paper. The sug-
gested font size is 10 pt in that case.
Warning
The raw TEX and LATEX lengths are available as well, and many a Stack
Exchange answer suggests modifying them directly. There is nothing wrong
with it, but geometry gives a nicer interface that avoids some surprising
things.
69
Technical side note
The pdf in pdflscape stands for the fact that the environment even tells the
PDF reader application to rotate the page on your screen. This is its sole
improvement over the older lscape package.
\setlength\parindent{0pt}
\setlength\parskip{4pt} Some text forming an example
paragraph. Just enough to get
Some text forming an example paragraph. it to a few lines.
Just enough to get it to a few lines.
Another example paragraph,
Another example paragraph, with quite a few words.
with quite a few words.
Let us then move to page breaks. The \clearpage command ends the
current page, then produces enough pages to set all the outstanding floats
(figures and tables), and finally starts a new page. The \cleardoublepage
variant ensures that the new page has odd number, which puts it on the
right-hand side of a twoside layout. This is done automatically at the end
of chapter in the report document class.
Generally, you should not otherwise interfere with the page breaking
algorithm, but sometimes it is necessary for a good layout. The \pagebreak
command forces a manual page break.
However, this command is dangerous. If the preceding text changes, it
is possible that the \pagebreak command now produces a mostly-empty
page!
Instead, it might be better to use the needspace package. The identically
named command approximates the remaining space on the page, and starts
a new page if there is not enough. For example, to ensure that there is space
for two more lines, one can say
70
\needspace{2\baselineskip}
Warning
Only do fine-tuning to the page layout at the very end of editing process –
even the tiniest change can cause a massive cascade of layout changes!
Quite often, you can do completely without these tweaks.
71
The right-hand-sides are internally implemented with the \chaptermark and
\sectionmark commands,6 and by renewing them it is possible to change
the format of marks. For example, to remove the automatic upper-casing
one can use
\renewcommand{\chaptermark}[1]{\markboth{\chaptername~\thechapter. #1}{}}
\renewcommand{\sectionmark}[1]{\markright{\thesection. #1}}
New in LATEX3
LATEX3 introduces a completely new marking mechanism. We do not discuss
it here, but its brief documentation does give the essential details.7
This is page
\thepage{} of \pageref*{LastPage}. This is page 72 of 200.
(Here we used the starred \pageref* command that does not produce a
clickable link. It is of course fine, if a bit odd, to provide a link to the last
page.)
Do note that this method gives the page number of the last page, not the
total number of pages. The two might not be equal if several page numbering
schemes have been in use.
6
These commands exist for all sectioning levels, not just chapters and sections.
72
3.4.3 Customized title pages
If the output of \maketitle is not sufficient for your artistic tastes, you
can of course set the title page by yourself. The titlepage environment
creates an empty page with no decorations.8 The title page of these notes
was created with the following code:
\begin{titlepage}
\vspace*{\stretch{1}}
\hrulefill
\begin{flushright}
\textbf{\LARGE A second course in \LaTeX}\\[1em]
\Large Petri Laarne\\[1em]
Draft version\\
\today
\end{flushright}
\hrulefill
\vspace*{\stretch{2}}
\end{titlepage}
[Page content]
73
\pagestyle{fancy}
To access the current chapter and section name, you can use the marks
described in Section 3.4.1. The following code replicates the default LATEX
headings page style:
\pagestyle{fancy}
% Clear all
\fancyhf[]{}
Remark
The package gives a warning if the header height is not large enough. The
warning even gives a suggested value for the \headheight length, which you
can pass to geometry (or do a raw \setlength, if not using the package).
You can customize the rule separating header and text by redefining
the \headrulewidth length, and correspondinly \footrulewidth. It is also
possible to customize the separation from header text and the line style, but
for these we refer to the package documentation.9
9
One has to be a bit careful with vertical spacing.
74
Chapter 4
Mathematics layout
Warning
Plain TEX used the $$ ... $$ syntax for display mathematics. Do not use
it – the LATEX-style environment has some hooks and accessibility features
that the TEX syntax does not have.
75
4.1.1 Single numbered equation
The basic equation environment of amsmath is equation. It sets its contents
on a single line and numbers the equation:
\begin{equation}
i \partial_t u - \Delta u = -u^3.
\end{equation} i∂t u − ∆u = −u3 . (4.1)
If you’d rather have an unnumbered equation, you can use the equation*
environment. It is essentially equivalent to \[ \] of LATEX.
To customize the equation number, you can use the \tag command.
\begin{equation}
i \partial_t u - \Delta u = -u^3.
\tag{NLS} i∂t u − ∆u = −u3 . (NLS)
\end{equation}
The tag also appears in cross-references to this equation. The tag is read in
text mode, so any mathematical symbols need to be wrapped with $. For
example, you would write \tag{$\ast$} to produce (∗).
If you want to change whether equations are numbered globally or per
section, use the \counterwithin mechanism described in Section 1.6:1
\counterwithin{equation}{section}
\begin{multline}
a^5 + 5 a^4 b \\ a5 + 5a4 b
+ 10 a^3 b^2 + 10 a^2 b^3\\
+ 5 a b^4 + b^5 + 10a3 b2 + 10a2 b3
\end{multline}
+ 5ab4 + b5 (4.2)
1
The amsmath package also defines \numberwithin, which is functionally identical to
\counterwithin. It does not matter which one you use.
76
The first line is left-aligned, the last line is right-aligned, and the rest are
centered.
If you need to control the alignment, you can use the split environment.
This environment needs to be put inside equation (or equation*). The
alignment point is denoted by &:
\begin{equation}
\begin{split}
(a+b)^2 (a + b)2 = (a + b)(a + b)
&= (a+b)(a+b)\\
&= a^2 + 2ab + b^2. = a2 + 2ab + b2 .
\end{split} (4.3)
\end{equation}
Sometimes, you need to align with things that are not really there. Let
us produce a slightly different version of the previous example:
\begin{equation}
\begin{split}
&\mathrel{\phantom{=}} (a+b)^2\\ (a + b)2
&= (a+b)(a+b)\\
&= a^2 + 2ab + b^2.
= (a + b)(a + b) (4.4)
\end{split} 2 2
= a + 2ab + b .
\end{equation}
The \phantom command reserves enough space on the first line for =, even
though it is not printed there; the \mathrel command ensures that the
spacing is that surrounding = as well. This ensures that the expressions
are aligned. The same effect can not be attained with moving the alignment
symbol, since the TEX spacing algorithm (described below) cannot see across
the &:
77
4.1.3 Many equations, many lines
The gather environment collects equations, each centered.
\begin{gather}
(a+b)^2 = a^2 + 2ab + b^2,\\
\begin{split}
(a+b)^3 &= a^3\\
&\mathord{\phantom{=}} + 3a^2 b + 3ab^2 + b^3.
\end{split}
\end{gather}
You can customize the tag of each individual equation with \tag, and
also suppress an individual tag with \notag. These commands can ap-
pear anywhere before the \\ that ends the particular equation. Again, the
gather* environment suppresses all tags except those explicitly created with
\tag.
\begin{gather}
(a+b)^2 = a^2 + 2ab + b^2,\\
(a+b)^3 = a^3 + 3a^2 b + 3a b^2 + b^3, \notag\\
a^2 - b^2 = (a+b)(a-b). \tag{$\ast$}
\end{gather}
2
Now we wrap the phantom equals sign in \mathord, which makes the + sign act as
binary plus, not unary plus.
78
(a + b)2 = a2 + 2ab + b2 , (4.10)
(a + b)3 = a3 + 3a2 b + 3ab2 + b3 ,
a2 − b2 = (a + b)(a − b). (∗)
If you need to have several aligned equations, you can use the align en-
vironment. In comparison to split, each line is now numbered individually:
\begin{align}
(a+b)^2 (a + b)2 = (a + b)(a + b)
&= (a+b)(a+b)\\ (4.11)
&= a^2 + 2ab + b^2.
\end{align}
= a2 + 2ab + b2 .
(4.12)
The same remarks about \tag and \notag with gather apply here. The
align environment also supports more than one alignment point.
Warning
There is also an eqnarray environment provided by base LATEX. It is far
less sophisticated and generally uglier than anything you can achieve with
the environments presented here, so I would avoid it.
\begin{subequations}
\begin{align}
(a+b)^2 (a + b)2 = (a + b)(a + b)
&= (a+b)(a+b)\\ (4.13a)
&= a^2 + 2ab + b^2.
\end{align}
= a2 + 2ab + b2 .
\end{subequations} (4.13b)
79
to that environment only; if you put it in the preamble, it applies to all
environments.
4.1.4 Cases
To group several expressions with vertical brackets, you can use the cases
environment inside an equation environment. This environment supports a
single alignment &:
\begin{equation}
f(n) = \begin{cases} (
n^2, & n > 0,\\ n2 , n > 0,
-n, & n \leq 0. f (n) = (4.14)
\end{cases} −n, n ≤ 0.
\end{equation}
If you mostly have text following the alignment character, you can use the
starred environment. It interprets the right-hand side of & in text mode:
\begin{equation}
f(n) = \begin{cases*} (
n^2+1, & if $n$ is even,\\ n2 + 1, if n is even,
n+7, & if $n$ is odd.
f (n) =
n + 7, if n is odd.
\end{cases*}
\end{equation} (4.15)
\begin{equation}
\begin{rcases}
i \partial_t u - \Delta u = -u^3,\\
\partial_{tt} u - \Delta u = -u^3
\end{rcases}
\text{ some dispersive PDE}
\end{equation}
)
i∂t u − ∆u = −u3 ,
some dispersive PDE (4.16)
∂tt u − ∆u = −u3
However, do note that there is some space put before the & alignment
position. If you want to collect several aligned equations inside a brace, it
80
might be nicer to fake the output with help from the aligned environment
and a suitably sized { character:
Not nice:
\begin{equation}
\begin{cases}
\partial_{tt} u - \Delta u &= 0,\\ Not nice:
u(0) &= X,\\
\partial_t u(0) &= Y.
∂tt u − ∆u = 0,
\end{cases}
u(0) = X, (4.17)
\end{equation}
∂t u(0) = Y.
Much nicer:
\begin{equation} Much nicer:
\left\{
∂tt u − ∆u = 0,
\begin{aligned}
\partial_{tt} u - \Delta u &= 0,\\
u(0) = X, (4.18)
u(0) &= X,\\
\partial_t u(0) &= Y. ∂t u(0) = Y.
\end{aligned}
\right.
\end{equation}
4.1.5 Matrices
Like cases, matrices are not equation environments on their own, but can
appear inside one. There are a few variants depending on how you like them:
\begin{gather*}
\begin{pmatrix}
1 & 2\\
3 & 4 1 2
\end{pmatrix}\\
3 4
\begin{bmatrix}
1 & \cdots & 1\\ 1 ··· 1
0 & \ddots & \vdots\\ . . ..
& \cdots & 1 0 . .
\end{bmatrix}\\ ··· 1
\begin{vmatrix}
a & b\\ a b
c & d c d
\end{vmatrix}
\end{gather*}
81
4.2 Fonts and text in mathematics
In mathematical mode TEX follows different spacing rules. Spaces are ig-
nored, and the spacing between letters is slightly altered:
To make your documents have that subtle final touch, it is therefore impor-
tant to understand where the boundary of text and math goes. We will first
discuss putting explanatory text within math environments, and then talk
about mathematical text styles like exp(fstat ) below.
Good practices
Also the spacing of punctuation is slightly different in math mode. You
should use math mode only for mathematics; in particular, the second ex-
ample below is preferable:
\[
a_k < a_{k+1}
\text{ for all } k \in \mathbb N. ak < ak+1 for all k ∈ N.
\]
82
\[
a_k < a_{k+1}
\text{ for all $k \in \mathbb N$, and }
a_1 > 1.
\]
\begin{align}
a^3 - b^3
&= \sum_{k=0}^3 \binom 3 k a^k b^{3-k},\\
\intertext{and by some computation this equals}
&= (a-b)(a^2 + ab + b^2).
\end{align}
3
X 3
a −b =
3 3
ak b3−k , (4.19)
k
k=0
= (a − b)(a2 + ab + b2 ). (4.20)
Good practices
As useful as \intertext is, remember that the display math environments
do not participate in page breaking by default. If you have a long chain of
equalities, you should think about the most reader-friendly way to present
it.
83
$\sin x$\\ sin x
$\mathrm{sin} x$ sinx
The spacing rules around operators are discussed in Section 4.3.2. The
\operatorname command described there also takes care of the upright
font.
This leaves us finally to talk things like fstat , R or R, and F. The
commands are similar to those used in text mode.
The upright roman style is produced with \mathrm, bold with \mathbf,
and the calligraphic style with \mathcal. There is also the sans serif style
\mathsf.
$\mathrm{F(x)}$\\ F(x)
$\mathbf{F(x)}$\\ F(x)
$\mathsf{F(x)}$\\ F(x)
$\mathcal{F(x)}$ F(§)
As you see from above, not all characters are supported by the default fonts,
sometimes producing confusing results.
Good practices
A common convention is to use upright style when something has a multi-
letter name. That is, the identity matrix should be Id and not Id, and a
stationary function should be fstat and not fstat .
Note that symbols are not typically set in bold font even when \mathbf
is used:
\[ ∞
\mathbf{\sum_{k=1}^\infty \frac{k}{1+k^2}}
X k
\] 1 + k2
k=1
84
% \usepackage{bm}
\[ ∞
X k
\bm{\sum_{k=1}^\infty \frac{k}{1+k^2}}
\] k=1
1 + k2
Whenever the font has a special bold symbol, it is used; otherwise, a “poor
man’s bold” is applied by overprinting the character with small offsets.
By loading the amsfonts package, you gain a couple more styles: “black-
board bold” by \mathbb and fraktur by \mathfrak. Again, these support
only a subset of the characters.
% \usepackage{amsfonts} ABC
$\mathbb{ABC}$\\
$\mathfrak{ABCdef}$ ABCdef
% \usepackage{amsfonts, dsfont}
ABC⊮⊭⊯
$\mathbb{ABC123}$\\
$\mathds{ABC123}$ ABC1
% \usepackage{dsfont}
\DeclareCommandCopy{\mathbb}{\mathds}
ABC1
$\mathbb{ABC123}$
85
New in LATEX3
If you copy mathematical text from a LATEX-produced PDF, the symbols
come in a normal font or might be completely random. This is another
example of TEX and Unicode having evolved separately. However, Unicode
nowadays has code points for symbols like “blackboard bold R”.
If you use a Unicode-native compiler (LuaLaTeX or XeLaTeX), you can
load the unicode-math package. This package replaces all math symbols
with their Unicode equivalents. Now they appear correctly for copy-paste
and screen readers.
With this package, you no longer need to load amsfonts, all digits have
blackboard bold variants, and there are no longer weird symbol substitu-
tions. Moreover, it is possible to easily load a different Unicode font for
maths.
Where’s the catch? The package is still marked as experimental, it does
not work with pdfLaTeX, and there are some subtle differences compared to
original math commands. This package should only be used for new projects
where backwards compatibility is not required.
\num{12345}\\
12 345
\num{3,9 +- 0,4}\\ 3.9(4)
\num{1.23(0.45:0.56)}\\ 1.23+0.45
−0.56
\num{1.28e-4}\\ 1.28 × 10−4
\complexnum{1+2ie3}
(1 + 2i) × 103
86
The next basic command is \unit, which offers two modes. In the
“literal” mode, units are given as strings. Multiplication is done with .,
division by /, and sub- and superscripts in the usual way. In the “macro”
mode, each part is given as a command (whose name corresponds to the
usual spoken version). The benefit of this mode is that the appearance can
be customized.
\unit{kg.m.s^{-2}}\\ kg m s−2
\unit{\kilogram\metre\per\second\squared}\\ kg m s−2
\unit{T_{eff}} Teff
Finally, the two commands can be put together with \qty (or its sibling
\complexqty):
\ang{60}\\ 60◦
\ang{12;34;56} 12◦ 34′ 56′′
The package offers a lot of customization in how the quantities are dis-
played. (This aligns well with the general LATEX philosophy.) See the pack-
age documentation for a thorough explanation.
Remark
See also page 144 for using siunitx in tables.
87
Gotcha!
The stmaryrd package should be loaded after amssymb, since it extends and
modifies some symbols there.
4.3.1 Spacing
TEX is quite smart about figuring out the spacing between different math-
ematical symbols. Just look at the difference between 2 − 1 and 2(−1).
Sometimes, it is important to choose the command properly to get expected
spacing. Compare the two examples:
Let us first see the manual commands for spacing, since their sizes cor-
respond to units used by TEX. Their sizes are defined based on the math
unit, which depends on the font size. Note that the difference of the units
is very small, just enough to be perceptible:
xx (no space)
$xx$ (no space)\\
$x\,x$ (thin space, 3~mu)\\ x x (thin space, 3 mu)
$x\:x$ (medium space, 4~mu)\\ x x (medium space, 4 mu)
$x\;x$ (thick space, 5~mu)\\ x x (thick space, 5 mu)
$x\!x$ (negative thin space)\\
xx (negative thin space)
$x\mspace{8mu}x$ (custom space)
x x (custom space)
88
characters, whereas there is a medium \: space between binary and ordinary
symbols.
\newcommand{\friends}{\mathbin\heartsuit}
Bad: x♥y
Bad: $x \heartsuit y$\\ Good: x ♥ y.
Good: $x \friends y$.
Gotcha!
This somewhat explains the difference between : and \colon, but only
partly. The symbol : is classified as Relation and \colon as Punctua-
tion. However, amsmath further modifies the spacing of \colon to fit the
f : A → B pattern – and only that pattern.
If you ever need the colon as a punctuation symbol, you can wrap it in
\mathpunct{:}.
Gotcha!
Another source of confusion is | and \mid. The first is Ordinary and the
second Relation. They should be used correspondingly: |a| for the absolute
89
value |a|, f|_A for the restriction of a function f |A , and a \mid b for the
divisibility relation a | b.
Gotcha!
The symbols . ! ? are of class Ordinary, not Punctuation. This is to do
with their mathematical meanings.
Gotcha!
If you write in a language where comma is used as the decimal separator,
you should wrap the comma in parentheses:
Gotcha!
Adding an accent turns the symbol into Ordinary.
Gotcha!
The occasionally used notation for open intervals conflicts with the algo-
rithm, since ]a, b[ is understood as Closing–Opening pair instead of the
opposite. It can be fixed manually as in the next example:
A quick fix is to wrap the intervals inside {}. If you use a lot of intervals,
you should either define some custom commands or check out the interval
package.
90
One common pain point is the humble dx that appears in integrals. It is
nice to get the spacing consistently right, and note also the upright d (this
is advocated by an ISO standard, but some prefer dx).
A common way to do this (based on Stack Exchange discussions) is:
\newcommand{\diff}{\mathop{}\!\mathrm{d}} In an integral:
In an integral: Z 1
\[ x dx,
\int_0^1 x \diff x, 0
\]
and inside parens: $\mu(\diff x)$. and inside parens: µ(dx).
Here the \sin command not only sets the operator name properly, but also
adjusts the spacing around the operator.
If the operator you need is not predefined as a LATEX command, you can
do the styling once with \operatorname…
\[
2 \operatorname{dim} X
\] 2 dim X
91
…or define a new command with \DeclareMathOperator in the preamble:
% In the preamble:
% \DeclareMathOperator{\arccosh}{arccosh}
\[ 2 arccosh π
2 \arccosh \pi
\]
For certain operators, limits can be put either to the side or above/below
the operator. Compare these two:
∞
X
P∞
text style i=1 and display style .
i=1
\[
\operatorname{dim}_H^\ast X
\text{ vs } ∗
\operatorname*{dim}_H^\ast X
dim∗H X vs dim X
H
\]
If you need to put multiple lines of text in a sum argument, you can use
the \substack command. Inside its argument, you can use the usual \\ line
breaks:
\[ X
\sum_{\substack{1 \leq j \leq 10\\ 1 \leq k \leq j}}
\] 1≤j≤10
1≤k≤j
Some special operators that deserve a mention are the modulus opera-
tors, since they have some special spacing rules:
92
\begin{gather*}
a \equiv b \mod p\\ a≡b mod p
a \equiv b \bmod p\\
a \equiv b \pmod p a ≡ b mod p
\end{gather*} a≡b (mod p)
4.3.3 Fractions
There are two basic fraction-like commands: \frac for fractions, and \binom
for binomial coefficients. Both take the numerator and denominator as their
arguments.
To produce generalized fraction-like operators like
a a
and ,
b b
the amsmath package provides the \genfrac command. Read the package
documentation to understand its six parameters.
Continued fractions are produced with the \cfrac command:
\[ 1
\cfrac{1}{\sqrt 3 + \cfrac{2}{\sqrt 3 + \dotsb}}
\]
√ 2
3+ √
3 + ···
Warning
Plain TEX does fractions and binomials with the \over and \choose com-
mands that have a different syntax: n \choose m instead of \binom n m.
As natural as the syntax might seem, you should only use the LATEX con-
structs.
93
\[
( \big( \Big( \bigg( \Bigg(
\]
(
Instead of setting the size manually, the \left and \right commands can
be used. They choose the size based on the content between delimiters.
Accordingly, the two commands must be paired correctly – however, the
symbols need not be the same. There is also \middle for an optional middle
delimiter in the matching size.
\[
\left\{ a \in \mathbb Q
1
\middle| a^2 < \frac 1 2 \right\} a∈Qa < 2
\] 2
If you only want to display one of the opening/closing symbols, you can
write e.g. \left( \right.. The full stop suppresses the output of closing
delimiter. See the example on page 81.
Gotcha!
It is not possible to have a line break between \left and \right, so in long
formulas you might need to do the sizing manually.
Good practices
I like to define the following two commands in my documents:
\newcommand{\abs}[1]{\left|#1\right|}
\newcommand{\norm}[1]{\left\|#1\right\|} Absolute value |x|,
Absolute value $\abs x$,\\ function norm kf k.
function norm $\norm f$.
There are two basic styles of sizing other mathematics: text style and
display style (there are also two levels of sub-/superscript styles). The first
is used with inline mathematics and the latter with display mathematics. It
is possible to override the style with \textstyle and \displaystyle:
94
n 1
Text with oversize Text with oversize
$\displaystyle \binom n m \frac 1 2$ m 2
mathematics, and a display with small maths: mathematics, and a display
\[ with small maths:
\sqrt{\textstyle \binom n m \frac 1 2} q
\] n 1
m 2
For fractions, there are the abbreviated \tfrac and \dfrac commands to
achieve this effect.
4.5 Decorations
4.5.1 Accents
You should not use accented Unicode characters like ‘â’ in math mode.
Instead, write \hat a. The supported accents are listed in various places
online.5
Gotcha!
The accents apply to the immediately succeeding character, and do not take
subscripts into account. Compare the three:
To put material over and under symbols, there are the aptly named
\overset, \underset, and \overunderset commands:
\[
\overset{\eqref{eq:pythagoras}}{=}
\quad \underset{\ast}{X} (5.1) a
\quad \overunderset{a}{b}{C}
= X C
∗ b
\]
To produce some very cursed versions of big operators, there is also the
\sideset command:
5
en.wikibooks.org/wiki/LaTeX/Mathematics#Accents
95
\[ ∞
\sideset{^a_b}{^c_d}\sum_{i=1}^\infty a Xc
\] b d
i=1
4.5.2 Dots
The amsmath package provides a context-sensitive \dots command. Com-
pare the vertical positions of the dots in these two examples:
\begin{gather*}
1 + \dots + n\\
1 + ··· + n
1, \dots, n
\end{gather*} 1, . . . , n
\[
catheti
\overbrace{a^2 + b^2}^{\text{catheti}} z }| {
= \underbrace{c^2}_{> 0}. a2 + b2 = |{z}
c2 .
\]
>0
96
\[
\overbracket[1pt][0.5cm]{a^2 + b^2}
= \underbracket[3pt]{c^2}.
\] a 2 + b2 = c 2 .
\[
\boxed{a^2 + b^2} = c^2.
\] a 2 + b2 = c 2 .
If you want to emphasize something with colour, the xcolor package offers
a \mathcolor command that works just like its text counterpart:6
\[
\mathcolor{blue}{a^2 + b^2} = c^2.
\] a 2 + b2 = c 2 .
4.5.4 Arrows
Mathematicians seem to like arrows. Here is a sample of some; note that
some have synonyms for semantically more meaningful code. You probably
can deduce the rules for even further variants:
\begin{gather*}
←→7→
\gets \to \mapsto\\
\leftarrow \uparrow \nwarrow \searrow \rightarrow\\ ←↑-&→
\Leftarrow \Leftrightarrow \Rightarrow\\
⇐⇔⇒
\Longleftarrow \Longleftrightarrow \implies\\
\hookleftarrow \rightharpoonup\\ ⇐=⇐⇒ =⇒
\leftrightharpoons \rightleftharpoons
\end{gather*}
←-*
⇋⇌
6
To be precise, it works very much unlike its text counterpart in that if you try to use
\textcolor in math mode, it breaks the spacing.
97
Sometimes it is useful to put longer sub- or superscripts on arrows. The
amsmath package provides extensible versions of arrows. The command
names are prefixed with x, and the optional argument goes below and the
main argument above the arrow:
\begin{gather*}
f(x) \xrightarrow[n \to \infty]{\text{weakly}} 0\\ weakly
f (x) −−−−→ 0
b^2 = 0 n→∞
\xRightarrow{\eqref{eq:pythagoras}} a^2 = c^2 (5.1)
\end{gather*} b2 = 0 ===⇒ a2 = c2
Gotcha!
These extended arrows should only be used in display size.
Good practices
This is now more of a personal opinion, but I strongly believe that all
theorem-like environments should share the same numbering. It is infu-
riating to find Theorem 5 in a document like
…, Definition 3, Lemma 3, Theorem 3, Lemma 4, Lemma 5,
Lemma 6, Theorem 4, Definition 4, …
where each environment has individual numbering.
98
The appearance of the environment is chosen with the \theoremstyle
command. It applies to all following \newtheorem invocations. There are
three predefined styles:
\theoremstyle{plain}
\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{corollary}[theorem]{Corollary}
\theoremstyle{remark}
\newtheorem{remark}[theorem]{Remark}
\newtheorem{example}[theorem]{Example}
\theoremstyle{definition}
\newtheorem{definition}[theorem]{Definition}
There is also the starred \newtheorem* command that does not produce
a number. It might be useful in some special cases.
\theoremstyle{plain}
\newtheorem*{riemannhyp}{Riemann hypothesis}
\begin{riemannhyp}
The real part of every nontrivial zero of the Riemann zeta function is $1/2$.
\end{riemannhyp}
Riemann hypothesis. The real part of every nontrivial zero of the Rie-
mann zeta function is 1/2.
99
\begin{theorem}[Pythagoras]
If $a$ and $b$ are the lengths of catheti of a right-angled triangle,
then the hypothenuse has length $\sqrt{a^2 + b^2}$.
\end{theorem}
\begin{theorem}
\LaTeX{} course participants are fantastic.
\end{theorem}
\begin{proof}[Sketch of proof]
Just look at them.
\renewcommand{\qedsymbol}{$\heartsuit$}
\end{proof}
If the environment ends with a list or display equation, the QED symbol
is placed on a new line. Since this is not very pretty, we can give LATEX a
hint with the \qedhere command.
100
Remainder of a long proof. It remains to notice that
a2 − b2 = (a + b)(a − b).
There are also some fancier theorem environments, such as those pro-
duced by ntheorem. However, ntheorem does have some subtly surprising
behaviors at times, and it might have compatibility issues with some other
packages.7
The LATEX Companion [4, Section 4.1.5] suggests using the thmtools pack-
age to iron out some differences between amsthm and ntheorem, but I have
no personal experience of it.
7
This observation sponsored by: using ntheorem in quite a few projects, including these
notes. Since the examples use amsthm syntax and ntheorem is at times very incompatible
with it, there are some nasty hacks involved.
101
Chapter 5
Good practices
Put the \label command immediately after the numbered thing. This is
both for readability and for maintainability.
The \ref command reproduces the number that the label was associ-
ated to. There is also a \pageref command that outputs the page number
instead. Finally, \eqref puts the number inside parentheses just like in the
equation tag.
\begin{equation}\label{eq:pythagoras}
a^2 + b^2 = c^2.
\end{equation} a 2 + b2 = c 2 . (5.1)
(Note the ~ that keeps the prefix and number on the same line. This is a
good practice.)
102
Good practices
The label can be quite free-form, and I do not dare give any advice on how
things should be named. I personally use a quite verbose style with spaces,
like eq:2d variational formula, but you could also argue against that.
However, one nice and common practice is to prefix the label with a
type. Above, I have used eq: to denote equations. Other common ones are
def(inition), fig(ure), rem(ark), sec(tion), tbl (table), and thm (theorem).
In the writing phase, it is useful to see the keys in PDF output. The
showkeys package does just that: wherever a \label is defined, the key
is printed to the page margin. Check out the package documentation for
options; in particular, the notref and notcite options suppress the display
of keys at \ref and \cite commands respectively.
Good practices
If the preceding paragraph sounded like a true story that has happened to
the present author, you are absolutely right.
Almost all journal styles are compatible with cleveref. Use it.
This package adds two more commands: \cref and \Cref. They do
exactly what you would expect them to: you write \Cref{thm:pythagoras}
or \cref{...}, and it outputs “Theorem 4.1” or respectively “theorem 4.1”.
That is, the two commands differ on the casing of the first letter.
The command automatically supports all standard LATEX labels. Theo-
rem types are recognized if you define theorems with amsthm or ntheorem
(as you should). See the package documentation for extension options.
A nice feature of this package is that you can also pass several references,
and cleveref sorts out how to present them. That is,
1
On a positive note: such a referee has really read the paper.
103
\Cref{thm:first,thm:second,thm:third}
might produce something like “Theorems 4.1 to 4.3” or “Theorems 4.1, 4.7,
and 5.1”. Again, see the package documentation for how to customize this.
There are also the \cpageref and \Cpageref commands to produce
page references (with the same support for ranges), and a few other more
specialized commands.
Gotcha!
Do not put spaces around the commas in the argument to \Cref.
The package does have predefined names for many common theorem
environments, but in some cases you need to define the name by yourself.
This is done with the \crefname command. It takes three arguments: name
of the environment, singular form, and plural form. Capitalization is handled
automatically.
\newtheorem{assumption}{Assumption}
\crefname{assumption}{assumption}{assumptions}
Gotcha!
Since cleveref modifies the referencing mechanism, it should be loaded after
any other packages that do so, but before any theorem environments are
defined.
Gotcha!
The cleveref package has some support for non-English languages; you can
pass a language name as an option when you load the package. However,
label names are always output in the nominative case, so the usefulness of
the package may be limited for most other languages.
104
about numbered, author-year, and abbreviated citations. Again, something
for computers to do.
There are three standard technologies to create bibliographies, so let us
go over them in the order of increasing preferability. Finally, we also mention
an unfortunate hack that some journals apparently require.
\begin{thebibliography}{9}
\bibitem{Oksendal}
Bernt \O{}ksendal,
\textit{Stochastic Differential Equations:
An Introduction with Applications},
Springer,
6\textsuperscript{th} edition, 5\textsuperscript{th} corrected printing,
2010.
\end{thebibliography}
105
Good practices
This method is only advisable for short throwaway notes when collecting
a .bib file would be too much of an effort. If you use a proper reference
management application, this is almost never the case.
Remark
When you submit your work to arXiv, you need to send the compiled .bbl
file. The arXiv processing system does not run the bibtex compiler. This
means that you should run it manually, verify that the resulting bibliography
is up to date, and then send both the .tex and .bbl files. You should then
check that the bibliography and citations appear correctly in the version
compiled by arXiv.
Good practices
You should also automate the process of collecting the bibliography. Ref-
erence management applications can help you organize your references and
are able to download information from bibliographic databases.
1
www.zotero.org
1
retorque.re/zotero-better-bibtex/
106
Most reference managers support exporting in the .bib format. One
good, free application is Zotero2 .
A small note as a Zotero user (as of April 2024): unfortunately, the
.bib export escapes LATEX commands like $ into \$, and ^ into even more
horrendous \textasciicircum. You can install the Better BibTeX plugin
to Zotero to get customizable, better-quality export.3
Gotcha!
The bibtex compiler is not Unicode-aware, so you need to write non-English
characters with TEX special commands. If an author name begins with a
non-English character, it may be sorted into an odd position. (You can use
the key entry to provide an alternative sorting key.)
The .bib file format consists of entries that begin with a @type dec-
laration, followed by {} that contains the citation key and further data in
key-value format. This is probably easiest to explain with examples, so let
us see some common entry types.
@article {OnPyth,
author = {Firstname Lastname and Secondauthor, Also},
title = {On {Pythagoras'} Theorem},
journal = {Journal of Fake Mathematics},
year = {2024},
month = {jan},
volume = {13},
number = {1},
pages = {653--675},
note = {Redacted in Feb~2024.},
doi = {10.1234/5678}
}
107
– “First von Last”,
– “von Last, First”,
– “von Last, Jr, First”.
• The bibliography style also defines if Each Word in The Title Will
Be Capitalized, or if The title should follow sentence case. To protect
words from automatic (de-)capitalization, wrap them inside {}; here
Pythagoras is protected from becoming pythagoras.
• The page range should have the -- en dash as per good style!
• The note entry can be used for anything else that should be printed
in the bibliography.
• The doi entry is not understood by original BibTeX styles, but newer
styles (such as those provided by natbib) display them as clickable
links. Similarly, there is an eid entry type for electronic article IDs
used by purely electronic journals.
Let us then see what a bibliographic entry for a book could look like.
@book {Pyth2,
author = {von Lastname, Firstname},
title = {Pythagoras Reloaded},
year = {2024},
publisher = {Fake Press},
address = {Kumpula, Finland},
edition = {Third},
series = {Misunderstanding Historical Mathematics},
number = {17}
}
108
There are also the self-explanatory @mastersthesis and @phdthesis
types; the precise type can be specified with a type key. There are also
@techreport for volumes in a report series, and @manual for technical doc-
umentation. See Table 5.1 for the typical entry keys in these types.
How to cite a preprint? Unfortunately, BibTeX is quite a bit older
than arXiv and friends, so there is no built-in support for referencing online
repositories. The best bet is to use the @unpublished entry type and write
something like “arXiv preprint yyyy.xxxxx” in the note field.
Good practices
As mentioned above, the built-in BibTeX styles have no support for DOI
codes either. Even if your current style does not show them, you should still
include doi entries in article data, since
3. They are very useful when you need to cross-check the data.
\bibliography{my-refs}
\bibliographystyle{plain}
Another built-in style is alpha, which produces short labels from author
names and year; for example [Mit23]. Most journals have their own preferred
style.
If you prefer author-year type citations (Mittelbach 2023), the cleanest
way is to load the package natbib with the authoryear option. This requires
replacing the bibliography style with plainnat or other compatible style.
109
Entry type Required Optional
@article author, title, volume, number,
journal, year pages, month, and
preferably also doi, eid
@book author or editor, volume or number,
title, publisher, series, address,
year edition, month
@incollection author, title, pages, chapter, and
booktitle, publisher, those in @book
year
@inproceedings author, title, pages, organization,
booktitle, year and those in @book
@manual title author, organization,
address, edition,
year, month
@mastersthesis author, title, type, address, month
@phdthesis school, year
@techreport author, title, number, address,
institution, year month
@unpublished author, title, note year, month
@misc At least one of author,
title, howpublished,
year, month, note
Table 5.1: Some common BibTeX entry types and recommended fields. All
entry types also support the note field.
110
This package also provides some new citation commands: \citep puts
the full citation in parentheses, whereas \citet wraps only the year; the
additional \citeauthor and \citeyear should be quite self-descriptive. See
the package documentation for more details.
Good practices
Even if you don’t use author-year citations, the plainnat style is useful in
its support for DOIs and URLs.
Gotcha!
BibLaTeX is quite backwards-compatible and BibTeX ignores unrecognized
keys, so it is quite easy to write a database compatible with both.
However, there are minor differences in e.g. how the edition key is
handled. Check the bibliography carefully before submitting!
Most importantly, the doi, eid (electronic article ID), and url keys
understood by natbib are natively supported by BibLaTeX. If you don’t
need BibTeX compatibility, you can specify a preprint with the new syntax:
@unpublished{Pyth,
title = {On {Pythagoras'} relativity theory},
author = {Firstname Lastname},
year = {2022},
eprint = {2211.16111v4},
eprinttype = {arxiv}
}
111
Supported eprinttype values include arxiv, jstor, pubmed, and hdl. These
all produce clickable hyperlinks.
The syntax to using BibLaTeX is quite different. The package is loaded
with \usepackage{biblatex}. Here it is possible to pass customization
options like the style (see below). Then the .bib files are specified with
\addbibresource commands. Finally, \printbibliography outputs the
bibliography in the specified place.
That is, a complete minimal example would be:
% In the preamble
\usepackage{biblatex}
\addbibresource{my-refs}
Moreover, to compile the bibliography you need to use the biber pro-
gram. If you cannot use biber, it is possible to pass backend=bibtex as a
package option to use legacy bibtex instead. Do note that Unicode support
is then unavailable, and some more advanced features might not work.
Good practices
Joking aside, unfortunately many journals are still to adopt BibLaTeX. This
means that one still also needs to work with legacy BibTeX as well.
112
5.2.4 Embedding the bibliography
Some journals require you to submit only one .tex file, with the bibliography
embedded in the text. This is no reason to go to the manual entry; instead,
you can copy and paste the BibTeX output:
0. Do all your editing, and only do the following as the last step.
If you use BibLaTeX, there are some good news and some bad news.
Good news: you can use BibLaTeX with all its benefits, since the journal
system is not in your way! Bad news: the .bbl file is not readily copy-
pasteable.
There is a hack for doing this in the form of biblatex2bibitem package.
Check out the package page on CTAN for more information.
113
5.3.1 Indexing*
In the uncommon case that you need to prepare an index, let us very briefly
go over the basic syntax. You need to put \makeindex in the preamble, and
the index is printed with \printindex.
As with bibliographies, an external program is used to compile the index.
This used to be done with makeindex, but nowadays a better option is
upmendex; the latter is fully compatible with makeindex syntax but
additionally supports Unicode.
Index entries are added with the \index command. At the simplest, it
takes the text to be inserted to the index. The index will point to the page
where command is executed. However, the syntax also supports subindex
entries and customizing the look of the entry.
A subindex entry like “counters, list” is created by putting ! between
the index key and the subindex key. If you need to control the placement
of the key, or want to apply styling, you can put @ between the sorting key
and the visual appearance.
See the examples below for how this is done.
As a final note, there is also the \see command that yield “see …” entries.
These index entries do not feature a page number, so the command can be
placed anywhere. As a real example from these notes:
Good practices
A good index is hard to make, but extremely useful for a reader. There are
even books on the art of indexing.
These notes are not to be looked as a model for good indexing; most of
the index is created automatically by the commands that format command,
environment, and package names. The manually created part of the index
has not received the love it would deserve.
114
5.4 Tools for the editing process
5.4.1 Line numbers
Some journals require line numbers for the referee copy of a submitted work.
This is usually achieved with the lineno package.
The syntax is very simple. Load the package and specify \linenumbers
in the preamble or beginning of the document. You can pause the numbering
with \nolinenumbers and resume it with \linenumbers again.
You can specify the \modulolinenumbers command to print a number
only every fifth line; the gap can be specified as an optional argument like
\modulolinenumbers[2] (for a number on every other line).
By default, equation environments are not numbered. Load the package
with [mathlines] optional argument to enable this.
Gotcha!
Built-in support for amsmath was only included in July 2022, so you may
need to update packages in your LATEX distribution.
There is also the [pagewise] package option to reset the line numbers
for each page, but be advised: it might require two LATEX runs to be correct.
5.4.2 latexdiff
The latexdiff program is an external script that is immensely useful in edit-
ing. It compares two .tex files and outputs a .tex file where any differences
between the two are highlighted.
Good practices
Many referees and journal editors really appreciate getting a latexdiff along
with a revised version. They are also useful to pass between coauthors, and
sometimes even for your own reference.
To make this work, you should preserve a copy of each submitted version
for later diffing. (This combines really well with version control software,
but that is a topic for a different course.)
115
The latexdiff program is a Perl script, so you will need a Perl interpreter
installed. It is usually installed by default on Linux and macOS systems,
but for Windows you will need to install it.4
On Linux and macOS the usage is as simple as
chcp 65001
perl path/to/latexdiff.pl old.tex new.tex > diff.tex
Here the chcp command stands for “choose code page”, and UTF-8 is num-
bered to be 65001. (Code pages are synonymous for LATEX encodings like
latin1.)
In Windows PowerShell, you can enter the legacy Command Prompt by
executing cmd. (The present author is not aware of a robust PowerShell-
native method that would work across all the versions in active use.)
The new .tex file produced by latexdiff is a merged copy of the two
input files, with additions wrapped inside \DIFadd and deletions wrapped
inside \DIFdel commands. By default, these produce coloured and under-
lined text.
Gotcha!
Unfortunately, latexdiff sometimes produces LATEX code that fails to com-
pile. For example, a subscript and the text preceding it might be separated
by a \DIFadd command.
4
There is also a “portable” distribution called Strawberry Perl, if you are uncomfort-
able about installing things.
5
The reason for this mismatch is historical. The Windows command-line interface was
introduced with Windows NT in 1993, and UTF-8 saw the light at around the same time.
It took some more years for UTF-8 to become the standard choice. The developers of
Windows have been as serious as the LATEX developers about backwards compatibility, so
the default is stuck to be UTF-16.
116
You need to manually fix up these issues, which makes for an exercise in
LAT
EX debugging. If you keep your lines reasonably short, at least you get
some assistance from the line numbers.
Gotcha!
Sometimes the differencing algorithm also produces non-obvious results: If
you delete some text and add new text in its place, you might not get two
neat “deletion” and “insertion” blocks. Instead, the diff is a salad of deleted,
inserted, and kept-intact pieces.
It is impossible to develop perfect heuristics for detecting the intended
changes. In principle, you could manually edit the diff, but most likely you
should just keep it as is. One can always look at the two versions side by
side; what is important is that the diff shows that something big has changed
at that position.
If your document is split into multiple .tex files, you only need to give
the paths to the main files. The algorithm is clever enough to parse \input
and \include commands.
% Preamble
\usepackage[final]{pdfpages}
\includepdf[pages=-]{article1.pdf}
The final package option ensures that pages are embedded even if the rest
of the document is in draft mode.
117
Chapter 6
Further customization
1
Processing drawing commands requires processing power and memory. The original
Apple laser printers were more powerful than the Macintosh computers used to lay out
the documents!
118
Another development was with the character sets. Original TEX used
7 bits per character, because 128 characters is enough for anybody (that is,
anybody writing in English). In the 1980s, this was recognized as unsustain-
able, so the character set was doubled into 8 bits. Any further extensions to
that are based on swapping fonts on the fly.
This limitation applies also to pdftex, but in the current2 age of Unicode
there are now alternatives. The two major alternative compilers are
Good practices
Based on the discussion above, it would be natural to suggest always using
luatex. For personal writing, either of the Unicode engines should be the
first choice.
Alas, arXiv and many publishers still use pdftex in their pipeline. This
means that we are still stuck with making our articles pdftex-compatible.
Hopefully the situation will change soon enough.
119
• Can a “screen reader” program read the document aloud for a blind
person?
• Can the text from the document be copy-pasted into another program?
Note that the last point might not sound like an accessibility issue, but it is
caused and solvable by the same reasons.
There are three layers of accessibility work going on:
1. The PDF format can include semantic metadata about the document
contents. LATEX is increasingly better at writing this metadata, but it
might require you to opt in to the new behavior.
2. LATEX can be compiled into another format, such as HTML web page.
This approach is increasingly used by major publishers and arXiv. It
requires you to use a sensible subset of LATEX.
Good practices
Accessibility is for everybody. Most people benefit from some accommoda-
tions at some point in their life. Even without an “obvious” disability, think
about reading your document
Not all accessibility issues have technological solutions – they also require
you to think about how you present your message. A complicated figure is
hard to read, no matter the technology used to produce it.
120
The translation is hampered by the need to rewrite LATEX internals with-
out breaking compatibility, and all the abuse of commands to get semanti-
cally incorrect but visually good results.
To enable PDF metadata, you should do the following steps:
Warning
Since some behavior changes subtly, you should take these into use only in
new projects and only when everybody involved (including the publisher)
uses a Unicode-native LATEX pipeline.
Be extra careful with checking the output when converting old projects,
or if you need to compile the project with both old and new toolsets.
Warning
As of April 2024, arXiv does not use Unicode-native LATEX tools; their pro-
cess involves pdftex. For arXiv submissions, follow the next section instead.
New in LATEX3
This work is still heavily in progress. There are some arguments to
\DocumentMetadata that enable further in-development features. As of
April 2024 these include tagging of mathematics and tables.
Since these arguments are unstable, they are not documented here and
should not be used in “real” documents quite yet. You can follow the
progress through LATEX release newsletters:
www.latex-project.org/news/
121
In order for the tagging to work, you need to produce semantically correct
code. That is, use \subsection* when you need an unnumbered subsection,
and only then – do not abuse it for bold, heavy text. Similarly, use \emph to
emphasize, instead of \textit or \textbf that carry only visual meaning.
• The text can be reflowed based on the screen size and magnification
factor.
• Existing screen reader programs can already read out web pages.
Good practices
Load and use only the packages that you really need. Prefer mainstream
packages supported by the arXiv converter. ArXiv has a help document
outlining some more best practices for HTML conversion.4
3
github.com/brucemiller/LaTeXML
4
info.arxiv.org/help/submit_latex_best_practices.html
122
6.2.3 Accessible source code
Both of the above methods require you to use semantically meaningful com-
mands: otherwise, the automated tools are unable to do tagging/conversion.
Yet writing good semantic LATEX code is also an accessibility feature: you
can always read the source code.
Remark
Source code posted to arXiv is public and downloadable.
If you want to set vectors in bold font, then do not write \mathbf but
redefine \vec to set vectors in bold style:
% Preamble
\renewcommand{\vec}{\mathbf}
a
$\vec a$
Now it is immediate from the source code that a refers to a vector. It can
not be confused with other things marked with boldface. Besides, if you
change your mind about the style, you only need to change one command
in the preamble.
6.3 Typefaces
We will discuss two methods for changing the typeface in your document.
In neither case, we do not comment too much on the aesthetic qualities –
use at your own risk!
Warning
When changing fonts, especially the one used for mathematics, make sure
that all the special characters still appear correctly. The character support
of different fonts varies wildly.
123
To find packaged typefaces, you can use the LATEX Font Catalogue5 main-
tained by TEX Users’ Group. Each catalogue entry displays the code needed
to load the font with typical installations.
In the Font implementation section, you should check what types are
available. Type 1 fonts can be used with pdfTeX, whereas LuaTeX and
XeTeX additionally support (and prefer!) OpenType or TrueType fonts.
Let us see a few examples of common fonts. First, for comparison, here
is a small standard text written with the default Latin Modern typeface (the
≲ symbol comes from amssymb):
J’ai écrit mon curriculum vitæ en français. Jag borde skriva det
också på svenska. Tänä yönä sekin tapahtuu.
\usepackage{newpxtext,newpxmath}
% No need to load amssymb
J’ai écrit mon curriculum vitæ en français. Jag borde skriva det
också på svenska. Tänä yönä sekin tapahtuu.
5
tug.org/FontCatalogue/
124
Technical side note
Typeface designs cannot be copyrighted, but the names are trademarks.
This is why near-identical implementations of the same typeface can appear
with very different names.
\usepackage{notomath}
% No need to load amssymb
For one more example, let us see a sans serif typeface. The Source Sans
typeface is an open source font by Adobe. When the package is loaded with
the default option, sans serif becomes the default font family. However,
it does not come with mathematics support. Without further tweaks, the
display mathematics comes in a very different typeface!
\usepackage[default]{sourcesanspro}
\usepackage{amssymb}
6
Its name comes from no tofu, since the rectangular ‘missing character’ symbol in
web browsers is sometimes called ‘tofu’.
125
Font specimen: Source Sans + Latin Modern Math
This is a long example text paragraph, demonstrating how the head‑
ing blends into the rest of the text. Usually, one writes something like
lorem ipsum dolor sit amet here.
∫ t
sin(x)
2
dx ≲ (A ⊗ B)({α, α̃, t}).
0 x +7
J’ai écrit mon curriculum vitæ en français. Jag borde skriva det också
på svenska. Tänä yönä sekin tapahtuu.
Many sans serif packages have options to make sans serif the default
style. The same can be achieved manually with
\renewcommand{\familydefault}{\sfdefault}
Remark
This section only applies to LuaTeX and XeTeX.
Like character sets, also font formats have undergone a parallel evolution
between TEX and the rest of the world. Nowadays, fonts are distributed in
the OpenType format (and its predecessor TrueType).
The fontspec package allows loading OpenType/TrueType fonts on the
Unicode-native compilers. In the preamble, the default roman, sans serif,
and typewriter fonts are set with the respective commands:
126
It is also possible to give file names to fonts, if you have the font files
in the same folder tree as your document.7 In this case, you might need to
specify file names for each weight separately:8
\setmainfont{FiraSans-Book.otf}[
BoldFont={FiraSans-SemiBold.otf},
ItalicFont={FiraSans-BookItalic.otf}]
% Preamble
\newfontfamily{\comicfont}{Comic Sans MS}
% Document
Some people hate {\comicfont Comic Sans},
but its history is often {\comicfont misunderstood}.
All these font loading command support a lot of optional arguments – see
the package documentation. These can be used to control the appearance
of the typeface and to enable stylistical variants of some letters.
For example, when using typefaces not originally designed to play to-
gether, it might be useful to slightly adjust the sizes of fonts:
127
\usepackage{fontspec}
\setmainfont{TeX Gyre Pagella}
\usepackage{unicode-math}
\setmathfont{Asana-Math.otf}
% No amssymb loaded
J’ai écrit mon curriculum vitæ en français. Jag borde skriva det
också på svenska. Tänä yönä sekin tapahtuu.
128
\fontsize{12pt}{14pt}\selectfont This is set in 12 pt font, with
This is set in 12~pt font,
14 pt baseline skip. Some
with 14~pt baseline skip.
Some extra text to illustrate extra text to illustrate the
the line heights. line heights.
Warning
Support for microtype features depends a lot on the compiler. If you use
the package, be aware that the page layout can change significantly between
different compilers.
Warning
Some fonts might not pair well with the built-in adjustment parameters.
6.3.4 Emoji
Emoji are Unicode characters, so in principle they can be included just as
is in the source code. The problem is choosing a font that can display the
characters.
The emoji package automatically chooses an available emoji font (that
is, the output will depend on your operating system!). It only works with
recent LuaTeX (2020 or newer). The command provides readable shorthand
names for the characters (listed in documentation):
% Preamble
\usepackage{emoji}
% In text
\emoji{thinking-face}
129
There is also the manual way of loading the emoji font with fontspec:
% Preamble
\usepackage{fontspec}
\newfontfamily{\emojifont}{Noto Color Emoji}[Renderer=Harfbuzz]
% In text
{\emojifont ...}
Here, ... should be replaced with the emoji (not displayed here, since these
notes do not have an emoji font set up!). You need to install the emoji font
or replace it by the system emoji font. (On Windows, it is called Segoe UI
Emoji; on macOS it is Apple Color Emoji.)
Warning
With the manual way, black-and-white emoji can be displayed by both Xe-
TeX and LuaTeX, but color emoji requires LuaTeX with the HarfBuzz
renderer. If you use fontspec to load an emoji font, you need to pass
Renderer=Harfbuzz as an optional font feature. This option is effective
only with LuaTeX.
130
Chapter 7
Warning
Again, careful with the spelling! The graphicx package replaces the old
graphics package, which has similar basic syntax but less flexibility.
\includegraphics[width=\textwidth]
{pictures/TheDogs.jpg}
131
There are quite a few optional parameters using the key=value syntax:
width Sets the width of the picture in document units. Can be any expres-
sion like width=0.5\textwidth or width=8cm. Height of the picture
is chosen to match the aspect ratio.
height Alternatively, the height can be fixed and width chosen automati-
cally. If both height and width are set, then the picture is stretched
to the given height and width.
origin Origin for the rotation. Most useful value is c for center; others are
l for left, r for right, t for top, b for bottom, and combinations of the
five.
bb, clip Named for “bounding box”, the bb parameter defines the region
of the image to use in size computations. The clip option then crops
the image to this size. If this option is not set, then the image extends
outside the region reserved for it!
The bounding box is specified as bb=1 2 3 4; in this example the
lower-left corner is at (1, 2) and the upper-right at (3, 4), and the
origin (0, 0) is at the lower-left corner of the image. By default the
unit is “big points” (1/72th of an inch), but other TEX length units
can be used. Due to the choice of units, this is most useful with PDF
images.
132
\includegraphics[bb=2.3cm 1.4cm 7cm 6cm,clip]
{pictures/TheDogs.jpg}
\includegraphics[totalheight=3cm, angle=45]
{pictures/TheDogs.jpg}
\includegraphics[height=3cm, draft]
{pictures/TheDogs.jpg}
pictures/TheDogs.jpg
What type of file should your graphics be? Nowadays the choice is between
essentially three formats:
PDF For vector graphics like graphs and line art. Vectorized graphics can
be zoomed without blurring and embedded text is still selectable.
However, for very complicated graphics (say, a scatter plot with 1000
points and transparency), it might be better to use a rasterized format.
133
PDF graphics are rendered on the reader’s device, so on a slow device
the picture can take a while to load!
PNG For complex line art. PNG is a lossless format, meaning that the
picture is reproduced pixel-perfectly. The compression algorithm is
designed for computer graphics with solid colors and simple gradients.
It is not suitable for photographs (due to massive file sizes).
JPEG For photographs. The algorithm is lossy, meaning that compression
artifacts can be seen when zoomed in. The artifacts are hard to see in
photographs, but are very distinguishable in line art and text.
The algorithm can be set to various compression levels. You should
experiment with your particular picture, but values between 80–90
usually yield a good balance between quality and file size.
What size should the picture be? To answer this, we need to talk about DPI
– dots per inch. Computer screens have something between 100 to 300 pixels
per inch. The standard for printed documents is usually 300 dots per inch,
and up to 600 dpi for high-quality line art.
This means that if your image will be printed 5 cm wide, its pixel width
must be at least
5 cm
× 300 pixels/in = 590 pixels.
2.54 cm/in
Conversely, the pixel width should not be much larger than this: the extra
resolution would only be seen at very large zoom levels. LATEX does not
rescale images to a reasonable DPI value, so extra-large images cause the
final document to have larger file size.1
The PDF format uses inches instead of pixels. Still, by setting the image
size to the correct value you ensure that text and lines are drawn at a scale
matching the rest of the document.
Good practices
To summarize:
1
You might ask whether file sizes matter in the age of terabyte hard drives and fiber
optic internet. I have downloaded enough many articles onboard long-distance trains to
be allergic to any unnecessary kilobytes. Fast connections are not universal.
134
Good practices
Avoid screenshots; always export your graphics directly from the application
if possible. Most operating systems render text with smoothing adapted to
your screen – the (no longer adapted) smoothing is visible in a screenshot.
In particular, Windows uses a sub-pixel rendering algorithm that is very
visible as coloured artifacts around black text.
New in LATEX3
Since late 2021, \includegraphics has also supported setting alt text: a
textual description of the image. It is passed as the optional alt parameter;
see the example on page 137. This text is used when the document is read
aloud by a screen reader program.
The alt text should give enough information to understand the message
in the image. Writing good alt text is not easy, but there are some resources
online. For some examples, see the decision tree and links therein by W3C2 .
7.2 Floats
Numbered figures and tables in LATEX are collectively known as floats.3 The
algorithm to place floats is again very complicated, with some 20 tunable
parameters; these are explained in detail in [4, Chapter 7.1].
A rough summary of the rules is:
• Floats are always placed in order within a float class. That is, Figure 1
always appears before Figure 2 and Table 1 before Table 2. However,
tables and figures are placed independently, so their order with respect
to each other might be anything.
• LATEX first tries to put the float on the page where the surrounding
code is set. If that fails, the float goes into a queue to be reconsid-
ered for the next page. Consequently, a float might appear above the
surrounding text on the same page, but never on an earlier page.
2
www.w3.org/WAI/tutorials/images/decision-tree/. The WWW Consortium
maintains web standards, so parts of the tutorial are web-specific.
3
Named after their tendency to float around into inconvenient places.
135
• LATEX might produce one or more pages containing only floats if the
queue is full enough.
h Tries to put the float inline at the given position. If there is not enough
space, the specifier is converted to t.
Good practices
As with overfull lines, you should not tweak the placement of floats until
at the very end. Small changes to the text might change the page layout
significantly. Unless you get a visually unpleasing arrangement, avoid adding
placement restrictions.
Gotcha!
Due to the algorithm, there are a few surprising things:
136
• In some rare cases, the placement of floats might push footnotes into
an incorrect page.
Figure captions are generated with the \caption command. This com-
mand also updates the figure number, so a possible cross-reference \label
must come after it.
As a complete example, Figure 7.1 is produced with the following code.
The specifier [ht] forces LATEX to put the figure either immediately after
this paragraph or on top of a following page; it cannot appear at the bottom
of a page. It is usually customary to center the figure, which is done with
the \centering command that applies until the environment ends.
\begin{figure}[ht]
\centering
\includegraphics[width=8cm,
alt={An old labrador retriever close up,
with intense gaze and mouth slightly open.
In the background, a younger labrador also stares at the camera.}]
{pictures/TheDogs.jpg}
\caption{Cira (2009--2022) having a say.}
\label{fig:cira}
\end{figure}
137
Figure 7.2: Left: some dogs. Right: some upside-down dogs.
7.2.1 Subfigures
Floats are just containers for arbitrary LATEX code, so in principle you are
free to put anything in there, even text. This can be abused to create
subfigures as in Figure 7.2:
\begin{figure}
\centering
However, there is also the subcaption package that does the same auto-
matically and with more style.
Warning
Do not use the subfigure or subfig packages; they are no longer maintained
and do not play as well together with hyperref.
4
Akin to the sectioning commands and table of contents.
138
This package offers the \subcaptionbox that takes 2–5 arguments: op-
tional short caption, the caption, optional width for the subfigure, optional
alignment for the subfigure (l, c, or r), and finally the figure contents.
Figure 7.3 shows how this looks in practice. Note how the lines of figures
need to be broken by a paragraph break (empty line); one could put a vertical
spacing command here. For the third subfigure (Figure 7.3c), the width is
set manually so that the caption is not broken into two lines. Note that
\label can be used, but it needs to be inside the caption argument.5
\begin{figure}
\centering
\subcaptionbox{As usual.}{
\includegraphics[width=0.4\textwidth]{pictures/TheDogs.jpg}}
\subcaptionbox{Upside down.}{
\includegraphics[angle=180, origin=c, width=0.4\textwidth]
{pictures/TheDogs.jpg}}
139
(a) As usual. (b) Upside down.
Lorem ipsum
dolor sit amet.
(c) The smaller one. (d) The larger one. (e) Right-aligned and
fixed width.
plaintop (caption on top), boxed, and ruled. The displayed name of the
new environment can be set with the \floatname command.
For example, a float class for source code listings could be defined as
follows. (Note: the listings package also has an option to define a float class,
so it is not necessary to do this manually.)
\floatstyle{ruled}
\newfloat{sourcecode}{tbp}{lst}[chapter]
\floatname{sourcecode}{Code Listing}
140
\begin{sourcecode}[h]
\begin{lstlisting}[language=Pascal]
program Hello;
begin
writeln("Hello world!");
end.
\end{lstlisting}
\caption{A Hello World program in Pascal.}
\label{src:hello pascal}
\end{sourcecode}
program H e l l o ;
begin
writeln ( ” H e l l o world ! ” ) ;
end .
141
Additionally, vertical lines can be specified with | and other inter-
column material with @{...}.
• Each line is ended with \\. If you forget to end a line, you will get an
error at the next &.
The table environment acts exactly like its figure counterpart, and
should be used for tables where the exact placement is not so important.
The following code produces Table 7.1:
\begin{table}[ht]
\centering
\begin{tabular}{l|ccc}
Breed & Drops fur & Tall & Long\\
\hline
Corgi & Somewhat & Very not & Quite\\
Labrador & Very much & Yes & Yes
\end{tabular}
\caption{An extensive comparison of dog breeds.}
\label{tbl:dogs}
\end{table}
142
Breed Drops fur Tall Long
Corgi Somewhat Very not Quite
Labrador Very much Yes Yes
If you need more customization for your tables, then the array package
is the starting point. First off, it adds the following format specifiers:
W Like above, but tries to squeeze the text a bit and if still fails, at least
raises an overfull hbox warning.
! Like the @ specifier, but preserves the horizontal space that would sur-
round a vertical line.
The previous example can be customized as follows. We use the > and <
specifiers to set the rating in a bold font and to remove the duplicated /10
texts. Since ! preserves the whitespace, we no longer need spaces around
the arrow symbol.
143
Breed Drops fur Notes Stars/10 ⇒ Conclusion
Has fairly short
Corgi Somewhat legs but a lot of 13/10 ⇒ Good dog
attitude
Excitable about
other dogs, hu-
Labrador Very much 13/10 ⇒ Good dog
mans, playing in
water
Note that the change from p to m does not improve legibility here; that’s
why I added a horizontal line to separate the two rows. There would also
be several methods to add vertical whitespace to the table:
• The cellspace package can be used to ensure top and bottom vertical
clearances when the cell contents are taller than usual characters. This
package defines a modifier for cell styles.
\begin{tabular}{l| S}
Important constant & {Value}\\
\hline
Pi & 3.14159\ldots\\
Gravity & 9.81\\
Inches to feet & 12\\
Finnish population & {some } 5.61e6
\end{tabular}
144
Important constant Value
Pi 3.141 59…
Gravity 9.81
Inches to feet 12
Finnish population some 5.61 × 106
\setlength\extrarowheight{2pt}
\centering
\begin{tabular}{l| c c @{ $\Rightarrow$ } r}
Breed & Drops fur & Rating & Conclusion\\
\hline
Corgi & Somewhat & 13/10 & Good dog\\
Labrador & Very much & 13/10 & Good dog\\
Roomba & Negatively?! &
\multicolumn{2}{c}{\emph{We're not quite sure}}
\end{tabular}
145
\centering
\begin{tabular}{>{\columncolor{green!15}}l | c c @{ $\Rightarrow$ } r}
\rowcolor{blue!15} Breed & Drops fur & Rating & Conclusion\\
\hline
Corgi & Somewhat & 13/10 & Good dog\\
Labrador & Very much & 13/10 & Good dog\\
Roomba & \cellcolor{orange!20} Negatively?! &
\multicolumn{2}{c}{\emph{We're not quite sure}}
\end{tabular}
Here the \columncolor command goes into the column specifier, and the
\rowcolor command goes into the beginning of each row. As you can see,
the latter is not fully compatible with custom separators. As each cell forms
a scope, you can also use \color to set the text color in a cell.
The diagbox makes it possible to split cells diagonally. It has quite a
lot of configuration options as optional arguments, but we refer the reader
to the package documentation. It also has a somewhat esoretic syntax that
accepts two or three required arguments, meaning that the two-argument
version cannot be followed by a {. (This is quite unlikely in a table cell.)
\centering
\begin{tabular}{l|ccc}
\diagbox{Breed}{Property} & Drops fur & Tall & Long\\
\hline
Corgi & Somewhat & Not & Quite\\
Labrador & Very much & Yes & Yes\\
Roomba & Negatively & Very not & It's round
\end{tabular}
Property
Drops fur Tall Long
Breed
Corgi Somewhat Not Quite
Labrador Very much Yes Yes
Roomba Negatively Very not It’s round
146
7.3.2 Footnotes in tables
Finally, let us talk about footnotes in tables, as sometimes mandated by
scientific style. As discussed in Section 2.5, \footnote commands inside a
tabular environment do not print the footnote text anywhere.
A simple fix is to place the table inside a minipage environment. Often,
an easier alternative is to use the threeparttable package that provides its
own footnote command. You are required to take care of the numbering, but
this is actually useful since commonly the same footnote is used for several
locations.
\centering
\begin{threeparttable}
\begin{tabular}{l|ccc}
Breed & Drops fur & Tall & Long\\
\hline
Corgi & Somewhat\tnote{a} & Not\tnote{b} & Quite\tnote{b}\\
Labrador & Very much\tnote{c} & Yes\tnote{b,c} & Yes\tnote{b,c}\\
Roomba & Negatively\tnote{d} & Very not\tnote{b} & It's round\tnote{b}
\end{tabular}
\begin{tablenotes}[para]
\item[] Sources:
\item[a] Googling.
\item[b] General knowledge.
\item[c] Having lived with some.
\item[d] Rumours.
\end{tablenotes}
\caption{Some extensive research into things.}
\end{threeparttable}
If you ever need to set a table that spans multiple pages, the supertabular
and longtable packages are your friends. The first one is simpler but the
second is more extensible and more maintained.
147
7.3.3 Final words
There are several more useful packages for controlling the layout of tabular
material. Most mathematicians will probably not need them, but [4] has
over 70 pages on this topic if the need arises.
New in LATEX3
As of this writing in April 2024, PDF tagging of tables has recently entered
testing. This means that tables should no longer be completely meaningless
jumbles of text and numbers to a screen reader.
The syntax for annotating tables is still being worked out. In a future
LATEX version, there should be syntax for annotating column headers. Follow
the news on LATEX homepage to know what’s happening!
148
Chapter 8
There are several methods for producing line graphics in LATEX. We cover
here TikZ, which is quite portable across compilers and extremely versatile.
It is contained in the tikz package.
There are several extension libraries that are bundled with TikZ and
loaded with the \usetikzlibrary command. Moreover, many other pack-
ages are built with TikZ. One such package is pgfplots, which provides much
more tools for plotting data.
TikZ has bit of a learning curve and its documentation spreads over
no less than 1321 pages (as of April 2024). We are able to only cover the
essentials here. An unofficial web version of the manual can be accessed at
tikz.dev/.
• That as useful as TikZ is, for complex graphics you probably should
use a proper, visual graphics editor.
Of course, the the acronym is not only recursive, but also oxymoronic, since
TikZ is a program (written in the TEX language) that outputs graphics…
149
two are synonymous.
\begin{tikzpicture}
\draw[->] (0,0) -- (2,0);
\draw[->] (0,0) -- (0,2);
\draw[dotted] (0,0) -- ({sqrt(2)}, 1);
\end{tikzpicture}
xyz As in the example above, coordinates in this system are tuples or triples
of numbers separated by commas. These are with respect to unit
vectors defined in the environment options. By default, the x and y
unit vectors are 1 cm long and along the usual axes. The z axis is
skewed towards the reader.
It is possible to use mathematical syntax like +, /, and sqrt(...)
to give more complicated coordinate expressions. You might need to
wrap the calculation inside {}.
canvas The numbers can also have units like (1cm, 20pt). In this case
the coordinates are the absolute length away from canvas origin. It is
possible to use expressions like 1cm + 2pt.
These units are still not completely absolute: the canvas can still be
scaled with an optional argument.
150
Warning: While it is technically possible to mix canvas and xyz coor-
dinates inside the tuple, it is ill-advised. Similarly, an expression like
1+2cm is interpreted as 1pt+2cm, not as “unit vector plus 1 cm to the
right”.
xyz polar Polar coordinates are like (30:2), which means: 30 degrees
counterclockwise, radius 2 units.
If the x and y unit vectors are set to non-default values, the angle
corresponds to a point on the ellipse specified by x and y vectors, and
the resulting vector is multiplied by the radius factor.
\begin{tikzpicture}
\coordinate (A) at (0:3cm);
\coordinate (B) at (120:2cm);
\begin{tikzpicture}
\draw (0,0) -- ++(0:3) -- ++(90:2)
-- ++(180:1) -- ++(270:1/2);
\end{tikzpicture}
8.1.1 Nodes
Nodes can be thought of as text placed in the picture. The text can contain
mathematics and formatting commands, and even pictures.
A node can be placed either as part of a path, or separately with a \node
command. In the latter case, it is possible to refer to the node later.
1
It is also possible to prefix with just +, in which case the current position is not
updated.
151
Above
\begin{tikzpicture}
\draw (0,0) -- (2,0) node {Left};
\node (A) at (0,2) {Above};
\draw (0,0) -- (A);
\node at (0,-1) {Below}; Left
\end{tikzpicture}
Below
Note the difference between the lines connecting the origin to the Left
and Above nodes. When a node is created as part of a path operation, it is
centered at the specified coordinate. That is, the center of the “Left” text
is at (2, 0). The position of the node can be customized by passing above,
below, left, or right as an optional argument.
On the other hand, when a path is drawn to a previously defined node,
TikZ tries to stop at the boundary of the node. It is possible to specify
the position on the border by cardinal directions (like north) or an angle;
or to specify center if you really mean the center. These are given by the
name.anchor syntax as in the example below.
To make the boundary of the “Above” node visible, we also pass the
draw option to the \node command.
\begin{tikzpicture}
Above
\draw (0,0) -- (2,0) node[right] {Left};
\node[draw] (A) at (0,2) {Above};
\draw (0,0) -- (A.west);
\end{tikzpicture}
Left
\begin{tikzpicture}
\draw[->] (0,0) -- (3,0) 1
node[pos=0.5,above] {$\frac 1 2$} 2
node[pos=0.25,below] {$\frac 1 4$} 1 3
node[pos=0.75,below] {$\frac 3 4$}; 4 4
\end{tikzpicture}
152
To embed pictures, you can use \includegraphics as usual inside a
node. To illustrate this once more with our fur-shedding assistants:
\newcommand{\dogfile}{pictures/TheDogs.jpg}
\begin{tikzpicture}
\node[draw] (Both) at (0,0)
{\includegraphics[height=3cm]{\dogfile}};
\node[draw] (Netta) at (-5,0)
{\includegraphics[bb=1cm 2cm 3cm 5cm, clip, height=2cm]{\dogfile}};
\node[draw] (Cira) at (5,0)
{\includegraphics[bb=2.8cm 1.4cm 7cm 6cm, clip, height=2cm]{\dogfile}};
\draw[->] (Both.west) -- (Netta.east) node[pos=0.5, above] {Netta};
\draw[->] (Both.east) -- (Cira.west) node[pos=0.5, above] {Cira};
\end{tikzpicture}
Netta Cira
\definecolor{Sciency}{cmyk}{0,0.46,1,0}
\begin{tikzpicture}
\draw[color=blue] (0,0)--++(3,0);
\draw[color=LimeGreen] (0,-0.5)--++(3,0);
\draw[color=Sciency] (0,-1)--++(3,0);
\draw[color=Sciency!60] (0,-1.5)--++(3,0);
\end{tikzpicture}
There is also a range of line weights. Do note that their names may
include spaces. Of these, thin is the default.
153
\begin{tikzpicture}[yscale=0.8]
\draw[very thin] (0,-0.5)--++(3,0);
\draw[thin] (0,-1)--++(3,0);
\draw[semithick] (0,-1.5)--++(3,0);
\draw[thick] (0,-2)--++(3,0);
\draw[very thick] (0,-2.5)--++(3,0);
\draw[ultra thick] (0,-3)--++(3,0);
\end{tikzpicture}
Then, there are the line styles. The basic ones are (it is possible to
specify custom ones, but that you have to read from the docs):
\begin{tikzpicture}[yscale=0.8]
\draw[solid] (0,0.5)--++(3,0);
\draw[dashed] (0,-0)--++(3,0);
\draw[dotted] (0,-0.5)--++(3,0);
\draw[densely dashed] (0,-1)--++(3,0);
\draw[densely dotted] (0,-1.5)--++(3,0);
\draw[loosely dashed] (0,-2)--++(3,0);
\draw[loosely dotted] (0,-2.5)--++(3,0);
\draw[dash dot] (0,-3)--++(3,0);
\draw[dash dot dot] (0,-3.5)--++(3,0);
\end{tikzpicture}
Good practices
As remarked in the section on colour, you should never use colour as the
sole means of giving information. In simple line graphics, the combination
of colour and line style is often useful. However, complex line styles are also
hard to read!
Finally, there are the arrows. The syntax for arrow tips is hstarti-hendi,
where the start/end specification can contain one or more <, >, or |.
\begin{tikzpicture}[yscale=0.8]
\draw[<->] (0,-0)--++(3,0);
\draw[->>] (0,-0.5)--++(3,0);
\draw[|->|] (0,-1.0)--++(3,0);
\end{tikzpicture}
The arrows.meta extension library contains many more tip styles and op-
tions to customize their size; see [5, Section 16].
154
% \usetikzlibrary{arrows.meta}
\begin{tikzpicture}[yscale=0.8]
\draw[Circle-{Circle[open]}] (0,-0)--++(3,0);
\draw[-{Stealth[length=5mm,width=2mm,red]}] (4,0)--++(3,0);
\draw[{->[harpoon]}] (8,0)--++(3,0);
\end{tikzpicture}
One more option: the rounded corners option does what is says. It
takes as its argument a radius of the corner. It is one of the few options
that can be changed in the middle of a path (none of the above can, unfor-
tunately).
\begin{tikzpicture}
\draw[rounded corners=2mm] (0,0) -- (2,0)
[rounded corners=5mm] -- (2,-2)
[sharp corners] -- (0,-2) -- (0,-1);
\end{tikzpicture}
155
8.2 Special paths
In addition to the -- style path joining two points, there are the |- and -|
styles. These split the line into vertical and horizontal segments, the order
of which you can probably guess.
\begin{tikzpicture}
\draw (0,0) -| (2,1);
\end{tikzpicture}
\begin{tikzpicture}
\draw (0,0) rectangle (3,2);
\draw[red] (3/2,1) circle
[x radius=3/2, y radius=1];
\filldraw[blue, fill=blue!20] (4,1) circle [radius=0.5];
\end{tikzpicture}
There are also commands for drawing arcs, parabolas, and even Bézier
curves; see [5, Section 14].
There is a helper command for drawing coordinate grids. TikZ provides
a shorthand style help lines that can be customized as in Section 8.5.
Here we overlay two grids with different step sizes (default is one unit).
2
If the lines cross, the definition of interior can be customized with optional arguments
nonzero rule and even odd rule. These are defined in [5, Section 15.5.2].
156
\begin{tikzpicture}
\draw[help lines, xstep=0.5, ystep=0.5] (0,0) grid (4,3);
\draw (0,0) grid (4,3);
\draw[red,very thick,->] (0,0) -- (2,1);
\end{tikzpicture}
\begin{tikzpicture}
\draw[help lines] (0,0) grid (8,3);
\draw[red, domain=0:8, samples=100] plot (\x, {1+sin(\x r)})
node[right] {$1+\sin(x)$};
\draw[blue, dashed, domain=0:8, samples=100] plot (\x, {exp(\x/8)})
node[right] {$\exp(x/8)$};
\draw[black, domain=0:8, samples=100] plot (\x, {pow(\x, 1/2)})
node[above right] {$\sqrt x$};
\end{tikzpicture}
√
x
exp(x/8)
1 + sin(x)
157
• The variable x is written with a backslash \x, but the mathematical
commands are spelled without a backslash.
• Mathematical expressions should be wrapped inside {}.
• Powers like x2 can be specified with pow(\x, 2).
• Trigonometric functions assume degrees by default; the suffix r after
\x converts the variable into radians.
Note that the plot is still defined as a pair of (x, y) coordinates. This
makes it possible to draw parametric plots. The name of the variable can
be customized.
\begin{tikzpicture}
\draw[help lines] (-2,-1) grid (2,2);
\draw[red, domain=1:15, samples=150, variable=\t]
plot ({2*cos(\t r) / \t}, {2*sin(\t r) / \t});
\end{tikzpicture}
Warning
“Division by zero” and “number too big“ errors can sometimes lead to con-
fusing (and repeated!) error messages.
Good practices
TikZ is excellent for producing small and simple function plots in a style
consistent with the rest of the document. However, compilation times can
get quite long for even slightly complicated functions.
If you need to plot lots of complex functions, you should precompute the
function values in a file and use the data plotting facility of TikZ; see [5,
Section 22].
158
8.3 Transformations
The xshift, yshift, rotate, and scale optional arguments can be used
to locally change the coordinate system.3 You can use a scope environment
within the picture to pass the transformation to multiple drawing operations:
\begin{tikzpicture}
\draw (0,0) rectangle (2,1);
\begin{scope}[xshift=3cm]
\draw[dotted] (0,0) rectangle (2,1);
\end{scope}
\begin{scope}[xshift=6.2cm, scale=0.5, rotate=30]
\draw[blue] (0,0) rectangle (2,1);
\end{scope}
\end{tikzpicture}
Note that the xshift parameter should be specified with a unit (otherwise
the unit is assumed to be pt). The scope environment can be used to pass
any optional arguments to enclosed commands; for example, color or line
style declarations can be passed as well.
Sometimes it is necessary to extend or to shrink the bounding box of
the picture. For this, the \useasboundingbox command is useful.4 (This
is especially useful in a Beamer slide where you gradually reveal parts of
the picture. You can use this command to reserve enough space for the full
picture.)
Here we instead shrink the bounding box so that the picture contents
extend beyond the reserved space. The dramatic effect is somewhat ruined
by displaying the bounding box.
3
There are some more; see [5, Section 25.3] for details. A particular example is rotate
around, which rotates around a specified point.
4
Let us note that this is a shorthand for \path[use as bounding box]; TikZ certainly
has many ways to do common operations.
159
Then a huge seagull
\begin{tikzpicture}
\useasboundingbox[draw,dotted,gray] (-1em,-0.7em) rectangle (1em,0.8em);
8.4 Loops
TikZ automatically loads the pgffor package that provides a useful \foreach
command. It can be used in two ways. The first is to loop over a given set:
\begin{tikzpicture}
\foreach \x in {0,1,2,3}
\draw (\x, 0) circle [radius=0.5] node {$\x$};
\end{tikzpicture}
0 1 2 3
\begin{tikzpicture}
\foreach \x in {1,2,3}
\foreach \y in {1,2,3}
\draw (\x, -\y) circle [radius={(\x+\y)/15}];
\end{tikzpicture}
160
With {}, it is possible to define several commands to be executed. It is also
possible to define several variables in one loop:
\begin{tikzpicture}
\foreach \x/\col in {1/red, 3/black, 5/blue} {
\draw[\col] (\x, 0) circle [radius=0.5] node {$\x$};
\draw[->] (\x,-0.2) -- (\x,-1) node[below] {\col};
}
\end{tikzpicture}
1 3 5
\begin{tikzpicture}
\foreach \x in {0,1,...,5}
\draw (\x, 0) circle [radius=0.5] node {$\x$};
\end{tikzpicture}
0 1 2 3 4 5
Finally, let us note that the \foreach command can freely be used out-
side TikZ. (If you do not need full TikZ, you can just load the pgffor package.)
161
8.5 Setting styles*
In the grid example, we saw the help lines style that produced thin, gray
lines. TikZ provides a general facility for setting up such shorthand styles.
If you find yourself repeating graphical options, you should consider using a
style instead.5
To customize the style, you use the /.style={} syntax in the optional
argument to the picture environment:
If you only want to customize part of the style, you can keep the previous
elements in place by using /.append style={} instead. Here we keep the
lines thin and gray, but also make them dashed:
You can define your own styles with the /.style syntax. To reuse them
across multiple TikZ environments, you can put the definition in a \tikzset
command. Such a command could go into the preamble. It is still possible
to override styles locally. Here we define a style called highlight:
5
Those familiar with web development notice that this system is similar to Cascading
Style Sheets (CSS); indeed, the TikZ style system is inspired by it.
162
\tikzset{highlight/.style={draw,very thick,orange}}
\newcommand{\dogfile}{pictures/TheDogs.jpg}
\begin{tikzpicture}
\node[highlight] at (-2,0)
{\includegraphics[bb=1cm 2cm 3cm 5cm, clip, height=2cm]{\dogfile}};
\node[highlight, blue] at (2,0)
{\includegraphics[bb=2.8cm 1.4cm 7cm 6cm, clip, height=2cm]{\dogfile}};
\end{tikzpicture}
Good practices
Do note that this idea goes very well with the separation of content and
presentation. If your document contains a lot of TikZ graphics with repeated
graphical styles, you should use styles with descriptive names. Not only is
the code semantically meaningful, but also easier to change.
\begin{tikzcd}
A \arrow[r] \arrow[d, dotted] & B \arrow[d, Rightarrow, bend left]\\
C \arrow[r, maps to, "\psi"] & D
\end{tikzcd}
163
A B
ψ
C D
Gotcha!
If you get an error message when you try to add a label (like "\psi" above),
you should try loading the babel TikZ library. This relates to the handling
of quotation marks by babel package; the TikZ support library fixes up the
handling inside TikZ environments.
6
tikzcd.yichuanshen.de/
164
Chapter 9
If you ask me, Beamer is an odd tool. Presentations are inherently visual,
so a programming tool like LATEX seems ill-suited for the job. On the other
hand, most graphical programs cannot match the quality of LATEX mathe-
matics, and technical talks often have modest visual needs.
Beamer does strike a nice balance between the two, if only your talk is
not too ambitious with the visuals. At the same time I find its complexity
to be similar to TikZ – a lot of things are possible, but not all of them are
advisable.
Good practices
Even though this course is not about presentation skills, I want to use this
opportunity for an important reminder: Beamer makes it very easy to throw
too much mathematics at your audience.
Leave whitespace on your slides, and focus on pictures to support your
point. If you want to dive deep into a mathematical topic, there is an even
superior tool: blackboard.
165
\documentclass{beamer}
\begin{document}
\begin{frame}
\end{frame}
\end{document}
Beamer automatically loads hyperref. It also loads amsthm and creates some
theorem environments by default.
Since TEX always believes it is typesetting for printing, Beamer modifies
the page size to be suitable. By default it is 128×96 mm, which corresponds
to 4:3 aspect ratio.
To modify the aspect ratio, you can pass the aspectratio class option.
It is a string of two to four digits, and interpreted like: aspectratio=32
means 3:2, 169 means 16:9, and 1610 means 16:10.
Good practices
Many computer screens have 16:9 or 16:10 aspect ratio, so 4:3 might seem
old-fashioned. However, 4:3 has the benefit of increased vertical space. Many
projectors can output either aspect ratio comfortably. If possible, check the
venue beforehand.
The default 11 pt font fits very nicely with the simulated paper size. You
can pass the 10pt or 12pt class options to modify the font size a bit.1
Gotcha!
You should put \usefonttheme{professionalfonts} in the preamble if
you use LuaTeX or XeTeX. It appears that Beamer does not always recognize
that Latin Modern is in use with these compilers. If the font theme is
not changed, Beamer might produce bad kerning for some specific letter
combinations.
For basic title design, you can use the usual \title, \author, and \date
commands. There is also an \institute command for specifying the author
institution, and a \titlegraphic command that can be used for a logo etc.
Thus a basic presentation with just a title page is set with:
1
There are also some more choices, but they make the text either very large of very
unreadable.
166
\title{My fantastic presentation}
\author{Firstname Lastname}
\institute{University of Puuhamaa}
\titlegraphic{\includegraphics[width=3cm]{TheDogs.jpg}}
\date{20 May 2024}
\begin{document}
\maketitle
\end{document}
My fantastic presentation
Firstname Lastname
University of Puuhamaa
20 May 2024
\begin{frame}
\frametitle{Hi there!}
Welcome to my presentation!
167
Hi there!
Welcome to my presentation!
We will talk about Pythagoras and his theorem.
Note that the paragraphs have no visual separation whatsoever. You can
of course set \parskip to a better value (I suggest a larger value than for
printed documents, like 1 em), but Beamer presentations are often composed
of blocks. The block environment has a title and content:
\begin{frame}
\frametitle{Hi there!}
Welcome to my presentation!
\begin{block}{Goal}
You will learn about Pythagoras and his theorem.
\end{block}
\end{frame}
Hi there!
Welcome to my presentation!
Goal
You will learn about Pythagoras and his theorem.
In this example the block is not very highlighted, but that can be changed
with a suitable colour theme. We’ll get to that in Section 9.5.
By default, Beamer creates a few common theorem environments. More
can be created with the usual amsthm commands (see Section 4.6).
168
\begin{frame}
\frametitle{The theorem}
\begin{theorem}
If $a$ and $b$ are the lengths of catheti of a right-angled triangle,
then the hypothenuse has length $\sqrt{a^2 + b^2}$.
\end{theorem}
\begin{proof}
We'll get to this soon.
\end{proof}
\end{frame}
The theorem
Theorem
If a and b are the lengths of √
catheti of a right-angled triangle, then
the hypothenuse has length a2 + b2 .
Proof.
We’ll get to this soon.
169
\begin{columns}
\begin{column}{0.5\textwidth}
Properties of \alert{Pythagoras}:
\begin{enumerate}[1.]
\item From Ancient Greece ...
\end{enumerate}
\end{column}
\begin{column}{0.5\textwidth}
Properties of \alert{the theorem}:
\begin{enumerate}[i)]
\item Not invented by Pythagoras ...
\end{enumerate}
\end{column}
\end{columns}
Gotcha!
Frames do not really support the verbatim environment; the listings package
is probably visually nicer anyways.
170
\begin{figure}
\begin{tikzpicture}
\draw (0,0) -- (0,2) node[pos=0.5, left] {$a$}
-- (3,0) node[pos=0.5, right] {$c$}
-- cycle node[pos=0.5, below] {$b$};
\end{tikzpicture}
\caption{A right triangle.}
\end{figure}
\begin{figure}
\includegraphics[width=3cm]{TheDogs.jpg}
\caption{Slide hijacked by a dog!}
\end{figure}
Some pictures
a c
Gotcha!
As with article classes, figures are not placed side by side. The subcaption
package is again useful for that; see Section 7.2.1. Moreover, there is no
automatic page breaking: if you put too much stuff on a slide, they will
overflow.
If you need to position graphics absolutely, you can use the absolute
positioning system of TikZ (Section 8.1.3). For instance, the following code
could be used as the basis of a slide header:
\begin{tikzpicture}[remember picture,overlay]
\node[yshift=0.15\paperheight] at (current page.center){%
\includegraphics[width=\paperwidth]{slideheader.jpg}};
\end{tikzpicture}
171
This assumes the picture to be wide but narrow. The code needs to be
compiled twice before anything is visible.
Warning
You can find code examples and Beamer documentation about embedding
video files inside a presentation. This is a great way to make a presentation
work only on a specific Acrobat Reader version and only on your current
computer. It is 99 % guaranteed not to work at a conference venue.
As annoying as it is to switch between programs to show videos, it is the
only reliable option.
\begin{frame}
\frametitle{A digression on numbers}
\begin{theorem}
Every natural number has a successor.
\end{theorem}
\pause
\begin{theorem}
There is at least one natural number.
\end{theorem}
\pause
\begin{corollary}
There are infinitely many natural numbers.
\end{corollary}
\end{frame}
172
A digression on numbers A digression on numbers A digression on numbers
Theorem Theorem
There is at least one natural number. There is at least one natural number.
Corollary
There are infinitely many natural numbers.
The \pause command can be used in many places: between blocks and
paragraphs and inside lists.
Gotcha!
The \pause command does not work inside amsmath environments.
\begin{frame}
\frametitle{A digression on numbers, version 2}
\begin{theorem}<1->
Every natural number has a successor.
\end{theorem}
\begin{theorem}<2->
There is at least one natural number.
\end{theorem}
\begin{corollary}<3->
There are infinitely many natural numbers.
\end{corollary}
\end{frame}
173
\begin{itemize}
\item<+-> This is shown starting from the first slide.
\item<+-> This is shown starting from the second slide.
\item<+-> This is shown starting from the third slide.
\end{itemize}
\begin{itemize}[<+->]
\item This is shown starting from the first slide.
\item This is shown starting from the second slide.
\item This is shown starting from the third slide.
\end{itemize}
\begin{frame}
\frametitle{On the infinitude of numbers}
\begin{corollary}
There are infinitely many natural numbers.
\end{corollary}
\begin{proof}
\uncover<2->{Suppose that $n$ is the largest natural number.}
\uncover<3->{But then its successor $n+1$ is an even larger natural number.}
\end{proof}
\end{frame}
174
\begin{frame}
\end{frame}
Bold on the first slide only. Bold on the first slide only.
Alerted on the second slide only. Alerted on the second slide only.
If necessary, you can combine uncover and alert specifications with syntax
like <1- | alert@2>, or the monstrous <+-|alert@+> (which alerts on the
same slide as where the item appears).
Good practices
The Beamer manual advises against gradually revealing lists, so making
them all visible from the start, but alerting each item in turn might be a
better option.
175
\begin{frame}<1-2>[label=surprise-dogs]
\end{frame}
\againframe<3>{surprise-dogs}
176
progress within the section – is displayed in the header. As usual, a shorter
section name can be passed in an optional argument.
The \sectionpage command can be used to set a “title page” for the
section. (The default theme used in this example does not set it very beau-
tifully.)
\sectionpage
Section 1
However, it might be more useful to create a frame that shows the new
section highlighted in the table of contents. This can be achieved with
\begin{frame}
\tableofcontents[currentsection]
\end{frame}
177
Good practices
Please think of your audience. Throwing seventeen references at them in the
last 20 seconds of your talk is beyond useless. Consider using e.g. footnotes
at the point of citation instead.
9.5 Styling it
Like the rest of LATEX, Beamer attempts to separate content and presenta-
tion. It does so via an extensive styling system. The appearance of presen-
tation is controlled with commands in the preamble.
First off, controlling the navigation symbols. There are several styles for
them, but I believe you only need one – the one where they are not shown:5
\beamertemplatenavigationsymbolsempty
Remark
As mentioned above, if you use LuaLaTeX or XeLaTeX, you should usually
also specify
\usefonttheme{professionalfonts}
dynamic The transparency effect depends on the number of slides until the
piece is uncovered. Use with extreme caution, might be distracting.
5
Have you ever seen anyone use them?
178
9.5.1 Themes
Beamer comes with a complex theming system for changing the appearance
of things. Essentially, you should only need to modify the preamble to
change how things look.
The overall appearance is determined by the presentation theme. It is
chosen with \usetheme in the preamble. The presentation theme, in turn,
consists of four parts, any of which can be changed independently:
Inner theme The appearance of frame contents (blocks, lists, etc.) Changed
with \useinnertheme.
Outer theme The appearance of frame border (footer, navigation bar etc.)
Changed with \useoutertheme.
Color theme The colours used for elements. Individual colours can be
further customized. Changed with \usecolortheme.
Font theme The fonts to be used for elements. Also these can be cus-
tomized individually. Changed with \usefonttheme.
It is thus possible to start from a presentation theme, and then change parts
of the style to suit your artistic tastes.
The built-in presentation themes are showcased in [6, Chapter 15], inner
and outer themes in [6, Chapter 16], and color and font themes in the
following chapters.
In this example, we use the Madrid presentation theme without any
further customization:6
\beamertemplatenavigationsymbolsempty
\usefonttheme{professionalfonts}
\usetheme{Madrid}
6
Except for using professionalfonts, since the file was compiled with XeLaTeX.
179
The theorem
Theorem
My fantastic presentation If a and b are the lengths√of catheti of a right-angled triangle, then the
hypothenuse has length a2 + b2 .
F. Lastname (U. Puuhamaa) My fantastic presentation 20 May 2024 1/2 F. Lastname (U. Puuhamaa) My fantastic presentation 20 May 2024 2/2
Then, let us modify the look a bit. We take the miniframes outer theme
into use; it displays the sections and progress within section in the header.
We also use its optional argument to simplify the footer. We then change
to the crane colour theme in order to induce a headache in our audience,
and use the default serif font:
\beamertemplatenavigationsymbolsempty
\usefonttheme{professionalfonts}
\usetheme{Madrid}
\useoutertheme[footline=authortitle]{miniframes}
\usecolortheme{crane}
\usefonttheme{serif}
The theorem
Theorem
My fantastic presentation If a and b are the lengths
√ of catheti of a right-angled triangle, then the
hypothenuse has length a2 + b2 .
9.5.2 Colours
Good practices
It is extra important to take care of colour contrast in presentations. Pro-
jectors have a far smaller colour range than computer displays, especially
if the room is bright. What might appear like two distinct colours on your
laptop might be indistinguishable when projected.
180
If the colour scheme provided by \usecolortheme is still not what you
want, it is possible to tweak the individual colours. This is done with
\setbeamercolor.
Beamer uses named colours for everything. For example, the block body
colour is used inside all block environments. Each colour also has two
components: foreground (fg) and background (bg). These can be set to any
values supported by xcolor.
For example, here we change the foreground colour of block titles, and
both the foreground and background colours of block bodies:
\setbeamercolor{block title}{fg=red}
\setbeamercolor{block body}{fg=white, bg=blue}
Section name
The theorem
Theorem
If a and b are the lengths
√ of catheti of a right-angled triangle, then the
hypothenuse has length a2 + b2 .
Proof.
We’ll get to this soon.
Some of these colours are also inherited from “parent colours”. Maybe the
most interesting of these is structure, which applies to all frame and block
headings, unless overridden by a child style. The colour of the “background
canvas” is determined by the bg colour of normal text.
You can find the full list of predefined colours in the Beamer documen-
tation for each element type. The source code of each Beamer colour theme
is also very readable, and can be used as a reference.7
9.5.3 Fonts
Good practices
Beamer uses a sans-serif font by default. This is a good choice since sans-
serif fonts are usually more readable in low resolution. However, a serif font
can be used to give a nice classic look.
7
Where your particular LATEX installation puts package sources might be complicated.
For Beamer, the source is also available on Github: github.com/josephwright/beamer.
181
Using italic for emphasis might be too subtle; prefer alerted and boldface
text in presentations.
As with colours, Beamer comes with a few built-in font themes accessible
with \usefonttheme. In addition to the professionalfonts mentioned
above (which just disables some internal features, and can be used together
with another font theme), there is the sans-serif default, its counterpart
serif, and a few others that modify headings only [6, Section 18.1].
The font size is controlled with the package options. Moreover, since
Beamer uses the default serif and sans-serif fonts, you can replace the fonts
with the methods described in Section 6.3.
If you really need to customize the font used for a particular element,
there is a system similar to the one used for colours. The \setbeamerfont
command takes the element name and a list of attributes to override. The
attributes are size, shape, series, and family, and their possible values
are the declarations listed in Section 2.2.
In this (now awfully ugly) example, we modify the frame title to be in
bold, sans-serif font:
\setbeamerfont{frametitle}{series=\bfseries, family=\sffamily}
Section name
The theorem
Theorem
If a and b are the lengths
√ of catheti of a right-angled triangle, then the
hypothenuse has length a2 + b2 .
Proof.
We’ll get to this soon.
9.5.4 Templates
Finally, the appearance of repeated elements like titles can be controlled by
templates. Since this goes deeper into the internals of Beamer, we only refer
to the documentation [6, Section 16.3].
182
9.6 Handouts
To produce handouts, pass the handout optional argument to the document
class. In this mode, the overlays are “flattened” so that everything is visible
at once.
If you still need to split a frame into multiple parts in the handout,
you can modify the overlay specification to also apply to handouts. The
following code shows its contents on the third slide in presentation mode,
and on the second slide in handout mode:
\only<3|handout:2>{...}
183
Chapter 10
There are several methods to creating posters with LATEX. To mention just
three of the many packages: tikzposter, beamerposter, and tcolorbox. All of
them suffer from the fact that posters are very visual, but TEX can really
only do boxes.
Here we discuss tikzposter since it is reasonably simple. However, the
package has not been actively maintained since 2014, and it appears to have
some bugs. The other packages use fairly similar principles.
\documentclass{tikzposter}
By default, the options a0paper, 25pt, and portrait are used. Paper
sizes A1 and A2 are also available, and the landscape option produces a
landscape page. The range of font sizes is limited to 12, 14, 17, 20, and
25 points. Of these, only the last one is suitable for A0 size.
Good practices
As with presentations, you should not have too much text. Use whitespace
and structure to guide the reader.
For one reason or other, the package adds a watermark to the lower-right
corner. It can be turned off with the monstrously long command
\tikzposterlatexaffectionproofoff
184
There are also some package options to control margins and default block
spacing; see the documentation for details.
The title is set with \maketitle as usual; you can set \title, \author,
and \institute in the preamble. You can also put graphical (or rather,
any) commands inside \titlegraphic. By default these elements are set
on top of each other. The customization is briefly discussed in Section 10.2.
The \maketitle command also accepts some optional arguments like
\maketitle[width=40cm]
As with Beamer, the basic layout consists of blocks. The \block com-
mand takes optional customization arguments, a title, and the contents:
The block will fill the available horizontal space, and the vertical size depends
on the contents. Contents can be any material (except floats). If the title is
empty, the “block header” disappears.
To set several blocks side by side, it is possible to use columns specified
inside a tikzpostercolumns environment. A new column is started with
the \column command. As its argument it takes the fraction of text area
width.1 Any blocks specified after this command will be placed vertically in
the column. For example, here we set two columns of equal size, and place
two blocks in the left column:
\begin{columns}
\column{0.5}
\block{Above left}{}
\block{Below left}{}
\column{0.5}
\block{Right}{}
\end{columns}
185
After the columns environment ends, all new blocks again fill the whole
horizontal space.
You cannot use the usual vertical spacing commands to adjust spacing
between blocks. A workaround is to add an offset both to the block title
and contents. Negative y values point downwards.2
\block[titleoffsety=-2cm, bodyoffsety=-2cm]{Title}{Contents}
Inside a block, you can use the \coloredbox command to create high-
lighted regions.
\block{Goal}
{
In this poster we discuss Pythagoras' theorem.
It is also possible to add small notes. They are defined outside blocks, but
they attach to the previous block. By default, they connect to the center of
the block, but the precise point can be adjusted with optional arguments,
as with the distance and angle (here east-southeast) to the anchor point:
Let us see how these pieces (and a few more content additions) play
together. The output of the following code is shown in Figure 10.1.
\documentclass[17pt,a2paper]{tikzposter}
\usepackage{graphicx}
\usepackage[svgnames]{xcolor}
\usepackage{fontawesome5}
\tikzposterlatexaffectionproofoff
\author{Firstname Lastname}
\title{My first poster}
2
It appears that this method might not work with blocks without title; this seems to
be a bug.
186
ē
My first poster
Firstname Lastname
University of Puuhamaa
I mean it!!!
where a, b are the catheti »
and c the hypothenuse of a
right triangle.
This poster will convince
you about it!
Below left
References
Some facts about Pythagoras:
Ancient Greek
A book I read once but forget its name
A bit weird
University of Puuhamaa anthem song
Did not invent the theorem
University of Puuhamaa assumes no responsibility for the scientific conduct or misconduct of its affiliates.
Figure 10.1: The example poster (set in A2 size, and scaled here).
187
\institute{University of Puuhamaa}
\titlegraphic{\Huge\faCoffee}
\begin{document}
\maketitle[width=40cm]
\begin{columns}
\block{Below left}
{
Some facts about Pythagoras:
\begin{itemize}
\item Ancient Greek
\item A bit weird
\item Did not invent the theorem
\end{itemize}
}
\subcolumn{0.6}
\block{Right}
{
Here's the theorem:
\[
a^2 + b^2 = c^2
\]
where $a$, $b$ are the catheti
and $c$ the hypothenuse of a right triangle.
}
\subcolumn{0.4}
\block[titleoffsety=-2cm, bodyoffsety=-2cm]{Right 2}
{\centering\Huge\faDizzy[regular]}
\end{subcolumns}
\block{References}
{
\begin{itemize}
188
\item A book I read once but forget its name
\item University of Puuhamaa anthem song
\end{itemize}
}
\end{columns}
\block{}
{
\centering
University of Puuhamaa assumes no responsibility
for the scientific conduct or misconduct of its affiliates.
}
\end{document}
10.2 Styling
The styling system of tikzposter is very similar to that of Beamer. There
are a few built-in styles.3
The overall look is controlled by \usetheme, and then e.g. the colour
and background styles can be customized. Individual colours can be changed
with \colorlet (unlike in Beamer, colours are not separated into foreground
and background colours).
For example, this code selects the theme in Figure 10.2:
189
the layout code for the title contents. The variables set by the \maketitle
companion commands can be used as below. The following code is also used
in Figure 10.2:
\settitle{
\makebox[8cm][c]{\@titlegraphic}
\parbox[b]{20cm}{
\color{titlefgcolor} {\bfseries \Huge \sc \@title \par}
\vspace*{1em}
{\huge \@author{} \Large (\@institute)}
}
}
190
My first poster
ē Firstname Lastname (University of Puuhamaa)
I mean it!!!
where a, b are the catheti »
and c the hypothenuse of a
right triangle.
This poster will convince
you about it!
Below left
References
Some facts about Pythagoras:
Ancient Greek
A book I read once but forget its name
A bit weird
University of Puuhamaa anthem song
Did not invent the theorem
University of Puuhamaa assumes no responsibility for the scientific conduct or misconduct of its affiliates.
191
Index
\-, 59 backslash
in text, 36
\Aboxed, 97 baseline, 55
\addbibresource, 112 .bbl file, 9
\addcontentsline, 113 arXiv, 106
addlines package, 71 beamerposter package, 184
\addtocounter, 30 \bf (do not use), 7
\againframe, 176 \bfseries, 38
\alert, 169, 174 .bib file, 10, 106
align environment, 79, 83 biber program, 10, 112
aligned environment, 81 \bibitem, 105
\allowdisplaybreaks, 79 biblatex package, 10
amsart package, 26 biblatex2bibitem package, 113
amsfonts package, 85, 86 \bibliography, 109
amsmath package, 27, 75, 76, 82, 84, bibliography environment, 105
92, 93, 96–98 produced by BibTeX, 113
colon, 89 \bibliographystyle, 109, 111
with Beamer, 173 bibtex program, 10, 106
with lineno, 115 arXiv, 106
amssymb package, 87, 88 embedding, 113
amsthm package, 98, 100, 101 Unicode, 107
Beamer, 166, 168 with BibLaTeX, 112
with cleveref, 103 bigfoot package, 46
\ang, 87 \bigskip, 65
\appendix, 49 \binom, 93
Beamer, 177 \block
array package, 143, 144 tikzposter, 185
arrows block environment, 168, 181
mathematics, 97 bm package, 84
\author, 166, 185 \boldsymbol, 84
.aux file, 8 \boxed, 97
boxes, 54
babel package, 60, 61
paragraph, 57
TikZ compatibility, 164
braket package, 87
\backmatter, 49
192
calc package, 66 \complexnum, 86
\caption, 137 \complexqty, 87
cases package, 81 \coordinate, 151
cases environment, 80 counters, 29
cellspace package, 144 defining, 30
\centering, 137 displaying, 30
\cfrac, 93 format in lists, 47
\chapter, 25 list, 47
\chaptermark, 72 \counterwithin, 31, 32, 76
\chaptertitlename, 51 \counterwithout, 32
\choose (do not use), 93 \cpageref, 104
\cite, 17, 105 \cref, 103
\citeauthor, 111 \crefname, 104
\citep, 111, 112 custom-bib program, 111
\citet, 111
\citeyear, 111 \date, 166
\cleardoublepage, 70 \DeclareCommandCopy, 19
\clearpage, 70 \DeclareMathOperator, 92
cleveref package, 103, 104 \def (do not use), 14
should be loaded last, 104 \definecolor, 44
\colon \DefineVerbatimEnvironment, 42
spacing, 89 \depth, 57
color package (do not use), 27, 43 description environment, 46
\color, 43 Detexify, 88
in table, 146 \dfrac, 95
color diagbox package, 146
blending, 44 diffcoeff package, 91
\coloredbox \dimeval, 66
tikzposter, 186 \displaybreak, 79
\colorlet \displaystyle, 94
tikzposter, 189 document environment, 25
colortbl package, 145 document classes, 25
\column \DocumentMetadata, 25, 121
tikzposter, 185 \dotfill, 64
column environment \dots, 96
Beamer, 169 dots per inch
\columncolor, 146 see DPI 134
columns environment, 186 DPI, 134
Beamer, 169 \draw, 150
commands dsfont package, 85
fragile, 34 dx, 91
robust, 34
\em, 39
comment
emoji package, 129, 130
large block, 41
193
\emph, 39 fontspec package, 119, 126
underline, 39 emoji, 130
empheq package, 97 footmisc package, 46
\enlargethispage, 71 \footnote, 45
enotez package, 46 in tables, 147
\enspace, 63 \footnotemark, 46
\ensuremath, 14, 22 \footnotesize, 40
enumerate package, 169 \footnotetext, 46
enumerate environment, 46 \footrulewidth, 74
shorthand styles, 169 \foreach, 33, 160, 161
enumitem package, 47 \frac, 93
environments, 19 fragility, 34
\epsilon, 18 frame environment, 167
eqnarray environment (do not use), \framebox, 56
79 \frametitle, 167
\eqref, 102 \frontmatter, 49
equation environment, 76 \frquote, 61
errors, 22 ftnright package, 46
194
fragility, 34 \listoftables, 113
\include, 10–12 lists
\includegraphics, 131 custom, 48
alt text, 135 standard, 46
in TikZ, 153 styling, 47
\includeonly, 11 .lof file, 9
\includepdf, 117 .log file, 9
\index, 114 longtable package, 147
\input, 10, 11 .lot file, 9
inputenc package, 24 lstlisting environment, 40, 41
\institute, 166, 185 luatex program, 119, 121
\intertext, 83
interval package, 90 macros, 12
\inteval, 66 \mainmatter, 49
\isodd, 33 \makebox, 56
\it (do not use), 7 makeindex program, 9, 114
italic correction, 38 \makeindex, 114
\item, 17, 46 \maketitle, 24, 25, 73, 167
itemize environment, 46 tikzposter, 185
\itshape, 38 \MakeUppercase, 13
manyfoot package, 46
koma-script package, 26 \markboth, 71
customizing headings, 50 \markright, 71
marks, 71
\label, 8, 102 \mathbb, 85
figures, 137 \mathbf, 84
shown in margin, 103 \mathbin, 89
subfigures, 139 \mathcal, 84
landscape environment, 69 \mathclose, 89
\large, 40 \mathcolor, 97
\Large, 16, 40 \mathds, 85
\LARGE, 40 \mathfrak, 85
lastpage package, 72 \mathop, 89
latexdiff program, 38, 115, 116 \mathopen, 89
problems, 116 \mathord, 78, 89
\left, 81, 94 \mathpunct, 89
\leftmark, 72 \mathrel, 77, 89
\lengthtest, 33 \mathrm, 84
\let (do not use), 14 \mathsf, 84
ligatures, 36 mathtools package, 75, 87, 92, 96, 97
lineno package, 115 \mbox, 55, 59
\linenumbers, 115 \medskip, 65
listings package, 40, 41, 140, 170 memoir package, 26
\listoffigures, 113, 137 customizing headings, 50
195
microtype package, 129 overlay specification, 173
\mid handout, 183
spacing, 89 \overset, 95
\middle, 94 \overunderset, 95
minipage environment, 57, 65, 147
footnotes, 46 packages
mktexmf program, 126 finding, 27
\modulolinenumbers, 115 loading order, 27
\mspace, 88 page styles, 71
\multicolumn, 145 \pagebreak, 70
multline environment, 76 \pagenumbering, 72
\pageref, 102
natbib package, 108, 109, 111 \pageref*, 72
do not use with BibLaTeX, 112 \pagestyle, 71
needspace package, 70 \par, 20, 42
\newcommand, 12, 13, 18 \parindent, 70
scope, 16 \parskip, 70
\newcounter, 30, 31 Beamer, 168
\newenvironment, 19 \part
\newfloat, 139 Beamer, 177
\newfontfamily, 127 \pause, 172, 173
\newgeometry, 69 pdflscape package, 69, 70, 118
\newlength, 66 pdfpages package, 117
\newtheorem, 98, 99 pdftex program, 118, 119, 121
\newtheorem*, 99 pgf package, 149
\nocite, 109 pgffor package, 33, 160, 161
\node, 151, 152 pgfplots package, 149
\noindent, 43, 70 \phantom, 58, 77
\nolinenumbers, 115 pictures, 131
\normalsize, 40 alt text, 135
\notag, 78, 79 file type, 133
ntheorem package, 9, 28, 101 preamble, 24
production notes, 200 \printbibliography, 112
with cleveref, 103 \printindex, 114
\num, 86 proof environment, 100
\numberwithin, 76 \protect, 34
196
\ref, 102 \sideset, 95
\renewcommand, 18 sidewaysfigure environment, 141
\renewenvironment, 20 sidewaystable environment, 141
\RequirePackage, 28 siunitx package, 86, 87, 144
\right, 81, 94 \small, 40
\rightmark., 72 \smallskip, 65
\rmfamily, 38 \sout, 39
robustness, 34 split environment, 77–79
rotating package, 141 \sqrt, 17
rotfloat package, 141 \stepcounter, 30
\rowcolor, 146 stmaryrd package, 87, 88
\rule, 58 strectch, 63
\stretch, 64
scope environment, 159 strike-out text, 39
scope, 15 strut, 58
counters, 32 subcaption package, 138, 171
\scriptsize, 40 \subcaptionbox, 139
\scshape, 38 \subcolumn
\section, 7, 25, 34 tikzposter, 185
Beamer, 176 subcolumns environment
\section*, 113 tikzposter, 185
\sectionmark, 72 subequations environment, 79
\sectionpage, 177 subfig package (do not use), 138
\see, 114 subfigure package (do not use), 138
\selectfont, 128 \subref, 139
\selectlanguage, 61 \substack, 92
\setbeamercolor, 181 supertabular package, 147
\setbeamercovered, 178 \swapnumbers, 99
\setbeamerfont, 182 symbol classes, 88
\setcounter, 30 symbols
\setlength, 66 finding, 88
\setlist, 47 .synctex.gz file, 9
\setmainfont, 126
\setmathfont, 127 table environment, 139, 142
\setmonofont, 126 Beamer, 170
\setsansfont, 126 \tableofcontents, 113
\settitle tabular environment, 141
tikzposter, 189 \tag, 76, 78, 79
\settodepth, 67 tcolorbox package, 184
\settoheight, 67 \texorpdfstring, 49
\settowidth, 67 \text, 82
\sffamily, 38 \textbf, 38
showframe package, 67 \textcolor, 43
showkeys package, 103 \textheight, 69
197
\textit, 38 \underset, 95
\textrm, 38 unicode-math package, 86, 121, 127
\textsc, 38 \unit, 87
\textsf, 38 upmendex program, 114
\textstyle, 94 \useasboundingbox, 159
\texttt, 38 \usecolortheme, 179, 181
\textwidth, 65, 69 \usefonttheme, 179, 182
\tfrac, 95 \useinnertheme, 179
\the, 31, 65 \useoutertheme, 179
\theoremstyle, 99 \usepackage, 18, 28
\thispagestyle, 71 \usetheme, 179
.thm file, 9 tikzposter, 189
thmtools package, 101 \usetikzlibrary, 149, 163
threeparttable package, 147
tikz package, 43, 149 \varepsilon, 18
\tikz, 150 \vbox (do not use), 55
TikZ \verb
accessibility, 122 as argument, 42
tikz-cd package, 163, 164 verbatim environment, 41
tikzpicture environment, 150 Beamer, 170
tikzposter package, 184 Verbatim environment, 41, 42
styling, 189 VerbatimOut environment, 200
tikzposter environment, 185 \vfill, 64
\tikzset, 162 \vspace, 64
\tiny, 16, 40 \vspace*, 65
\title, 166, 185
warnings, 21
\titleformat, 50
\whiledo, 33
\titleformat*, 50
\width, 56
\titlegraphic, 166, 185
\wordsep, 51
\titlepage, 167
titlepage environment, 71, 73 xcolor package, 43, 97, 181
titlesec package, 50 with TikZ, 153
\titlespacing, 52 xetex program, 119, 121
.toc file, 9
tocbibind package, 113
\today, 61
\totalheight, 57
\ttfamily, 38
ulem package, 39
\uline, 39
\uncover, 173–175
\underbrace, 96
underfull, 59
198
Bibliography
[1] Philip Kime, Moritz Wemheuer, and Philipp Lehman. The biblatex
package. Version 3.20. 2024. url: https://ctan.org/pkg/biblatex
(cit. on pp. 111, 112).
[2] Donald Knuth. The TEXbook. Sixth printing. Addison-Wesley, 1986 (cit.
on p. 54).
[3] Leslie Lamport. LATEX, a document preparation system. User’s guide
and reference manual. Second edition. Addison-Wesley, 1994 (cit. on
p. 106).
[4] Frank Mittelbach and Ulrike Fischer. The LATEX Companion. Third edi-
tion. Tools and Techniques for Computer Typesetting. Addison-Wesley,
2023 (cit. on pp. 5, 17, 60, 101, 105, 135, 148).
[5] Till Tantau. The TikZ and pgf packages. Version 3.1.10. 2023. url:
https://ctan.org/pkg/pgf (cit. on pp. 105, 151, 154–156, 158, 159,
163).
[6] Till Tantau, Joseph Wright, and Vedran Miletić. The beamer class.
Version 3.71. 2024. url: https : / / ctan . org / pkg / beamer (cit. on
pp. 179, 182).
199
Colophon
These notes are set in Latin Modern, an updated version of Donald Knuth’s
Computer Modern typeface. The typeface is a Didone design, meaning a
high contrast between thin and thick lines. Knuth designed it after mathe-
matics textbooks set in metal type. I am personally not that fond of Com-
puter Modern, especially when reading on computer screen. I still kept it
so that the notes are honest to LATEX’s default behaviour.
As you can see from the source code, there is nothing too special in these
notes. The highlighted Gotcha! blocks are created with ntheorem and a bit
of customization command magic. There are also a few custom commands
for setting/indexing commands and packages.
The largest programming trick was the examples. Code for the examples
appears in the .tex code inside a VerbatimOut environment. The code is
stored into a temporary file, and then read twice: once to show the code,
and a second time to evaluate the output.
Due to this design, the examples are guaranteed to really work. However,
a few examples include a few lines of secret extra code. This code mainly
hides the fact that the examples live inside a minipage, and restores some
customizations to LATEX defaults.
There are just a couple sleight-of-hand tricks: as mentioned above, these
notes use ntheorem internally, but Section 4.6 talks about amsthm. The two
packages cannot be loaded simultaneously. Moreover, they have similar-
looking but very incompatible syntax: whereas amsthm changes the end-of-
proof symbol by renewing \qedsymbol, ntheorem expects the user to call
\qedsymbol with the desired symbol.
Renewing the ntheorem \qedsymbol command as in the example on
page 100 causes massive havoc, so there is sneaky code to re-define it back
just before the proof environment ends. If you are interested in low-level
LATEX programming, hooks are the next topic to learn.
200