Lshort
Lshort
Introduction to LATEX
Or LATEX in 280 minutes
The illustration on the first page was created for this booklet by Roman Schmid
(@bummzack on GitHub). It is dedicated to the public domain via CC0 1.0
Universal Public Domain Dedication. This means that you can use it freely in
your own work without any licensing issues. See https://creativecommons.
org/publicdomain/zero/1.0/ for more details.
Additionally, the code examples (text written using monospace font in this
document) are dedicated to the public domain via CC0 1.0 Universal Pub-
lic Domain Dedication. This means that you can use them freely in your
own work without any licensing issues. See https://creativecommons.org/
publicdomain/zero/1.0/ for more details.
The full text of the GNU General Public License can be found in Appendix C
on page 237.
Thank you!
LATEX is available for most computers, from the PC and Mac, to large
UNIX and VMS systems. On many university computer clusters, you
will find that a LATEX installation is available, ready to use. Information
on how to access the local LATEX installation should be provided in the
Local Guide [1]. If you have problems getting started, ask the person
who gave you this booklet. The scope of this document is not to tell you
how to install and set up a LATEX system, but to teach you how to write
your documents so that they can be processed by LATEX.
If you need to get hold of any LATEX related material, have a look at
one of the Comprehensive TEX Archive Network (CTAN) sites. The
homepage is at http://www.ctan.org.
You will find other references to CTAN throughout the book, espe-
cially pointers to software and documents you might want to download.
Instead of writing down complete URLs, I just wrote CTAN: followed by
whatever location within the CTAN tree you should go to.
If you want to run LATEX on your own computer, take a look at what
is available from CTAN://systems.
OETIKER+PARTNER AG
Aarweg 15
4600 Olten
Switzerland
Thank you! i
Preface iii
1 LATEX Basics 1
1.1 A Bit of History . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1 TEX . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.2 Other TEX engines . . . . . . . . . . . . . . . . . . 2
1.1.3 LATEX . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Author, Book Designer, and Typesetter . . . . . . 3
1.2.2 Layout Design . . . . . . . . . . . . . . . . . . . . 4
1.2.3 Advantages and Disadvantages . . . . . . . . . . . 4
1.3 LATEX Input Files . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.1 Spaces . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.2 Comments . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.3 Special Characters . . . . . . . . . . . . . . . . . . 6
1.3.4 LATEX Commands . . . . . . . . . . . . . . . . . . . 7
1.3.5 Groups . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.6 Optional parameters . . . . . . . . . . . . . . . . . 8
1.4 Input File Structure . . . . . . . . . . . . . . . . . . . . . 8
1.5 A Typical Command Line Session . . . . . . . . . . . . . 9
1.6 Logical Structure of Your Document . . . . . . . . . . . . 11
1.6.1 A Neverending Story of Problems with WYSIWYG
Editors . . . . . . . . . . . . . . . . . . . . . . . . 11
1.6.2 Your First Text Command . . . . . . . . . . . . . 12
1.6.3 Your First Environment . . . . . . . . . . . . . . . 13
1.6.4 Summary . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8 The Structure of Text and Language . . . . . . . . . . . . 14
1.9 Files You Might Encounter . . . . . . . . . . . . . . . . . 17
vi CONTENTS
4 Bibliographies 125
4.1 thebibliography environment . . . . . . . . . . . . . . . 125
4.2 biblatex with biber . . . . . . . . . . . . . . . . . . . . . . 126
4.2.1 Database files . . . . . . . . . . . . . . . . . . . . . 127
4.2.2 Using biblatex . . . . . . . . . . . . . . . . . . . . . 127
4.2.3 Controlling the bibliography . . . . . . . . . . . . . 129
4.2.4 Citing commands . . . . . . . . . . . . . . . . . . . 133
4.2.5 More about entries . . . . . . . . . . . . . . . . . . 135
viii CONTENTS
5 Specialities 137
5.1 Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5.2 Installing Extra Packages . . . . . . . . . . . . . . . . . . 139
5.3 LATEX and PDF . . . . . . . . . . . . . . . . . . . . . . . . 140
5.3.1 Hypertext Links . . . . . . . . . . . . . . . . . . . 140
5.3.2 Document Metadata . . . . . . . . . . . . . . . . . 143
5.3.3 Problems with Outline . . . . . . . . . . . . . . . . 144
5.4 Creating Presentations . . . . . . . . . . . . . . . . . . . . 145
5.4.1 Basic Usage . . . . . . . . . . . . . . . . . . . . . . 145
5.4.2 Overlay Specification . . . . . . . . . . . . . . . . . 148
5.4.3 Customisation . . . . . . . . . . . . . . . . . . . . 150
5.4.4 Handouts . . . . . . . . . . . . . . . . . . . . . . . 153
Bibliography 253
Index 259
List of Figures
List of Tables
LATEX Basics
The first part of this chapter presents a short overview of the philosophy and
history of LATEX. The second part focuses on the basic structures of a LATEX
document. After reading this chapter, you should have a rough knowledge
of how LATEX works, which you will need to understand the rest of this book.
where X is the letter “ch” or “chi”. TEX is also the first syllable of the
Greek word technique. In an ASCII environment, TEX becomes TeX.
1.1.3 LATEX
LATEX is a set of macros3 for the TEX engine. LATEX was originally
developed by Leslie Lamport for his own use. After some consideration,
he decided to make them more general so that others could use them for
their own projects. Thus, in 1985, the first version of LATEX — named
LATEX 2.09 — was released [42].
The original LATEX became quite popular and promoted the creation
of many extension packages. Unfortunately, some of the more popular
extensions were not compatible with each other. LATEX 2𝜀 managed to
unify many of the extensions, and also provided an extension packaging
system, dealing with third party extensions in a standardised way.
proper pronunciation is heard in Greece, where you have the harsher ch of ach and
Loch.” ([38])
2
The original TEX will not work at all, because LATEX requires an 𝜀-TEX-enabled
engine since 2017 [56].
3
Macros are short names for long lists of instructions, which are created to avoid
retyping the instructions each time they are needed.
1.2 Basics 3
The same year LATEX 2𝜀 was released, the LATEX3 project was started.
Its aim was to create improved standards for writing LATEX documents,
fixing some of the mistakes that were made when defining the initial
LATEX macros. While at the beginning, it was planned to release LATEX3
as a standalone system that was not backward compatible with LATEX 2𝜀 ,
in the end, the consensus was that abandoning the huge collection of
third party packages written for LATEX 2𝜀 , would be a mistake. Thus, the
development team decided that LATEX3 would be slowly backported into
LATEX 2𝜀 format, while avoiding breaking changes as much as reasonably
possible [47].
LATEX is pronounced “Lay-tech” or “Lah-tech.” If you refer to LATEX
in an ASCII environment, you type LaTeX. LATEX 2𝜀 is pronounced “Lay-
tech two e” and typed LaTeX2e. LATEX3 is pronounced “Lay-tech three”
and typed LaTeX3.
1.2 Basics
1.2.1 Author, Book Designer, and Typesetter
To publish something, authors give their typed manuscript to a publishing
company. One of their book designers then decides the layout of the
document (column width, fonts, space before and after headings, …). The
book designer writes his instructions into the manuscript and then gives
it to a typesetter, who typesets the book according to these instructions.
A human book designer tries to find out what the author had in mind
while writing the manuscript. He decides on chapter headings, citations,
examples, formulae, etc., based on his professional knowledge and from
the contents of the manuscript.
In a LATEX environment, LATEX takes the role of the book designer and
uses TEX as its typesetter. But LATEX is “only” a program and therefore
needs more guidance. The author has to provide additional information
to describe the logical structure of his work. This information is written
into the text as “LATEX commands.”
This is quite different from the WYSIWYG4 approach that most
modern word processors, such as MS Word or LibreOffice, take. With
these applications, authors specify the document layout interactively
while typing text into the computer. They can see on the screen how the
final work will look when it is printed.
When using LATEX, it is not normally possible to see the final output
while typing the text, but the final output can be previewed on the screen
after processing the file with LATEX. Corrections can then be made before
actually sending the document to the printer.
4
What You See Is What You Get.
4 LATEX Basics
LATEX also has some disadvantages, and I guess it’s a bit difficult for me
to find any sensible ones, though I am sure other people can tell you
hundreds ;-).
• LATEX does not work well for people who have sold their souls …
1.3.1 Spaces
“Whitespace” characters, such as blank or tab, are treated uniformly as
“space” by LATEX. Several consecutive whitespace characters are treated
as one “space”. Whitespace at the start of a line is generally ignored,
and a single line break has the same effect as “whitespace”.
An empty line between two lines of text defines the end of a paragraph.
Multiple empty lines are treated the same as one empty line. The text
below is an example. On the left-hand side is the text from the input
5
Some examples of these are listed in Appendix A.
6 LATEX Basics
It does not matter whether you It does not matter whether you
enter one or many spaces enter one or many spaces after a
after a word.
word.
An empty line starts a new An empty line starts a new para-
paragraph. graph.
1.3.2 Comments
When LATEX encounters a % character while processing an input file, it
ignores the rest of the present line, the line break, and all whitespace at
the beginning of the next line.
This can be used to write notes into the input file, which will not
show up in the printed version.
This is an % stupid
% Better: instructive <----
This is an example: Supercalifrag-
example: Supercal%
ifragilist% ilisticexpialidocious
icexpialidocious
The % character can also be used to split long input lines where no
whitespace or line breaks are allowed.
# $ % ^ & _ { } ~ \
As you will see, these characters can be used in your documents all
the same by using a prefix backslash:
Many more other symbols and many more can be printed with special
commands in mathematical formulae or as accents. The backslash
character \ can not be entered by adding another backslash in front of it
(\\); this sequence is used for line breaking. Use the \textbackslash
command instead.
1.3 LATEX Input Files 7
1.3.5 Groups
Many commands act on parameters. Parameters are the first things
the command encounters after its name ends in the source file. If the
command name consists of letters, then it ignores following spaces. For
example, if command ‘foo’ accepts two arguments, then
\foo bar
will be read as command ‘foo’ with first argument ‘b’ and second argument
‘a’ followed by the letter ‘r’. In order to pass more than one letter as a
parameter, groups are used.
Groups are delimited by { and }. They tell LATEX to treat the content
between them as a single unit. For example,
\foo{bar}{baz}qux
will be interpreted as command ‘foo’ with first argument ‘bar’ and second
argument ‘baz’ followed by text ‘qux’. Always using groups when passing
parameters makes the source code easier to read.
Commands that do not take any parameters still ignore any spaces
after them. The easiest way to stop this behaviour, is to follow them by
an empty group.
New \TeX users may miss New TEXusers may miss the
the whitespace whitespace after a command.
after a command. % renders wrong
Experienced \TeX{} users are
Experienced TEX users are
\TeX nicians, and know how to use TEXnicians, and know how to
whitespace. % renders correct use whitespace.
8 LATEX Basics
Class Description
article for articles in scientific journals, short reports,
and any other short document.
proc a class for proceedings based on the article class.
report for longer reports. containing several chapters,
small books, PhD theses, …
book for real books.
beamer for presentations.
letter for letters.
1.5 A Typical Command Line Session 9
\end{document}
command, which tells LATEX to call it a day. Anything that follows this
command will be ignored by LATEX.
Listing 1.1 shows the contents of a minimal LATEX file. A slightly
more complicated input file is given in Listing 1.2.
1. Edit/Create your LATEX input file. This file must be plain text.
On Unix-like systems, most of the editors will create just that. On
Windows, you might want to make sure that you save the file in
Plain Text format. When picking a name for your file, make sure
it bears the extension .tex.
xelatex foo.tex
or
lualatex foo.tex
Small is beauti-
ful.
\documentclass{article}
\begin{document}
Small is beautiful.
\end{document}
\documentclass[a4paper,11pt]{article}
\author{H.~Partl}
Minimalism
\title{Minimalism}
H. Partl
\maketitle
\tableofcontents Contents
1 Some Interesting Words 1
1
\end{document}
Listing 1.2: Example of a realistic journal article. Note that all the
commands you see in this example will be explained later.
1.6 Logical Structure of Your Document 11
red and that one in cursive. Thus, changing it to a different style means
going over everything again, and manually changing the style of each
and every paragraph and word.
Wouldn’t it be nice if you could somehow communicate to your editor
“these paragraphs are happening in dimension A”, and then simply decide
that all such paragraphs are green or use a different font? This is exactly
what logical markup does.
\emph{〈text〉}
It stands for “emphasise” and does just that: it emphasises the 〈text〉 it
received as a parameter.
Are you gonna eat \emph{that}? Are you gonna eat that?
If you write the code on the left in the body of your document (you can
use Listing 1.1 as a template), you will get the output on the right in
the PDF file you produce.
As you can see, LATEX typesets the emphasised text in cursive font
by default. It is important to understand that the \emph command does
not mean “write this text in cursive”. It is much smarter than that. To
illustrate this, let’s see how \emph behaves when used inside text that is
already in cursive
Are you gonna eat \emph{that}? Are you gonna eat that?
As you can see, in this case it changed the font back to upright.
Remember that you should only use the \emph command to emphasise
text and nothing else, even if the resulting output would be the same
(for example cursive font). If you stick to this rule, then if you later
decide to use a different form of emphasis, you can simply change the
definition of the \emph command and other things that just happened to
be in cursive will be unaffected.
Are you gonna eat \emph{that}? Are you gonna eat that?
1.7 Packages 13
\begin{em}
This paragraph is emphasised.
This paragraph is emphasised.
This one is \emph{too}. This one is too.
\end{em}
1.6.4 Summary
Using logical markup, we can embed the logical structure of our document
inside the document itself. Instead of saying “write this in green and
write this word in cursive”, we say “this text happens in dimension A
and this word is emphasised”. The style of all text in ‘dimension A’, or
of emphasised words, can be decided later and easily changed.
If you started writing your hypothetical novel using LATEX instead
of a WYSIWYG editor, and used custom environments for typesetting
events in different dimensions, and \emph for emphasis, then changing it
to a black and white version would come down to simply changing the
definition of the custom environments.
Before learning how to define your own commands and environments,
this book will introduce you to many of the standard ones that are
provided either by LATEX itself or third-party packages.
1.7 Packages
While writing your document, you will probably find that there are
some areas where basic LATEX cannot solve your problem. If you want
6
It is not useful because there is very little reason to emphasise more than one
paragraph. In order to make the emphasis effective, it should be used with restraint.
After all, if everything is emphasised then nothing is.
14 LATEX Basics
\usepackage[〈options〉]{〈package〉}
Package Description
amsmath [55] Provides additional commands for typesetting mathe-
matical symbols, and environments for aligning equa-
tions. Described in Chapter 3.
polyglossia [15] Makes it easy to write LATEX documents in languages
other than English, or even in multiple languages. De-
scribed in Section 2.8.
booktabs [17] Provides commands for producing beautifully format-
ted tables for your document. Described in Sec-
tion 2.18.
biblatex [44] Provides commands for automatically specifying and
producing a bibliography for your document. De-
scribed in Chapter 4.
makeidx [76] Provides commands for producing indexes. Described
in Section 5.1.
fancyhdr [50] Lets you easily customise page headers and footers.
Described in Section 7.7.
beamer [74] Provides a document class that changes output to pro-
duce presentations and provides command to typeset
slides. Described in Section 5.4.
16 LATEX Basics
% Example 1
…when Einstein intro-
\ldots when Einstein introduced
duced his formula
his formula
\begin{equation} e = m · c2 , (1)
e = m \cdot c^2 \; ,
\end{equation} which is at the same time the
which is at the same time the most widely known and the
most widely known and the least least well understood physi-
well understood physical formula. cal formula.
1
% Example 2
…from which follows
\ldots from which follows
Kirchhoff’s current law:
Kirchhoff's current law:
\begin{equation} n
(1)
X
\sum_{k=1}^{n} I_k = 0 \; . Ik = 0 .
\end{equation} k=1
1
% Example 3
…which has several ad-
\ldots which has several
vantages.
advantages.
\begin{equation} ID = IF − IR (1)
I_D = I_F - I_R
\end{equation} is the core of a very different
is the core of a very different transistor model. …
transistor model. \ldots
1
1.9 Files You Might Encounter 17
The next smaller text unit is the sentence. In English texts, there
is a larger space after a period that ends a sentence than after one that
ends an abbreviation. LATEX tries to figure out which one you wanted to
have. If LATEX gets it wrong, you must tell it what you want. This is
explained later in the next chapter.
The structuring of text even extends to parts of sentences. Most lan-
guages have very complicated punctuation rules, but in many languages
(including German and English), you will get almost every comma right
if you remember what it represents: a short stop in the flow of language.
If you are not sure about where to put a comma, read the sentence aloud
and take a short breath at every comma. If this feels awkward at some
place, delete that comma; if you feel the urge to breathe (or make a short
stop) at some other place, insert a comma.
Finally, the paragraphs of a text should also be structured logically
at a higher level, by putting them into chapters, sections, subsections,
and so on.
.sty LATEX Macro package. Load this into your LATEX document using
the \usepackage command.
.dtx Documented TEX. This is the main distribution format for LATEX
style files. If you process a .dtx file you get documented macro
code of the LATEX package contained in the .dtx file.
.ins The installer for the files contained in the matching .dtx file. If
you download a LATEX package from the net, you will normally get
a .dtx and a .ins file. Run LATEX on the .ins file to unpack the
.dtx file.
.cls Class files define what your document looks like. They are selected
with the \documentclass command.
The following files are generated when you run LATEX on your input
file:
.log Gives a detailed account of what happened during the last compiler
run.
.toc Stores all your section headers. It gets read in for the next compiler
run and is used to produce the table of contents.
.aux Another file that transports information from one compiler run
to the next. Among other things, the .aux file is used to store
information associated with cross-references.
.idx If your document contains an index, LATEX stores all the words
that go into the index in this file. Process this file with makeindex.
Refer to Section 5.1 on page 137 for more information on indexing.
.ind The processed .idx file, ready for inclusion into your document on
the next compile cycle.
After reading the previous chapter, you should have some general idea about
LATEX. This chapter will fill in the remaining structure you will need to know
in order to produce real world documents.
Books are often typeset with each line having the same length. LATEX
inserts the necessary line breaks and spaces between words by optimising
the contents of a whole paragraph. If necessary, it also hyphenates words
that would not fit comfortably on a line. How the paragraphs are typeset
depends on the document class. Normally the first line of a paragraph
is indented, and there is no additional space between two paragraphs.
Refer to subsection 7.6.4 for more information.
In special cases it might be necessary to order LATEX to break a line.
\\[〈length〉] or \newline
starts a new line without starting a new paragraph. The optional 〈length〉
20 Real World LATEX
\\*[〈length〉]
additionally prohibits a page break after the forced line break.
\newpage
starts a new page.
\linebreak[〈n〉]
\nolinebreak[〈n〉]
\pagebreak[〈n〉]
\nopagebreak[〈n〉]
suggest places where a break may (or may not) happen. They enable the
author to influence their actions with the optional argument n, which
can be set to a number between zero and four. By setting n to a value
below 4, you leave LATEX the option of ignoring your command if the
result would look very bad. Do not confuse these “break” commands
with the “new” commands. Even when you give a “break” command,
LATEX still tries to even out the right border of the line and the total
length of the page. As described in the next paragraph, this can lead to
unpleasant gaps in your text. If you really want to start a “new line” or
a “new page”, then use the corresponding command. Guess their names!
2.1.2 Hyphenation
\hyphenation{〈word list〉}
\hyphenation{FORTRAN Lo-co-mo-tion}
Several words can be kept together on one line with the command
\mbox{〈text〉}
The names for these dashes are: ‘-’ hyphen, ‘–’ en-dash and ‘—’
em-dash. Hyphens are used when writing compound words (and inserted
automatically by LATEX when splitting a single word), en-dashes are used
for writing a range of numbers, and em-dashes are used to mark an
interruption in speech or an abrupt change of thought.
2.4 Slash (/) 23
read\slash write
which allows hyphenation. Normal ‘/’ characters may be still used for
inline fractions. The typesetting of units, such as MiB/s, will be described
in Section 3.5.
2.6 Ligatures
Some letter combinations are typeset not just by setting the different
letters one after the other, but by actually using special symbols.
2.7 Abstract
In scientific publications, it is customary to start with an abstract which
gives the reader a quick overview of what to expect. LATEX provides the
abstract environment for this purpose. Normally abstract is used in
documents typeset with the article document class.
\begin{abstract} Abstract
This paper will talk about This paper
abstracts. will talk about
\end{abstract} abstracts.
1
2.8 International Language Support
By Axel Kielhorn <A.Kielhorn@web.de>
When you write documents in languages other than English, there are
three areas where LATEX has to be configured appropriately:
2. LATEX needs to know the hyphenation rules for the current language.
If your keyboard does not have all the special characters, you can
also enter accents and special characters via dedicated commands. The
commands for adding accents to characters are listed in Table 2.1. Keep
in mind that while older TEX engines worked by combining accents with
existing letters manually, nowadays they simply look up the correct glyph
in the font. This means that accents and characters can no longer be
freely combined, and output is produced only if the font supports the
combination. The example above would look like this if entered on an
english keyboard:
The Unicode standard defines over 100 000 glyphs for use across many
languages and specialized disciplines. Currently, no font implements the
whole set, so if you are working with a lot of non-Latin characters you will,
sooner or later, find one that is not supported by your currently selected
font. In such cases, LATEX will not typeset the requested character, and
prints a “Missing character” warning in its log. Because such warnings
are easy to overlook, we recommend you put
\tracinglostchars=3
somewhere in the preamble of the document. This command will elevate
the warnings to error status, so they will be much harder to miss.
% In the preamble
\setdefaultlanguage{english}
\setotherlanguage{german}
% ...
Today is not \today.
Today is not January 19, 3022.
Heute ist nicht 19. Januar 3022.
\begin{german}
Heute ist nicht \today.
\end{german}
You can also use lang environment, which accepts the 〈language〉 as
its first argument. This is especially useful if you prefer to specify the
language via a BCP-47 tag, since environment names cannot contain the
‘-’ symbol.
\begin{lang}{de-DE}
Heute ist nicht \today. Heute ist nicht 19. Januar 3022.
\end{lang}
\begin{german}[
script=blackletter
] Heute ist nicht 17. Auguſt 3023.
Heute ist nicht \today.
\end{german}
2.8 International Language Support 27
\textlanguage[〈options〉]{〈text〉}
or the
\textlang[〈options〉]{〈language〉}{〈text〉}
command:
In Austria they write
\textlang[variant=austrian]{de}{Jänner}
instead of \textgerman{Januar}. And in the olden
days \textlang{de}{August} was written
\textgerman[script=blackletter]{Auguſt}.
For languages that are not very different from English, the results
are not very impressive. We get correct hyphenation, and some context-
aware commands, such as \today, adjust their output. However, the
further we stray from English, the more useful these commands become.
Sometimes the font used in the main document does not contain
glyphs required by the second language. The default Latin Modern font,
for example, does not contain Cyrillic letters. The solution is to define a
custom font that will be used for that language.
To set the fonts, use the preamble command
\newfontfamily{\〈familyname〉}[〈options〉]{〈font〉}
If you are using XƎLATEX and don’t have the font installed, then you
need to specify the font by its file name.
\newfontfamily\greekfont[
Extension=.otf, UprightFont=*rm, ItalicFont=*ti,
BoldFont=*bx, BoldItalicFont=*bi,
]{Cm}
With the appropriate fonts loaded, you can now write:
\newfontfamily\greekfonttt[
Extension=.otf, UprightFont=*btl, ItalicFont=*bto,
BoldFont=*tb, BoldItalicFont=*tx,
]{cmun}
The commands above redefine the fonts for languages used as ‘other’
in polyglossia. If you want to influence the font of the main document
language, use \setmainfont, \setsansfont and \setmonofont. These
work the same way, but without the 〈familyname〉 argument.
\setmainfont{CMU Serif}
\setsansfont{CMU Sans Serif}
\setmonofont{CMU Typewriter Text}
If you want to learn even more about fonts, have a look at Section 7.3.
\documentclass{article}
\begin{document} ١
هذا نص عربي
\end{document}
The package xepersian [34]5 offers support for the Persian language.
It supplies Persian LATEX-commands that allows you to enter commands
like \section in Persian, which makes this really attractive to native
speakers. xepersian is the only package that supports kashida with
XƎLATEX. A package for Syriac, which uses a similar algorithm, is under
development.
4
bidi supports only the XƎTEX engine. If you use LuaTEX, polyglossia uses the
luabidi [35] package, but keep in mind that it is much more limited than bidi.
5
Works only with XƎLATEX.
30 Real World LATEX
• arab (Arabic)
• persian
• urdu
• sindhi
• pashto
• ottoman (turk)
• kurdish
• kashmiri
• malay (jawi)
• uighur
It offers a font mapping that enables XƎLATEX to process input using the
ArabTEX ASCII transcription.
There is no package available for Hebrew, because none is needed.
The Hebrew support in polyglossia should be sufficient, but you do need
a suitable font with real Unicode Hebrew. An extension to the default
Latin Modern font, called New Computer Modern [82], adds, among
other things, a full Hebrew character set. It’s distributed with TEXLive,
so there is a good chance you already have it. Another Hebrew font,
available under the SIL Open Font License, is Ezra SIL [78].
\NewDocumentCommand{\〈name〉}{}{〈definition〉}
command. The 〈name〉 is the name of the command that you will use in
the code, while the 〈definition〉 is the output it will produce. The second
argument is left empty for now, but will be explored in subsection 7.1.1.
\NewDocumentCommand{\lukas}{}{%
Łukasiewicz%
} Polish notation (also known as
Łukasiewicz notation, due to its
Polish notation (also known as inventor, Jan Łukasiewicz) is a
\lukas{} notation, due to its mathematical notation …
inventor, Jan \lukas) is a
mathematical notation \ldots{}
\NewDocumentCommand{%
\comminus}{}{⁒}
Now I can type ⁒ or ⁒.
Now I can type ⁒ or \comminus.
Yet another use is to define a command for a simple string you may
want to change later. For example, let’s imagine you are writing a novel,
but are not so sure about your protagonist’s name. You can define a
command for it, and in the event you change your mind, you need only
32 Real World LATEX
\NewDocumentCommand{%
\hero}{}{Launcelot} Launcelot unsheathed his sword.
\hero{} unsheathed his sword.
He had a bad feeling about this
He had a bad feeling about place from the start.
this place from the start.
\RenewDocumentCommand{%
\ldots}{}{...}
I like my ellipsis looking uglier ...
I like my ellipsis looking
uglier \ldots
Mr.~Smith was happy to see her\\ Mr. Smith was happy to see her
cf.~Fig.~5\\ cf. Fig. 5
I like BASIC\@. What about you? I like BASIC. What about you?
The additional space after periods can be disabled with the command
\frenchspacing
which tells LATEX not to insert more space after a period than after
an ordinary character. This is very common in non-English languages
(polyglossia sets it automatically, based on the main language).
\section{〈title〉}
\subsection{〈title〉}
\subsubsection{〈title〉}
\paragraph{〈title〉}
\subparagraph{〈title〉}
If you want to split your document into parts without influencing the
section or chapter numbering use
\part{〈title〉}
When you work with the report or book class, an additional top-level
sectioning command becomes available:
\chapter{〈title〉}
As the article class does not know about chapters, it is quite easy
to add articles as chapters to a book. The spacing between sections, the
numbering, and the font size of the titles will be set automatically by
LATEX.
34 Real World LATEX
Contents
\tableofcontents 1 Title for the table of con-
tents 1
\section[Title for the
table of contents]{A long
and especially boring title,
1 A long and espe-
shown in the text} cially boring title,
shown in the text
\frontmatter should be the very first command after the start of the
document body (\begin{document}). It will switch page num-
bering to Roman numerals and sections will be non-enumerated as
if you were using the starred sectioning commands (for example
\chapter*{Preface}) but the sections will still show up in the
table of contents.
\mainmatter comes right before the first chapter of the book. It turns
on Arabic page numbering and restarts the page counter.
\backmatter should be inserted before the very last items in your book,
such as the bibliography and the index. In the standard document
classes, this has no visual effect.
7
Note that these commands are not aware of what they refer to. \label just saves
the last automatically generated number.
36 Real World LATEX
2.13 Footnotes
With the command
\footnote{〈footnote text〉}
2.14 Lists
The itemize environment is suitable for simple lists, the enumerate
environment for enumerated lists, and the description environment for
descriptions.
\begin{enumerate}
\item You can nest the list 1. You can nest the list envi-
environments to your taste: ronments to your taste:
\begin{itemize}
\item But it might start to • But it might start to
look silly. look silly.
\item[-] With a dash. - With a dash.
\end{itemize}
\item Therefore remember: 2. Therefore remember:
\begin{description}
\item[Stupid] things will not Stupid things will not be-
become smart because they are come smart because
in a list.
they are in a list.
\item[Smart] things, though,
can be presented beautifully Smart things, though, can
in a list. be presented beauti-
\end{description} fully in a list.
\end{enumerate}
FlushLeft
FlushRight
Center
\begin{FlushRight}
This text is right-\\aligned. This text is right-
\LaTeX{} is not trying to make aligned. LATEX is not trying to
each line the same length. make each line the same length.
\end{FlushRight}
\begin{Center}
At the centre
At the centre\\of the earth
\end{Center} of the earth
2.16 Quotations
You should not use the ‘"’ character for quotation marks as you would
in a WYSIWYG program. In publishing, there are special opening and
closing quotation marks. In LATEX, the csquotes [43] package provides the
\enquote{〈text〉}
command that automatically encloses the 〈text〉 within the right quotes.
\enquote{Please press
the \enquote{x} key.}
“Please press the ‘x’ key.”
If you want to skip directly to the inner form of quotation, use the
starred version of the command:
For longer quotations you may want to use the displayquote envi-
ronment.
If you prefer to count words instead of lines, you may change the
thresholdtype from lines to words and set threshold accordingly. If
you want to ignore paragraphs, and rely only on automatic line/word
counting, set the parthreshold to false.
The quote attribution shown in the previous examples is especially
useful when combined with bibliography commands described in Chap-
ter 4.
If you load the package with the autostyle option, it will also adapt
the quotation marks to the language of the surrounding text.
% In preamble
\usepackage[autostyle]{csquotes}
% ...
“English quote”
\enquote{English quote}
„Deutsches zitat“
\begin{german}
\enquote{Deutsches zitat}
\end{german}
% In preamble
\usepackage[
autostyle,
german=guillemets,
]{csquotes} »Deutsches zitat«
% ...
\foreignquote{german}{%
Deutsches zitat}
I wanted to quote my
favourite speech: I wanted to quote my favourite
\begin{quotation} speech:
This is a very
long speech. This is a very long
speech.
It spans over multiple It spans over mul-
paragraphs. tiple paragraphs.
\end{quotation}
2.17 Code Listings 41
2.17.1 Verbatim
LATEX itself comes with the \verb command. It is unusual in that it
does not use groups for getting its first argument. Instead, you pass the
argument between a chosen delimiter that can be any character except a
letter, * or space. For example, to use | as the delimiter (as is typical),
you type
\verb|〈text〉|
Any text that is enclosed between these delimiters will be directly printed,
as if typed on an old typewriter (in a monospaced font), with all spaces,
and without any LATEX commands being executed.
Use \verb|\LaTeX{}| to
print \LaTeX. Use \LaTeX{} to print LATEX.
We normally use | but when it’s
We normally use \verb+|+ but
when it's not available we
not available we use + to delimit
use \verb|+| to delimit the the argument of the \verb com-
argument of the \verb|\verb| mand.
command.
42 Real World LATEX
The starred version of the \verb command replaces spaces with the
‘␣’ symbol.
For longer text, you may want to use the verbatim environment from
the verbatim [66] package.
\begin{verbatim}
\documentclass{article} \documentclass{article}
\begin{document} \begin{document}
Small is beautiful. Small is beautiful.
\end{document} \end{document}
\end{verbatim}
Its starred version will draw the ‘␣’ symbol instead of spaces.
For code snippets, it may be useful to store them in separate files,
outside of the LATEX document. This allows you to edit them in your editor
of choice, and makes the LATEX code less cluttered. To accomplish this,
use the \verbatiminput{〈file〉} command from the verbatim package.8
\verbatiminput{hello.c}
// A simple program
#include "stdio.h"
int main() {
printf("Hello, World!\n");
return 0;
}
While the verbatim environment is fine for small snippets, they are very
crude and look basic. In order to make them a bit more fancy, you can
use the listings [23] package. It defines the
\lstinline|\LaTeX{}|
\begin{lstlisting}
Here is some \LaTeX{} code.
\end{lstlisting}
\lstinputlisting{hello.c}
\LaTeX{}
Here i s some \LaTeX{} code .
// A s i m p l e program
#i n c l u d e " s t d i o . h "
i n t main ( ) {
p r i n t f ( " H e l l o , World ! \ n " ) ;
return 0;
}
As you can see, by default it isn’t much different from the verbatim
environment. The big difference is that every command accepts optional
argument that allows you to customise the output. The argument accepts
a comma-delimited key-value list. For example, to automatically highlight
44 Real World LATEX
// A s i m p l e program
#include " s t d i o . h "
int main ( ) {
p r i n t f ( " H e l l o , World ! \ n " ) ;
return 0 ;
}
For many, the default style of the listings may look a bit strange. No
worries, this is easily fixed. The output can be customized using the
following keys:
basicstyle, keywordstyle, identifierstyle and commentstyle
Note that you will need to use some font changing commands, when
configuring the styles. More about font changing command can be found
in Section 7.2.
\lstinputlisting[
language=SQL, -- A simple query
basicstyle=\ttfamily, SELECT * FROM employees
commentstyle=\color{gray}, WHERE salary > 2000.00
keywordstyle=\itshape, ORDER BY last_name ;
]{employee.sql}
If you intend to use similar options for many listings in the document,
you can use the \lstset command to set them beforehand. In this way,
you will avoid repeating them every time you want to typeset some code.
\lstset{
language=C,
numbers=left, 1 // A simple program
breaklines, 2 # include " stdio .h"
basicstyle=\ttfamily, 3
commentstyle=\color{gray}, 4 int main () {
prebreak=\textrightarrow,
}
5 printf ("Hello , World→
!\n");
\lstinputlisting{hello.c} 6 return 0;
7 }
The statement
\lstinline|int x = 1;| The statement int x = 1; assigns 1
assigns 1 to variable to variable x.
\lstinline|x|.
2.17 Code Listings 45
If a language has several dialects, you may specify which inside square
brackets before the language name. You must enclose the value in curly
brackets.
\lstinputlisting[language={[LaTeX]TeX}]{hello.tex}
\ documentclass { article }
\ begin { document }
Hello , World !
\end{ document }
\lstinputlisting[language=C, numbers=left]{hello.c}
1 // A simple program
2 # include " stdio .h"
3
4 int main () {
5 printf ("Hello , World !\n");
6 return 0;
7 }
stepnumber prints only every 𝑛-th number. For example, if you pass
stepnumber=7, then only line numbers 1, 8, 15, 22, … will be printed.
If you have a long file and want to show it piecewise, you can use the
firstline and lastline keys.
The \lstinline|main|
function body
consists of: The main function body consists of:
\lstinputlisting[ printf ("Hello , World !\n");
language=C,
firstline=5,
return 0;
lastline=6,
]{hello.c}
If you are trying to typeset long lines, you may order the listings to
automatically break them by using the breaklines key.
1 import math
2
\lstinputlisting[ 3 def oneline_factorial (n):
language=python,
4 return math.prod(i for
numbers=left,
breaklines, i in range (1, n + 1)
]{factorial.py} )
5
6 print ( oneline_factorial (5))
You can customise the indentation width with the breakindent key.
It may be useful to indicate that a line break has occurred by using
the prebreak and postbreak keys, which print their value respectively
before and after an artificial line break. Listing 2.1 shows an example of
this.
2.17 Code Listings 47
\lstinputlisting[
language=python,
numbers=left,
breaklines,
breakindent=1cm,
prebreak=\textrightarrow,
postbreak=\textleftarrow,
]{factorial.py}
1 import math
2
3 def oneline_factorial (n):
4 return math.prod(i for→
← i in range (1, n →
←+ 1))
5
6 print ( oneline_factorial (5)→
←)
One of the neat features of the listings package is that you can evaluate
LATEX code inside the listing. The easiest way is to pass the texcl key,
which enables LATEX syntax within comments.
\begin{lstlisting}[
texcl,
language=haskell, -- I can use LATEX here.
] -- The cost is in €
-- I can use \LaTeX{} here.
-- The cost is in \texteuro{}
cost x = show (
cost x = show ( foldr (+) 0 x
foldr (+) 0 x ) ++ " eur"
) ++ " eur"
\end{lstlisting}
\begin{lstlisting}[
texcl,
numbers=left,
language=haskell, 1 cost x = show (
]
2 foldr (+) 0 x
cost x = show (
foldr (+) 0 x 3 ) ++ " eur" --
) ++ " eur" -- \label{concat} The ++ in Haskell as seen in line 3
\end{lstlisting}
means string concatenation.
The \lstinline|++| in Haskell
as seen in line~\ref{concat}
means string concatenation.
This has the downside that it introduces empty comments that are just
there to include label. To fix this we may use the escapeinside key
that accepts sets the two delimiters between which LATEX code can be
typed. The delimiters themselves will not be printed.
\begin{lstlisting}[
escapeinside={(*}{*)},
numbers=left,
language=haskell, 1 cost x = show (
] 2 foldr (+) 0 x
cost x = show ( (*\label{show}*) 3 ) ++ " eur" (€)
foldr (+) 0 x
) ++ " eur" (*(\texteuro)*) The show in Haskell as seen in
\end{lstlisting} line 1 converts its argument to a
The \lstinline|show| in Haskell string.
as seen in line~\ref{show}
converts its argument to a string.
2.17 Code Listings 49
\mintinline[〈options〉]{〈language〉}{〈code〉}
\inputminted[〈options〉]{〈language〉}{〈code〉}
\begin{minted}[〈options〉]{〈language〉}
delimiters.
\LaTeX{}
\mintinline{latex}|\LaTeX{}|
x = 0
\begin{minted}{python} for i in range(10):
x = 0 x += 2**i
for i in range(10): print(f"Result: {x}")
x += 2**i
print(f"Result: {x}") fn main() {
\end{minted} let age = 25;
println!("I am {} years old.",
\inputminted{rust}{age.rs}
age);
}
1 .review {
2 font-size: large;
\inputminted[ 3 background-color: darkred;
linenos, 4 color: aliceblue;
]{css}{review.css} 5 display: flex;
6 align-items: center;
7 }
You can change the line numbering using firstnumber and stepnumber.
Additionally you may highlight some lines using the highlightlines
key to draw attention to them. Note that highlightlines uses the
transformed line numbers.
2.17 Code Listings 51
Theorem em_irr:
6 forall A: Prop, ~~(A \/ ~A).
Proof.
\inputminted[ unfold not.
linenos, 9 intros.
firstnumber=5, apply H.
stepnumber=3, right.
highlightlines={6, 10-12} 12 intros.
]{coq}{em.v} apply H.
left.
15 exact H0.
Qed.
\begin{minted}[
linenos,
texcomments, 1 <!DOCTYPE html>
escapeinside=||, 2 <html>
]{html} 3 <head>
<!DOCTYPE html>
4 <title>On LATEX</title>
<html>
<head> |\label{head}| 5 </head>
<title>On |\LaTeX{}|</title> 6 <body>
</head> 7 <div class="review">
<body> 8 <!-- LATEX review -->
<div class="review"> 9 <p>It's awesome!</p>
<!-- \LaTeX{} review --> 10 </div>
<p>It's awesome!</p>
11 </body>
</div>
</body> 12 </html>
</html>
\end{minted} The <head> element in line 3 con-
The \mintinline{html}{<head>} tains page metadata.
element in line~\ref{head}
contains page metadata.
\inputminted[ #!/bin/bash
style=bw, echo LaTeX is awesome!
]{bash}{echo.sh}
\inputminted[
#!/bin/bash
style=sas,
]{bash}{echo.sh} echo LaTeX is awesome!
\inputminted[
style=xcode, #!/bin/bash
]{bash}{echo.sh} echo LaTeX is awesome!
To avoid having to set the options for every listing and code snippet,
you can use \setminted to define the default values.
1 #include <iostream>
\setminted{ 2
linenos, 3 int main() {
breaklines,
4 std::cout << "Goodbye!"
style=xcode,
} ↪ << std::endl;
\inputminted{c++}{goodbye.cpp} 5 return 0;
6 }
2.18 Tables 53
2.18 Tables
In LATEX, the environment to typeset tables (and more) is called tabular.
While it can be used on its own, the resulting table layouts look extremely
old fashioned. We recommend adding the booktabs [17] package, which
provides several commands that let you typeset beautiful modern looking
tables.
Note that the booktabs [17] package does not modify the tabular
environment, it just adds some extra commands for spacing and adding
lines to your tables. If you write for a publication which has other
requirements, like not using any extra packages, simply do not use the
extra commands from booktabs [17].
To achieve some more advanced table layouts, you will also learn
about the longtable [11], array [46] and multirow [51] packages in this
section. They are so useful, that you’ll probably want to put them all
into the preamble of your document right away.
In addition to a description of its commands, the booktabs documen-
tation [17] contains guidelines on typesetting professional-looking tables.
We have taken these guidelines to heart when writing this booklet. You
will find some of them in this section.
\begin{tabular}[〈pos〉]{〈colspec〉}
The 〈colspec〉 argument, which stands for column specifiers, defines the
format of the columns in the table. Use an l for a column of left-
aligned text, r for right-aligned text, and c for centred text. Within the
environment, use & to begin the next cell within the current row, and \\
to begin the next row.
\begin{tabular}{lcr}
left & centre & right \\ left centre right
1 & 2 & 3 \\ 1 2 3
\end{tabular}
Note that the text inside the cells will not be wrapped. If you want
the column to contain justified text with line breaks, use the p{〈width〉}
54 Real World LATEX
1 2
1 2
text text 1 2 text 3 4 text
3 4
3 4
What we have seen so far, allows aligning some items in rows and
columns, but real tables need visible headings. To insert them, use the
commands \toprule, \midrule and \bottomrule from the booktabs
package. All of these accept an optional argument that specifies their
thickness, but usually the default settings are just fine. See Listing 2.2
for an example of using these commands.
With these commands you are already able to produce simple, yet
nicely looking tables. You may be are wondering why we have not
mentioned how to add vertical lines between the columns. Well, we did
not mention them because the first rule of producing professional-looking
tables is that you must not use vertical lines.
The second rule is to never use double lines such as these shown in
Listing 2.3. The default lines are already of different weight in order
to signify their meaning. Using more lines than is necessary means
cluttering the space without adding information. If you stick to these
two rules, your tables will look quite good already.
To make the tables look even more sleek, you may want to remove
the padding in the first and last column. To control the space between
2.18 Tables 55
\begin{tabular}{lcl}
\toprule
Alignment & Letter & Niceness \\
\midrule
Left & l & Very nice \\
Centre & c & Very nice \\
Right & r & Very nice \\
\bottomrule
\end{tabular}
\begin{tabular}{lll}
\toprule[0.1cm]
\toprule
Person & Face & Table \\
\midrule
\midrule
Me & :( & Not nice \\
You & :[ & Awful \\
Your reader & :< & Terrible \\
\bottomrule
\bottomrule[0.1cm]
\end{tabular}
the columns use the @{〈sep〉} column specifier, where 〈sep〉 is either
text or space. Space of arbitrary length can be inserted using the
\hspace{〈width〉} command. The contents of the 〈sep〉 arguments will
be put between cells in the relevant column.
\begin{tabular}{
@{a} c @{\hspace{1cm}} c @{|} c @{ b}
} a1 2|3 b
1 & 2 & 3 \\ a4 5|6 b
4 & 5 & 6\\ a7 8|9 b
7 & 8 & 9\\
\end{tabular}
If you leave the 〈sep〉 empty it will suppress the padding between the
columns. See Listing 2.4 for an example.
Sometimes it may make sense to group columns under one heading.
To achieve this, we need two things: a way to group multiple heading
columns, and to have a line covering the same columns (sitting underneath
the merged heading cell). Use the
\multicolumn{〈ncols〉}{〈colspec〉}{〈text〉}
command to merge the cells. The 〈ncols〉 argument indicates how many
columns should the 〈text〉 span, while the 〈colspec〉 is the column spec-
ification for the new content—the same as when starting a tabular
environment. See Listing 2.5 for an example.
To get a horizontal line to span multiple columns, use the command
\cmidrule[〈dim〉](〈trim〉){〈a-b〉}
While the command uses nonstandard syntax for 〈trim〉, this is just an
optional argument with different pair of delimiters.9 The 〈dim〉 allows
us to specify the thickness of the line. The 〈trim〉 argument accepts any
combination of r, r{〈dim〉}, l or l{〈dim〉}. This allows you trim the rule
from right or left, either by the package default or the specified 〈dim〉. It
is usually recommended to trim the rules from the side where they touch
other columns. The command’s only required argument is the span of
columns to draw the line over (〈a-b〉). See Listing 2.6 for an example.
If you need a cell to span multiple rows instead of columns, then
you have to use package multirow. Its main command is a little more
complicated
\multirow[〈vpos〉]{〈nrows〉}{〈width〉}[〈vmove〉]{〈text〉}
The arguments are
9
This syntax allows specification of the second optional argument without the first,
which would be impossible if square brackets were used for both.
2.18 Tables 57
\begin{tabular}{@{}lll@{}}
\toprule
Person & Face & Table \\
\midrule
Me & :) & Nice \\
You & :] & Sleek \\
Your reader & :> & Informative \\
\bottomrule
\end{tabular}
\begin{tabular}{@{}lll@{}}
\toprule
Person & Face & Table \\
\midrule
Me & :) & Nice \\
You & :] & Sleek \\
Your reader & \multicolumn{2}{c}{Not available} \\
\bottomrule
\end{tabular}
\begin{tabular}{@{}lll@{}}
\toprule
& \multicolumn{2}{c}{Reaction} \\
\cmidrule(l){2-3}
Person & Face & Exclamation \\
\midrule
Me & :) & Nice \\
You & :] & Sleek \\
Your reader & \multicolumn{2}{c}{Not available} \\
\bottomrule
\end{tabular}
Reaction
Person Face Exclamation
Me :) Nice
You :] Sleek
Your reader Not available
〈vpos〉 is the vertical position of the text within the cell. Can be either
c for centre (the default), t for top or b for bottom.
〈width〉 is the width of the cell. Apart from a regular length, you can
also pass two special arguments here: * for the natural length of
the text and = for the same width as the column (this only makes
sense if the column width was specified, for example via p{3cm}).
〈vmove〉 allows adjusting the position of the text if it sits too low or too
high.
Unlike with \multicolumn you still have to write all the cells in remaining
rows, but they should be empty. See Listing 2.7 for an example.
In general it is not a good idea to use the \multirow command for
showing values common to multiple rows. Usually repeating the values
in question makes the table more readable.
When typesetting numerical data in the table, you may want to
align it by decimal point. A way to do this (and more) is described
in subsection 3.5.4. The section also contains some guidelines about
typesetting numerical data in tables.
2.18 Tables 59
\begin{tabular}{@{}lll@{}}
\toprule
& \multicolumn{2}{c}{Reaction} \\
\cmidrule(l){2-3}
Person & Face & Exclamation \\
\midrule
\multirow[t]{2}{*}{VIPs} & :) & Nice \\
& :] & Sleek \\
Others & \multicolumn{2}{c}{Not available} \\
\bottomrule
\end{tabular}
Reaction
Person Face Exclamation
VIPs :) Nice
:] Sleek
Others Not available
\begin{longtable}[〈align〉]{〈colspec〉}
\begin{tabular}{@{}cllcl@{}}
\toprule
Digit & Word && Digit & Word \\
\midrule
0 & Zero && 5 & Five \\
1 & One && 6 & Six \\
2 & Two && 7 & Seven \\
3 & Three && 8 & Eight \\
4 & Four && 9 & Nine \\
\bottomrule
\end{tabular}
Listing 2.8: An example of producing table with rows next to each other.
Number Word
\begin{longtable}{cl} 0 Zero
\toprule 1 One
Number & Word \\ 2 Two
\midrule 3 Three
0 & Zero \\ 4 Four
1 & One \\
2 & Two \\ 5 Five
% ... 6 1 Six
10 & Ten \\ 7 Seven
\bottomrule 8 Eight
\end{longtable} 9 Nine
10 Ten
2
Listing 2.9: An example of using the longtable environment.
2.18 Tables 61
\begin{longtable}{
cp{2cm}
} Number Words
\toprule
0 Zero
Number & Words \\
\midrule
0 & Zero \\ 1 Multi
1 para-
1 & Multi paragraph graph text.
text. It makes the
table cell
It makes the table very tall.
cell very tall. \\ 2 Two
2
2 & Two \\
\bottomrule
\end{longtable}
3
Listing 2.10: An anti-example of using longtable assuming it will break
the paragraphs inside the cells.
In regular text, you can specify the amount of space between two lines
as an optional argument to the \\TU\textbackslash command. Can
the same be done within a table? It turns out that it can, but there is
one caveat. If you use it together with a p{...} column, the resulting
space will be different depending on column order.
62 Real World LATEX
\begin{longtable}{cl}
\toprule
\multicolumn{2}{c}{V.~Important Table} \\
Number & Word \\
\midrule \endfirsthead
\toprule
\multicolumn{2}{c}{VIT (continued)} \\
Number & Word \\
\midrule \endhead
\midrule
\multicolumn{2}{c}{Not the end} \\
\bottomrule \endfoot
\midrule
\multicolumn{2}{c}{The end of VIT} \\
\bottomrule \endlastfoot
0 & Zero \\
1 & One \\
% ...
10 & Ten \\
\end{longtable}
1 2
Listing 2.11: An example of longtable with running headers and footers.
2.18 Tables 63
\begin{tabular}{lp{1cm}}
1 & 2\newline x \\[1cm] 1 2
2 1
3 & 4 \\ x
\end{tabular} x
\begin{tabular}{p{1cm}l}
2\newline x & 1 \\[1cm] 4 3
3 4
4 & 3 \\
\end{tabular}
1 that the space to
This counterintuitive behaviour is caused by the fact
add is calculated based on the last column. In order to prevent that,
simply add \usepackage{array} to your preamble. Since there are no
downsides to this, it is recommended to always use this package when
starting a new document, to avoid breaking tables that rely on the
original behaviour later. The array package also defines some additional
column specifiers.
The p{...} specifier allows the insertion of text with line breaks
into the table. The text always starts from the top though, so the array
package defines two additional specifiers: m{...} for vertically centred
text, and b{...} for text placed vertically from the bottom.
\begin{tabular}{
lp{1.4cm}m{1.4cm}b{1.4cm} Bottom
} Centre matches
Cell &
Cell Top matches cell.
Top matches cell. &
Centre matches cell. & matches cell.
Bottom matches cell. \\ cell.
\end{tabular}
\begin{tabular}{
l
>{\begin{em}}l<{\end{em}} text emphasised text
}
text emphasised text
text & emphasised text \\
text & emphasised text \\ text emphasised text
text & emphasised text \\
\end{tabular}
While using >{...} and <{...} comes in handy if we only have one
such column, it quickly becomes inconvenient when many columns of the
64 Real World LATEX
same type appear in any tables. In that case, it may be desirable to use
the command
\newcolumntype{〈newcolspec〉}{〈definition〉}
\newcolumntype{e}{
>{\begin{em}\begin{FlushLeft}}
p{2.5cm}
<{\end{FlushLeft}\end{em}}
}
\begin{tabular}{ee}
This cell will
This cell will This cell will
be flushed left
and emphasised. & be flushed left be flushed left
This cell will and empha- and empha-
be flushed left sised. sised.
and emphasised.
\tabularnewline This cell will This cell will
be flushed left be flushed left
This cell will and empha- and empha-
be flushed left
sised. sised.
and emphasised. &
This cell will
be flushed left
and emphasised.
\tabularnewline
\end{tabular}
\begin{tabular}{c|c|c}
O & X & O \\
\hline O X O
X & X & O \\ X X O
\hline X O X
X & O & X \\
\end{tabular}
In case your grid gets more complicated, you may need the \cline{〈a-b〉}
2.19 Including Graphics and Images 65
command, which draws a horizontal line spanning only the specified rows.
\begin{tabular}{|cccc|}
\cline{4-4}
a & a & \multicolumn{1}{c|}{a} & b \\
\cline{2-3} a a a b
a & \multicolumn{1}{|c}{b} & b & b \\ a b b b
\cline{2-2} a a b b
a & a & \multicolumn{1}{|c}{b} & b \\
\cline{1-2}
\end{tabular}
\includegraphics[〈options〉]{〈file〉}
Here is an image:
Here is an image:
\includegraphics{example-image} Image
The file may be a PDF, PNG or JPEG. If you omit the extension, then
LATEX will try the following in order: .pdf, .png, .jpg, .mps, .jpeg,
.jbig2, .jb2. Note that if your filename contains dots (other than the
extension dot), then its basename has to be put in curly braces like so:
\includegraphics{{image.with.dots}.jpg}
10
In the subsequent examples, we are using images from the mwe [64] package that
should be installed with your LATEX distribution.
66 Real World LATEX
image.
\includegraphics[width=2cm]{example-image}
\includegraphics[height=1cm]{example-image}
\includegraphics[width=2cm, height=1cm]{example-image}
Image
Image Image
You may also pass the keepaspectratio key. This will change the
meaning of width and height keys to the maximum possible width and
height.
\includegraphics[
width=2cm,
height=2cm,
]{example-image}
\includegraphics[ Image
width=2cm, Image
height=2cm,
keepaspectratio,
]{example-image}
Instead of specifying width or height, you may also pass the scale
argument to scale it by a specific amount. Passing negative values will
reflect the image.
\includegraphics[
scale=0.1,
]{example-image}
\includegraphics[ Image
scale=0.3,
Image
]{example-image}
\includegraphics[
scale=-0.15, Image
]{example-image}
If you want to rotate the picture, you can pass the angle key. By
default, the image is rotated about its bottom-left corner. You can
change the anchor point by specifying the origin key. Its value may
contain one or two of the following specifications: l for left, r for right,
c for centre, t for top, b for bottom, and B for baseline (useful with TikZ
pictures as described in Chapter 6). So, for example, lc will rotate the
2.19 Including Graphics and Images 67
image about the centre of its left edge, while c will rotate it about its
centre.
Text \includegraphics[
angle=45,
]{example-image}
Text \includegraphics[
e
ag
angle=180,
Im
]{example-image} \\ Text Text
Text \includegraphics[ Image
angle=180,
origin=c, Image
]{example-image}
Text \includegraphics[ Image
angle=180, Text Text
origin=lt,
]{example-image}
If you want to show only a part of the picture, you may specify
the clip key and set the viewport key to required part of the image.
The viewport takes as its value four numbers: the first two specify the
bottom-left point of a rectangle, while the last two specify the top-right
point of rectangle.
\includegraphics[
clip,
viewport=3cm 3cm 8.5cm 5.5cm,
]{example-image} Image
If you are including a PDF file, \includegraphics will only include
its first page. If you want to specify a different page, pass it to the page
key.
\includegraphics[
width=1.5cm,
]{example-image-a4-numbered}
\includegraphics[
width=1.5cm,
page=2, 1 2 11
]{example-image-a4-numbered}
\includegraphics[
width=1.5cm,
page=11,
]{example-image-a4-numbered}
68 Real World LATEX
If you pass the draft option then, instead of the actual images, only
their names are printed, to save on file size and processing time. This key
will be inherited from the \documentclass options, if specified there.
\includegraphics[
scale=0.3,
example-image.pdf
draft,
]{example-image}
\begin{figure}[〈placement specifier〉]
\begin{table}[〈placement specifier〉]
\begin{table}[!hbp]
2.20 Floating Bodies 69
The placement specifier [!hbp] allows LATEX to place the table right
here (h) or at the bottom (b) of some page or on a special floats page
(p), and all this even if it does not look that good (!). If no placement
specifier is given, the standard classes assume [tbp].
LATEX will place every float it encounters according to the placement
specifier supplied by the author. If a float cannot be placed on the current
page it is deferred either to the figures queue or the tables queue.11 When
a new page is started, LATEX first checks if it is possible to fill a special
‘float page’ with floats from the queues. If this is not possible, the first
float on each queue is treated as if it had just occurred in the text: LATEX
tries again to place it according to its respective placement specifiers
(except h, which is no longer possible). Any new floats occurring in the
text get placed into the appropriate queues. LATEX strictly maintains the
original order of appearance for each type of float. That’s why a figure
that cannot be placed pushes all subsequent figures to the end of the
document. Therefore:
command to define a caption for the float. A running number, and the
string “Figure” or “Table”, will be added by LATEX.
The two commands
\begin{figure} 1
\centering
\includegraphics[
scale=0.2
]{example-image}
\end{figure} Image
\caption[Short]{LLLLLoooooonnnnnggggg}
\DeclareFloatingEnvironment[〈options〉]{〈name〉}
List of Figures
\listoffigures 1 A figure . . . . 2
\include{〈filename〉}
\input{〈filename〉}
Table 1: Numbers
\begin{longtable}{@{}cl@{}}
\caption{Numbers} \\
\toprule Number Word
Number & Word \\ 0 Zero
\midrule \endfirsthead 1 One
2 Two
\caption[]{(continued)} \\ 3 Three
\toprule
Number & Word \\
\midrule \endhead Table 1: (continued)
1
\bottomrule \endfoot
Number Word
\bottomrule \endlastfoot
4 Four
0 & Zero \\ 5 Five
% ... 6 Six
\end{longtable} 7 Seven
2
Listing 2.15: An example of longtable with running caption.
To make LATEX quickly check your document, use the syntonly package.
This makes LATEX skim through your document, only checking for proper
syntax and usage of commands, but doesn’t produce any (PDF) output.
As LATEX runs faster in this mode, you may save yourself valuable time.
Usage is very simple:
\usepackage{syntonly}
\syntaxonly
When you want to produce pages, just comment out the second line (by
adding a percent sign).
Chapter 3
Typesetting Mathematical
Formulae
The TEX typesetting system has become nearly ubiquitous when it comes
to typesetting mathematics. Many software packages even offer to export
their mathematical formulae to LATEX (for example, SageMath [81]) or allow
entering math expressions in LATEX or LATEX-derived syntax (for example,
Wikipedia [84]). In this chapter, you will learn how to insert math formulae
into your document.
you to use more symbols and makes the commands for accessing math
symbols a bit more consistent. The problem with unicode-math, is that
some older math packages rely on the classic math font encoding. So if
you have to use them, do not use the unicode-math package, to protect
your sanity.
Throughout this section, we assume that your preamble contains
these two lines in this order:
\usepackage{mathtools}
\usepackage[
math-style=ISO,
warnings-off={mathtools-colon, mathtools-overbracket},
]{unicode-math}
\begin{equation}
\label{trivial}
2 + 2 = 4 2+2=4 (1)
\end{equation}
Equation~\ref{trivial}
Equation 1 is true.
is true.
\begin{equation}
\tag{Ingsoc's theorem}
\label{ingsoc} 2 + 2 = 5 (Ingsoc’s theorem)
2 + 2 = 5
\end{equation} Equation (Ingsoc’s theorem) is
Equation~\eqref{ingsoc} is false. false.
The spaces around symbols are derived logically from the mathematical
expressions. We will talk more about those in Section 3.7. Since there
is no concept of a paragraph in math formulae, leaving empty lines
inside math mode is not allowed. Doing so will result in the “Bad math
environment delimiter.” error.
Another difference is the fact that all letters are treated as math-
ematical variables. Variables are printed using an italic font, and the
spacing around each letter is wider than in text-mode.
If you want to typeset normal text within a formula, you can use the
\text command.
\( (4 \times 6) \div 3 = 8 \) (4 × 6) ÷ 3 = 8
If you prefer to use dots for multiplication or slash for division, you can
use \cdot and \divslash, respectively. To typeset a negated equality,
you can precede the equal sign with \not.
\( (5 \cdot 3) \divslash 2
(5 ⋅ 3) ∕ 2 ≠ 7
\not= 7 \)
Alternatively, you can use \neq which will produce the same result. The
\not notation is more general in that it works with many more symbols.
To typeset weak inequalities, you can use the \leq (less or equal)
and \geq (greater or equal) commands. If you prefer slanted versions,
swap them for \leqslant and \geqslant.
\( 1 \leq 2 \) vs.\
\(1 \leqslant 2\)
1 ≤ 2 vs. 1 ⩽ 2
3.3 Building Blocks of Mathematical Formulae 79
In the example above, the second superscript doesn’t know about the
first one inside the parenthesis, and it adapts only to the height of the
closing parenthesis. To fix this, enclose the parentheses in a group.
2
\( {(a^2)}^2 \) is better. (𝑎2 ) is better.
\sqrt[〈n〉]{〈expr〉}
The optional argument 〈n〉 allows you to typeset 〈n〉-th root radicals.3
3
The name \sqrt is a bit misleading in that respect ;-).
80 Typesetting Mathematical Formulae
\(x = \frac{\sqrt{z+3}}{y^3}\).
To indicate set membership (“is an element of”), you can use the \in
command.4 Sets defined by a predicate are often written using set-builder
notation with a colon. The naïve way would be to write it like this:
\( \{x \in X:
{𝑥 ∈ 𝑋 ∶ ∃𝑛 𝑥𝑛 = 1}
\exists_n x^n = 1\} \)
4
Try to guess its left-flipped version name.
3.3 Building Blocks of Mathematical Formulae 81
The result doesn’t look right, though. The reason is the aforementioned
automatic spacing based on mathematical meaning. The : character is
used in LATEX for ratios, such as 1 ∶ 2, which is why it has equal spacing
on both of its sides. To typeset colons in set-builder notation, use the
\colon command instead.
As you can see above, in most fonts (including the default LATEX one)
there is no visual difference between some uppercase Greek letters and
their Latin equivalents. If you want to use them, make sure they do not
clash in your document.
Some Greek letters have defined variants. These are accessible by
prepending the word var before the letter name; \varepsilon, for
example. A list of all defined variants is presented in Table 3.1.
Note that all Greek letters in math mode, the same as all the Latin
letters, are considered to be mathematical variables. In particular, \pi
should not be used to denote the famous constant.
82 Typesetting Mathematical Formulae
\[
\forall_{p \in \symbb{P}}
\exists_{n \in \symbb{N}}
p < 5 \lor p^2 = 24n + 1 ∀𝑝∈ℙ ∃𝑛∈ℕ 𝑝 < 5 ∨ 𝑝2 = 24𝑛 + 1
\]
\NewDocumentCommand{\e}{}{\symrm{e}}
\NewDocumentCommand{\im}{}{\symrm{i}}
\NewDocumentCommand{\cpi}{}{\symrm{\pi}}
\[ \e^{\im\cpi} + 1 = 0 \]
eiπ + 1 = 0
3.3 Building Blocks of Mathematical Formulae 83
Example
Command Latin Greek Numerals
\symup ABCabc … ΑΒΓαβγ … 123 …
\symbfup 𝐀𝐁𝐂𝐚𝐛𝐜 … 𝚨𝚩𝚪𝛂𝛃𝛄 … 𝟏𝟐𝟑 …
\symit 𝐴𝐵𝐶𝑎𝑏𝑐 … 𝛢𝛣𝛤 𝛼𝛽𝛾 …
\symbfit 𝑨𝑩𝑪𝒂𝒃𝒄 … 𝜜𝜝𝜞 𝜶𝜷𝜸 …
\symsfup 𝖠𝖡𝖢𝖺𝖻𝖼 … 𝟣𝟤𝟥 …
\symbfsfup 𝗔𝗕𝗖𝗮𝗯𝗰 … 𝝖𝝗𝝘𝝰𝝱𝝲 … 𝟭𝟮𝟯 …
\symsfit 𝘈𝘉𝘊 𝘢𝘣𝘤 …
\symbfsfit 𝘼𝘽𝘾𝙖𝙗𝙘 … 𝞐𝞑𝞒 𝞪𝞫𝞬 …
\symtt 𝙰𝙱𝙲𝚊𝚋𝚌 … 𝟷𝟸𝟹 …
\symbba 𝔸𝔹ℂ𝕒𝕓𝕔 … ℾℿℽℼ 𝟙𝟚𝟛 …
\symbbitb ⅅⅆⅇⅈⅉ
\symscrc 𝒜ℬ𝒞𝒶𝒷𝒸 …
\symbfscrd 𝓐𝓑𝓒𝓪𝓫𝓬 …
\symfrak 𝔄𝔅ℭ𝔞𝔟𝔠 …
\symbffrak 𝕬𝕭𝕮𝖆𝖇𝖈 …
a
In the Greek set, only the four presented glyphs (\Gamma, \Pi, \gamma and \pi)
are defined by the Unicode standard.
b
Only the five presented glyphs (D, d, e, i and j) are defined by the Unicode
standard.
c
The default font does not contain lowercase glyphs. Here they are shown using a
different font.
d
Same as above.
84 Typesetting Mathematical Formulae
% In preamble
\DeclareMathOperator{\argh}{argh}
% ...
\[ \argh(x) = \sinh(\max(x, x^2)) \]
argh(𝑥) = sinh(max(𝑥, 𝑥2 ))
\(
\sum_{k=0}^{n} \frac{1}{k^2} ∑𝑛𝑘=0 1
𝑘2
\)
The appearance in text style differs massively from the one in display
style.
\[ 𝑛
1
\sum_{k=0}^{n} \frac{1}{k^2} ∑
\] 𝑘=0
𝑘2
\[
c = \max_{x\in X} f(x) 𝑐 = max 𝑓(𝑥)
𝑥∈𝑋
\]
You can define your own big operators by using a starred version of
the \DeclareMathOperator command.
% In preamble
\DeclareMathOperator*{\nut}{Nut}
% ...
\[ \nut_y = \lim_{x \to y} \argh{x} \]
\[
\sum^n_{
𝑛
\substack{0<i<n \\
j\subseteq i} ∑ 𝑃 (𝑖, 𝑗) = 𝑄(𝑖, 𝑗)
0<𝑖<𝑛
} 𝑗⊆𝑖
P(i,j) = Q(i,j)
\]
The integral symbol is also a big operator, but it only shifts the lower
limit left.
\[ 𝑏
\int_a^b \liminf_{a \to x} a^2 ∫ lim inf 𝑎2
𝑎→𝑥
\] 𝑎
86 Typesetting Mathematical Formulae
Due to the fact that the symbol is highly slanted to the right, type-
setting multiple integrals leads to excessive space around them. Use
\iint,\iiint,\iiiint instead for improved spacing.
∫∫∫∫
\[ \int\int\int\int \]
vs.\ vs.
\[ \iiiint \]
⨌
\[
{\sum_{a}}^b 𝑏
𝑏 𝑏
{\int}_a^b ∑ ∫ Nut𝑎
{\nut^b}_a 𝑎 𝑎
\]
𝑏
\[ {\sum_{loooooong}}^{b} \] ∑
𝑙𝑜𝑜𝑜𝑜𝑜𝑜𝑛𝑔
\sideset{〈left〉}{〈right〉}{〈symbol〉}
\[ \sideset{^{a}}{^{b}}{\sum}_{loooooong} \]
𝑎 𝑏
∑
𝑙𝑜𝑜𝑜𝑜𝑜𝑜𝑛𝑔
3.3 Building Blocks of Mathematical Formulae 87
\(\bar{x}\) \(\hat{x}\)
\(\grave{x}\) \(\acute{x}\) 𝑥̄ 𝑥̂ 𝑥 ̀ 𝑥́ 𝑥̃ 𝑥̈
\(\tilde{x}\) \(\ddot{x}\)
\(\hat{ABC}\) vs.\
̂ vs. 𝐴𝐵𝐶
𝐴𝐵𝐶 ̂
\(\widehat{ABC}\)
\(0.123\overline{456789}\) 0.123456789
Some wide accents even have limits. For example, the \overbrace
and \underbrace commands enable you to create horizontal braces with
an expression above or below them.
\[
\underbrace{
\overbrace{(a+b+c)}^6 6 7
\times ⏞
(𝑎⏞
+⏞ ⏞⏞
𝑏+ 𝑐) × ⏞
⏟⏟⏟⏟⏟⏟⏟⏟⏟⏟⏟ (𝑑⏞
+⏞ ⏞⏞
𝑒+ 𝑓) = 42
\overbrace{(d+e+f)}^7
meaning of life
}_{\text{meaning of life}}=42
\]
88 Typesetting Mathematical Formulae
You can even create your own math-accents using \overset and
\underset.
\(\overset{\text{foo}}{x}\) foo
𝑥 𝐴
\(\underset{\times}{A}\) ×
These commands may also be used when creating custom binary relations.
Make sure that you do not overwrite existing commands!
3.3.7 Delimiters
Besides the standard parentheses, brackets and braces, LATEX provides
all sorts of symbols for delimiters, such as:
\[
\langle x \rangle
\lBrack x \rBrack
\lfloor x \rfloor ⟨𝑥⟩ ⟦𝑥⟧ ⌊𝑥⌋ |𝑥|
\lvert x \rvert
\]
While all of them work fine for bungalow-style math, things get ugly
when the expression inside them starts getting tall.
\[
{\lfloor
\frac
{{\langle\sum_{k=1}^{\infty} k^{-4}\rangle}^3}
{\frac{{\lvert\{a,b,c\}\rvert}^8}{{(x^4)}^3}}
\rfloor}^6
\]
∞ 3 6
⟨∑𝑘=1 𝑘−4 ⟩
⌊ ⌋
|{𝑎,𝑏,𝑐}|8
3
(𝑥4 )
To fix this, you can use the \left and \right commands. They take
one argument—the delimiter to extend—and adapt its size based on the
3.3 Building Blocks of Mathematical Formulae 89
content they delimit. You must close every \left with a corresponding
\right, but they do not have to use the same delimiter.
\[
\left(
\frac{1}{1 +
\frac{1}{1 + ⎛ 1 ⎤
\frac{1}{1 + ⎜
⎜ ⎥
⎜1 + 1 ⎥
\frac{1}{1 + 1+ 1
\sqrt{2}}}}}
⎝ 1+ 1√
1+ 2 ⎦
\right]
\]
If you want to typeset a delimiter only on one side of the expression, a
special value may be passed: the dot character ., which is treated as an
invisible delimiter.
\[
x = \left.
∞
\sum_{k=1}^{\infty} 1
𝑥= ∑ }
\frac{1}{k^2} 𝑘2
𝑘=1
\right\}
\]
While using the \left and \right commands directly is sometimes
necessary, the simplest case of using some predefined delimiters on both
sides is the most common. For this usage, the command
\DeclarePairedDelimiter{\〈name〉}{〈left delim〉}{〈right delim〉}
is really useful. It declares the 〈name〉 command which simply encloses
its argument between 〈left delim〉 and 〈right delim〉, while its starred
version additionally uses \left and \right commands when typesetting
delimiters.
\DeclarePairedDelimiter{\set}{\{}{\}}
\DeclarePairedDelimiter{\size}{\lvert}{\rvert}
\DeclarePairedDelimiter{\mean}{\langle}{\rangle}
\DeclarePairedDelimiter{\floor}{\lfloor}{\rfloor}
\DeclarePairedDelimiter{\group}{(}{)}
\[
\floor*{
\frac
{\mean*{\sum_{k=1}^{\infty} k^{-4}}^3}
{\frac{\size*{\set{a,b,c}}^8}{\group*{x^4}^3}}
}^6
\]
3 6
⎢ ⟨∑∞ 𝑘−4 ⟩ ⎥
⎢ 𝑘=1 ⎥
⎢ |{𝑎,𝑏,𝑐}|8 ⎥
⎣ (𝑥4 )
3
⎦
90 Typesetting Mathematical Formulae
In some special circumstances, you may also want to select the size of
the delimiter yourself. You can do this by using the \big, \Big, \bigg
and \Bigg commands. These may be either prepended to a delimiting
symbol with “l” and “r” suffixes, or passed as an optional argument to a
declared delimiter.
\DeclarePairedDelimiter{%
\set}{\{}{\}}
\( \bigl[ \ddagger \Biggr) \)
[‡) {1, 34 }
\( \set[\Big]{1,\frac{3}{4}} \)
\begin{equation}
a = b + c + d + e + f
+ g + h + i + j 𝑎 = 𝑏+𝑐+𝑑+𝑒+𝑓+𝑔+ℎ+𝑖+𝑗+𝑘+𝑙+𝑚+𝑛+𝑜+𝑝
+ k + l + m + n + o + p (1)
\end{equation}
\begin{multline}
a + b + c + d + e
+ f + g + h + i \\ 𝑎+𝑏+𝑐+𝑑+𝑒+𝑓 +𝑔+ℎ+𝑖
= j + k + l + m + n
= 𝑗 + 𝑘 + 𝑙 + 𝑚 + 𝑛 (1)
\end{multline}
The first line in multline environment is aligned to the left, and the last
one to the right, while all the others are centred.
\begin{multline}
a + b + c + d + e \\ 𝑎+𝑏+𝑐+𝑑+𝑒
+ f + g + h + i \\
= j + k + l + m + n +𝑓 +𝑔+ℎ+𝑖
\end{multline} = 𝑗 + 𝑘 + 𝑙 + 𝑚 + 𝑛 (1)
If you do not want some particular inner line centred, you can use
\shoveleft and \shoveright commands to force the line to be left or
right aligned.
\begin{multline}
a + b + c \\ 𝑎+𝑏+𝑐
\shoveleft{+ d + e + f} \\
\shoveright{+ g + h + i} \\
+𝑑+𝑒+𝑓
= j + k + l + m + n +𝑔+ℎ+𝑖
\end{multline} = 𝑗 + 𝑘 + 𝑙 + 𝑚 + 𝑛 (1)
Use the gather environment to eliminate the extra space. It allows you
to break lines using the \\ command, and centres each equation.
\begin{gather}
2 + 2 = 4 \\ 2+2=4 (1)
2 \times 2 = 4 \\
2 + 2 \times 2 = 6 2×2=4 (2)
\end{gather} 2+2×2=6 (3)
\begin{gather}
2 + 2 = 4
\tag{Easy}\label{easy} \\ 2+2=4 (Easy)
2 \times 2 = 4 \notag \\
2 + 2 \times 2 = 6 2×2=4
\label{hard} 2+2×2=6 (1)
\end{gather}
Note:~\eqref{easy} is easier Note: (Easy) is easier than (1).
than~\eqref{hard}.
The above example also illustrates that the centring of the equations
inside the environment may depend upon the length of the tag. Keep
this in mind if your tags and/or equations get long.
As always, the starred version of the environment, gather*, sup-
presses all equation numbers.
\begin{align}
2 + 2 & = 2 \times 2 \\ 2+2=2×2 (1)
3 + 3 & \neq 3 \times 3 \\
2 + 2 \times 2 & < 8 3+3≠3×3 (2)
\end{align} 2+2×2<8 (3)
\begin{align}
a & \succeq b & c & \leq d \\
𝑎⪰𝑏 𝑐≤𝑑 (1)
a & \geq d & d & \prec c
\end{align} 𝑎≥𝑑 𝑑≺𝑐 (2)
𝑛 𝑛−1
\begin{align}
\sum_{k=0}^n k ∑𝑘 = ∑𝑘 + 𝑛 (1)
&= \sum_{k=0}^{n-1} k + n \\ 𝑘=0 𝑘=0
&= \frac{n(n-1)}{2} + n \\ 𝑛(𝑛 − 1)
= +𝑛 (2)
&= \frac{n(n+1)}{2} 2
\end{align} 𝑛(𝑛 + 1)
= (3)
2
\begin{align*}
\sum_{k=0}^n k 𝑛 𝑛−1
&= \sum_{k=0}^{n-1} k + n ∑𝑘 = ∑𝑘 + 𝑛 definition
&& \text{definition} \\ 𝑘=0 𝑘=0
&= \frac{n(n - 1)}{2} + n 𝑛(𝑛 − 1)
&& \text{induction} \\ = + 𝑛 induction
&= \frac{n(n + 1)}{2} 2
&& \text{trivial} 𝑛(𝑛 + 1)
= trivial
\end{align*} 2
\begin{align}
a + b + c
&= d + e + f \nonumber \\ 𝑎+𝑏+𝑐=𝑑+𝑒+𝑓
& \phantom{=}\ + g + h
+𝑔+ℎ
\nonumber \\
& \phantom{=}\ + i \\ +𝑖 (1)
&= j + k + l =𝑗+𝑘+𝑙 (2)
\end{align}
All the environments presented above can be used inside other equations
by appending “-ed” to their name. They no longer number the equations
inside them, and accept an optional vertical positioning argument, with
the same semantics as those accepted by tabular (see Section 2.18 on
page 53).
\[
\begin{multlined}[t]
1 + 2 \\
+ 3 + 4
\end{multlined} =
\begin{gathered}[c]
1 + 2 \\ 1+2
1+2
+ 3 + 4 1+2 = = +3+4
\end{gathered} = +3 + 4
+3+4
\begin{aligned}[b]
1 & + 2 \\
& + 3 + 4
\end{aligned}
\]
These are useful if you want to, for example, break an equation into
multiple lines with alignment, but still retain only a single equation
number.
\begin{equation}
\begin{aligned}
2 + 2 \times 2 2+2×2=2×2+2
&= 2 \times 2 + 2 \\ (1)
&\neq 2 \times (2 + 2) \\ ≠ 2 × (2 + 2)
\end{aligned}
\end{equation}
3.4 Multiline Equations 95
\begin{IEEEeqnarray}{rCl}
a & = & b + c \\ 𝑎=𝑏+𝑐 (1)
& = & d + e + f + g + h \\
& = & i + j + k =𝑑+𝑒+𝑓 +𝑔+ℎ (2)
\end{IEEEeqnarray} =𝑖+𝑗+𝑘 (3)
\begin{IEEEeqnarray}{rCl}
a & = & b + c \\
& = & d + e + f 𝑎=𝑏+𝑐 (1)
+ g + h + i + j
\IEEEeqnarraynumspace \\ = 𝑑 + 𝑒 + 𝑓 + 𝑔 + ℎ + 𝑖 + 𝑗 (2)
& = & k + l + m + n. = 𝑘 + 𝑙 + 𝑚 + 𝑛. (3)
\end{IEEEeqnarray}
\begin{IEEEeqnarray}{rCl}
\IEEEeqnarraymulticol{3}{l}{
a + b + c + d = e + f 𝑎+𝑏+𝑐+𝑑 =𝑒+𝑓 (1)
} \\
e + f & = & g + h \\ 𝑒+𝑓=𝑔+ℎ (2)
& = & i + j + k + l + m = 𝑖 + 𝑗 + 𝑘 + 𝑙 + 𝑚 (3)
\end{IEEEeqnarray}
\begin{IEEEeqnarray*}{rCl}
a & = & b + c \\ 𝑎=𝑏+𝑐
& = & d + e \IEEEyesnumber\\
& = & f + g =𝑑+𝑒 (1)
\end{IEEEeqnarray*} =𝑓 +𝑔
\begin{IEEEeqnarray}{rCl}
a & = & b + c \\
& = & d + e \notag \\ 𝑎=𝑏+𝑐 (1)
& = & f + g =𝑑+𝑒
\IEEEyessubnumber
\end{IEEEeqnarray} =𝑓 +𝑔 (1a)
\begin{IEEEeqnarray*}{rCl}
a & = & b + c + d \\ 𝑎=𝑏+𝑐+𝑑
& & + e \quad \text{too narrow!}\\
& & \negmedspace{} + e \\
+𝑒 too narrow!
& = & f + 2e +𝑒
\end{IEEEeqnarray*} = 𝑓 + 2𝑒
3.5 Units
When dealing with real world data, you will often find yourself writing
units such as 10 kg or 25 C mol−1 . In technical writing, it is crucial to
accurately convey values to avoid errors and ambiguity. The International
System of Units (SI ) [54], comes with a detailed set of typesetting rules.
For example, you may have noticed that in the first sentence the space
between 10 and kg is smaller than between the words.
Fortunately, thanks to the logical nature of LATEX markup and the
excellent siunitx [86] package, you do not need to know most of the rules.
Just use the special unit-commands provided by the package, and all the
units in your document will be typeset correctly.
This may look fine initially, but if your document gets longer you will
probably get into a situation where an unfortunate line break occurs.
A non-breaking space will fix this problem, but the next one is already
waiting—the space between numbers. Digits of long numbers should be
grouped to make them easier to read. The above example should then
be written like this:
Yet another challenge arises when trying to write the units inside math
mode
\(10~\frac{m}{s} 10 𝑚
× 12 𝑠 = 120 𝑚
\times 12~s = 120~m\) 𝑠
Here we need to make sure that the units are written in roman font. The
above example should be then written as
\(10~\frac{\textrm{m}}
{\textrm{s}} 10 m
× 12 s = 120 m
\times 12~\textrm{s} s
= 120~\textrm{m}\)
Hopefully, these examples illustrate why a better method is needed.
\unit{\kilo\gram} is a unit,
\qty{10}{\metre\per\second} kg is a unit, 10 m s−1 is a quantity
is a quantity
At first glance this may seem less convenient, but this enables the package
to recognize the logical structure of the units, which means that the
formatting can be changed on the fly.
kg m
Which one do you prefer: N = kg m s−2 , N = s2 or
N = kg m/s2 ?
\unit{\kg\of{mol}}, kgmol , Bi
\unit{\bel\of{i}}
Note that the \per command only works on the next unit by default.
If we want it to apply to all following units, we may use sticky-per
option.
Sometimes, you may want to make the units use a different colour,
so they figure more prominently. This can be done using unit-color.
Options number-color and color may be used to colour only the numeric
100 Typesetting Mathematical Formulae
Now let’s turn our attention to numbers. Numeric values will always
use dot as a decimal separator, regardless of the symbol entered. If
you want to use comma as the decimal separator, change the output-
decimal-marker option.
\(\cpi \approx \num{3.14159}\)
\(\cpi \approx \num{3,14159}\) π ≈ 3.141 59
\(\cpi \approx \num[ π ≈ 3.141 59
output-decimal-marker={,} π ≈ 3,141 59
]{3.14159}\)
Numbers may also be entered using exponent notation. The symbols
before the exponent and base may be controlled using exponent-product
and exponent-base options
\(\qty{1}{\tonne}
= \qty{1e6}{\g}\) \\
\(\qty{1}{\gibi\byte} = \qty[
1 t = 1 × 106 g
exponent-base = 2,
]{1e30}{\byte}\) \\ 1 GiB = 1 × 230 B
\(\qty{1}{\L} = \qty[ 1 L = 1 ⋅ 10−3 m3
exponent-product = \cdot,
]{1e-3}{\cubic\m}\)
If we want all numbers to be formatted in exponent notation, regard-
less of their entered form, we may use the exponent-mode option.
\(2^{16} = \num{65536}\) \\
\(2^{16} = \num[
exponent-mode = scientific,
]{65536}\) \\
\(2^{16} = \num[ 216 = 65 536
exponent-mode = engineering,
216 = 6.5536 × 104
]{65536}\) \\
\(2^{16} = \num[ 216 = 65.536 × 103
exponent-mode = fixed, 216 = 65 536
]{65.536e3}\) \\ 216 = 0.655 36 × 105
\(2^{16} = \num[
exponent-mode = fixed,
fixed-exponent = 5,
]{65.536e3}\)
3.5 Units 101
\(M_{\oplus} = \qty{
5.9722(6) e24}{\kg}\)
\(M_{\oplus} = \qty{
5.9722 +- 0.0006 e24}{\kg}\) 𝑀⊕ = 5.9722(6) × 1024 kg
\(M_{\oplus} = \qty{ 𝑀⊕ = 5.9722(6) × 1024 kg
5.9722 \pm 0.0006 e24}{\kg}\)
\(M_{\oplus} = \qty[
𝑀⊕ = 5.9722(6) × 1024 kg
uncertainty-mode = separate 𝑀⊕ = (5.9722 ± 0.0006) × 1024 kg
]{5.9722(6) e24}{\kg}\) 𝑀⊕ = 5.9722(0.0006) × 1024 kg
\(M_{\oplus} = \qty[
uncertainty-mode = full
]{5.9722(6) e24}{\kg}\)
\qty{1}{\degreeCelsius} is
equal to \qty{1}{\kelvin},
but \qty[
mode = text, 1 °C is equal to 1 K, but 0 °C is
]{0}{\degreeCelsius} is \qty[ −273.15 K. Bizarre, isn’t it?
mode = text,
]{-273.15}{\kelvin}.
Bizarre, isn't it?
\sisetup{〈options〉}
\documentclass{article}
\usepackage{booktabs}
\usepackage[per-mode = fraction, unit-color = red]{siunitx}
\begin{document}
Units are typeset like this: \qty{9.81}{\m\per\s\squared}.
\begin{table}[h]
\centering
\sisetup{exponent-mode = fixed, fixed-exponent = 1}
\begin{tabular}{@{}lr@{}}
\toprule
No. & Result (\unit{\kg}) \\
\midrule
1 & \num{12.3} \\
2 & \num{0.3} \\
3 & \num{1e2} \\
\bottomrule
\end{tabular}
\caption{Measurement results.
Here custom options are used.}\label{table}
\end{table}
1
Listing 3.1: An example of using siunitx in a document.
3.5 Units 103
The conjugate of
\complexnum{2+3i} is The conjugate of 2 + 3i is
\complexnum{2-3i} 2 − 3i which is approximately
which is approximately
\complexnum{3.6056:-56.310}. \\
3.6056∠−56.310°.
Why is my scale showing my Why is my scale showing my
weight is weight is (65 + 21i) kg?
\complexqty{65+i21}{\kg}?
\DeclareSIUnit[〈options〉]{〈unit〉}{〈symbol〉}
command. The 〈unit〉 is the macro we will use in the interpreted mode,
while the 〈symbol〉 is the typeset symbol. The 〈options〉 allow us to define
defaults concerning, for example, the spacing of the unit in quantities.
\DeclareSIUnit{\pt}{pt}
The default font size in LATEX is
The default font size
in \LaTeX{} is \qty{10}{\pt}. 10 pt.
This command may also be used when we want to adjust the appear-
ance of a predefined unit. For example, the default litre is typeset using
uppercase ‘L’, but you may want to change to lowercase ‘l’, instead.
\DeclareSIPrefix
\DeclareSIPower
\DeclareSIQualifier
allow definition of unit-related macros in case additional are needed.
\DeclareSIUnit{\pt}{pt}
\DeclareSIPower{\quartic}{\tothefourth}{4}
\DeclareSIPrefix{\decakilo}{dk}{4}
\DeclareSIQualifier{\polymer}{pol}
\begin{tabular}{@{}lS@{}}
\toprule
Day & {Candy eaten (\unit{\g})} \\
\midrule
Monday & .3011 \\
Tuesday & 54.86 \\
Wednesday & 1000.9722 \\
Thursday & -1000.9722 \\
\bottomrule
\end{tabular}
\sisetup{exponent-mode = fixed}
\begin{tabular} {@{}SS@{}}
\toprule
{\unit{\ug}} & {\unit{\kg}} \\
\midrule
1 & 1e-9 \\
0.2 & 2e-10 \\
35 & 35e-8 \\
-100 & -1e-7 \\
\bottomrule
\end{tabular}
µg kg
1 0.000 000 001
0.2 0.000 000 000 2
35 0.000 000 35
−100 −0.000 000 1
\sisetup{exponent-mode = fixed}
\begin{tabular} {
@{}
S[table-format = +3.1]
S[table-format = +1.10]
@{}
}
\toprule
\multicolumn{2}{c}{Weight} \\
\midrule
{\unit{\ug}} & {\unit{\kg}} \\
\midrule
1 & 1e-9 \\
0.2 & 2e-10 \\
35 & 35e-8 \\
-100 & -1e-7 \\
\bottomrule
\end{tabular}
Weight
µg kg
1 0.000 000 001
0.2 0.000 000 000 2
35 0.000 000 35
−100 −0.000 000 1
\begin{tabular} {
@{}
S[
table-format = 2.1(1.1),
table-number-alignment = left,
uncertainty-mode = separate,
]
S[
table-format = 2.2e2{ big!},
table-text-alignment = right,
]
@{}
}
\toprule
{Confidence (\unit{\percent})}
& {Value} \\
\midrule
57.1(2) & 10e2 \\
25.3(0) & 2e-1 \\
0(0.1) & 99.99e99{ big!} \\
92(1) & 7.2e10 \\
\bottomrule
\end{tabular}
Listing 3.6: An example of aligning text and numbers inside the siunitx’s
S column.
110 Typesetting Mathematical Formulae
\sisetup{table-format = 4.4e1}
\begin{tabular}{@{}lr@{}}
\toprule
Candy & Friend \\
\midrule
Chocolate & Peter \\
Lollipop & Jane \\
\multicolumn{2}{c}{\tablenum{12,34 e0}} \\
\multicolumn{2}{c}{\tablenum{333.5567 e1}} \\
\multicolumn{2}{c}{\tablenum{4563.21 e2}} \\
\bottomrule
\end{tabular}
Candy Friend
Chocolate Peter
Lollipop Jane
12.34
333.5567 × 101
4563.21 × 102
\sisetup{
table-alignment-mode = none,
output-decimal-marker = {,},
unit-color = red,
}
\begin{tabular}{@{}cS@{}}
Variable Value
\toprule foo 101,892
Variable & {Value} \\ bar 2 × 10−1
\midrule
baz 2,1 kg
foo & 101.892 \\
bar & 2e-1 \\
baz & \qty{2.1}{\kg} \\
\bottomrule
\end{tabular}
\( \left[
\begin{matrix}
1 & 2 \\ 1 2
3 & 4 \\
[ ]
3 4
\end{matrix}
\right] \)
Because matrices are usually delimited, there are five additional
versions that simply surround the matrix contents within delimiters.
These are
pmatrix that uses parentheses as delimiters: ( 13 24 ).
bmatrix that uses brackets as delimiters: [ 13 24 ].
Bmatrix that uses braces as delimiters: { 13 24 }.
vmatrix that uses vertical lines as delimiters: ∣ 13 24 ∣.
Vmatrix that uses double vertical lines as delimiters: ∥ 13 24 ∥.
Matrices created using these environments are rather large, because
they are meant to be typeset in display math. If for some reason you
want to typeset a matrix within text, you may get better results with the
smallmatrix environment. Note that there are no delimited variants, so
you must provide any delimiters yourself.
Compare \(
\begin{matrix}
1 & 2 \\
3 & 4 \\
\end{matrix} 1 2
\) with \( Compare with 12
34
\begin{smallmatrix}
3 4
1 & 2 \\
3 & 4 \\
\end{smallmatrix}
\)
The matrix environment could also be used to typeset piecewise
functions, by using the . character as an invisible \right delimiter in
conjunction with a left brace. However, a much better alternative is the
cases environment. Its contents are left aligned, and the delimiters are
already provided.
\[
\lvert x \rvert =
\begin{cases} ⎧−𝑥 if 𝑥 < 0,
-x & \text{if } x < 0, \\ {
0 & \text{if } x = 0, \\
|𝑥| = ⎨0 if 𝑥 = 0,
x & \text{if } x > 0. {𝑥 if 𝑥 > 0.
⎩
\end{cases}
\]
112 Typesetting Mathematical Formulae
If you need more control over the alignment of the individual columns,
you may also use the array environment. It accepts the column specifier,
just like tabular, but typesets its contents in math mode. Note that it
introduces a bit more spacing compared to the matrix environments.
\[
\begin{array}{rcl}
12 & 1 & 21 \\ 12 1 21
1 & 22 & 101 \\ 1 22 101
\end{array}
\]
Another good example is the difference between the vertical bar symbol,
|, as compared to the \lvert and \rvert commands. The former is a
symbol, while the latter are commands suitable for delimiting expressions.
Class commands should not be used throughout the body of the
document. If you want to use a new symbol (for example, an image) or
3.7 Spacing in Math Mode 113
\NewDocumentCommand{\modulo}{}{%
\mathbin{\%}%
}
17 % 3 = 2
\( 17 \modulo 3 = 2 \)
\mspace{〈width〉}
The 〈width〉 is specified using a special unit “mu”, which is roughly equal
to 1⁄18 of the width of letter “M” in the current math font.5
\( 1 \mspace{18mu} 2 \)
\textinterrobang{} vs.\
1 2
\( ? \mspace{-7mu} ! \) ‽ vs. ?!
There also exist predefined synonyms for the values most commonly used.
These are presented in Table 3.5 and are usually sufficient when creating
114 Typesetting Mathematical Formulae
\NewDocumentCommand{\ud}{}{%
\,\symrm{d}%
𝑏
}
\[
∫ 𝑓(𝑥) d𝑥
𝑎
\int_a^b f(x)\ud x
\]
Negative spaces can also be used if you want to create your own
mathematical symbols by overlaying existing ones.
\NewDocumentCommand{\myrel}{}{
\mathrel{
-\mspace{-11mu}
\infty{} 𝑥−
∞−𝑦
\mspace{-11mu}-
}
}
\( x \myrel y \)
3.7.3 Phantoms
In some situations, it may be useful to insert the space that would
normally be occupied by some existing symbol. While you could eyeball
5
Units are explained in more detail in subsection 7.5.1.
3.8 Theorems and Proofs 115
\phantom{〈text〉}
\vphantom{〈text〉}
\hphantom{〈text〉}
Each of these typesets an invisible box that has dimensions equal to the
text that it received as an argument. The \vphantom has zero width,
while the \hphantom has zero height.
For example, when creating left superscripts and subscripts, they will
be aligned to the left, since they actually apply to the previous (empty)
symbol. A simple fix would be to pad the space using appropriate
phantom. In the real world, it would be better to use the \prescript
command from the mathtools package.
\( {}^{14}_{6}A \) vs.\
\( \prescript{14}{6}A \) vs.\ 14
6 𝐴 vs. 14
6𝐴 vs. 14
6𝐴
\( {}^{14}_{\phantom{1}6}A \)
\begin{multline*}
f(a, b) = \left(
\int_a^b f(x)
loooooong
\right. \\ 𝑏
\left. 𝑓(𝑎, 𝑏) = (∫ 𝑓(𝑥)𝑙𝑜𝑜𝑜𝑜𝑜𝑜𝑛𝑔
\vphantom{ 𝑎
\int_a^b f(x)
loooooong 𝑠ℎ𝑜𝑟𝑡 d𝑥)
}
short \ud x
\right)
\end{multline*}
\newtheorem{〈name〉}[〈counter〉]{〈caption〉}[〈section〉]
\begin{〈name〉}[〈title〉]
This is my interesting theorem
\end{〈name〉}
The optional 〈title〉 argument can be used to locally typeset the theorem
name next to the caption.
\newtheorem{proposition}{Proposition}
% ... Proposition 1 I propose
\begin{proposition} that this should be enough of
I propose that this should dummy text.
be enough of dummy text.
\end{proposition} Proposition 2 (More) It
\begin{proposition}[More] is not enough for more than
It is not enough for more one proposition.
than one proposition.
\end{proposition}
1
The amsthm [3] package provides the
\theoremstyle{〈style〉}
\usepackage{amsthm}
\theoremstyle{definition}
\newtheorem{axiom}{Axiom}[section]
\theoremstyle{plain} 1 First
\newtheorem{theorem}[axiom]{Theorem}
\theoremstyle{remark} Axiom 1.1 (Uncertainty).
\newtheorem*{remark}{Remark} Nothing is certain.
% ...
\section{First} Theorem 1.2. It is uncer-
\begin{axiom}[Uncertainty] tain whether this theorem is
Nothing is certain. true.
\end{axiom} Remark (Other things).
\begin{theorem} Other things are probably
It is uncertain whether
also uncertain.
this theorem is true.
\end{theorem}
\begin{remark}[Other things]
Other things are
probably also uncertain. 1
\end{remark}
\begin{proof}
Trivial. Proof. Trivial.
\end{proof}
The QED symbol ( ) is put at the end of the last line in the environment.
This may create unnecessary lines if the proof does not end with a
paragraph.
\begin{proof}
Trivial, use Proof. Trivial, use
\[ E=mc^2. \qedhere \]
\end{proof} 𝐸 = 𝑚𝑐2 .
If you do not like the default symbol, you can redefine the \qedsymbol
macro to your liking.
\RenewDocumentCommand{%
\qedsymbol}{}{QED}
\begin{proof}
Trivial.
\end{proof} Proof. Trivial. QED
\RenewDocumentCommand{%
Proof. Trivial. ∎
\qedsymbol}{}{\(\QED\)}
\begin{proof}
Trivial.
\end{proof}
Command Example
∞
\displaystyle ∑ 𝐴𝐵𝐶𝑎𝑏𝑐123
𝑘=0
\textstyle ∑∞
𝑘=0
𝐴𝐵𝐶𝑎𝑏𝑐123
\scriptstyle ∞
∑𝑘=0 𝐴𝐵𝐶𝑎𝑏𝑐123
\scriptscriptstyle ∑∞
𝑘=0 𝐴𝐵𝐶𝑎𝑏𝑐123
\[
\frac
{\frac 1
2
{\frac{1}{2}} 2
{2}} 2
{2}
\]
If you want to prevent this, use the appropriate command in its argu-
ments.
\[
\frac 𝑛
{\displaystyle ∑(𝑥𝑘 − 𝑥)2
\sum_{k=1}^n (x_k - x)^2} 𝑘=1
{\displaystyle 𝑛 2
\left(
(∑(𝑥𝑘 − 𝑥))
\sum_{k=1}^n (x_k - x)
𝑘=1
\right)^2}
\]
When typesetting formulae within text, you may enclose tall or deep
math expressions, or sub-expressions, within \smash. This makes LATEX
ignore the height of these expressions and keeps the line spacing even,
but risks overlap with the surrounding text.
A \(d_{e_{e_p}}\) mathematical
expression followed by a
A 𝑑𝑒𝑒 mathematical expression
\(h^{i^{g^h}}\) expression. 𝑝
As opposed to a smashed 𝑔ℎ
followed by a ℎ𝑖 expression. As
\smash{\(d_{e_{e_p}}\)} opposed to a smashedℎ𝑑𝑒𝑒 expres-
expression followed by a
sion followed by a ℎ𝑖 expression.
𝑔 𝑝
\smash{\(h^{i^{g^h}}\)}
expression.
120 Typesetting Mathematical Formulae
\( \sqrt{x}
+ \sqrt{y}
+ \sqrt{z}\) √ √ √ √ √
√
vs.\ 𝑥+ 𝑦+ 𝑧 vs. 𝑥 + 𝑦 + 𝑧
\( \sqrt{x}
+ \sqrt{\smash[b]{y}}
+ \sqrt{z} \)
3.10 Dots
Use the \dots command to omit an easily deduced part of a mathematical
expression, like 0, 1, 2, … to indicate the sequence of all natural numbers.
It attempts to adjust its output based on the surrounding symbols.
\dotsb for dots between binary operators or relations (1 < 2 < ⋯ < 100)
You can also redefine the above wrappers if the version chosen by LATEX
is not to your liking. By default, all of these commands choose between
\ldots, for dots on baseline, and \cdots, for centred dots.
\RenewDocumentCommand{%
\dotsb}{}{\ldots} 1 + 2 + 3 + … + 100
\( 1 + 2 + 3 + \dotsb + 100 \)
3.11 More About Fractions 121
\[ \begin{bmatrix}
a_{1,1} & \cdots & a_{1,n} \\ 𝑎1,1 ⋯ 𝑎1,𝑛
\vdots & \ddots & \vdots \\ ⎡ ⋮ ⋱ ⋮ ⎤
⎢ ⎥
a_{m,1} & \cdots & a_{m,n} \\ ⎣𝑎𝑚,1 ⋯ 𝑎𝑚,𝑛 ⎦
\end{bmatrix} \]
1
vs.
\( \frac{1}{2} \) vs.\ 2
1
\[ \frac{1}{2} \]
2
\( \dfrac{1}{2} \) vs.\ 1
\( \tfrac{1}{2} \)
vs. 1
2
2
\[ \dfrac{1}{2}\text{ vs.\ } 1
\tfrac{1}{2} \]
vs. 1
2
2
When writing the fractions in-line, often the slashed form 1/2 is
preferable for small fractions. You may also want to use the xfrac [26]
package and the \sfrac command it provides to typeset them in a
slashed form with smaller numbers.
\( \frac{1}{2} \) vs.\
\sfrac{1}{2} vs.\ 1
2 vs. 1⁄2 vs. 1/2 vs. ½
\( 1/2 \) vs.\ \textonehalf{}
If you have tried writing continued fractions, you may have noticed
that the spacing is not ideal. The amsmath package defines a special
\cfrac command to fix this issue.
\[
\dfrac{1}{ 1
1 + \dfrac{1}{ 1
1 + \dfrac{1}{ 1+
1
1 + \dotsb}}} 1+
\] 1+⋯
vs.\ vs.
\[ 1
\cfrac{1}{ 1
1 + \cfrac{1}{ 1+
1 + \cfrac{1}{ 1
1+
1 + \dotsb}}} 1+⋯
\]
Binomial coefficients can be typeset using the \binom, \tbinom and
\dbinom commands. These work the same as the \frac, \tfrac and
\dfrac commands.
\[
𝑛
\sum_{k=0}^{n} \binom{n}{k} 𝑛
∑ ( ) = 2𝑛
= 2^{n} 𝑘
𝑘=0
\]
You should avoid using \genfrac inside the body of the document, and
always define logical wrappers if you intend to use it in multiple places.
Chapter 4
Bibliographies
When writing articles or books concerned with some topic you will often need
to reference other books and articles to point out where some information
might be found. You have already seen this done multiple times throughout
this book. Doing this by hand would be tedious, so LATEX comes with an
option to manage the bibliographic data of our document.
\bibitem[〈label〉]{〈marker〉}
The 〈marker〉 is then used to cite the book, article, or paper within the
document.
\cite{〈marker〉}
If you do not use the 〈label〉 option, the entries will get enumerated
automatically. The parameter after the \begin{thebibliography} com-
mand defines how much space to reserve for the number of labels. In the
126 Bibliographies
example below, {99} tells LATEX to expect that none of the bibliography
item numbers will be wider than the number 99.
1
In order to get the citations typeset properly, two passes of LATEX
compiler are needed similar to how tables of contents are done.
This approach has the advantage that it is simple and entirely self-
contained—no external packages and programs are needed since it is
supported out of the box by LATEX. There are however many problems:
• If you want to use different citation style than numeric, you have
to manually set all the labels.
For all projects that contain more than few citations biblatex is strongly
recommended.
@〈entry type〉{〈marker〉,
〈field1〉 = {〈value1〉},
〈field2〉 = {〈value2〉},
〈field3〉 = {〈value3〉},
⋮
}
The fields required depend on the bibliography style you choose, the
default style of biblatex will accept the following 〈entry type〉s:
book for single-volume book. With the fields author, title, date,
publisher, volume.
online for accessed online resources. With author, title, date, url,
urldate.
misc for entries that do not fit any of the predefined categories. With
author, title, date, howpublished, note.
Note that the above list is far from exhaustive both in terms of 〈entry
type〉s and the field names mentioned. For a full list check the biblatex
manual or the style you are using.
Each .bib file will typically contain multiple entries. See Listing 4.1
for an example.
\usepackage[〈options〉]{biblatex}
command. The 〈options〉 are comma delimited key value pairs that allow
to customise the behaviour of biblatex package. Some of them will be
explained later.
128 Bibliographies
@book{lshort,
title = {The Not So Short Introduction to \LaTeXe},
author = {Tobias Oetiker and Hubert Partl
and Irene Hyna and Elisabeth Schlegl},
date = {2021-03-09},
version = {6.4},
url = {https://www.ctan.org/pkg/lshort-english}
}
@article{curie,
title = {Les nouvelles substances radioactives},
author = {Curie, Marie},
year = {1900},
journaltitle = {Revue scientifique},
series = {4},
volume = {14},
number = {3}
}
@misc{dream,
title = {Yesterday's dream},
howpublished = {The vision came to me while I was sleeping},
note = {It was very vivid},
author = {Jane Diviner},
date = {3012-07-19},
keywords = {dreamy, unreliable}
}
The command
\addbibresource[〈options〉]{〈file〉}
must be put in the preamble. The 〈file〉 is the name of the .bib file
containing bibliographic entries. You may also specify a remote location
here, but then you must also put location=remote in the 〈options〉.
Finally the
\printbibliography[〈options〉]
typesets the loaded bibliography. The 〈options〉 may be used to alter the
title or filter the entries included.
Processing files requires three LATEX passes in addition to the biber
command. A typical command line run may look like this:
$ xelatex document.tex
$ biber document
$ xelatex document.tex
$ xelatex document.tex
The first LATEX pass extracts the citation data from the document which
are then read by biber. In the second pass, the bibliography is placed in
the document and the third pass finally typesets the document with all
the correct citations.
Listing 4.2 is a complete example that shows how the bits work
together. In this and all the following examples, the example.bib file is
assumed to be the same as in the Listing 4.1.
1
130 Bibliographies
\documentclass{article}
\usepackage{biblatex}
\addbibresource{example.bib}
\begin{document}
\ldots{} Recently I was learning to use Bib\LaTeX{}
from~\cite{lshort}. It seems very useful. \ldots
\printbibliography
\end{document}
References
[1] Marie Curie. “Les nouvelles substances radioactives”. In:
Revue scientifique. 4th ser. 14.3 (1900).
[2] Jane Diviner. Yesterday’s dream. The vision came to me
while I was sleeping. It was very vivid. July 19, 3012.
[3] Tobias Oetiker et al. The Not So Short Introduction to
LATEX 2ε . Mar. 9, 2021. url: https://www.ctan.org/
pkg/lshort-english.
1
Listing 4.2: An example of using biblatex to manage references in an
article
4.2 biblatex with biber 131
While the default citation style is numeric, this can be easily changed
by setting the preferred style via the 〈style〉 option. Choose from
alphabetic, authoryear, authortitle or verbose. Some styles come
in several variations.
% ...
References
[Cur00] Marie Curie. “Les nouvelles
The validity of~\cite{dream} substances radioactives”. In:
as a scientific source was Revue scientifique. 4th ser.
recently called into question 14.3 (1900).
though it correctly claims
that polonium was first [Div12] Jane Diviner. Yesterday’s
described in~\cite{curie}. dream. The vision came to
me while I was sleeping. It
was very vivid. July 19, 3012.
References
I've only [1] Marie Curie. “Les nouvelles sub-
cited~\cite{lshort}. stances radioactives”. In: Revue sci-
entifique. 4th ser. 14.3 (1900).
\nocite{*} [2] Jane Diviner. Yesterday’s dream. The
\printbibliography vision came to me while I was sleep-
ing. It was very vivid. July 19, 3012.
[3] Tobias Oetiker et al. The Not
So Short Introduction to LATEX 2ε .
Mar. 9, 2021. url: https : / / www .
ctan.org/pkg/lshort-english.
1
132 Bibliographies
1
By default, the bibliography does not appear in the table of con-
tents. This is because it is using starred version of \chapter/\section
(depending on the class) to generate its heading. In order to change
the default we may pass the option heading to \printbibliography.
Available options include
bibnumbered will use non starred version for heading, thus numbering
it and appearing in table of contents
subbibintoc will drop the bibliography one level and put it in table of
contents
subbibnumbered will drop the bibliography one level and use non starred
version of heading
Contents
\tableofcontents 1 Important section 1
\section{Important section}
2 Other 1
% ... 2.1 Bibliography . . . . . . . . 1
\section{Other}
1 Important section
\printbibliography[
heading=subbibnumbered, 2 Other
title=Bibliography,
] 2.1 Bibliography
% ... [1] Marie Curie. “Les nouvelles sub-
stances radioactives”. In: Revue sci-
entifique. 4th ser. 14.3 (1900).
1
As you may have noticed, when entries have many authors, then not
all of them will be printed; instead “et al.” shows up at the end of the
author list. This behaviour may be controlled via maxnames (default 3)
and minnames (default 1) options. If the number of names is greater
than 〈maxnames〉 then it will be shortened to 〈minnames〉 and “et al.”
will be added.
1
4.2.4 Citing commands
Until now we have only used the basic \cite command. biblatex extends
the command set to allow extra control with citations.
134 Bibliographies
\usepackage[
This is auto citation.1
style=verbose,
autocite=footnote,
]{biblatex}
1
4.2 biblatex with biber 135
\usepackage[
style=authoryear, This is auto citation (Curie
autocite=inline,
1900).
]{biblatex}
% ...
1
4.2.5 More about entries
biber uses “and” as a separator in certain entries. To prevent this
behaviour, enclose “and” in curly brackets
@book{kru,
publisher = {Kruger {and} sons}
}
The same trick may be useful when biber changes capitalisation, even
though it shouldn’t. On top of this biber splits author entries into smaller
bits which are then used elsewhere. So in Listing 4.1 the name Jane
Diviner is split into the first name Jane and the surname Diviner. When
you don’t want this, enclose the entire name in braces
@book{kru,
author = {{Kruger brothers}}
}
When writing about certain subject it often happens that the same
author or publishing company released several books. In order to reuse
the information in several entries in the .bib file, a special entry xdata
is available. It may be used like this
@xdata{krugers,
author = {{Kruger brothers}}, References
publisher = {Kruger {and} sons},
location = {Paris} [1] Kruger brothers. LATEX
} is awesome! Paris:
Kruger and sons, 2022.
@book{kru21, [2] Kruger brothers. Why is
title = {Why is \LaTeX{} so hard?}, LATEX so hard? Paris:
year = {2021}, Kruger and sons, 2021.
xdata = {krugers}
}
@book{kru22,
title = {\LaTeX{} is awesome!},
year = {2022},
xdata = {krugers}
}
1
Chapter 5
Specialities
When putting together a large document, LATEX will help with some special
features like index generation, automatic linking to relevant pages and other
things. A much more complete description of specialities and enhancements
possible with LATEX can be found in the LATEX Manual [42] and The LATEX
Companion [48].
5.1 Indexing
A very useful feature of many books is their index. With LATEX and the
support program makeindex,1 an index can be generated quite easily.
This introduction will only explain the basic index generation commands.
For a more in-depth view, please refer to The LATEX Companion [48].
To enable the indexing feature of LATEX, the makeidx package must
be loaded in the preamble with
\usepackage{makeidx}
and the special indexing commands must be enabled by putting the
\makeindex
command in the preamble.
The content of the index is specified with
\index{〈key〉@〈formatted entry〉}
commands, where 〈formatted entry〉 will appear in the index and 〈key〉
will be used for sorting. The 〈formatted entry〉 is optional. If it is missing
the 〈key〉 will be used. You enter the index commands at the points
in the text that you want the final index entries to point to. Table 5.1
explains the syntax with several examples.
1
On systems not necessarily supporting filenames longer than 8 characters, the
program may be called makeidx.
138 Specialities
When the input file is processed with LATEX, each \index command
writes an appropriate index entry, together with the current page number,
to a special file. The file has the same name as the LATEX input file, but
a different extension (.idx). This .idx file can then be processed with
the makeindex program:
makeindex filename
The makeindex program generates a sorted index with the same base
file name, but this time with the extension .ind. If now the LATEX input
file is processed again, this sorted index gets included into the document
at the point where LATEX finds
\printindex
The showidx package that comes with LATEX prints out all index
entries in the left margin of the text. This is quite useful for proofreading
a document and verifying the index. Make sure to load the package afer
the hyperref package.
Note that the \index command can affect your layout if not used
carefully.
Note that the makeindex has no clue about characters outside the
ASCII range. To get the sorting correct, use the @ character as shown in
the Käse and école examples above.
5.2 Installing Extra Packages 139
1. Run LATEX on the .ins file. This will extract a .sty file.
2. Move the .sty file to a place where your distribution can find
it. Usually this is in your …/localtexmf/tex/latex subdirectory
(Windows or OS/2 users should feel free to change the direction of
the slashes).
1. Run XƎLATEX on the .dtx file. This will generate a .pdf file. Note
that you may have to run XƎLATEX several times before it gets the
cross-references right.
2. Check to see if LATEX has produced a .idx file among the various
files you now have. If you do not see this file, then the documenta-
tion has no index. Continue with step 5.
5. Last but not least, make a .ps or .pdf file to increase your reading
pleasure.
140 Specialities
Sometimes you will see that a .glo (glossary) file has been produced.
Run the following command between step 4 and 5:
makeindex -s gglo.ist -o name.gls name.glo
Be sure to run LATEX on the .dtx one last time before moving on to
step 5.
% In preamble
\usepackage{hyperref}
% ... The reference to this section now
The reference to this section looks like that:1 Section 5.3.1 is
now looks like that:\footnote{ on page 140. The hyperref biblio-
Footnotes are also graphic entry is [58].
made into hyperlinks.}
Section~\ref{hyperlinks} is 1
Footnotes are also made into hyper-
on page~\pageref{hyperlinks}. links.
The hyperref bibliographic
entry is~\cite{pack:hyperref}.
By default links are marked by a red box around them. This box is only
visible when viewing the document on screen and will not be printed. The
boxes are, however, rather ugly, so you may want to add the colorlinks
5.3 LATEX and PDF 141
This is the option used throughout this booklet and assumed in further
examples. While this makes the links more visually appealing, it has
the disadvantage that the coloured links will be printed. To marry the
best of both worlds you can use the ocgx2 [19] package with the option
ocgcolorlinks like this
\usepackage{hyperref}
\usepackage[ocglinks]{ocgx2}
\url{https://www.ctan.org/} https://www.ctan.org/
If you want to display different text for the clickable link you can use the
\href{〈URL〉}{〈text〉}
command. Note that if you intend for the document to be useful when
printed, you have to provide the full URLs anyway.
Packages can be found on
\href{https://www.ctan.org/}{ Packages can be found on CTAN.
CTAN}.
A similar command is
\hyperref[〈marker〉]{〈text〉}
that allows to create a hyperlink within the document with a different
text.
\hyperref[hyperlinks]{
Hyperlinks section} Hyperlinks section describes the
describes the usage of usage of hyperlinks.
hyperlinks.
142 Specialities
\hyperref[hyperlinks]{
Section~\ref*{hyperlinks}}
describes the usage of Section 5.3.1 describes the usage
hyperlinks. of hyperlinks.
This ref 5.3.1 is not hyperlinked.
This ref~\ref*{hyperlinks}
is not hyperlinked.
\autoref{〈marker〉}
\autopageref{〈marker〉}
Their usage is identical to the \ref and \pageref commands, but they
produce additional text based on the counter the 〈marker〉 refers to.
\autoref{hyperlinks} in
subsection 5.3.1 in chapter 5 on
\autoref{specialities} on
\autopageref{hyperlinks}. page 140.
\hypersetup{
urlcolor = pink,
citecolor = purple,
https://www.ctan.org/
linkcolor = teal!50!yellow,
} [58]
\url{https://www.ctan.org/} \\ subsection 5.3.1
\cite{pack:hyperref} \\
\autoref{hyperlinks}
5.3 LATEX and PDF 143
You can also adjust the borders around the links. The basic key is
pdfborder. It accepts three numbers: horizontal corner radius, vertical
corner radius and border width.
\hypersetup{pdfborder = 0 0 1}
\url{https://www.ctan.org/} \\
\hypersetup{pdfborder = 10 10 3} https://www.ctan.org/
\url{https://www.ctan.org/} \\ https://www.ctan.org/
\hypersetup{pdfborder = 10 5 2} https://www.ctan.org/
\url{https://www.ctan.org/} \\ https://www.ctan.org/
\hypersetup{pdfborder = 2 7 5}
\url{https://www.ctan.org/}
You can also control the way your document presents itself when
opening. For example you can choose whether the bookmarks should
be shown (bookmarksopen), whether external links should be opened in
new windows (pdfnewwindow) whether the pages should initially fit the
window (pdffitwindow).
If you want to set the metadata without redefining internal LATEX
commands to produce links, you may pass implicit=false to hyperref
package options.
\section{\LaTeX{} is awesome!}
to
\section{\texorpdfstring{\LaTeX}{LaTeX} is awesome!}
\pdfstringdefDisableCommands{〈commands〉}
command, which allows you to define general fallbacks for some com-
mands. The 〈commands〉 argument is a list of redefinitions to be done
when evaluating outline titles. Commands may be redefined using the
\RenewExpandableDocumentCommand command. For a description of
how to redefine the commands see subsection 7.1.1. An example of using
this command would be
5.4 Creating Presentations 145
\pdfstringdefDisableCommands {
\RenewExpandableDocumentCommand{\ldots}{}{...}
\RenewExpandableDocumentCommand{\LaTeX}{}{LaTeX}
\RenewExpandableDocumentCommand{\emph}{m}{*#1*}
}
\documentclass{beamer}
〈subtitle〉 are displayed at the top of the slide. Despite the curly brackets,
these are optional arguments and have been omitted in the previous
example.
Interesting title
\begin{frame}{% Even more interesting subtitle
Interesting title}{%
Even more interesting
subtitle}
Not so interesting contents.
Not so interesting contents.
\end{frame}
The title and subtitle can also be specified using the \frametitle and
\framesubtitle commands.
As in the standard classes, you can specify a title, author and date in
the preamble by using the \title, \author and \date commands. The
\maketitle command uses these settings to create a title frame.
\author{Jane Doe}
Interesting Title
\title{Interesting Title}
\date{\today}
% ... Jane Doe
\maketitle
May 12, 2025
has no visible impact on the frames themselves, but they allow for a nice
\tableofcontents with properly hyperlinked entries.
\begin{frame}{Outline}
\tableofcontents
\end{frame} Outline
\section{A Section}
A Section
\begin{frame}
% ...
\end{frame} A Longer Section
\section{A Longer Section} A Subsection
% ...
\subsection{A Subsection}
% ...
3
amsmath is loaded automatically by beamer.
148 Specialities
frame options.
\begin{frame}[fragile]
Inside \verb|fragile| frames Inside fragile frames you
you can use the verbatim can use the verbatim freely.
freely.
\begin{verbatim} Hello!
Hello!
\end{verbatim}
\end{frame}
\begin{frame}
This will be shown first. \pause Then this. \pause
And finally this.
\end{frame}
While presenting, this has the effect of revealing statements one by one.
A more powerful frame splitting command is exists:
\onslide<〈overlay specification〉>
\begin{frame}
\onslide<1> One. \onslide<2> Two. \onslide<1,3> One and
three. \onslide<2-> Two onwards. \onslide<1-2> One to two.
\end{frame}
One. Two.
One and three. One and three.
Two onwards. Two onwards.
One to two. One to two.
\begin{frame}
\uncover<1>{One.} \uncover<2>{Two.} \uncover<1,3>{One
and three.} All.
\end{frame}
One. Two.
One and three. One and three.
All. All. All.
transparent option.
\setbeamercovered{transparent}
% ...
\begin{frame}
This will be shown first. \pause Then this. \pause
And finally this.
\end{frame}
\setbeamercovered{dynamic}
% ...
\begin{frame}
This will be shown first. \pause Then this. \pause
And finally this.
\end{frame}
5.4.3 Customisation
If the default appearance of the presentation is not to your liking, beamer
provides a lot of options to customise it. The most basic commands are
\usetheme and \usecolortheme. These allow you to choose from a pre-
4
The effect is amplified a bit in the below example, so it is more visible. The
default variant works better when there are more \pauses.
5.4 Creating Presentations 151
defined set of themes that alter the style and colours of the presentation.
\usetheme{Madrid}
\usecolortheme{wolverine}
\author{Jane Doe}
\title{Title}
Title
\date{Yesterday}
% ...
Normal text. Alerted text.
\begin{frame}{Title} Block
Normal text.
A block.
\alert{Alerted text}.
\begin{block}{Block}
A block.
Jane Doe Title Yesterday 1 / 1
\end{block}
\end{frame}
\usefonttheme{serif}
% ... Is serif better?
\begin{frame}{Is serif better?} Often repeated assertion is
Often repeated assertion is that serif fonts are easier to
that serif fonts are easier read on paper, however, this
to read on paper, however,
is not scientifically
this is not scientifically
confirmed. confirmed.
\end{frame}
\setbeamerfont{〈element〉}{〈attributes〉}
\setbeamercolor{〈element〉}{〈attributes〉}
background colours, fg and bg. Fonts are further discussed in Section 7.3,
while colours are covered in Section 7.4.
\setbeamercolor{frametitle}{
fg=red,
bg=lime,
}
\setbeamerfont{block title}{
Frame Title
series=\bfseries,
family=\ttfamily,
} Normal text.
% ...
Block title
\begin{frame}{Frame Title} More text.
Normal text.
\begin{block}{Block title}
More text.
\end{block}
\end{frame}
\usepackage{unicode-math}
\setsansfont{Fira Sans}
With these fonts Greek
\setmathfont{Fira Math}
\setoperatorfont{\mathsf} variables don’t look silly
% ... next to the Latin ones.
\documentclass[
aspectratio=169
]{beamer}
Wide is beautiful.
\begin{document}
\begin{frame}
Wide is beautiful.
\end{frame}
\end{document}
5.4.4 Handouts
\documentclass[handout]{beamer}
\begin{document}
\begin{frame} All of the text is on a single
All of the \pause text is on slide, even though pauses are
\pause a single slide, \pause present.
even though \pause pauses
are present.
\end{frame}
\end{document}
\documentclass[handout]{beamer}
\begin{document}
\begin{frame}
Some text \pause with pauses.
\onslide<beamer: 3-| handout: 2-> This text
will be on a separate slide, even in handout.
\end{frame}
\end{document}
Often you will want to show some parts only in one mode—to provide
additional commentary in handouts, or to hide things that only make
sense during the presentation. This is easily achieved by using a special
zeroth slide that is not included in the rendered document. An example
of doing so is presented in Listing 5.1.
Handouts created in this way still use the slide structure—titles, lots
of empty space, and bright colours. As an alternative, the article mode
will typeset the document in a fashion similar to a regular article. Due
to the more pronounced differences between layouts, this may require
more tweaking than the handout mode, but the result will often be much
more suitable for a printed handout.
Switching to the article mode differs from switching to other beamer
modes. Rather than passing options to the class, the class is replaced by
article and the beamerarticle is included in the preamble. See Listing 5.2
for an example. The beamerarticle package defines all of the beamer
commands and environments, so that they will produce sensible output
in the article.
Because the concept of slides is not present in an article,5 the overlay
specifications will be useless. However the special zeroth slide works
5
To be more precise, only contents of the first slide are typeset.
5.4 Creating Presentations 155
\documentclass[handout]{beamer}
\begin{document} A frame.
\begin{frame}
A frame.
\end{frame}
\begin{frame}<handout: 0>
A frame only visible in presentation.
\end{frame} A frame only
\begin{frame}<0>
visible in
A frame only visible in handout.
\end{frame} handout.
\end{document}
% \documentclass{beamer}
\documentclass{article}
\usepackage{beamerarticle}
\title{Handouts}
\author{Me and Myself} Handouts
\begin{document}
\maketitle Me and Myself
\begin{frame}<0>
Additional information for
the article.
\uncover<article: 2->{This Additional information
won't print.} for the article.
\end{frame}
\begin{frame}<article: 0>
Additional information for
the presentation.
\end{frame} 1
\begin{frame}<article>
Content for the article. Content for the article.
\end{frame}
\begin{frame}<beamer>
Content for the presentation.
\end{frame}
1
Chapter 6
Most documents these days contain some graphics alongside the text. While
photos and drawings can be easily added, integrating diagrams and schemat-
ics seamlessly with your document might prove difficult. Fonts, colours, and
lines must be adjusted so that they do not look out of place. Furthermore,
later changes to your document layout may force you to redo this work.
Fortunately it is possible to create your graphics directly in LATEX, which will
automatically take care of adjusting the aforementioned settings and keep
them in sync with the document itself.
6.1 Overview
First, some background on how to think about graphics. Roughly, there
are three types of pictures that you may find yourself dealing with:
Photos are pictures that contain realistic shading and lots of detail.
These include actual photos, photo-realistic renders, and screen-
shots from video games. In photos, exact pixel colour is not really
important, and lossy compression can be used without visual degra-
dation. It is best to store photos in the JPEG format.
Drawings are pictures with flat colours and relatively few details. This
category includes pixel art and screenshots of program interfaces.
Here, lossy compression would result in visible degradation, and
would not be very efficient anyway. It is best to use a lossless
compression format such as PNG. This will ensure that each
picture is reproduced with pixel-perfect fidelity, while keeping the
file sizes small.
Diagrams or Charts are simple graphics that contain text, lines, and
other geometric objects. Logos and schematics are prime examples
158 Graphics in Your Document
You have already learned about including photos and drawings, in Sec-
tion 2.19. You can use the same techniques to include diagrams, and
this is totally fine. Some programs, such as Inkscape [29], even support
ways to easily include produced graphics in LATEX documents. However,
this chapter will focus on drawing diagrams directly in LATEX. This has
many advantages, such as logical structuring, plain text formatting, and
seamless integration with the document layout.
Creating graphical output with LATEX has a long tradition. It started
out with the picture environment, which allows you to create graphics
by cleverly placing predefined elements onto a canvas. Unfortunately,
this environment is not very robust, and so many alternatives have
been developed over the years, such as metapost [80], asymptote [22] or
xypic [62]. Today, the most widely used package is pgf [73] (short for
“Portable Graphics Format”) and its user interface TikZ (a recursive
acronym—“TikZ ist kein Zeichenprogramm”—German for “TikZ is not
a drawing program”). This chapter will introduce the basic concepts of
writing graphics in TikZ. More detailed tutorials can be found in the pgf
documentation.
While TikZ is a powerful and versatile language, using it for com-
plicated graphics is not always easy. Many packages and libraries build
upon the pgf foundation to simplify the creation of specialized diagrams.
These include pgfplots [18], for plotting functions and presenting data,
and commutative-diagrams [8], for creating commutative diagrams. It’s
usually a good idea to search CTAN for a package which already solves
your problem before writing new TikZ code from the ground up, yourself.
\usepackage{tikz}
\begin{tikzpicture}
\draw (0, 0) % bottom left
-- (15:4) % angle:length
-- (1, 2); % x,y
\end{tikzpicture}
\tikz{\draw (0, 0) -- (1,1);}
If you want to close the shape you are drawing, use cycle instead of
repeating the first point. In addition to being clearer about the intention,
it also produces a better looking line connection (a properly mitred join,
as they say).
\begin{tikzpicture}
\draw (0, 0) -- (2, 0) -- (60: 2) -- (0, 0);
\end{tikzpicture}
vs.\
\begin{tikzpicture}
\draw (0, 0) -- (2, 0) -- (60: 2) -- cycle;
\end{tikzpicture}
vs.
\begin{tikzpicture}
\path[draw]
(0, 0) -- (0, 2) -- (2, 2) -- (2, 0) -- cycle;
\end{tikzpicture}
\begin{tikzpicture}
\path[fill]
(0, 0) -- (0, 2) -- (2, 2) -- (2, 0) -- cycle;
\end{tikzpicture}
160 Graphics in Your Document
vs. vs.
\begin{tikzpicture}
\node (text) at (0,0) {% 𝐵
Some \LaTeX{} text};
\node (A) at (3, 1) {\(A\)}; 𝐴
\node (B) at (0, 2) {\(B\)};
\draw (A) -- (text) -- (B); Some LATEX text
\end{tikzpicture}
TikZ attempts to be smart about the way it positions lines between nodes.
If you want to influence this, you can specify the exact connection-point
on a node after a dot. The available points are, for example, north,
west, south east and so on. You can also put a number, which will be
interpreted as an angle (in degrees).
\begin{tikzpicture}
\node (T) at (1,1) {%
Some \LaTeX{} text};
\node (A) at (0, 0) {\(A\)}; Some LATEX text
\node (B) at (2, 0) {\(B\)};
\draw (A.north) -- (B.south); 𝐴 𝐵
\draw (T.0) -- (T.145)
-- (T.265) -- cycle;
\end{tikzpicture}
6.3 Curves and Shapes 161
\begin{tikzpicture}
\draw (0, 0) node {Start} End
-- node {Midpoint} Midpoint
(3, 1) node {End}; Start
\end{tikzpicture}
\begin{tikzpicture}
\coordinate (A) at (0, 0);
\coordinate (B) at (1, 1);
\node (C) at (2, 0) {};
\draw (A) -- (B) -- (C);
\end{tikzpicture}
The looseness key may be used to define how much the curve is out-
stretched.
\tikz{\draw (0, 0)
to[out=90, in=-90, looseness=0.5] (2, 0);}
\tikz{\draw (0, 0)
to[out=90, in=-90, looseness=2] (2, 0);}
Often it might be easier to specify relative angles, using the bend left
and bend right keys. If no angle is provided, a default value is used.
If you need even finer control over the curves you, can use a .. controls ..
connection to specify a Bézier curve with one or two control points.
To specify how fine the grid is, use the step key.
\tikz{\draw (0, 0) grid[step=0.5] (2, 2);}
\tikz{\draw (0, 0) grid[step=1.5] (2, 2);}
Many more shapes are available, such as arc, parabola or sin. Be sure
to check out the documentation[73] for the specifics of their use.
The endings of lines can also be customized. For example, line cap
allows you to specify rounded end-caps.
\tikz{\draw[line width=10]
(0, 0) -- (1, 1);}
\tikz{\draw[line width=10,
line cap=round]
(0, 0) -- (1, 1);}
You can turn a line into an arrow by specifying the arrows key.
\tikz{\draw[arrows=->]
(0, 0) -- (1, 1);}
\tikz{\draw[arrows=<<->]
(0, 0) -- (1, 1);}
\tikz{\draw[dash pattern=
on 4 off 1 on 2 off 1]
(0, 0) -- (1, 1);}
\tikz{\draw[dotted]
(0, 0) -- (1, 1);}
Adjust how lines are connected by using line join. Set it to round,
bevel, or miter.
\tikz{\draw[line join=round]
(0, 0) -- (0.5, 1) -- (1, 0);}
\tikz{\draw[line join=bevel]
(0, 0) -- (0.5, 1) -- (1, 0);}
If you want the line joins to be rounded, you can also pass the rounded
corners key with the value set to the radius of the arc.
\tikz{\draw[rounded corners]
(0, 0) -- (0.5, 1) -- (1, 0);}
\tikz{\draw[rounded corners=25]
(0, 0) -- (0.5, 1) -- (1, 0);}
\tikz{\node[draw] (0, 0)
{Some Text};}
\tikz{\node[fill=red] (0, 0) Some Text Some Text
{Some Text};}
6.4 Customizing Paths and Nodes 165
By default, all nodes are rectangles, but they can be changed to circles
by passing the circle key to their options.
\tikz{\node[draw, circle]
(0, 0) {Some text};} Some text
If you want to place multi-line text inside a node, you have to specify
the align key; without it, new lines are ignored. Possible values are
left, center and right.
\tikz{\node[draw, align=left]
(0, 0) {Some more\\ text};} Some more Even more
\tikz{\node[draw, align=center] text text
(0, 0) {Even more \\ text};}
When nodes are placed along a path, their positions may be adjusted
using the anchor key. Its value is the point on the node boundary that
should be anchored on the given point in path.
\tikz{\draw
(0, 0) node[anchor=south] {A}
C
-- node[anchor=north west] {B}
(1, 1) node[anchor=135] {C}; A B
}
Using relative commands, such as left or above right, for this purpose
usually leads to more readable code, though they are not so powerful.
\tikz{\draw
(0, 0) node[above] {A} C
-- node[below right] {B}
(1, 1) node[right] {C}; A B
}
All these options can be freely combined, but the resulting style
specification may turn out to be lengthy. To avoid retyping it for many
nodes or paths, you can define new styles. Some predefined styles already
exist. For example, the help lines style sets the colour of the lines to
166 Graphics in Your Document
grey and makes them a bit thinner, which is useful for drawing alignment
grids when constructing your own pictures.
\begin{tikzpicture}
\draw[help lines]
(0, 0) grid (3,3);
\draw (1, 1) -- (3,2);
\draw (1.5, 2.5)
circle[radius=0.5];
\end{tikzpicture}
If you want to set up some styles globally, you can also use the \tikzset
command.
\tikzset{
red style/.style={draw=red},
}
\tikz{\draw[red style]
(0, 0) -- (1, 1) -- (2, 0);} Red node
\tikz{\node[red style]
at (0, 0) {Red node};}
If you want to avoid specifying the style for every node or path within a
TikZ picture, you can set the special styles every node and every path
to change them all at once.
\begin{tikzpicture}[
every path/.style={
ultra thick, dotted},
every node/.style={
circle, draw=red}, A
]
\draw (0, 0) -- (3, 1);
\node at (4, 0.5) {A};
\end{tikzpicture}
6.5 Coordinates 167
6.5 Coordinates
So far, we have always used the default unit of centimetres for specifying
coordinates. However, it is possible to use any LATEX dimension (see
subsection 7.5.1 for details).
\tikz{\draw (0, 0)
-- (1in, 1pt);}
\tikz{\draw (0, 0)
-- (1dd, 1em);}
\tikz[scale=2]{\draw
(0, 0) -- (1, 1);}
\tikz{\draw (0, 0) -- (2, 2);}
\tikz[scale=1in/1cm]{\draw
(0, 0) -- (1, 0.5);}
\tikz[scale=1em/1cm]{\draw
(0, 0) -- (1, 0.5);}
Keep in mind that coordinates with dimensions will also be scaled, which
may have unintended consequences. A more robust way of changing
dimensionless values is the x and y keys.
\tikz[x=1in, y=1in]{\draw
(0, 0) -- (1, 0.5);}
\tikz[x=1em, y=10ex]{\draw
(0, 0) -- (1, 0.5);}
pointing 45 degrees to the bottom left and is a bit shorter.2 This gives
the effect of a parallel (or axonometric) projection.
\begin{tikzpicture}[scale=2]
\draw (0, 0, 0) -- (0, 0, 1) -- (0, 1, 1) --
(0, 1, 0) -- cycle;
\draw (1, 0, 0) -- (1, 0, 1) -- (1, 1, 1) --
(1, 1, 0) -- cycle;
\draw (0, 0, 0) -- (1, 0, 0) (0, 0, 1) -- (1, 0, 1)
(0, 1, 1) -- (1, 1, 1) (1, 1, 0) -- (0, 1, 0);
\end{tikzpicture}
\begin{tikzpicture}[scale=2]
\draw (0, 0) -- ++(0, 1) --
++(1, 0) -- ++(0, -1) --
cycle;
\draw (1.5, 0) -- ++(0, 1) --
++(1, 0) -- ++(0, -1) --
cycle;
\end{tikzpicture}
\begin{tikzpicture}[rotate=45]
\draw (0, 0) -- (0, 1) --
(1, 1) -- (1, 0) -- cycle;
\end{tikzpicture}
2
Formally, (0, 0, 1) is the same as (−0.385, −0.385).
6.5 Coordinates 169
\begin{tikzpicture}
\draw (0, 0) -- (1, 1);
\draw[red, xshift=1cm]
(0, 0) -- (1, 1);
\end{tikzpicture}
If you want to apply the same transformation to more than one command
within the same picture, you can use the scope environment. It is
especially useful when your picture consists of more than one sub-picture,
each of which is more or less independent.
\begin{tikzpicture}
\begin{scope}[rotate=45]
\draw (0, 0) rectangle (1, 1);
\draw (0, 0) -- (1, 1);
\end{scope}
\begin{scope}[xshift=2cm]
\draw (0.5, 0.5) circle [radius=0.5];
\draw (0, 0) -- (1, 1);
\end{scope}
\end{tikzpicture}
When TikZ pictures are positioned within text, their bottom end sits
on the baseline of the text. If you want to modify this, you can use the
baseline key to set the 𝑦 coordinate at which the baseline should be. If
no position is specified, it defaults to 0.
\begin{tikzpicture}
\draw (0, 0) circle[radius=1cm];
\foreach \i in {0, 60, 120, 180, 240, 300} {
\draw (0, 0) -- (\i: 1);
\fill (\i: 1) circle[radius=0.1cm];
}
\end{tikzpicture}
If your values are a simple arithmetic sequence, you need only provide
the first two values and the last, replacing the rest with triple dots.
\begin{tikzpicture}
\draw (0, 0) circle[radius=1cm];
\foreach \i in {0, 20, ..., 340} {
\draw (0, 0) -- (\i: 1);
\fill (\i: 1) circle[radius=0.1cm];
}
\end{tikzpicture}
6.6 Reusing Pictures 171
\begin{tikzpicture}[
heart/.pic={
\draw (0,0) .. controls (-1, 0.7) and (-0.2, 1.7)
.. (0, 1) .. controls (0.2, 1.7) and (1, 0.7)
.. (0, 0);
},
]
\pic at (0, 0) {heart};
\pic[red] at (1, 1) {heart};
You can also iterate over pairs by separating respective parts with /.
\begin{tikzpicture}
\foreach \i/\j in {0/a,
1/b, 2/c, 3/d} {
a b c d
\node[draw] at (\i, 0) {\j};
}
\end{tikzpicture}
6.7 Libraries
pgf and TikZ do not rely on LATEX. In fact, they can be used with any
TEX based system or even TEX itself. For this reason, TikZ provides
its own system of extensions that does not use LATEX’s \usepackage
command. Extensions of TikZ are called libraries, and can be loaded
using the \usetikzlibrary command, which receives a list of comma
separated libraries.
For example, if you intend to draw some geometry problems, you will
often find yourself looking for intersections of objects. While you could
calculate their exact coordinates by hand, the intersections library
will do it for you. An example is presented in Listing 6.2.
Other libraries extend the number of available shapes. For example,
the arrows.meta library defines numerous additional arrow tips, if you
do not like the classical one. Some are presented in Listing 6.3.
You can perform additional calculations on existing coordinates. The
calc library allows you to do so by enclosing them within $ symbols.
An example is presented in Listing 6.4.
If you have a lot of TikZ code in your document, you may notice
that compiling it takes much longer. This is because TikZ redraws each
picture with every LATEX pass. If this becomes annoying, you can cache
your images to external files and reuse them on subsequent runs. To do
this, simply put the following code in your preamble.
\usetikzlibrary{external}
\tikzexternalize
This method has some limitations, but should be sufficient for most uses.
Read up on it in the documentation if problems occur.
These are not the only libraries—additional node shapes, real 3D-
perspective, matrices, mind maps and many more are covered. Most of
them are described in the pgf [73] package documentation. Check it out
if you haven’t found solution to your problem here.
6.7 Libraries 173
% In preamble
\usetikzlibrary{intersections}
% ...
\begin{tikzpicture}
\draw[name path=O] (0, 0) circle [radius=1];
\draw[name path=L] (-2, -1.5) -- (3, 1);
% In preamble
\usetikzlibrary{arrows.meta}
% ...
% In preamble
\usetikzlibrary{calc}
% ...
\begin{tikzpicture}
\coordinate (A) at (1, -1);
\coordinate (B) at (0, 1);
\draw[red, ->] (0, 0) -- node[above] {\(A\)} (A);
\draw[blue, ->] (0, 0) -- node[left] {\(B\)} (B);
\draw[green, ->] (0, 0) --
node[below right] {\(A+2B\)} ($(A)+2*(B)$);
\end{tikzpicture}
𝐵
𝐴 + 2𝐵
𝐴
Customising LATEX
Documents produced with the commands you have learned up to this point
will look acceptable to a large audience. While they are not fancy-looking,
they obey all the established rules of good typesetting, which will make them
easy to read and pleasant to look at.
However, there are situations where LATEX does not provide a command
or environment that matches your needs, or the output produced by some
existing command may not meet your requirements.
In this chapter, I will try to give some hints on how to teach LATEX new
tricks and how to make it produce output that looks different from what is
provided by default.
\begin{lscommand}
\csi{dum} \dum
\end{lscommand}
name and makes a corresponding entry in the index. Check this out by
looking up the \dum command in the index at the back of this book,
where you’ll find an entry for \dum, pointing to every page where we
mention the \dum command.
If I ever decide that I do not like having the commands typeset in
a box any more, I can simply change the definition of the lscommand
environment to create a new look. This is much easier than going through
the whole document to hunt down all the places where I have used some
generic LATEX commands to draw a box around some word.
You have already learned some basic command creation in Section 2.9.
The main command is the
\NewDocumentCommand{\〈name〉}{〈argspec〉}{〈definition〉}
\NewDocumentCommand{\tnss}{}{%
The not so Short Introduction This is “The not so Short Intro-
to \LaTeX} duction to LATEX” … “The not so
This is \enquote{\tnss} \ldots{} Short Introduction to LATEX”
\enquote{\tnss}
use #1 for the first argument, #2 for the second, and so on.
\NewDocumentCommand{\txsit}{mm}
{This is the \emph{#1}
#2 Introduction to \LaTeX} This is the not so short Introduc-
tion to LATEX
% in the document body: This is the very long Introduction
\txsit{not so}{short} to LATEX
\txsit{very}{long}
\MyCommand\\
\MyCommand[hello]
There are two variations of it: \IfValueT and \IfValueF which may
be used if you only need output for one of the branches. The example
with -NoValue- in the output could be fixed by writing
\NewDocumentCommand{\txsit}{om}
{This is the
\IfValueT{#1}{\emph{#1} }% This is the definitive Introduction
#2 Introduction to \LaTeX}
to LATEX
% in the document body: This is the very long Introduction
\txsit{definitive} to LATEX
\txsit[very]{long}
178 Customising LATEX
\NewDocumentCommand{\txsit}{O{not so}m}
{This is the \emph{#1}
#2 Introduction to \LaTeX} This is the not so definitive Intro-
duction to LATEX
% in the document body: This is the very long Introduction
\txsit{definitive} to LATEX
\txsit[very]{long}
\NewDocumentCommand{\txsit}{sO{not so}m}
{This is the \emph{#2}
#3 Introduction to \LaTeX%
\IfBooleanT{#1}{% This is the not so long Introduc-
: Superstar Edition%
tion to LATEX
}%
} This is the not so long Introduc-
tion to LATEX: Superstar Edition
% in the document body:
\txsit{long}\\
\txsit*{long}
These are just the most common argument specifications. For a full
description, take a look at the [57].
As we have discussed in Section 2.9, LATEX will not allow you to create
a new command that would overwrite an existing one, you can do so
using \RenewDocumentCommand. It uses the same argument specification
syntax as the \NewDocumentCommand command.
In some cases you might want to use the \ProvideDocumentCommand
command. It works like \NewDocumentCommand, but if the command is
already defined, LATEX will silently ignore the new definition. Yet another
variant is the \DeclareDocumentCommand. It always creates the given
command, overwriting old definition if it exists.
7.1 New Commands, Environments and Packages 179
Obviously you can use the same internal commands to define them, for
example renaming the previous implementation to kinginternal making
the king and king* a thin wrapper around it.
The \NewDocumentEnvironment also introduces a special argument
specification: +b, short for body.1 It is only allowed as the last argument
in the 〈argspec〉. It allows you to receive the body of the environment as
an argument.
\NewDocumentEnvironment{twice}{+b} {%
First time:\\ #1
First time:
Second time:\\ #1 This will be printed twice!
} {}
Second time:
\begin{twice} This will be printed twice!
This will be printed twice!
\end{twice}
While this makes one of the 〈at begin〉, 〈at end〉 arguments redundant,
they are still required. (In the example above we provided an empty 〈at
end〉.)
Do not overuse +b as this will both add limitations to the environments
like \verb not being allowed inside and it will slow down the typesetting.
1
The + indicates that it may contain multiple paragraphs.
180 Customising LATEX
\NewDocumentEnvironment{king}{}{%
\emph{Listen! For the
king made a statement:}%
\\[1em]% Listen! For the king made a state-
} {% ment:
\\[1em]%
\emph{This concludes My humble subjects …
the king's statement.}%
} This concludes the king’s state-
ment.
\begin{king}
My humble subjects \ldots
\end{king}
\NewDocumentEnvironment{king}{s}{%
\IfBooleanTF{#1}{
\begin{center}
\emph{Thus spoke Charles I:}
\\[1em]%
\end{center}%
} {
\emph{Listen! For the Thus spoke Charles I:
king made a statement:}%
\\[1em]% My humble subjects …
}%
} {% This concludes the king’s state-
\\[1em]% ment.
\emph{This concludes
the king's statement.}%
}
\begin{king}*
My humble subjects \ldots
\end{king}
\RenewDocumentCommand{\emph}{m}{%
\emph{#1}~(\enquote{#1} is emphasised)%
}
but when you try to compile the document you will get the error message
\emph{foo}~(\enquote{foo} is emphasised)~(\enquote{foo} is
↪ emphasised)
This process will never end and at some point TEX simply gives up.
Note that
\NewDocumentCommand{\oldemph}{m}{\emph{#1}}
\RenewDocumentCommand{\emph}{m}{%
\oldemph{#1}~(\enquote{#1} is emphasised)%
}
will suffer the same fate since \oldemph{...} will be replaced by TEX
with \emph{...} and the cycle repeats.
In order to avoid this problem a special command exists
\NewCommandCopy{\〈name〉}{\〈command〉}
It makes the 〈name〉 the exact copy of the 〈command〉. The following
182 Customising LATEX
\NewDocumentCommand{\foo}{}{Batman!}
\NewDocumentCommand{\newfoo}{}{\foo}
\NewCommandCopy{\copiedfoo}{\foo} Na Na Na Na Na Na
Batman!
\RenewDocumentCommand{\foo}{}{Na Na Na}
\NewCommandCopy{\oldemph}{\emph}
\RenewDocumentCommand{\emph}{m}{%
\oldemph{#1}~(\enquote{#1} And here it
is emphasised)% comes (“comes” is
} emphasised).
And here it \emph{comes}.
\IfBooleanTF{\blackandwhite} {
% "black and white" mode; do something...
} {
% "color" mode; do something different...
}
xelatex '\NewCommandCopy{\blackandwhite}{\BooleanTrue}
\input{test.tex}'
\ProvidesExplPackage{〈name〉}{〈date〉}{〈version〉}{〈description〉}
for use at the very beginning of your package file. This command tells
the LATEX to process the file in expl mode. The most visible effect of this
is that all whitespace is ignored. You may have noticed that in many
of the examples above we had to end most lines with % to get correct
spacing in the output. In expl mode, spaces have to be added explicitly
if needed at all. They are usually quite rare when writing a package. To
insert spaces, use the ~ character, which normally denotes non-breaking
space.2 Paragraphs can be started with the \par command.
The arguments are used to provide information about package in the
log file. If you use this package and look at the log file you will find
Package: demopack 2022-05-05 v0.1 Package by Tobias Oetiker
in the .log file.
\ProvidesExplPackage will also issue a sensible error message when
you try to include a package twice. Listing 7.3 shows a small example
package that contains the commands defined in the examples above.
shape The shape of glyphs within a font family. For example, ‘small
caps’ or ‘italics’.
size The size of the glyphs. For example, ‘10 pt’ or ‘12 pt’.
2
If you want to insert non-breaking space in expl mode, use \nobreakspace.
184 Customising LATEX
\ProvidesExplPackage{demopack}{2022-05-05}{0.1}{%
Package by Tobias Oetiker
}
\NewDocumentCommand{\tnss}{} {
The~not~so~Short~Introduction~to~\LaTeX
}
\NewDocumentCommand{\txsit}{O{not~so}} {
The~\emph{#1}~Short~Introduction~to~\LaTeX
}
\NewDocumentEnvironment{king}{} {
\begin{quote}
} {
\end{quote}
}
LATEX automatically chooses the appropriate font family, series, shape and
size based on the logical structure of the document (sections, footnotes,
emphasis, …). It is possible however to instruct LATEX manually which
font to use. It is important to note that not every combination of family/
series/shape exists as an actual font. LATEX will complain if you try for
something that does not exist.
LATEX predefines three font families to use throughout the document:
the upright or roman family accessible via \textrm, the sans serif family
accessible via \textsf and monospace or typewriter family accessible
via \texttt.
There are only two predefined LATEX series: medium (\textmd) and
bold (\textbf).
Shapes are a bit more complicated. The three basic shapes are: italics
(\textit), oblique or slanted3 (\textsl) and small capitals (\textsc).
However there are two additional shapes that are not provided by default
LATEX fonts: swash (\textsw), for decorative fonts and spaced caps and
small caps (\textssc). These are rarely used but may come in handy
when using custom fonts as described in Section 7.3.
\textsl{\textsc{Back to
\textup{upright.}}} \\ Back to upright.
\textsl{\textsc{Back to
\textulc{lowercase.}}} \\
Back to lowercase.
\textsl{\textsc{Back to Back to normal.
\textnormal{normal.}}}
All of the commands described above also exist in their switch ver-
sion. Instead of receiving the text via argument, they change the font
permanently until it is changed again. For example, the switch version of
\textit and \textrm are \itshape and \rmfamily, respectively. While
the argument versions are useful for defining commands, switch versions
are especially useful when defining your own environments.
Only \textit{argument} is
Only argument is affected. After
affected. After \itshape
everything is in italics everything is in italics until is en-
until \upshape is encountered. countered.
When working with switch versions of fonts that are slanted right it
is important to remember about italic correction. This is a small space
after the end of right slanting text that is sometimes necessary to avoid
overlapping letters. It is inserted using \/ command.
Size (pt)
Command 10pt 11pt 12pt
\tiny 5 6 6
\scriptsize 7 8 8
\footnotesize 8 9 10
\small 9 10 10.95
\normalsize 10 10.95 12
\large 12 12 14.4
\Large 14.4 14.4 17.28
\LARGE 17.28 17.28 20.74
\huge 20.74 20.74 24.88
\Huge 24.88 24.88 24.88
{\Large Here the line spacing Here the line spacing is not
is not updated. A bit tight!} updated. A bit tight!
{\Large Much better! I can Much better! I can breathe
breathe freely again!\par} freely again!
An arbitrary font size can be specified using the
\fontsize{〈size〉}{〈line skip〉}\selectfont
command combo. The 〈line skip〉 determines the height of the text line
and should be usually around 1.2 times larger than the 〈size〉.
\fontsize{2cm}{2.4cm}\selectfont A big one!
A big one!
Fun fact: LATEX default font is a bit unusual in that it looks slightly
different depending on its size. The difference is presented in the table
below where the text written using different sizes was rescaled to the
same height.
188 Customising LATEX
\NewDocumentCommand{\oops}{m}{%
\textbf{#1}} Do not enter this room, it’s oc-
Do not \oops{enter} this room, cupied by machines of unknown
it's occupied by \oops{machines} origin and purpose.
of unknown origin and purpose.
This approach has the advantage that you can decide at some later
stage that you want to use a visual representation of danger other than
\textbf, without having to wade through your document, identifying all
the occurrences of \textbf and then figuring out for each one whether
it was used for pointing out danger or for some other reason.
7.2.3 Advice
To conclude this journey into the land of fonts and font sizes, here is a
little word of advice:
!
Reme𝔪𝔟𝔢𝔯 The MO ℛE fonts you
use in a document,
.../texmf-dist/fonts/opentype/adobe
where the ... denotes the install-path of TEXLive. LuaTEX checks this
directory automatically, so it should work fine, but if you are using XƎTEX
you must first install these fonts in your system. You can also download
and install them manually from the links provided in the bibliography.
Alternatively swap out their respective names with some other fonts
installed in your system.
Many free OpenType fonts are available at https://fontlibrary.
org/.
\setmainfont[〈options〉]{〈font〉}
\setsansfont[〈options〉]{〈font〉}
\setmonofont[〈options〉]{〈font〉}
This commands change, respectively, the main font of the document, the
sans serif font used in the document and the monospace font in the
document.
Normal text.
\emph{Emphasised.} \\
\textsf{Sans serif text.
\emph{Emphasised}.} \\
Normal text. Emphasised.
\texttt{Monospace text.
\emph{Emphasised}.} \\ Sans serif text. Emphasised.
Monospace text. Emphasised.
\setmainfont{Source Serif Pro}
\setsansfont{Source Sans Pro} Normal text. Emphasised.
\setmonofont{Source Code Pro} Sans serif text. Emphasised.
Normal text.
Monospace text.
\emph{Emphasised.} \\
\textsf{Sans serif text. Emphasised.
\emph{Emphasised}.} \\
\texttt{Monospace text.
\emph{Emphasised}.}
numerals that are not used by default. You can pass Number=OldStyle
if you want to use them in your document.
Some fonts also provide special glyphs for a given language. For
example the Latin Modern Font provides a special “fk” ligature for the
Polish language. You can set the Language key to a given language to
enable these features.
agrafka
\setmainfont[ agrafka
Language=Polish, agrafka
]{Latin Modern Roman}
agrafka
\setmainfont[
Fractions=On,
]{Latin Modern Roman} 1/2 3/4 123/456
1/2 3/4 123/456 1/2 3/4 123/456
1/2 3/4 123/456
\setmainfont[
Fractions=On,
]{Source Serif Pro}
1/2 3/4 123/456
The OpenType font format defines a lot of more font features, that
may or may not be supported by your font of choice. Consult with the
fontspec [60] package documentation for a comprehensive description and
examples.
7.3 Custom Fonts with fontspec 191
\setmainfont[
SlantedFont=Latin Modern Roman Slanted,
]{Latin Modern Roman}
\textit{italics} vs. \textsl{slanted}
\newfontfamily{\〈command〉}[〈options〉]{〈font〉}
\newfontfamily{\sourcefamily}[
Numbers=OldStyle,
]{Source Serif Pro} Normal text when suddenly … a
Normal text when suddenly
different font! 0123456789
\ldots{} \sourcefamily
a different font! 0123456789
192 Customising LATEX
\setmainfont{SourceSerifPro-Regular.otf}
Normal text. \textit{Italics.} \textbf{Bold.}
\textit{\textbf{Bold italics.}} \\
\setmainfont[
ItalicFont=SourceSerifPro-RegularIt.otf,
BoldFont=SourceSerifPro-Bold.otf,
BoldItalicFont=SourceSerifPro-BoldIt.otf,
]{SourceSerifPro-Regular.otf}
Normal text. \textit{Italics.} \textbf{Bold.}
\textit{\textbf{Bold italics.}} \\
\setmainfont[
Extension=.otf,
UprightFont=*-Regular,
ItalicFont=*-RegularIt,
BoldFont=*-Bold,
BoldItalicFont=*-BoldIt,
]{SourceSerifPro}
Normal text. \textit{Italics.} \textbf{Bold.}
\textit{\textbf{Bold italics.}}
is equivalent to
\setmathfont{STIXTwoMath-Regular.otf}
and the latter works in both LuaLATEX and XƎLATEX. While changing
math fonts throughout the document is possible, it may lead to some
problems; prefer to set them in the preamble for the whole document.
\setmainfont{EB Garamond}
\setmathfont{Garamond Math}
% ...
Now we are using Garamond fonts. Now we are using Garamond fonts.
\[ ∞
\symrm{e}^{\symrm{\pi}
𝑏 √
3
𝔸
eπi + 1 = 0 ∑ ∬ lim d𝑥
\symrm{i}} + 1 = 0 \quad 𝑖=0 𝑎 ℎ→0 2ℎ
\sum_{i=0}^\infty \iint_a^b
\lim_{h\to0}\frac{\sqrt[3]{
\symbb{A}}}{2^h}\,\symrm{d}x 1
\]
Not all math fonts have the same character coverage. For example,
the default font doesn’t have lowercase script letters. If you don’t want
to switch the fonts entirely but just use some characters from a different
194 Customising LATEX
font, you can use the range key in the options to the \setmathfont
command.
\(\symscr{ABCDabcd}\) vs.\ 1
\(\symcal{ABCDabcd}\)
\(\not\cong\) vs.\
\NewNegationCommand{%
\cong}{\simneqq}%
≇ vs. ≆
\(\not\cong\)
7.4 Colours
7.4.1 Coloured Text
In the Section 1.6 we have used different text colours to illustrate an
example. These can be obtained with the xcolor [31] package. It provides
7.4 Colours 195
\color[〈model〉]{〈color〉}
\textcolor[〈model〉]{〈color〉}{〈text〉} \mathcolor[〈model〉]{〈color〉}{〈text〉}
\textcolor{yellow}{foo} \\
\color{red} baz foo
\[ baz
\mathcolor{blue}{ 10
\sum_{k=0} ∑𝑖
}^{10} i 𝑘=0
\]
The list of predefined colours can be found in Table 7.4. You can also
pass dvipsnames, svgnames or x11names as a package options to extend
the predefined colours. Consult the package documentation for a full list.
\textcolor{green!100!red}{C}%
\textcolor{green!80!red}{o}%
\textcolor{green!60!red}{l}%
\textcolor{green!40!red}{o}%
\textcolor{green!20!red}{r}% Colors
\textcolor{green!0!red}{s} \\ Blue
\textcolor{blue!100}{B}%
\textcolor{blue!75}{l}%
\textcolor{blue!50}{u}%
\textcolor{blue!25}{e}
〈A〉!〈n〉!〈B〉!〈m〉!〈C 〉
196 Customising LATEX
means calculate the mixture of 〈A〉 and 〈B〉 and then mixture of the
result and 〈C 〉. You can also use the minus sign before the expression to
get the complementary colour.
\color{green!20!red!60!blue}
\LaTeX{} \\ LATEX
\color{-green!20!red!60!blue} LATEX
\LaTeX{}
7.4.2 Models
While colour mixing via expression is useful for simple colour specification,
it is often the case that we want to use colour that is defined in terms of
its RGB or HSB values. Different input method colours can be specified
using the optional 〈model〉 argument. Note that it is case-sensitive.
The simplest model is Gray. It accepts a single number from 0to 15
and produces a grey colour with the given brightness.
\textcolor[Gray]{0}{Zero} \\ Zero
\textcolor[Gray]{3}{Three} \\ Three
\textcolor[Gray]{7}{Seven} \\ Seven
\textcolor[Gray]{11}{Eleven} \\ Eleven
\textcolor[Gray]{15}{Fifteen}
Fifteen
You can input RGB values in three ways: rgb, RGB and HTML models.
The HTML model accepts a hexadecimal colour code. The code may be
either upper or lowercase.
\textcolor[HTML]{e63946}{e63946}
\textcolor[HTML]{06D6A0}{06D6A0}
e63946 06D6A0
7.4 Colours 197
The rgb model accepts three decimal numbers, each between 0 and 1,
while the RGB model accepts three integers from 0 to 255.
If you prefer the subtractive colour model, both cmy and cmyk are
available. They accept decimal numbers between 0 and 1 to specify the
amount of each colour.
There are three models that enable defining colours by HSB: hsb,
Hsb and HSB. The first two accept three decimal numbers for each value,
the difference being that the Hsb accepts hue as an angle in degrees, that
is a number between 0 and 360. The hsb accepts it as a number between
0 and 1, while saturation and brightness are passed the same way in
both model—as a number between 0 and 1.
\textcolor[hsb]{
0.4, 0.8, 0.75
}{
0.4, 0.8, 0.75
}\\ 0.4, 0.8, 0.75
\textcolor[Hsb]{ 144, 0.8, 0.75
144, 0.8, 0.75
}{
144, 0.8, 0.75
}
The HSB in turn accepts all three as integers—each between 0 and 240.
\textcolor[HSB]{
144, 200, 120
}{ 144, 200, 120
144, 200, 120
}
198 Customising LATEX
If you are writing a paper about light you may also find that the wave
model comes in handy. It allows you to specify a colour by its wavelength.
It accepts a single decimal number that represents a wavelength in visible
spectrum in nanometres.
\textcolor[wave]{452}{
If a light has wavelength
\qty{452}{\nm} it looks
like this. If a light has wavelength 452 nm
} \\ it looks like this.
\textcolor[wave]{700}{ Light with wavelength above
Light with wavelength above 814 nm is called infrared.
\qty{814}{\nm} is called
infrared.
}
\definecolor{〈name〉}{〈model〉}{〈value〉}.
\definecolor{MyRed}{wave}{712}
\textcolor{MyRed}{MyRed is MyRed is the perfect colour for
the perfect colour for you!}
\textcolor{MyRed!60}{Tints
you! Tints are also available!
are also available!}
\pagecolor[〈model〉]{〈color〉}
\pagecolor{orange} \color{-orange}
Small is colourful \ldots? Small is colourful …?
1 instead of the
If you only want to specify a background of some text
whole page you can use the
\colorbox[〈model〉]{〈color〉}{〈text〉}
\fcolorbox[〈model〉]{〈color〉}[〈model〉]{〈color〉}{〈text〉}
commands. The first one only colours the background, while the second
one allows also drawing a frame (the ‘f’ stands for “framed”).
It is \colorbox{gray}{curious}
how much a document can be It is curious how much a docu-
enhanced or ruined by
\fcolorbox{blue}{red}{
ment can be enhanced or ruined
colours. by colours.
}
The last three units mentioned in the table are relative to the current
font used. Historically they were related to the ‘M’ and ‘x’ glyphs in
a given font but today they are arbitrarily set by fonts. These units
are useful if we want the length to scale proportionally when used with
different font sizes. The em unit is usually used for horizontal lengths,
while the ex is used for vertical lengths. The mu unit can only be used
in math mode for math spacing (see Section 3.7).
\fontsize{12pt}{15pt}\selectfont
Text in 12 \TeX{} points. Text in 12 TEX points.
\fontsize{12bp}{15bp}\selectfont Text in 12 DTP points.
Text in 12 DTP points.
7.5 Lengths and Spacing 201
\hspace{〈length〉}
This\hspace{1.5cm}is a space
This is a space of 1.5 cm.
of \qty{1.5}{\cm}. A bit too
cramped\hspace{-5pt}here. A bit too crampedhere.
The space added that way will disappear if it lands on the end of a line,
similarly to an interword spacing. If you want to retain the extra space,
use the starred version of the command.
So far all the lengths we have seen have been rigid, that is the length
is exactly as specified. But you probably noticed that the spaces between
words are not rigid—they can stretch and shrink, so that TEX can make
the right margin equal. Lengths that can do that are called rubber
lengths.
Such lengths can be specified using a special plus and minus syntax.
For example to specify that a space can stretch if a need arises you can
specify it by writing plus followed by the maximum allowed stretch.
The additional space can extend even beyond the specified maximum,
but in such cases LATEX will print a warning.
202 Customising LATEX
When there are multiple rubber spaces in text TEX calculates the
amount of ‘stretch’ proportionally to the specified maximum. Thus if
TEX needs additional 2 cm of whitespace and one length has plus 1cm
while the other has plus 3cm modifier, it will result in the first one being
enlarged by ( 1+3
1
) × 2 cm while the second one by ( 1+33
) × 2 cm.
This approach will, however, interfere with the spacing inside the centred
expression, since the spaces are still distributed proportionally. The
effect will be getting smaller if you set the allowed stretching to a larger
number but it will still be present. For situations like these, TEX actually
supports a concept of infinitely stretchable space—by using the special
fill unit, allowed only as stretching and shrinking value, we can ensure
that all the other rubber lengths will not stretch.5
Because the fill value is often used with zero width space LATEX
defines a macro that simplifies entering it—the
\stretch{〈n〉}
command.
\hspace*{\stretch{1}}
is equivalent to is equivalent to
\hspace*{0pt plus 1fill}
\linebreak
Paragraph.\\ Paragraph.
LATEX has a dedicated command for setting the space between paragraphs,
the
\vspace{〈length〉}
command. It works similarly to the \hspace command, however when
used inside a line it will only produce the space after the line is ended.
Since it does not produce empty lines when used, it is perfect for inserting
a space between paragraphs. Similarly to the \hspace command, the
space will be discarded if it lands at the end of a page—use the starred
version if this is not desirable.
The rubber lengths, \stretch and \vfill work for vertical space
too. However, since manual vertical spacing is much more common com-
pared to manual horizontal spacing, LATEX also declares three semantic
commands for inserting them:
\bigskip
\medskip
\smallskip
The exact sizes of these skips is dependent on the class used. You can
access them as length by appending “amount” to their name, for example,
\medskipamount. These are useful when creating your own environments
or to indicate a thought break between paragraphs.
There also exist the \addvspace command, which works similarly
to the \vspace command, however when multiple such commands are
entered one after another, only the one with the biggest length will be
used. Note that using it will lead to an error if it is not used between
paragraphs.
Hello.
Hello.
\addvspace{1pt}
\addvspace{1em}
\addvspace{1cm}
There is \qty{1}{\cm} space There is 1 cm space above me.
above me.
\NewDocumentCommand{%
\mylength}{}{2em} foo bar
foo\hspace{\mylength}bar
\newlength{\〈variable〉}
\setlength{\〈variable〉}{〈length〉}
\newlength{\mylength}
\setlength{\mylength}{2em}
foo\hspace{0.5\mylength}bar% foo bar baz
\hspace{2\mylength}baz
foo\hspace{\mylength}bar\\
\addtolength{\mylength}{2em}
foo bar
foo\hspace{\mylength}bar foo bar
Since length variables are not stored as text macros, but as TEX
internal numbers, trying to typeset them in a document results in an
error. To translate them back into their textual representation use the
\the command. Note that their value will always be printed using points
as units.
\setlength{\mylength}{1cm}
\the\mylength
28.45274pt
\settoheight{\〈variable〉}{〈element〉}
\settodepth{\〈variable〉}{〈element〉}
\settowidth{\〈variable〉}{〈element〉}
The element height is calculated by taking into account the part of the
element that extends above baseline, while the depth takes into account
206 Customising LATEX
\newlength{\myheight} \settoheight{\myheight}{Major}
\newlength{\mydepth} \settodepth{\mydepth}{Major}
\newlength{\mywidth} \settowidth{\mywidth}{Major}
The word Major has width of \the\mywidth, height of
\the\myheight{} and depth of \the\mydepth.
These commands are especially useful when creating your own envi-
ronments requiring complicated alignment or spacing. An example of
using them is presented in Listing 7.5.
As you will see LATEX uses length variables for many things. When
typesetting a document you can use some of them when setting lengths
to make them relative. For example, the \linewidth length holds the
length of the current line. You can use it when inserting a picture to
make it fill the page or scale it to take up half the space available.
\includegraphics[
width=0.5\linewidth, Image
]{example-image}
\documentclass[〈options〉]{〈class〉}
\newlength{\vardescindent}
\NewDocumentEnvironment{vardesc}{m}{%
\settowidth{\vardescindent}{#1:\ }%
\RenewDocumentCommand{\item}{so}{%
\IfBooleanTF{##1}{#1: }{\\\hspace*{\vardescindent}}%
\IfValueT{##2}{##2 ---}%
}%
\ignorespaces
}{}
\[ a^2+b^2=c^2 \]
\begin{vardesc}{Where}
\item*[\(a\), \(b\)] are adjacent to the right angle
of a right-angled triangle.
\item[\(c\)] is the hypotenuse of the triangle and
feels lonely.
\item[\(d\)] finally does not show up here at all.
Isn't that puzzling?
\end{vardesc}
𝑎2 + 𝑏 2 = 𝑐 2
Where: 𝑎, 𝑏 — are adjacent to the right angle of a right-
angled triangle.
𝑐 — is the hypotenuse of the triangle and feels
lonely.
𝑑 — finally does not show up here at all. Isn’t that
puzzling?
Options Description
10pt, 11pt, Sets the size of the main font in the document. If no
12pt option is specified, 10pt is assumed.
a4paper, Defines the paper size. The default size can be config-
letterpaper ured when installing LATEX. Besides these, a5paper,
b5paper, executivepaper, and legalpaper can be
specified. Note that it only affects the layout of mar-
gins, not the PDF paper size itself, see subsection 7.6.5
for more details.
fleqn Typesets displayed formulae left-aligned instead of cen-
tred.
leqno Places the numbering of formulae on the left hand side
instead of the right.
titlepage, Specifies whether a new page should be started after
notitlepage the document title or not. The article class does not
start a new page by default, while the report and book
classes do.
onecolumn, Instructs LATEX to typeset the document in one column
twocolumn or two columns.
twoside, Specifies whether double or single sided output should
oneside be generated. The classes article and report are single
sided, while the book class is double sided by default.
Note that this option concerns the style of the docu-
ment only. twoside does not tell the printer to make
a two-sided printout.
landscape Changes the layout of the document to print in land-
scape mode.
openright, Makes chapters begin either only on right hand pages
openany o,r on the next page available. This does not work with
the article class, as it does not know about chapters.
By default, the report class by default starts chapters
on the next page available, while the book class starts
them on right hand pages.
7.6 The Layout of the Document 209
\pagestyle{〈style〉}
command defines which one to use. Table 7.7 lists the predefined page
styles.
It is possible to change the page style of the current page with the
command
\thispagestyle{〈style〉}
You may also control the style of the displayed page numbers. To
change it, use the
\pagenumbering{〈style〉}
Style Description
plain Prints the page numbers on the bottom of the
page, in the middle of the footer. This is the
default page style.
headings Prints the current chapter heading and the page
number in the header on each page, while the
footer remains empty. (This is the style used in
this document.)
empty Sets both the header and footer to be empty.
myheadings Similar to the headings style but leaves the head-
ers and footers empty, allowing them to be de-
fined by the author. A description of how to do
this is in Section 7.7.
Style Description
arabic Arabic numerals (1, 2, 3, …)
roman Lowercase Roman numerals (i, ii, iii, …)
Roman Uppercase Roman numerals (I, II, III, …)
alph Lowercase Latin letters (a, b, c, …)
Alph Uppercase Latin letters (A, B, C, …)
7.6 The Layout of the Document 211
\linespread{〈factor〉}
command. Once used, each line skip will be multiplied by the 〈factor〉.
Note, that outside the preamble, you must follow it by \selectfont for
the changes to be visible.
\linespread{0.9}\selectfont
If you want to save paper, set
If you want to save paper, set the
the linespread to a value
linespread to a value below 1 to
below 1 to sacrifice a bit of
sacrifice a bit of space between
space between lines.
lines.
\linespread{1.1}\selectfont On the other hand, if your assign-
On the other hand, if your ment is short a few pages, setting
assignment is short a few it to a value above 1 might just
pages, setting it to a value
above 1 might just save you save you some typing.
some typing.
{\setlength{\baselineskip}{%
1.5\baselineskip} This paragraph is typeset with the
This paragraph is typeset with
baseline skip set to 1.5 of what
the baseline skip set to 1.5 of
what it was before. Note the it was before. Note the par com-
par command at the end of the
paragraph.\par} mand at the end of the paragraph.
Here the line spacing returns to
Here the line spacing returns normal, because line skip changes
to normal, because line skip are local to a group.
changes are local to a group.
\setlength{\parindent}{0pt}
\setlength{\parskip}{%
\medskipamount} On the web it is common to sep-
arate paragraphs by some space
On the web it is common to instead of indenting.
separate paragraphs by some
space instead of indenting. Like this.
Like this.
Beware, that these lengths also affect the table of contents—its lines
get spaced more loosely. To avoid this, you might want to put the two
commands after the \tableofcontents command or to not use them at
all, because you’ll find that most professional books use indenting and
not spacing to separate paragraphs.
If you want to indent a paragraph that is not indented, use \indent
at the beginning of the paragraph. Obviously, this will only have an
effect when \parindent is not set to zero. In continental Europe it is
sometimes the case that every paragraph should be indented, even after
sections. To avoid using ths \indent command everywhere, simply use
the indentfirst [9] package in your preamble.
\usepackage{indentfirst}
% ... 1 Title
\section{Title} The first paragraph is now in-
dented.
The first paragraph is now
indented.
1
To create a non-indented paragraph, use \noindent as the first
command of the paragraph. This might come in handy when you start a
document with body text and not with a sectioning command.
take a few seconds to think. As with most things in LATEX, there are
good reasons for the page layout to be as it is.
Sure, compared to your off-the-shelf page of your favourite WYSI-
WYG editor, the margins look awfully wide. But take a look at your
favourite, professionally printed book and count the number of characters
on a standard text line. You will find that most lines contain between
45 and 80 characters. Now do the same on your LATEX page. You will
find that the same relationship holds. Empirical studies suggest that
averaging around 66 characters per line creates the optimal reading
experience for readers. If you want to save space when printing your
document consider using twocolumn option or smaller page sizes.
With that warning in place let us proceed to the proper introduction
of geometry [83] package that allows you to easily customize the page
dimensions of your document. It is worth noting that simply including
the package in your preamble will result in considerably narrower margins,
(the very thing we warned you to avoid) so only use the package if you
intend to set them manually or use the pass option that disables most
of the package functions but retains the paper size adjustments.
As we have mentioned in Table 7.6, simply setting a5paper (or similar)
option will only adjust margins of the document without changing the
paper dimensions themselves. The simplest way to fix that is to add the
geometry package to your preamble. It will read the page size option and
adjust it accordingly. The package itself also supports many more page
sizes, such as a0paper or a6paper.
\documentclass{article}
This document is typeset on A6 paper in landscape mode.
\usepackage[
a6paper,
landscape,
]{geometry}
\begin{document}
This document is typeset on
A6 paper in landscape mode. 1
\end{document}
If the predefined dimensions are not enough you can always set it
directly using paperheight and paperwidth keys.
\usepackage[
paperwidth=6cm, This page has dimensions
paperheight=3cm
of 6 by 3 centimetres.
]{geometry}
% ...
\usepackage[ Lorem
top=0.5cm, ipsum do-
bottom=1cm, lor sit amet,
left=1.5cm, consectetuer
right=2cm, adipiscing elit.
]{geometry} Etiam lobortis
% ...
Note that by default the header and footer are not considered part of the
page body, so they may not fit on page if the margins are too narrow (like
in the example above). If you want to include them when considering
margins use the includefoot and/or includehead options.
One of the killer features of the geometry package is its ability to
calculate the correct margin sizes based on other metrics. For example, we
can declare that we want the text to have a given width via textwidth
option and that each page should have a given number of lines via
lines option and the appropriate sizes of margins will be calculated
automatically.
\usepackage[
Lorem ipsum dolor sit
textwidth=5cm,
amet, consectetuer adipiscing
lines=3
elit. Etiam lobortis facilisis sem.
]{geometry}
% ...
1
There are many more options to influence the margins: specifying their
ratios (ratio), defining them to take up certain percent of available
paper size (scale), or including binding offset (bindingoffset). Check
out the package documentation [83] for a full list with examples.
A useful option for prototyping your layout is the showframe option
that draws frames around document body and margins to easier evaluate
the chosen layout.
7.7 Fancy Headers 215
The fancyhdr [50] package provides a few simple commands that allow
you to customise the header and footer lines of your document. It defines
an additional page style fancy and a set of commands to customise it to
your liking. By default, it only adds a line separating the header from
the page body.
\documentclass{article}
\usepackage{fancyhdr}
\pagestyle{fancy} This statement is false.
\begin{document}
This statement is false. 1
\end{document}
\fancyhf[〈places〉]{〈field〉}
The 〈places〉 is a comma separated list of places where the 〈field〉 should
be displayed. There are total of 12 different places and each is identified
by a combination of three letters:
• The second letter specifies the location within the header or footer:
L for left, C for centre, and R for right.
• The third letter defines whether the field should be printed on even
(E) or odd (O) pages. If the document is not two sided, then all
pages are treated as odd.
For example, the combination FCE identifies the centre part of the footer
on even pages. If any of the letters is omitted, then the identifier points
toward all positions specifiable by the omitted letter. For example, HR is
216 Customising LATEX
\documentclass[twoside]{article}
\usepackage{fancyhdr} B D
\pagestyle{fancy}
The next statement is false. The
\fancyhf[HCE]{A}
\fancyhf[L]{\emph{B}} B 1 C
\fancyhf[FR]{\textbf{C}}
\fancyhf[HCO, HRE]{\textsl{D}} B A D
previous statement is true.
\begin{document}
The next statement is false. B 2 C
The previous statement is true.
\end{document}
\fancyhead[L]{A} A
\fancyfoot[R]{B}
“Yields a falsehood when ap-
\enquote{Yields a falsehood when pended to its own quotation”
appended to its own quotation} yields a falsehood when ap-
yields a falsehood when appended pended to its own quotation.
to its own quotation.
1 B
\headrulewidth
\footrulewidth
\RenewDocumentCommand{\headrulewidth}{}{.2cm}
\RenewDocumentCommand{\footrulewidth}{}{.5cm} Do not read
this sentence.
Do not read this sentence.
1
7.7 Fancy Headers 217
By default, headers and footers are as long as the text on the page.
If you want to extend or shorten them, use the
\fancyhfoffset[〈places〉]{〈offset〉}
Added comma after \fancyhf. command. The 〈places〉 argument is the
same as in \fancyhf, except that it cannot contain C.
\fancyhfoffset[L]{-1cm}
\fancyhfoffset[R]{.2cm} If this sentence is true, then
2 + 2 = 5.
If this sentence is true,
then \(2 + 2 = 5\).
1
Then you can access these marks inside the headers by using the appro-
priate command. The first- commands refer to the first mark occurring
on the page, while the last- refer to the last one.
\usepackage{extramarks}
Let us now look at the default marks defined by LATEX. After loading
extramarks, these may be set and accessed similarly:
\markboth{〈left〉}{〈right〉}
\firstleftmark
\firstrightmark
\lastleftmark
\lastrightmark
The only difference between these and the extra marks is that LATEX
classes automatically fill them. Hence, if you are not careful, you may
lose your content.8 For example, in the article class, 〈left〉 is set by the
\section command, while 〈right〉 is set by the \subsection command.
1 FIRST 2 SECOND
\fancyhead[L]{\firstleftmark}
\fancyhead[R]{\lastleftmark} 1 First
\fancyfoot[L]{\firstrightmark}
\fancyfoot[R]{\lastrightmark} 1.1 Sub
\section{First} 2 Second
\subsection{Sub}
\section{Second} 2.1 Sub
\subsection{Sub}
1 2.1 Sub
8
You may prevent this by setting the pagestyle to myheadings and then redefining
it to use it with fancyhdr as described later.
7.7 Fancy Headers 219
\fancyhead[R]{% 1 Today
\nouppercase{\firstleftmark}%
} 1 Today
is opposite day.
\section{Today}
is opposite day. 1
If you only want to change the right mark, use the \markright command.
By default, the field in the centre of the header or footer will expand
equally to the left and right. This is usually the desired behaviour, but
in some cases it may overlap with either left or right text, while still
having some space on the other side.
\fancyhead[L]{\thepage} 1 1 SECTION
Jane Doe
\fancyhead[C]{\firstleftmark}
\fancyhead[R]{Jane Doe} 1 Section
Section by Jane Doe
\section{Section}
Section by Jane Doe 1
9
Or \chaptermark, \subsectionmark …
220 Customising LATEX
\fancycenter[〈distance〉][〈stretch〉]{〈left〉}{〈centre〉}{〈right〉}
command, which automatically shifts the centre toward the shorter text.
The 〈distance〉 is the minimum distance by which the elements are always
surrounded (1em, by default). The 〈stretch〉 controls the preference for
shifting the 〈centre〉; 1 means shift only when and as much as necessary.
Higher numbers will start shifting sooner and more aggressively. The
default is 3. This command writes over the whole header/footer space
so it should only be put in one place (typically C) and other places (L,R)
should be empty.
\fancyhead[L,R]{}
\fancyhead[C]{%
\fancycenter% 1 1 SECTION Jane Doe
{\thepage}%
{\firstleftmark}% 1 Section
{Jane Doe}%
Section by Jane Doe
}
1
\section{Section}
Section by Jane Doe
You may want to present different headers or footers when the corre-
sponding page starts with a float or ends with a footnote. The fancyhdr
package defines four commands that let you achieve this.
page.
\fancyhead[C]{%
\iftopfloat{%
A float is below me%
} {} Ignore this footnote.1
}
\fancyfoot[C]{%
\iffootnote{%
A footnote is above me%
1 Read this.
} {%
\thepage% A footnote is above me
}%
} A float is below me
\RenewDocumentCommand{\headrule}{}{
\rule{0.05\headwidth}{0.2cm}%
\rule[0.1cm]{0.9\headwidth}{\headrulewidth}%
My age is the
\rule{0.05\headwidth}{0.2cm}%
first number
}
not nameable
in under twenty
\RenewDocumentCommand{\headruleskip}{}{-0.2cm}
words.
My age is the first number not
nameable in under twenty words. 1
\fancypagestyle{〈name〉}{〈code〉}
command. The 〈name〉 is the name of page style to (re)define, while the
〈code〉 is the code to set the page style. All page styles declared this way
222 Customising LATEX
use the fancy page style as their basis, so if empty 〈code〉 is given they
will match fancy exactly.
\fancypagestyle{mine}{ My style
\fancyhead[L]{My style}
} You may be disappointed.
\pagestyle{mine}
7.8 Boxes
LATEX builds up its pages by pushing around boxes. At first, each letter
is a little box, which is then glued to other letters to form words. These
are again glued to other words, but with special glue, which is elastic so
that a series of words can be squeezed or stretched as to exactly fill a
line on the page.
I admit, this is a very simplistic version of what really happens, but
the point is that TEX operates on glue and boxes. Letters are not the
only things that can be boxes. You can put virtually everything into a
box, including other boxes. Each box will then be handled by LATEX as
if it were a single letter.
In earlier chapters you encountered some boxes, although I did not
tell you. The tabular environment and the \includegraphics, for
example, both produce a box. This means that you can easily arrange
two tables or images side by side. You just have to make sure that their
combined width is not larger than the text width.
You can also pack a paragraph of your choice into a box with either
the
\parbox[pos]{width}{text}
command or the
\makebox[width][pos]{text}
width defines the width of the resulting box as seen from the outside.10
Besides the length expressions, you can also use \width, \height, \depth,
and \totalheight in the width parameter. They are set from values
obtained by measuring the typeset text. The pos parameter takes a one
letter value: center, flushleft, flushright, or spread the text to fill the
box.
The command \framebox works exactly the same as \makebox, but
it draws a box around the text.
The following example shows you some things you could do with the
\makebox and \framebox commands.
\makebox[\textwidth]{%
c e n t r a l}\par
\makebox[\textwidth][s]{% central
s p r e a d}\par
s p r e a d
\framebox[1.1\width]{Guess I'm
framed now!} \par Guess I’m framed now!
\framebox[0.8\width][r]{Bummer, Bummer, I am too wide
I am too wide} \par
never Can
mind,you
so read
am I this?
\framebox[1cm][l]{never
mind, so am I}
Can you read this?
\raisebox{lift}[extend-above-baseline][extend-below-baseline]{text}
command lets you define the vertical properties of a box. You can use
10
This means it can be smaller than the material inside the box. You can even set
the width to 0pt so that the text inside the box will be typeset without influencing
the surrounding boxes.
11
Total control is only to be obtained by controlling both the horizontal and the
vertical …
224 Customising LATEX
\raisebox{0pt}[0pt][0pt]{\Large%
\textbf{Aaaa\raisebox{-0.3ex}{a}%
\raisebox{-0.7ex}{aa}% Aaaaaaa she shouted,
\raisebox{-1.2ex}{r}% r
but not even gthe next one in
\raisebox{-2.2ex}{g}%
\raisebox{-4.5ex}{h}}} h something
line noticed that
she shouted, but not even the next terrible had happened to her.
one in line noticed that something
terrible had happened to her.
7.9 Rules
A few pages back you may have noticed the command
\rule[lift]{width}{height}
\rule{3mm}{.1pt}%
\rule[-1mm]{5mm}{1cm}%
\rule{3mm}{.1pt}%
\rule[1mm]{1cm}{5mm}%
\rule{3mm}{.1pt}
This is useful for drawing vertical and horizontal lines. The line on the
title page, for example, has been created with a \rule command.
The End.
Appendix A
Installing LATEX
Knuth published the source to TEX back in a time when nobody knew about
Open Source and/or Free Software. The license that comes with TEX lets
you do whatever you want with the source, but you can only call the result of
your work TEX if the program passes a set of tests Knuth has also provided.
This has led to a situation where we have free TEX implementations for
almost every Operating System under the sun. This chapter will give some
hints on what to install on Linux, macOS and Windows, to get a working
TEX setup.
Over the past few years I have come to like Texmaker quite a lot.
Apart from being very a useful editor with integrated pdf-preview and
syntax high-lighting, it has the advantage of running on Windows, Mac,
and Unix/Linux equally well. See [6] for further information. There is
also a forked version of Texmaker called TeXstudio [87]. It also seems
well maintained and is also available for all three major platforms.
You will find some platform specific editor suggestions in the OS
sections below.
which exists for Windows, Unix, and Mac OS to get your base setup
going.
If you are looking for a more windows like graphical editing environ-
ment, check out Texmaker. See Section A.2.
Most Linux distros insist on splitting up their TEX environments into
many optional packages, so if something is missing after your first install,
go check again.
Appendix B
LATEX has been around for well over 30 years now. And it has remained
largely backward compatible. This means you can easily steal snippets from
a friends document written ten years ago and use them in your document
today. In many instances this work without any problem. But even though
LATEX seems happy with the old code, you still should not do it. Have a
look!
$$ 2 + 2 = 4 $$ ⟶ \[ 2 + 2 = 4 \]
but it may become an issue if you want to modify the command yourself.
Also, the \(, \) commands can detect math mode nesting and produce
an error if it happens.
$ 2 + 2 = 4 $ ⟶ \( 2 + 2 = 4 \)
{a \over b} ⟶ \frac{a}{b}
\newcommand{\foo}[4][bar]{ ... }
\NewDocumentCommand{\foo}{O{bar}mmmm}{ ... }
B.5 … for Copying Commands 231
\def\foo#1#2#3{ ... }
\NewDocumentCommand{\foo}{mmm}{ ... }
Instead of Use
\let \NewCommandCopy
\RenewCommandCopy
\DeclareCommandCopy
Like Section B.4, \let is also a plain TEX primitive that does not guard
against accidental redefinition. Moreover it does not work correctly
with some LATEX commands. Use \NewCommandCopy as described in
subsection 7.1.3.
\let\foo\bar ⟶ \NewCommandCopy\foo\bar
Instead of Use
\begin{eqnarray} \begin{align}
\begin{eqnarray*} \begin{align*}
(Both in amsmath.)
\begin{eqnarray}\obeyedline ⟶
f(x) & \usepackage{amsmath}\obeyedline%
= & 1 + 2 \\\obeyedline g(x) & ...\obeyedline\beg
> & 52\obeyedline\
232 Things You Shouldn’t Use
Instead of Use
\bf \bfseries
\rm \rmfamily
\sf \sffamily
\tt \ttfamily
\it \itshape
\sc \scshape
\sl \slshape
These are plain TEX commands. Each of them resets the font to normal
before changing it, so for example bold italics cannot be achieved using
them. Use newer commands as described in Section 7.2.
Instead of Use
\begin{flushleft} \begin{FlushLeft}
\begin{flushright} \begin{FlushRight}
\begin{center} \begin{Center}
(ragged2e)
The default LATEX 2𝜀 environments for changing text alignment make
it nearly impossible to hyphenate words inside them. Therefore, it is
recommended to use the ragged2e equivalents, as described in Section 2.15,
that make the text less ‘ragged’ than it should be.
\begin{center}\obeyedline text\obeyedline\end{center}
⟶ \usepackage{ragged2e}\obeyedline% ...\obey
Instead of Use
`` \enquote
,, \enquote*
<<
>>
''
B.10 … for Printing Verbatim 233
The TEX version of entering quotes was to rely on ligatures for the
given quotation mark. This method is not context aware and cannot be
customized. Using csquotes package as described in Section 2.16 allows
greater control over the typesetting of the quotations.
Instead of Use
verbatim verbatim (from the verbatim pack-
age)
LATEX comes with a verbatim environment built into the core, however
there are problems with it. Firstly, due to the way delimiting is handled
you cannot put spaces between \end and {verbatim}. The second
and more important problem is that it reads the whole input at once
which risks overflowing TEX’s memory. The verbatim package described
in subsection 2.17.1 solves both of these problems.
\begin{verbatim}\obeyedline ⟶
code\obeyedline\end{verbatim}
\usepackage{verbatim}\obeyedline% ...\obeyedline\be
Instead of Use
natbib and bibtex biblatex and biber
\usepackage{natbib} ⟶ \usepackage{biblatex}
Instead of Use
\stackrel \overset
\stackbin
234 Things You Shouldn’t Use
The commands are primitives that always define the underlying symbol
to be either a relation or binary operator. The \overset detects this
based on the symbol that is overset. See subsection 3.3.6 for an example
of usage.
\stackrel{f}{=} ⟶ \overset{f}{=}
\stackbin{f}{+} ⟶ \overset{f}{+}
Instead of Use
\mathrm \symrm
\mathit \symit
\mathbf \symbf
\mathcal \symcal
\mathscr \symscr
\mathbb \symbb
\mathfrak \symfrak
(unicode-math package)
\(\mathit{ffi}\) vs.\
\(\symit{ffi}\)
ffi vs. 𝑓𝑓𝑖
These commands should not be used for changing the font for symbols.
For historical reasons, some of the \math... commands are actually just
synonyms for the symbol versions. For example there is no \mathscr
version for math operators, so it is just a synonym for \symscr. For
operators it is better to use the \DeclareMathOperator command.
\(\mathrm{foo}(\mathcal{F})\)
\DeclareMathOperator{\foo}{foo}\obeyedline% ...\obeyedline\(\foo(\symcal{F})\)
B.14 … for Spacing 235
Preamble
2. Basic Permissions.
All rights granted under this License are granted for the term
of copyright on the Program, and are irrevocable provided the
stated conditions are met. This License explicitly affirms your
unlimited permission to run the unmodified Program. The output
from running a covered work is covered by this License only if the
output, given its content, constitutes a covered work. This License
acknowledges your rights of fair use or other equivalent, as provided
by copyright law.
You may make, run and propagate covered works that you do
not convey, without conditions so long as your license otherwise
remains in force. You may convey covered works to others for the
sole purpose of having them make modifications exclusively for you,
or provide you with facilities for running those works, provided that
you comply with the terms of this License in conveying all material
for which you do not control copyright. Those thus making or
running the covered works for you must do so exclusively on your
behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside
their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section
10 makes it unnecessary.
241
(a) The work must carry prominent notices stating that you
modified it, and giving a relevant date.
(b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section
4 to “keep intact all notices”.
(c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section
7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
242 GNU General Public License, Version 3
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of
this License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program
shall be treated as though they were included in this License, to
the extent that they are valid under applicable law. If additional
permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program
remains governed by this License without regard to the additional
permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any
part of it. (Additional permissions may be written to require their
own removal in certain cases when you modify the work.) You
may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright
permission.
Notwithstanding any other provision of this License, for material
you add to a covered work, you may (if authorized by the copyright
holders of that material) supplement the terms of this License with
245
terms:
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate
or modify it is void, and will automatically terminate your rights
246 GNU General Public License, Version 3
under this License (including any patent licenses granted under the
third paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally termi-
nates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior
to 60 days after the cessation.
Moreover, your license from a particular copyright holder is re-
instated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate
the licenses of parties who have received copies or rights from you
under this License. If your rights have been terminated and not
permanently reinstated, you do not qualify to receive new licenses
for the same material under section 10.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.
The work thus licensed is called the contributor’s “contributor
version”.
A contributor’s “essential patent claims” are all patent claims
owned or controlled by the contributor, whether already acquired
or hereafter acquired, that would be infringed by some manner,
permitted by this License, of making, using, or selling its contributor
version, but do not include claims that would be infringed only as
a consequence of further modification of the contributor version.
For purposes of this definition, “control” includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-
free patent license under the contributor’s essential patent claims,
to make, use, sell, offer for sale, import and otherwise run, modify
and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce
a patent (such as an express permission to practice a patent or
covenant not to sue for patent infringement). To “grant” such a
patent license to a party means to make such an agreement or
commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through
a publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be
so available, or (2) arrange to deprive yourself of the benefit of
the patent license for this particular work, or (3) arrange, in a
248 GNU General Public License, Version 3
way you could satisfy both those terms and this License would be
to refrain entirely from conveying the Program.
<one line to give the program's name and a brief idea of what it does.>
251
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands show w and show c should show the ap-
propriate parts of the General Public License. Of course, your program’s
commands might be different; for a GUI interface, you would use an
“about box”.
You should also get your employer (if you work as a programmer)
or school, if any, to sign a “copyright disclaimer” for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see https://www.gnu.org/licenses/.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read https://www.gnu.org/licenses/why-not-lgpl.html.
Bibliography
[12] David Carlisle et al. setspace – Set space between lines. Version 6.7a.
Dec. 19, 2011. url: https://ctan.org/pkg/setspace.
[13] François Charette. arabxetex – An ArabTEX-like interface for
XƎTEX. Version 1.2.1. Sept. 4, 2015. url: https://www.ctan.
org/pkg/arabxetex.
[14] François Charette and Philip Kime. biber. Version 2.17. 2022. url:
https://www.ctan.org/pkg/biber.
[15] François Charette et al. polyglossia – An alternative to babel for
XƎLATEX and LuaLATEX. Version 1.57. July 18, 2022. url: https:
//www.ctan.org/pkg/polyglossia.
[16] L. Peter Deutsch. Ghostscript. Version 9.56.1. 2022. url: https:
//www.ghostscript.com/.
[17] Simon Fear and Danie Els. booktabs – Publication quality tables
in LATEX. Version 1.61803398. Jan. 14, 2020. url: https://www.
ctan.org/pkg/booktabs.
[18] Christian Feuersänger. pgfplots – Create normal/logarithmic plots
in two and three dimensions. Version 1.18.1. May 17, 2021. url:
https://www.ctan.org/pkg/pgfplots.
[19] Alexander Grahn. ocgx2 – Drop-in replacement for ‘ocgx’ and ‘ocg-
p’. Version 0.54. Apr. 1, 2022. url: https://www.ctan.org/pkg/
ocgx2.
[20] Frank Grießhammer and Adobe. Source Serif. Version 4.004. Jan. 25,
2021. url: https://github.com/adobe-fonts/source-serif.
[21] MacTeX TeXnical working group. MacTeX. Version MacTeX-2022.
2022. url: https://tug.org/mactex/.
[22] Andy Hammerlindl, John Bowman, and Tom Prince. asymptote
– 2D and 3D TEX-Aware Vector Graphics Language. Version 2.80.
Apr. 5, 2022. url: https://www.ctan.org/pkg/asymptote.
[23] Carsten Heinz, Brooks Moses, and Jobst Hoffmann. listings – Type-
set source code listings using LATEX. Version 1.8d. Mar. 24, 2020.
url: https://www.ctan.org/pkg/listings.
[24] Martin Hensel. mhchem – Typeset chemical formulae/equations
and H and P statements. Version 2021-12-31. Dec. 31, 2021. url:
https://www.ctan.org/pkg/mhchem.
[25] Morten Høgholm, Lars Madsen, and The LATEX3 Project. mathtools
– Mathematical tools to use with amsmath. Version 1.28a. Feb. 7,
2022. url: https://www.ctan.org/pkg/mathtools.
[26] Morten Høgholm and The LATEX3 Project. xfrac – Split-level frac-
tions in LATEX 2𝜀 *. Version 2022-06-22. June 22, 2022. url: https:
//www.ctan.org/pkg/xfrac.
BIBLIOGRAPHY 255
[27] Paul D. Hunt and Adobe. Source Code Pro. Version 2.038. Jan. 15,
2021. url: https://github.com/adobe-fonts/source-code-
pro.
[28] Paul D. Hunt and Adobe. Source Sans 3. Version 3.046. July 14,
2021. url: https://github.com/adobe-fonts/source-sans.
[29] Inkscape. Version 1.2.1. July 14, 2022. url: https://inkscape.
org/.
[30] International Organization for Standardization. ISO 80000-2:2019.
2nd ed. Nov. 2021. url: https://www.iso.org/obp/ui/#iso:
std:iso:80000:-2:ed-2:v2:en.
[31] Dr. Uwe Kern. xcolor – Driver-independent color extensions for
LATEX and pdfLATEX. Version 2.14. June 12, 2022. url: https :
//www.ctan.org/pkg/xcolor.
[32] Jonathan Kew, Stefan Löffler, and Charlie Sharpsteen. TeXworks.
Version 0.6.7. 2022. url: https://www.tug.org/texworks/.
[33] Vafa Khalighi and bidi-tex GitHub Organisation. bidi – Bidirec-
tional typesetting in plain TEX and LATEX, using XƎTEX. Ver-
sion 36.7. Feb. 18, 2022. url: https://www.ctan.org/pkg/bidi.
[34] Vafa Khalighi and bidi-tex GitHub Organisation. XePersian –
Persian for LATEX, using XƎTEX. Version 23.7. Feb. 20, 2022. url:
https://www.ctan.org/pkg/xepersian.
[35] Vafa Khalighi, Arthur Reutenauer, and Jürgen Spitzmüller. luabidi
– Bidi functions for LuaTEX. Version 0.5. Oct. 27, 2019. url:
https://www.ctan.org/pkg/luabidi.
[36] Spencer Kimball and Peter Mattis. GIMP. Version 2.10.30. 2021.
url: https://www.gimp.org/.
[37] Daniel Kirsch. Detexify. url: https://detexify.kirelabs.org/
classify.html.
[38] Donald E. Knuth. Knuth message on ‘Diskussion:TeX — Aussprache’.
Posted by user S (https://de.wikipedia.org/wiki/Benutzer:
S). Apr. 5, 2004. url: https://de.wikipedia.org/w/index.
php?title=Diskussion:TeX&oldid=217574275#Aussprache.
[39] Donald E. Knuth. The TEXbook. 2nd ed. Vol. A. Computers and
Typesetting. Reading, Massachusetts: Addison-Wesley, 1984. isbn:
0-201-13448-9.
[40] Markus Kohm. koma-script – A bundle of versatile classes and
packages. Version 3.37. July 4, 2022. url: https://ctan.org/
pkg/koma-script.
256 BIBLIOGRAPHY
[68] Michael Shell. “How to Use the IEEEtran LATEX Class.” In: Journal
of LATEX Class Files 14.8 (Aug. 2015). url: http://www.ctan.org/
tex - archive / macros / latex / contrib / IEEEtran / IEEEtran _
HOWTO.pdf.
[69] Michael Shell. ieeetrantools. Version 1.4. 2014. url: https://www.
ctan.org/pkg/ieeetrantools.
[70] Axel Sommerfeldt. newfloat – Define new floating environments.
Version 1.1l. Sept. 2, 2019. url: https://www.ctan.org/pkg/
newfloat.
[71] Wenchang Sun, Leo Liu, and Qing Lee. xecjk – Support for CJK
documents in XeLaTeX. Version 3.8.8. Dec. 14, 2021. url: https:
//github.com/CTeX-org/ctex-kit.
[72] Supreme Council of Information and Communication Technology
and Mohammad Saleh Souzanchi. Iran Nastaliq font. 2020. url:
https://github.com/font-store/font-IranNastaliq.
[73] Till Tantau and Henri Menke. pgf – Create PostScript and PDF
graphics in TEX. Version 3.1.9a. May 15, 2021. url: https://www.
ctan.org/pkg/pgf.
[74] Till Tantau, Vedran Miletić, and Joseph Wright. beamer – A LATEX
class for producing presentations and slides. Version 3.67. May 17,
2022. url: https://www.ctan.org/pkg/beamer.
[75] The LATEX Team. LATEX 2𝜀 font selection. Mar. 2021. url: https:
//www.ctan.org/pkg/fntguide.
[76] The LATEX Team. makeidx – Standard LATEX package for creating
indexes. Version 1.0m. Sept. 29, 2014. url: https://www.ctan.
org/pkg/makeidx.
[77] The TeXnicCenter Team. TeXnicCenter. Version 2.02. 2013. url:
https://www.texniccenter.org/.
[78] SIL Language Technology. Ezra SIL. Version 2.51. Oct. 4, 2007.
url: https://software.sil.org/ezra/.
[79] The TEX Live Team and Peter Breitenlohner. 𝜀-TEX – An extended
version of TEX, from the NTS project. Version 2.0. Feb. 1998. url:
https://www.ctan.org/pkg/etex.
[80] John Hobby and The METAPOST Team. metapost – A development
of METAFONT for creating graphics. Version 2.00. Dec. 31, 2020.
url: https://www.ctan.org/pkg/metapost.
[81] The SageMath Developers. SageMath. Version 9.6. 2022. doi: 10.
5281/zenodo.593563. url: https://www.sagemath.org/.
BIBLIOGRAPHY 259
[82] Antonis Tsolomitis. New Computer Modern. Version 4.1. Dec. 15,
2021. url: https://www.ctan.org/pkg/newcomputermodern.
[83] Hideo Umeki and David Carlisle. geometry – Flexible and complete
interface to document dimensions. Version 5.9. Jan. 2, 2020. url:
https://ctan.org/pkg/geometry.
[84] Wikipedia contributors. Help:Displaying a formula — Wikipedia,
The Free Encyclopedia, year = 2022. [Online; accessed 10-June-
2022]. url: https://en.wikipedia.org/w/index.php?title=
Help:Displaying_a_formula&oldid=1091087776.
[85] Peter R. Wilson and Lars Madsen. memoir – Typeset fiction, non-
fiction and mathematical books. Version 3.7r. July 29, 2022. url:
https://ctan.org/pkg/memoir.
[86] Joseph Wright. siunitx – A comprehensive (SI) units package.
Version 3.1.1. May 3, 2022. url: https://www.ctan.org/pkg/
siunitx.
[87] Benito van der Zander. TeXstudio. Version 4.2.3. 2022. url: https:
//www.texstudio.org/.
[88] Timothy Van Zandt and Herbert Voss. fancyvrb – Sophisticated
verbatim text. Version 4.2. Apr. 12, 2022. url: https://www.ctan.
org/pkg/fancyvrb.
Index
Symbols ~, 98
", 37 \], 76, 229
\(, 76, 229, 230
\), 76, 229, 230 A
\,, 114 A4 paper, 208
-, 22 A5 paper, 208
\-, 21 å, 25
\above, 230
–, 22
\abovewithdelims, 230
—, 22
abstract, 24
., 89, 98
accent, 25
., space after, 33
acute, 25
…, 23
\acute, 87
\/, 186
\addbibresource, 129
\:, 93, 114
\addtolength, 205
\;, 93, 114
\addvspace command, 204
\[, 76, 77, 229
\adots, 121
$, 229 advantages of LATEX, 4
$$, 229 æ, 25
%, 6, 31, 183 \alert, 147
&, 53, 92 align, 92, 93, 95, 231
\, 20 align*, 231
^, 78, 79 \Alpha, 81
_, 78 \alpha, 81
\\, 61 American Mathematical Society, 75
articleclass, 8, 154, 208 amsmath, 15, 75, 90, 95, 107, 122,
beamerclass, 8, 145, 147, 153 147, 229–231, 235
bookclass, 8, 208 amsmath, 95
letterclass, 8 amsthm, 116, 118
memoirclass, 209 \and, 34
procclass, 8 \ang, 103
reportclass, 8, 208 \appendix, 35
slidesclass, 145 Arabic, 30
{, 7 arabxetex, 30
}, 7 \arccos, 84
~, 33, 183 \arcsin, 84
INDEX 261
\arctan, 84 \blockquote, 38
\arg, 84 Bmatrix, 111
array, 53, 63 bmatrix, 111
array, 112 bold face, 186
asymptote, 158 booktabs, 15, 53, 54
\atop, 230 booktabs, 55
\atopwithdelims, 230 \BooleanFalse, 182
\author, 34, 146 \BooleanTrue, 182
\autocite, 134 \bot, 112, 113
\autopageref, 142 \bottomrule, 54
\autoref, 142
C
B \cap, 81
B5 paper, 208 \caption, 70, 71, 73
babel, 24 cases, 111
\backmatter, 35 \cdot, 78
backslash, 7 \cdots, 120
\bar, 87 Center, 37, 232
base font size, 208 center, 232
\baselineskip, 211 \cfrac, 122
beamer, 15, 145, 147, 149, 150, 152–155
\chapter, 33, 132, 221
beamerarticle, 154 \chapter*, 132
\begin, 13, 179 \chaptermark, 219
\Beta, 81 chemformula, 115
\beta, 81 \Chi, 81
\bf, 232 \chi, 81
\bfseries, 186, 232 Chinese, 30
biber, 126 \choose, 230
\bibitem, 125 \cite, 125, 133, 134
biblatex, vii, 15, 125–127, 130, 131, \citeauthor, 134
133 \citedate, 134
biblatex, 233 \citetitle, 134
bibliography, 125 \citeurl, 134
bidi, 29 \citeyear, 134
\Big, 90 \cleardoublepage, 71
\big, 90 \clearpage, 71
\bigcap, 113 \cline, 64
\Bigg, 90 \cmidrule, 56, 58
\bigg, 90 \colon, 81, 113
\bigskip, 204 \coloneq, 76
\bigwedge, 85 \Coloneqq, 76
binary relations, 88 \coloneqq, 76
\binom, 122, 230 \color, 195, 199
block, 147 \colorbox, 199
262 INDEX
M mhchem, 115
MacTeX, 226 \midrule, 54
\mainmatter, 35 MiKTEX, 226
\makebox, 223 \min, 84
makeidx, 15, 137 minipage, 222
makeidx package, 137 minted, vi, 49, 50
\makeindex, 137 minted, 49
makeindex program, 137 \mintinline, 49
\maketitle, 34, 146, 221 \mkern, 235
Malay, 30 \mskip, 235
margins, 212 \mspace, 113, 115, 235
\markboth, 218 \Mu, 81
\markright, 219 \mu, 81
math mode, 77 \multicol, 107
math spacing, 112 \multicolumn, 56–58, 61
\mathbb, 234 multirow, 53, 56
\mathbf, 234 \multirow, 56, 58, 59, 61, 107
\mathbin, 113 multline, 91
\mathcal, 234 multline*, 91
\mathclose, 113 mwe, 65
\mathcolor, 195 N
mathematical natbib, 233
accents, 87 \negmedspace, 97, 114
\mathfrak, 234 \negmedspace, 97
\mathit, 234 \negthickspace, 114
\mathop, 113 \negthinspace, 114
\mathopen, 113 \neq, 78
\mathord, 113 \newcolumntype, 64
\mathpunct, 113 \newcommand, 230
\mathrel, 112, 113 \NewCommandCopy, 181, 198, 231
\mathrm, 234 \NewDocumentCommand, 31, 32, 176,
\mathscr, 234 178, 179, 181, 188, 198, 230
mathtools, 75, 76, 90, 115 \NewDocumentEnvironment, 179–181
matrix, 107 newfloat, 71
matrix, 107, 111, 112 \newfontfamily, 27, 191, 193
\max, 84 \newlength, 205
\mbox, 22, 223 \newline, 19
\mdseries, 186 \NewNegationCommand, 194
\medskip, 204 \newpage, 20
\medskipamount, 204 \newtheorem, 116
\medspace, 114 \nobreakspace, 183
memoir, 209 \nocite, 131
metapost, 158 \node, 160, 161
INDEX 275
xepersian, 29, 30
xfrac, 121
\Xi, 81
\xi, 81
xypic, 158
Z
\Zeta, 81
\zeta, 81