Scientific Writing With LaTeX
Scientific Writing With LaTeX
1 Scientific writing 5
2 A quick start to writing in LATEX 5
3 Expanding your manuscript 8
3.1 Types of commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 The document structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3 Document classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Reserved characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.5 Type face styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.6 Typographic features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.7 Breaks and space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.8 Headings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.9 Table of contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.10 Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.11 cross-referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.12 Special commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4 Tabular information 17
5 Floats; tables and figures on the run 18
6 Mathematical typesetting 19
7 Extending the functionality of LATEX, packages 21
7.1 inputenc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
7.2 graphicx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
7.3 geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7.4 natbib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7.5 hyperref . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
7.6 booktabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
7.7 siunitx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.8 lineno . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.9 dcolumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.10 tikz/pgf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
7.11 xcolor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
7.12 caption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
7.13 float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
7.14 amslatex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
7.15 babel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
7.16 lipsum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
8 Managing references 31
8.1 The natbib package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
8.2 The fully automated reference system . . . . . . . . . . . . . . . . . . . . . . . . 32
8.3 Integration of Overleaf and Zotero . . . . . . . . . . . . . . . . . . . . . . . . . . 33
8.4 The semi-automated reference system . . . . . . . . . . . . . . . . . . . . . . . . 33
9 Automating LATEX or creating your own commands 34
10 Copying documents from Word to LATEX 35
11 Making presentation slides in LATEX 36
12 Reinventing the wheel? …or not 37
13 How does it really work? 38
14 Saving the worst to last 39
A Running LaTeX on your own computer 41
A.1 LATEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
A.2 LATEX editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
A.3 Other software that may be required . . . . . . . . . . . . . . . . . . . . . . . . . 41
A.4 Reference management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
A.5 Yet more software that might be of use . . . . . . . . . . . . . . . . . . . . . . . . 42
2
B Install LATEX on your computer 42
B.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
B.2 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
B.3 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
C Learning more on LATEX 43
D Revision history 44
3
Preface
This document is intended to provide you with a good working knowledge of LATEX so that you
can freely use it for your scientific output. LATEX was, and is, created by scientists for scientists
and is widely used by publishers for both journals and books. To have working knowledge of
LATEX should be part of every scientist’s toolbox.
There are two choices for running LATEX, on-line or off-line tools. These should not be
considered mutually exclusive, you may need to work both ways. In this text I will assume you
are working with the on-line platform Overleaf which is what I would also recommend to anyone,
beginner or experienced, since all you need is a web-browser and an internet connection, no
installation on your computer. Overleaf is similar to Google docs in that documents are stored in
the cloud and that several persons can interactively collaborate on a document. The drawback
is of course that you cannot work on your documents without internet access. You can, however,
synchronise your files in the cloud with Dropbox or Git so that you always have updated versions
on your own computer. To work off-line you need to install a LATEX environment locally on
your own computer; this is covered in appendix A.
So I strongly advice the beginner to sign up for and use Overleaf. Note that you may be
covered by an institutional license if you study or work at a university. Please visit the Overleaf
site and look at the introductory video to familiarise yourself with the Overleaf environment.
This document was entirely written on and using Overleaf but does not detail how you use the
interface. Of particular use is the keyboard shortcuts sheet.
Although not covered in any detail in this document, I also strongly urge you to start using
a reference manager for handling your scientific references. Unless you already use a software
I would recommend using the online manager Zotero which integrates with Overleaf. This
integration is briefly covered in section 8.3.
In this text, I will use typewriter type face to highlight LATEX code. In the cases where a
complete section of code is given
it will be presented in a blue field.
Apart from what is covered in this text, you probably should download the LATEX 2ε Cheat
Sheet and the LATEX quick reference and keep them handy. The comprehensive list of LATEX
symbols is also useful to have handy. You should also be aware of the TEX StackExchange site,
which is a question and answer site where probably all your questions are already answered. At
the time of writing there are 181 306 answered questions on the site. You can also find many
solutions to type-setting issues by typing ‘latex’ followed by whatever you are looking for. It is
almost certain some of the highest hits are from the TEX StackExchange.
More details on how different macro packages work can be obtained from their documenta-
tion which is available on the Comprehensive TEX Archive Network (CTAN) site. At the time
of writing there are 5740 macro packages contributed by 2632 different users.
4
1 Scientific writing
Apart from the linguistic aspects of scientific writing, such as clarity, brevity and density,
what distinguishes scientific writing is the use of many technical terms, technical notation and
cross-referencing of citations, figures, tables and equations as well as the need to follow precise
document formatting instructions. Clearly you can accomplish the first aspect with any type of
writing tool from the Goose pen to a modern word processor, it is the second part that requires
some special tools. This is where LATEX fits.
Now LATEX is not the universal response to all writing issues; as with everything there
are definite pro’s and con’s. Since LATEX involves knowing a fair number of commands and
understanding exactly how to use them, it is associated with a learning curve similar to that
of learning a programming language. In fact, it is a programming language (Turing complete).
It is therefore evident that it makes little sense to use LATEX for menial tasks such as writing a
letter or a memo to colleagues or a list for making purchases, that is the realm of Word. LATEX
comes into its own when the document is more complex.
There are probably many different imaginable tasks where LATEX is preferable, I will just
mention a few. When you write a scientific article you greatly benefit from using LATEX because
you can clearly express, for example, complicated notation and mathematics, and it is also
very likely that the journal accepts LATEX manuscripts in their own journal format. LATEX is
also very useful when you try to write a long document, book or similar, where you need cross
referencing, you may need to create a table of contents and perhaps an index; tools built into
LATEX. A third type of document is that which has to be formatted exactly the same time after
time. This could, for example, be a report series from a project or organisation or from ongoing
research. In all such instances, there is little competition.
So the conclusion is that the more complex your writing task the more you will benefit from
using LATEX. Another way to describe this is that what is difficult in Word is simple in LATEX
and vice versa.
\title{Example}
\author{Peter Jansson}
\date{September 2019}
\begin{document}
\maketitle
\section{Introduction}
\end{document}
In Overleaf you start a new blank project and provide a project name. In my example, I
called it ‘Example’. Overleaf will then open the document in a three pane display as shown
in the figure below. To the left is the project pane which displays what files are included in
the project. By default the file you receive will be named main.tex but this can be changed
to something more meaningful. Next is the LATEX code pane which is where you enter your
text and code to create your document. Finally the is the preview pane which shows how the
document looks.
5
The simple document we receive in Overleaf shows us several things. First you notice is
that there are commands identifiable by the backslash and often with an argument within
curly braces, such as \documentclass{article}. LATEX produces documents in response to such
commands, similar to how you build a web-page in html. You will with time learn many
commands but it is still a surprising few that are needed to get you far.
If we look at the code we can identify three mandatory commands:
\documentclass{article}
\begin{document}
\end{document}
These must be present in all LATEX documents because they tell LATEX what kind of document
to produce (in this case an article) and where the document text that should be type set begins
and ends. These three lines should always be in any document you start.
In our example we can identify three commands
\title{Example}
\author{Peter Jansson}
\date{September 2019}
entered before the \begin{document}. The first command \title{} allows you to provide a title
for your document and the second \author{} allows you to provide your name to the document.
The thirds allows you to enter a date. In my case Overleaf entered ‘September 2019’ because
this is when I started the project.
The three commands creates the document header we see in the preview pane. However,
they will only display if we enter a fourth command \maketitle which takes the first three and
produces a title for your document. It is possible to remove the \date{} command, \maketitle
will then extract the current date from the computer and display the date instead of the text
provided in the example.
What we now have is the header of the document. We now turn to the content.
In the remaining document text you see the command \section{} which produces your first
heading from whatever you write within the curly braces. Note that headings are numbered
by default. LATEX has predefined the look of the headings so that all you have to do to start a
new section in your text is to use the \section{} command. The heading will always be on a
separate line with spacing above and below the heading.
After the heading you can simply type in the text you want, the text body that belongs to
that heading. When you do so you will probably notice a few unexpected things. If you try
to start a new paragraph by pressing the enter (or return) key ‘Word style’, no new paragraph
will start. Instead the text runs on continuously. This is because LATEX uses an empty line
6
to identify a new paragraph. So, you need one return to end the line and a second to cause a
paragraph break.
Another aspect that can cause confusion is that LATEX determines all relevant spacing in
a document. This means that, for example, if you type in four consecutive spaces LATEX still
interprets this as one space. This also applies if you try to use the tab key to offset text.
It will still result in a single space. So you will not be able to push text around by adding
several spaces. It is actually the same with paragraph breaks. Adding several returns between
paragraphs will still result in a normal paragraph break. We will return later to how we can
create space in a document if we really need to.
A final command that I have not commented on is \usepackage[utf8]{inputenc}. This line
asks LATEX to load a macro package called ‘inputenc’ (input encoding; section 7.1) into your
document. The reason for this is that LATEX by default does not recognise accented letters.
The package allows LATEX to understand accented letters such as the Swedish å, ä and ö. If you
type in accented letters in a LATEX document without having loaded the ‘inputenc’ package,
they will simply not be visible.
Do it
• Add some text of your own and observe what happens if you put many consecutive spaces
or tabs in the text and use the return key to make new paragraphs.
A mostly overused but nevertheless useful feature of a document is the list. A bullet list in
LATEX is referred to as itemize and is invoked by the following code
\begin{itemize} • first item
\item first item
\item second item • second item
\item third item
\end{itemize} • third item
As you can see the list created by the \begin–\end{itemize} environment. Each item, bullet
point, is created by writing the command \item followed by the content of that bullet. There
are other forms of lists and you can create your own but we will cover that in section 3.10.
Do it
• Make your own list. Try nesting lists.
Do it
• Make your own larger table. Use your own data or try to mimic something from a journal.
7
Now let us look at an original strength in LATEX, typesetting mathematical notation and
equations. Type in the following into your document
The definition of
$X_Z$ is given by The definition of XZ is given by
\begin{equation} ∑
X_Z = \sum x_z + \beta^n XZ = xz + β n (1)
\end{equation}
This equation is of course nonsensical but serves the purpose of showing some mathematics.
First, you notice that there is code in the sentence: $X_Z$ which yields XZ . The dollar signs
signals to LATEX that it should switch in and out of mathematical mode. LATEX works in two
modes, mathematical and text mode. Certain commands and features only work in either
mathematical or text mode, rarely in both. If you use them in the wrong mode they give rise
to an error. In this example the underscore _ is LATEX mathematical code for a subscript.
It is very important to remember to keep the dollar signs paired. If you left the code above
without a dollar sign, $X_Z, LATEX would continue to think everything afterwards until the end
of the paragraph is mathematics and eventually yield an error message.
After the sentence there is a construction using the environment \begin–\end{equation}.
This is the way you create so called display mathematics, equations that are on a separate line
and as in this case also centred and numbered. In the equation given by the code X_Z = \sum x_z
+ \betaˆn you see a couple of mathematical commands \sum which yields the summation sign
and \beta which yields the Greek letter β. You also notice the LATEX command for superscript,
ˆ.
More on mathematical typesetting will be discussed in section 6 but for information, use,
for example, the LATEX cheat sheet to see examples of mathematical notation.
Do it
• Make your equations using the cheat sheet.
You now have almost all you need to write a complete scientific manuscript, but you obvi-
ously wonder about figures (graphics) and references. This is a bit more involved and we will
return to these aspects in sections 7.2 and 8.
8
braces, sometimes additional braces for input to the command. These commands do not need
any completion since the braces provide the information LATEX needs to understand that the
command is complete. A classical mistake with these types of commands is to forget to add
the closing brace which then will yield an error.
The third type of command is the ‘environment’ \begin–\end{} where the command has an
opening and a closing statement and where the argument is everything you place between the
two. We have already looked a three such environments document, itemize and equation. In
this case it is important to match any \begin with a matching \end statement.
It is important to know how the different commands should be written and what may be
optional arguments. But you will build your knowledge as you continue working with LATEX.
and we also began writing our text in the \begin–\end{document} environment. The general
structure requires a few more comments.
First, the \documentclass command must be the first command encountered in a LATEX
document. It may be preceded by comments but not by any other command or plain text.
Second, all text that we want displayed in a document must occur between the \begin–
\end{document}. In fact anything you write after the \end{document} will be ignored. This can
be quite useful since you can move the \end{document} up into the text in order to compile only
a portion of the text file. It also means you can cut and paste bits of text into your document
file after the \end{document} for later use.
Third, the space between \documentclass and \begin{document} is usually called the preamble
and is reserved for LATEX code that is used to influence the behaviour of what you write in the
document environment. You will see how this part of the document usually gets filled with
several useful tools. It is however, important to realise that no ordinary text can be written in
this part of the document, only commands. Errors will otherwise occur.
Class Description
article Common scientific article
book Book with chapters and parts
letter Letters with letterheads
report Report with chapters
slides Overhead slides
Apart from the standard classes, there are numerous other classes available. Many are
written by enthusiasts for particular purposes such as CV, sheet music, sudoku, etc. Other
classes have been developed by publishers and journals to facilitate authoring in journal specific
formats. For scientific publishing, the latter is probably what we should look for.
To provide some examples, the American Geophysical Union and the Open Access publisher
Copernicus has classes for their journals. Most journals on, for example, Wiley, Springer and
Taylor & Francis also have class files for their own style. Note that classes may contain new or
redefined commands which can lead to unexpected behaviour if you do not carefully check how
the class works. In most cases, you will not notice any differences but not all classes may be
up-to-date or well written.
9
Do it
• Look at some key journals in your field and locate their class files. Or, search Overleaf
for journal templates. You may want to try them out when you feel ready.
Type Command
italics \textit{}
bold face \textbf{}
Small Caps \textsc{}
slanted \textsl{}
sans serif \textsf{}
typewriter \texttt{}
underline \underline{}
The size of the text can also be varied but not in the way you may think. LATEX scales fonts
relative to the ‘normal size’, that is the size of the main text. Thus in order to get larger or
smaller font sizes you can use the following set of commands, relative to the ‘normal size’.
10
The default type size for LATEX is 10pt. The basic sizes you can use are 10, 11, and 12pt
and this can be set using the \documentclass command as an optional argument. If you want
to make an article in 12pt you need to provide
\documentclass [12pt]{ article}
at the beginning of your document. Here the square bracket indicates that the command takes
an optional argument stated within the brackets. If you do not specify any optional argument
LATEX will use a default value.
Changing type faces is not necessarily straight forward; I am almost tempted to state you
should not even try, yet. The reason for the hesitation is that while LATEX typesetting has
remained more or less constant since its infancy, fonts have not. This is because as comput-
ers have gone from 8-bit to 64-bit and capacity has sky-rocketed, Fonts have developed from
containing 128 to now over a million characters. With the backwards compatibility of LATEX
it has not been possible to develop with the new standards but rather find ways to implement
the new while keeping the old.
In Overleaf, you are most likely using an implementation of LATEX called pdfLATEX. This
directly generates pdf files from your LATEX source and is probably the most widely used form
of LATEX. In the core LATEX distributions (incl. Overleaf) many fonts are installed that work
with pdfLATEX.
Another implementation called XeLATEX was developed to make use of the newer Unicode
type faces containing over a million characters. If you run XeLATEX you can quite easily access
your system type faces (the same you access in Word). This is quite tempting but remember
that in order for someone else to run your document, they need to have the same type face. So
there are benefits and pitfalls with going either way.
In section 2 we had issues with accented letters. This problem is easily circumvented by
switching to the XeLATEX compiler in Overleaf since we can then access such accented letters
the way they are entered from our computer keyboard. So if you are writing in languages that
use accented letters it may be useful to use XeLATEX instead of pdfLATEX.
That said, I can mention the LATEXFont Catalogue, which contains an overview of generally
available free type faces and also how to make them usable in your document. An important
point to make is that only certain type faces have support for mathematics. These are identified
in the font catalogue. If you use a type face that does not include mathematics anything written
with mathematics will be written using the default font. In some cases you will probably barely
notice the difference but in other cases it will just be ugly. The freedom to chose can thus be
quite limited.
You can try to change fonts by following the instructions in the font catalogue and try other
solutions found on TEX StackExchange.
Do it
• Play around with the different ways to change font and size, including the switch between
10, 11, and 12 pt in the documentclass command.
11
Most of these need no further comment but I will point out a couple of details. First, when
it comes to using quotes, it is possible to use the common double quote on the keyboard but
it does not look very good. In addition, double quotes in English is American typography so
unless you are American or come from a country that uses the American typesetting standard,
you should stick to the British English single quote.
Second, a common problem with texts is that authors do not know the difference between
a hyphen (dash) and a longer dash (en-dash). The hyphen is part of your key board and used
when you hyphenate words or put two words together. The longer dash is used when you want
the meaning to be ‘to’ as in 4–7 (four to seven). The longer dash looks like a normal minus sign
but LATEX actually have a special minus sign produced in math mode, compare – (en-dash) and
− (math minus). Since it is very easy to distinguish between the different types of dashes in
LATEX you should make an effort to use them appropriately.
in the preamble, you pass this information to the hyphenation engine to correctly deal with the
word any time it is encountered in the document.
By default LATEX uses English hyphenation rules. If you write in another language you may
therefore get word breaks that do not fit that language. You can correct this problem by using
a language package called ‘Babel’ which we cover in section 7.15.
LATEX uses an intricate system to keep track of good word spacing. By default you will get
a slightly wider space after a period, indicating the end of sentence and beginning of a new.
This rule is, however, not always correct. If we have an abbreviation with periods each period
will be interpreted as an end-of-sentence. If we look at the following example
12
Example Code
J. Geophys. Res. J. Geophys. Res.
J. Geophys. Res. J. Geophys.\ Res.
You can see that the space between ‘Geophys.’ and ‘Res.’ becomes shorter in the second
case, in fact it is a common inter-word space. This means that you should add a backslash after
abbreviations written in common letters unless the period really is the end of the sentence.
Another issue that can arise is that LATEX by default interprets a period after a capital letter
as an abbreviation and hence provides inter-word spacing. If you end a sentence with such an
abbreviation the space is too short. To solve this you can add the command \@ between the
abbreviation and the period as in …in UNESCO\@. Another ….
Lastly, in the old days of days of monospaced typewriter fonts, it was customary to insert
two spaces between sentences. You sometimes see people still do this in word processors. LATEX
inserts a space that is slightly longer than a single space, but still shorter than two, by default. It
is possible to get single space between sentences by adding the command \frenchspacing at the
beginning of the document. You can turn the French spacing off by adding \nonfrenchspacing.
Since adding two or more spaces between sentences in LATEX does not affect the spacing, it does
not matter if you accidentally hit the space bar a couple of times extra, the only way to really
easily affect the spacing is through the French-spacing commands.
Do it
• Test the different commands affecting spacing within your own text so that you understand
the difference they make. It may be beneficial to work on several identical paragraphs in
parallel so that you can visually compare the results.
3.8 Headings
The headings in LATEX come in two flavours, numbered (default) and unnumbered. The un-
numbered versions can be obtained by using so called ‘starred’ versions of the command. The
section command \section{} is thus converted to unnumbered by writing \section*{}.
Numbered Unnumbered
\part{} –
\chapter{} \chapter*{}
\section{} \section*{}
\subsection{} \subsection*{}
\subsubsection{} \subsubsection*{}
\paragraph{} \paragraph*{}
\subparagraph{} \subparagraph*{}
The levels part and chapter are only available in the book class.
In addition the book class contains several other features. By adding the command \appendix
LATEX will start alphabetic sectioning numbering instead of numeric, which is the common
form for an appendix. There are also two commands called \frontmatter and \mainmatter that
numbers pages with roman numerals from the frontmatter command until the main matter
command. After that numbering will be with Arabic numerals. this is common in type setting
books where pages with roman numerals are used for pages containing material that is not part
of the main book content such as table of contents, preface etc.
Do it
• Try out the different forms of headings. Note, however, that for some to work you need
to switch your document to the book class.
13
3.9 Table of contents
To create a table of contents is very simple in LATEX. You need to do one thing and that is
to type the command \tableofcontents where you wish the table of contents to go. There is,
however, one caveat. The table of contents can only be generated from the numbered sections.
If you, for example, have numbered headings in your document and edit in a star in one of
the heading commands, that heading will no longer be visible in the table of contents. There
is a work-around for this by changing the way the table of contents work. If you add
\setcounter{secnumdepth }{0}
to the preamble this tells LATEX not to number any sections. By adding or removing this line
from your file you can essentially turn numbering on or off.
Another way to accomplish this is to add
\addcontentsline {toc}{ type }{ heading title}
after each heading. type refers to the heading level. If you for example have an unnumbered
section and subsection that should be in the table of contents you will provide the following
after each heading
\section{The section heading}
\addcontentsline {toc}{ section }{The section heading}
The \addcontentsline command tells LATEX to add information about a section to a file that it
keeps to create the table of contents. The first argument is the name of the file. This will be a
file named the same as your document but with the extension .toc. The second argument tells
LATEX what level of heading you add to the file. The third is the heading text.
In LATEX you can also provide similar table of contents for your figures and tables using
the commands \listoffigures and \listoftables. We will get back to details how this can be
accomplished in section 5.
If you have many sections of all levels it may make sense to remove the lowest level (subsub-
section) from the table of contents in order to shorten it. The command \setcounter{tocdepth}{1}
is then useful because it allows you to limit the ‘depth’ of the table of contents. With the ar-
gument ‘1’ only sections and subsections will be visible.
3.10 Environments
In the quick start we came a cross several environments. When you enter text there are several
more that you should be aware of. Common to all is that the use the environment structure
\begin{}–\end{}.
Environment Action
center centers content
flushleft flushes content left
flushright flushes content right
quotation decreases text area width for a quote with indentation
quote decreases text area width for a quote without indentation
verse for poetry
minipage produces a separate environment with its own dimensions
itemize produces bullet lists
enumerate produces numbered lists
description produces lists with key words as ‘bullets’
verbatim reproduces all text including protected symbols as written
Most of these environments are self-explanatory and something you can explore on your own.
The minipage environment is worth looking into a bit deeper. In this text I have used the
minipage to create ‘side-by-side’ looks at code and result. The following display
14
\begin{itemize} • first item
\item first item
\item second item • second item
\item third item
\end{itemize} • third item
is created by
\ noindent \begin{minipage }[c]{0.4\ textwidth}
\begin{verbatim}
\begin{itemize}
\item first item
\item second item
\item third item
\end{itemize}
\end{verbatim}
\end{minipage }\ hfil
\begin{minipage }[c]{0.4\ textwidth}
\begin{itemize}
\item first item
\item second item
\item third item
\end{itemize}
\end{minipage}
This may seem daunting but if you look closely, it consists of two minipage environments typeset
side by side (no paragraph break) and where the mini-pages are set to be 40% of the text width
(0.4\textwidth) each. What is not obvious from the typesetting is that I have pushed the
two mini-pages apart by inserting the command \hfil which is a basic command for inserting
space if there is extra space to be had. There are a whole series of such commands but they
are beyond the scope of this text. I can only urge you to start a little self study on the more
advanced topics that allows you to dive into the interior of LATEX.
The description environment is very useful and works just like the itemize and enumerate
environment but with the exception that you need to provide an argument.
It is also possible to change the look of all list environments. A simple way to change the
bullets in itemize is to add an argument after \item[]. If you want an en-dash instead of the
bullet you simply write \item[--] for each of the items you want to list.
Do it
• Try the different environments. In the case of lists, try to nest them to see the effects of
nesting on their behaviour.
3.11 cross-referencing
LATEX comes with a powerful cross referencing system. The system works on the principle
that you put a label on everything you want cross-referenced and then use a command to take
information about that label and insert it into the text. The following are the commands you
may encounter.
Command Action
\label{} establishes a label
\ref{} takes a label and replaces it with a number
\eqref{} specific references to equation numbers
\pageref{} specific references to page numbers
\cite{} generic literature references (see section 7.4)
15
The \label command is used to assign a unique name (label) to a section, figure, table or
equation. You need to provide a name for the label and this can be any name you chose. If we,
for example, have a map in our manuscript, I would label this figure \label{fig:map}. First,
I would recommend that you have a descriptive word in the label so that you know what that
figure is. Second, I prefer to add a ‘tag’ ‘fig:’ for figure ‘tab:’ for table and ‘eq:’ for equation
so that I do not confuse a tag for a figure with one for an equation. You can come up with
your own scheme, however, you will be limited to letters a–z, numbers and basic punctuation
for your labels. So no protected symbols or accented letters can be used.
Once you have assigned a label to an object you can reference, for example the map we
labelled above as \ref{fig:map}. In the resulting layout LATEX will take the number of the
figure labelled fig:map and insert that instead of the \ref{fig:map} command. The benefit of
this is that all figures (and tables and equations) are numbered implicitly, which means that if
you rearrange figures the labels will be assigned new appropriate numbers and so will all you
references in the text. You simply do not have to worry.
There are a set of specific reference commands. \eqref{} takes only labels from equations
but you can just as easily use the \ref{} command. The \pageref{} will display the page
number where your label is defined. This means that if you have labelled your map somewhere
and wish to refer to it, not by its figure number but the page on which it occurs, then you
should use \pageref{fig:map}.
Finally, LATEX comes with a cross-referencing system for citations and reference lists. I will
not go into any details here because there is more to the system than just cross-referencing.
Please refer to section 7.4 for a detailed description. At this point it is sufficient to know that
the \cite command exists for literature references coupled to a reference list.
Numbered Unnumbered
\today provides current date
\the allows typesetting of internal variable values from LATEX
\year variable containing current year
\day variable containing current day
\month variable containing current month
\footnote{} typesets footnote
\noindent cancels indentation of a new paragraph
\marginpar{} adds text in the margin where the command occurs
LATEX can take information from the computer and display in documents. The most common
command for this is \today which displays the current date. When you created the title of the
document with \maketitle LATEX implicitly uses the \today command to add a date to the title.
You can use the command anywhere if you want to have the current date in your document but
do not confuse this with a fixed date, it will be updated every time you run your document.
A usually little known but powerful command is \the. This command takes a value from
some parameter within LATEX and displays it as text in your document. Since LATEX has
variables for year, month and day called (of course), \year, \month and \day, it is possible to
extract that information into the text by using the combination of commands \the\year etc.
But, this will only yield the numbers, not, for example, the month in text. It is however,
possible to program LATEX to convert the number to text.
Footnotes are rarely used in scientific articles but is of course an integral part of any text.
LATEX has a footnote command that will take the text you enter as an argument and place it
at the bottom of the page like in the example here1 . To create a footnote you simply add the
command \footnote{} right where you want the reference to occur. LATEX will insert an index
number and add the footnote at the bottom of the page automatically.
1 This is footnote text entered in the paragraph on footnotes above
16
The marginpar command is useful if you want to, for example, add visual reminders to your
self in the text. I find it useful to define a new command (see section 9) based on the marginpar
where the type size is smaller and perhaps also in some colour to make it more visible.
Do it
• Try the different special commands.
4 Tabular information
Typesetting good tables is not easy anywhere. Quite often we see tables made to look like a
heap of boxes. This is not good type-setting practise. We will thus focus on simple publication
quality tables.
In LATEX, the basic environment for creating tables is called tabular and a simple table
would be made as follows (with output to the right):
\begin{tabular }{l c c}
\hline
1 &2 &3 \\ 1 2 3
\hline
A &B &C \\
A B C
a &b &c \\ a b c
\hline
\end {tabular}
This is neither sophisticated or beautiful but shows the principles. Obviously the tabular
uses a \begin–\end structure. After the \begin{tabular} is a set of curly braces containing
the letters l c c. These letters tells LATEX how to align the content in the three columns,
first column l for left-adjusted and the other two c for centred. There is of course an r for
right-adjusted columns.
The core of the table contains rows such as for example 1 &2 &3 \\. We can see that the
ampersand is used to mark columns 2 and 3 but is not used for column 1. This is how LATEX
uses the ampersand in the tabular environment, it indicates a jump, tab, to the next column.
The line ends with a double backslash which tells LATEX that the line is complete and to switch
to a new line. All lines of data in a table must end with the double backslash. I have also
inserted some horizontal lines using the \hline command. This code does not take a double
backslash to mark that it is on a separate line.
This example shows us a few things worth noting. First, that a table should be as simple
as possible when it comes to lines, this is good typography. Second, LATEX will determine the
width of columns and the width of the table based on the content. This is of course fine as long
as our data and column headers are simple and short.
By loading an extension called booktabs (see section 7.6) you have access to a series of
additional lines, called rules that will help you organise more complex tables. In the following
example we use the non-native commands \toprule, \midrule, \bottomrule and \cmidrule. They
are all self-explanatory except the last.
\cmidrule[](){} takes three arguments (note the different types of brackets used). The first
specifies the thickness of the line and the second if it should be trimmed. Both the thickness
and trim arguments are optional. If not trimmed, the lines will go the full width of the columns
and possibly meet with neighbouring lines. Trimming can be achieved by entering l for left
trim and r for right trim or both into the argument. The third argument takes the column
numbers across which the rule should span.
As an example we can look at this small but relatively complex table.
17
Year bw Hss bw (k) Swi bc (k) ba (k)
29 28S3 29 28S3 29 28S3 29 28S3
(m w.e.) (m) (m w.e.) (%) (m w.e.)
6 0.06 0.06 0.09 0.12
1997/98 1.35 2.7 2.4 0.03 0.06 7 0.07 0.07 0.10 0.13
8 0.08 0.09 0.11 0.14
6 0.06 0.08 0.09 0.13
1998/99 1.33 2.9 2.6 0.03 0.06 7 0.07 0.09 0.10 0.15
8 0.08 0.10 0.11 0.16
was created by
{\ begin{tabular }{l c c c c c c c c c c}
\toprule
Year &$b_w$ &\ multicolumn {2}{c}{$H_{ss}$} &\ multicolumn {2}{c}{$b_w(k)$}
&$S_{wi}$ &\ multicolumn {2}{c}{$b_c(k)$} &\ multicolumn {2}{c}{$b_a(k)$}\\
\cmidrule(rl){3 -4} \cmidrule(rl){5 -6} \cmidrule(rl){8 -9} \cmidrule(rl ){10 -11}
& &29 &28S3 &29 &28S3 & &29 &28S3 &29 &28S3\\
&(m w.e.) &\ multicolumn {2}{c}{(m)} &\ multicolumn {2}{c}{(m w.e.)}
&(\%) &\ multicolumn {4}{c}{(m w.e .)}\\
\midrule
& & & & & &6 &0.06 &0.06 &0.09 &0.12\\
1997/98 &1.35 &2.7 &2.4 &0.03 &0.06 &7 &0.07 &0.07 &0.10 &0.13\\
& & & & & &8 &0.08 &0.09 &0.11 &0.14\\
& & & & & &6 &0.06 &0.08 &0.09 &0.13\\
1998/99 &1.33 &2.9 &2.6 &0.03 &0.06 &7 &0.07 &0.09 &0.10 &0.15\\
& & & & & &8 &0.08 &0.10 &0.11 &0.16\\
\bottomrule
\end{tabular}
Do it
• Typeset some of your own tables. Start with a simpler table.
The figure environment should contain three commands. First is a command \includegraphics{}
which brings in a graphics file into the document. We will discuss this command in more detail
in section 7.2. Second is a new command called \caption which produces a figure caption using
the text you enter as the argument to the command. This caption should always be typeset
below the figure graphics, which is why we place the commands in that order, and the figure–
caption pair will never separate across pages etc. Third is the \label command which allows
you to refer to the figure using the label name (see section 3.11).
18
A table follows the same basic recipe but the table itself is made up of a tabular environment
(section 4)
\begin{figure}
\caption{This is the figure caption text}
\label{tab:x}
\begin{tabular }{c c}
. . .
\end{tabular}
\end{figure}
In this case we place the caption before the tabular environment because the table caption must
go above the table. We also have a label working the same way as for the figure environment.
Creating these floats is thus quite simple. It is, however, possible to influence the placement
of the floats in the document. To do this, we can add an optional argument to the \begin{}[]
command. This optional argument can be one or a combination of
Option Action
h here, approximately where it occurs in the source text
t top of the page
b bottom of the page
p on a special floats page
! Override internal parameters for ‘good’ float position
H H ere, precisely at the location in the code, similar to !ht1
1
This requires a package called ‘float’, section 7.13
The way float placement works has been described by Frank Mittelbach on TEX StackEx-
change. and I will summarise the flow here.
When a float is encountered, LATEX attempts to place it immediately according to its rules.
If this does not succeed, then LATEX places the float into a holding queue to be considered when
the next page is started. Once a page is completed, LATEX tries to place remaining floats in the
holding queue as best as possible. To do this it will first try to generate as many float pages
as possible. If this is not possible, it will try to place the floats into top and bottom of pages.
It looks at the remaining floats and either places them or defers them to a later page. After
that, it starts processing the text for the page. In the process, it may encounter further floats
and the process goes on. If the end of the document is reached before the queue is emptied,
LATEXwill add pages and dump remaining floats there.
As you can tell the process is quite involved and never random. If there is need to try to
create a page of floats inside a document, you can use the command \clearpage which will
empty the queue onto pages before continuing with the document.
The option H is not generic LATEX and requires additional work which we will discuss in
section ??.
Do it
• Test the different float environments with a simple figure and table and change the po-
sitioning arguments to see their effects. Note that you need to have a few pages of text
with plenty of paragraph breaks to be able to really test the floats. I recommend loading
the lipsum package (section 7.16) and adding text by typing \lipsum[n] where n can be
a number or a range (e.g. 2-5). Check the package documentation for details; lipsum is
useful if you need text to see how a layout works.
6 Mathematical typesetting
Since mathematics is one of LATEX original strong points there are too many introductions to
count on writing mathematics out on the Internet. I will therefore not try to add another one
to the mix but draw up some basics that will allow you to go along way and form a basis for
your own research. As we saw in the quick start, mathematics come in two flavours, in line
and display mathematics. The same commands are used in both cases in order to produce the
19
mathematical notation so we will first focus on the different forms for displaying mathematics
and then onto the details of how to create the equations.
The basic display mathematics environment is equation. As we have seen earlier it works
just like any other environment
\begin{equation }\ label{eq:x}
a^2 = b^2 + c^2 a2 = b2 + c2 (2)
\end{equation}
In this example I have also added the label which means you can now cross-reference the
equation number as \ref{eq:x} in the text. There is also an environment for sets of equations
\begin{eqnarray}
c_1 &=& a_1x + b_1x \label{eq:a} \\
c_1 &=& a_2x + b_2x \label{eq:b}
c1 = a1 x + b1 x (3)
\end{eqnarray} c1 = a2 x + b2 x (4)
The alignment is set up by the ampersands in the two equations, in this case to make sure
the equal signs line up. You can also use the eqnarray to take care of longer equations
\begin{eqnarray}
y = a_1x &+& b_1x + c_1x + d_1x
\nonumber \\ y = a1 x + b1 x + c1 x + d1 x
&+& e_1x + f_1x \label{eq:y}
\end{eqnarray} + e1 x + f1 x (5)
With AMSLATEX (see below), you can access another environment to do what we did with
eqnarray above. This is the align environment
\begin{align}
y = a_1x &+ b_1x + c_1x + d_1x
\nonumber \\ y = a1 x + b1 x + c1 x + d1 x
&+ e_1x + f_1x \label{eq:y}
\end{align}
+ e1 x + f1 x (6)
In this case the alignment is much better. This is but one example of how using AMSLATEX
improves your capabilities.
When you build equations, you need to know the commands that produce all the different
mathematical symbols and notation. A good source is the American Mathematical Society
(AMS). It is worth mentioning at this stage that while LATEX does excellent mathematical
type setting, AMS has improved on the capabilities through their AMSLATEX extension. If
you just need to type set a few formulas and ordinary equations, basic LATEX should be more
than sufficient. But if you need some more special features, they are almost certainly available
through the AMSLATEX extension.
Now turning to formulating an equation. When you type in an equation, you do generally
not need to worry about spacing. As we noted earlier all letters will be typeset in mathematical
italics, this is the norm for mathematical variables. The italics only applies to Latin letters,
Greek letters are not italicised. This means that if you want to type in a function such as sine
you need to be careful as this example shows
\begin{eqnarray}
\tau &=& \rho gh sin\alpha \\
\tau &=& \rho gh \sin\alpha
τ = ρghsinα (7)
\end{eqnarray} τ = ρgh sin α (8)
In the upper row we typed in the letters ‘s i n’ and they came out in italics but with a
similar spacing as between the variables g and h In the second row we used the mathematical
command \sin. In the first case, ‘sin’ is treated as three variable names. LATEX, therefore has
all the mathematical functions established as commands so that they are type set correctly.
Adding letters after each other is just interpreted as a series of variables multiplied by each
other. This has a bearing on those who persist to form variables more or less at abbreviations
20
such as ET for evapotranspiration or worse NDVI for Normalized Difference Vegetation Index
N IR − V IS
N DV I = (9)
N IR + V IS
where NIR is the near infrared band and VIS is the visible. This clearly does not look good
partly because of the way LATEX handles text i mathematical mode but also because it is a poor
way to defined variable names. So let this be a warning when you define your own variables
and equations.
Despite the poor look of equation 9 we see that we can produce division. This is easily
accomplished with the \frac{}{} command. frac takes two arguments. In the first is everything
that goes in the numerator and in the second, everything that goes in the denominator.
\begin{equation }\ label{eq:NDVIb}
I_\ mathrm{NDV} = \frac{E_\ mathrm{IR}
- E_\ mathrm{VIS}} ENIR − EVIS
{E_\ mathrm{IR} INDV = (10)
ENIR + EVIS
+ E_\ mathrm{VIS}}
\end{equation}
In this example we can see how the \frac command works but we can also see that it is
possible to type in the equation in almost any form, in this case to try to make it structured,
sine it has no consequence for the output. You can also see a new command \mathrm{} which
produces regular text inside mathematical mode.
When you use the frac command and you need to put a parenthesis around the equation,
you can obtain scalable parenthesis using the \left and \right commands
\begin{equation }\ label{eq:NDVIb}
I_\ mathrm{NDV} = \left(
\frac{E_\ mathrm{IR}
- E_\ mathrm{VIS}} ( )
ENIR − EVIS
{E_\ mathrm{IR} INDV = (11)
+ E_\ mathrm{VIS}} ENIR + EVIS
\right)
\end{equation}
The \left and \right commands must pair up. You can use ( ), [ ] and { } and also | with
these commands. It is also possible to set only one side of the pairs you should use a period for
the side you want to omit: \left. \right. . Note that when you use \left and \right, both
must be included.
Making mathematical type setting is otherwise mostly finding the right commands to obtain
what you want. There are many lists floating around that summarizes these so I will not take
up space here. I would argue that mathematics is one of the easiest things you can do in LATEX.
Do it
• Typeset some of your own equations or try to reproduce an equation out of an article or
book, or both.
21
problem for a given situation that may not apply to you. Much of this is stated in the package
documentation.
In the following sections I will provide information on some packages that vary from a must
to being of general interest. A package is loaded by adding the command \usepackage to the
preamble:
\usepackage []{}
As can be seen the command has a normal argument field (denoted by the curly braces) and an
optional input field (denoted by the square brackets). Many packages can be loaded without any
options which means you can ignore the square brackets. Other packages require or has options
for providing specific features. Such options are described in the package documentation.
7.1 inputenc
While scientific writing is primarily done in English and LATEX is made with English in mind it
is often necessary to include words, for example, place names with accented letters in the text.
Generic LATEX does, for example, not support the å, ä, and ö on the Swedish keyboard. You
can of course create these letters through LATEX accenting commands, in this case by typing
\aa, \"a and \"o, respectively. If this happens a few times it is not a major issue. There is
however a way to ensure that what is on your keyboard is also possible to handle in LATEX.
The package inputenc (short for ‘input encoding’) allows LATEX to use an extended encoding,
that is beyond the letters and numbers of the English keyboard. this is not limited to Swedish
letters but to a large variety of other accented letters. The package should be called with
the option utf8. The UTF8 encoding allows a computer to manage over a million different
characters which includes all characters in modern Unicode type faces. By adding the following
to your preamble, you have full use of your font character set. The package is loaded by
\usepackage[utf 8]{ inputenc}
Note that this package is not necessary when you use XeLATEX to compile your document.
7.2 graphicx
The graphicx package is a must. Without this package you will not be able to include graphics
into your document. The package is loaded by
\usepackage{graphicx}
The file name is provided as the main argument in curly braces. It is not necessary to type
the extension. It is also possible to provide a path to the graphics file if it is not in the folder
where your LATEX document resides. valid graphics formats are JPEG, PNG, and PDF. Note
that SVG and TIFF are not supported.
The optional arguments in the example provide LATEX with the information that the figure
should be reproduced with a width that is 0.5× the width of the text. This type of scaling is
convenient but you can also specify a fixed width in, say millimetres, by writing, for example
[width=57mm]. In addition we have also asked LATEX to rotate the figure by 45◦ , which, of course,
is unusual. In addition you can scale the figure by its height in a similar way to the width.
There is a command \textheight that allows you to scale relative to the height of the text area.
If you provide only one of width= or height= the figure will be scaled proportionally in the
other directions. You can scale an image disproportionally by providing different scaling factors
for width and height.
Do it
• Add a figure and test the scaling and rotation capabilities.
22
7.3 geometry
The geometry package provides an easier interaction with LATEX page layout settings. The
package is loaded by
\usepackage[a4paper ]{ geometry}
In this example, the option a4paper has been added in order for margins etc. to be scaled
correctly for that paper size. This is the minimum of what you need to add to your preamble.
It is worth noting that the documentclass command also takes a4paper as an argument but I
prefer to use it in the call to geometry.
If you need to change your margins, you do this by simply using the following
\usepackage[a4paper ,left =35mm ,right =30mm ,top =30mm ,bottom =25mm]{ geometry}
which just happens to be the call made for this document. This sets the left and right margins
to 25 mm wide and the top and bottom margins to 30 mm. You should study the geometry
package information for more details
Do it
• Use the arguments to the geometry package to change margin widths, paper size etc.
7.4 natbib
The natbib package is a must if you need Harvard style author-year referencing system in your
work. The package is loaded by
\uepackage{natbib}
I will not dwell on natbib functionality here since we will go into much more detail when
discussing referencing in section 8. What may be of more interest here is a section of code
that I recommend you to use in conjunction with the natbib package. This code referred to as
natbibspacing.sty
\ newdimen \bibspacing
\setlength\bibspacing\z@
\renewenvironment {thebibliography }[1]{%
\bibfont\bibsection\ parindent \z@\list
{\ @biblabel {\ arabic{NAT@ctr }}}{\ @bibsetup {#1}%
\setcounter{NAT@ctr }{0}}%
\ifNAT@openbib
\renewcommand\newblock {\ par}
\else
\renewcommand\newblock {\ hskip .11em \@plus .33em \@minus .07em}%
\fi
\sloppy\ clubpenalty 4000\ widowpenalty 4000
\sfcode `\.=1000\ relax
\let\citeN\cite \let\shortcite\cite
\let\citeasnoun\cite
\itemsep\bibspacing %
\parsep\z@skip %
}{\ def\@noitemerr{%
\PackageWarning{natbib}
{Empty `thebibliography ' environment }}%
\endlist\vskip -\ lastskip }
% ---------------------
\setlength {\ bibspacing }{0pt}
You may be able to load this code by adding the name to the call for natbib
\uepackage{natbib ,natbibspacing}
but only if it exists in your LATEXdistribution. Otherwise, you can enter the code into your
preamble after you have loaded natbib.
The natbibspacing is an example of pure code and may get an insight into how much details
can be changed but also that it involves learning LATEX as a programming language in detail.
Fortunately, others do these things for you in the community.
23
7.5 hyperref
The hyperref package enables you to make workable links in your pdf output. The package is
loaded by
\usepackage{natbib}
When you use hyperref all the cross-links in your document becomes clickable and allows you
to move around in the document. The table of contents is also clickable by default as are any
references. In addition, you have access to the command \href{}{} which allow you to produce
links to web URLs outside of your document. To show an example how this works we can set
up a link to TEX StackExchange
\href{http :// tex.stackexchange.com }{\ TeX\ StackExchange}
The command takes two arguments. The first is the complete URL and the second is the text
that will be highlighted as a link in the text.
You can modify the way links are shown by the command hypersetup
\hypersetup{
pdftoolbar=true , % show Acrobat 's toolbar ?
pdfmenubar=true , % show Acrobat 's menu?
pdffitwindow=true , % window fit to page when opened
pdfstartview ={ FitH}, % fits the height of the page to the window
pdftitle ={ title}, % title
pdfauthor ={ name}, % author
pdfsubject ={ subject}, % subject of the document
pdfkeywords ={ keyword 1} {key2} {key3}, % list of keywords
pdfnewwindow=true , % links in new window
colorlinks=true , % false : boxed links ; true: colored links
linkcolor=black , % color of internal links
citecolor=SUBlue , % color of links to bibliography
filecolor=blue , % color of file links
urlcolor=blue % color of external links
}
Note that you do not need to list all settings, simply the ones you wish to change from default
values. Just remember to separate them by a comma. With this setting, the links to external
ages are blue, internal links are black except citations which are in a blue defined as SUblue (see
section 7.11). As you can tell, the hypersetup also dictates how the pdf should be opened by
Acrobat reader. You should refer to the hyperref package documentation for more information.
Do it
• Try the hyperref package by adding some urls and also changing the parameters in the
hypersetup command.
7.6 booktabs
The booktabs package is a small package that improves table formatting. The package is loaded
by
\usepackage{booktabs}
It is the booktabs package that allows you to use the commands \toprule,\midrule and \bottomrule
in tables. I have consistently used these for the tables in this text unless stated otherwise. The
package provides a few other commands as well but the booktabs package documentation is
well worth reading because it outlines ideas around good practises in table design.
Do it
• Try the different rules in your tables to replace the \hline.
24
7.7 siunitx
The siunitx package is a very complex package that deals with how to write numbers and units
(with focus on SI units). The package is loaded by
\usepackage{siunitx}
This package may to many seem a bit over the top. Let us look at some of the core ideas. Let
us say we want to write a complex unit such as square volt cubic lumen per farad (V2 lm3 F−1 ).
This seems like a disaster waiting to happen. With the siunitx package and its command \si{}
we will get the correct units through the following
\si{\ square\volt\cubic\lumen\per\farad}
As you can see all the words we used to describe the unit in text is available as a command and
the result is a perfect SI unit form. If you need to add a number to the unit there is a second
command \SI{}
\SI {203}{\ kilo\gram\metre\per\second}
which yields 203 kg m s−1 . Now why is this good? There are several benefits. First it becomes
quite clear what your unit is. Second, the spacing between numbers and units and between the
units themselves are constant and of accurate length. It is true that you end up writing a lot
but the benefits definitely outweighs the disadvantages.
The package contains much more on representing data in text so you should study the
extensive siunitx package documentation.
Do it
• Try siunitx package by typing in some units that you are familiar with.
7.8 lineno
The lineno package does one thing, it allows you do add line numbers to, for example a
manuscript. Some journals, for example, ask for such manuscripts. The package is loaded by
\usepackage{lineno}
You turn the line numbers on by inserting the command \linenumbers where you want the
numbers to start. You can stop line numbers by placing the command \nolinenumbers where
you want them to stop. You should look at the lineno package documentation for more details
on different options.
Do it
• Try lineno package in your document
7.9 dcolumn
The dcolumn package provides means to define new alignments for tabular environments. The
package is loaded by
\usepackage{dcolumn}
To provide an example of what can be accomplished with dcolumn we can define a new column
type called ‘.’ (period) using the command \newcolumntype
\newcolumntype {.}{D{.}{.}{ -1}}
This new column type will align numbers on the period. As you can see the command takes
many arguments. The first argument is the name of the column type (‘.’). The second argu-
ment is divided into three parts, the first part indicates what character should be used for the
alignment (the period), the second part shows what symbol should be used for the separator
(usually the same as the first), the third part indicates how many decimal places should be
shown. With -1 as the third argument, the column will be centred on the decimal point. An
25
example
\begin{tabular }{. . .}
\toprule
45.73 &43.894 &5.463\\ 45.73 43.894 5.463
33 &0.0001 &0.02\\ 33 0.0001 0.02
7.76 &.2 &9.75\\ 7.76 .2 9.75
\bottomrule
\end{tabular}
And then the same table but with a different column type called ‘:’ (colon) which has the
\cdot) as decimal separator and 4 decimal places (the maximum number of decimals in the
table; \newcolumntype{:}{D{.}{\cdot}{4}})
\begin{tabular }{: : :}
\toprule
45.73 &43.894 &5.463\\ 45·73 43·894 5·463
33 &0.0001 &0.02\\ 33 0·0001 0·02
7.76 &.2 &9.75\\ 7·76 ·2 9·75
\bottomrule
\end{tabular}
As you realize you can do a lot with this package and define your own numeric column types.
The dcolumn package documentation is quite brief so experimentation is best way to learn this
package.
The siunitx package also has table alignment support which may be useful to study.
Do it
• Try the dcolumn package by making your own definition or changing parameters in exam-
ples given above and using the new column definitions in your own table.
7.10 tikz/pgf
The tikz/pgf package is actually two packages. Tikz is a front end for the drawing capabilities
set up by pgf. TikZ is a recursive name, Tikz ist kein zeichenprogram. The package is loaded
by
\usepackage{tikz}
The tikz package documentation is 1302 pages (at the time of writing, version 3.1.4b) and
hence extremely detailed. The manual doubles as a tutorial and dictionary. We will briefly
look at two examples that shows you what is needed and what can be done. It is noteworthy
that this is still just scratching the surface of what can be done. Please visit TEXsample.net for
numerous examples of Tikz output.
The first example shows a flow diagram for data collection at Tarfala Research Station.:
\tikzstyle{block} = [rectangle , draw , fill=blue !20,
text width =5em , text centered , rounded corners , minimum height =4em]
\tikzstyle{rblock} = [rectangle , draw , fill=red!20,
text width =5em , text centered , rounded corners , minimum height =4em]
\tikzstyle{line} = [draw , -latex ']
\node [block , left of=pc , node distance =3cm] (shuttle) {shuttle download };
\path [line] (logger) -| (shuttle );
\path [line] (shuttle) -- (pc);
26
\node [block , left of=sync , node distance =3cm] (ftp) {ftp to server };
\path [line] (rename) -| (ftp);
\path [line] (ftp) |- (server );
logger in
the field
shuttle PC in field
download or office
local folder
rename file
copy to
Dropbox
ftp to sync
server Dropbox
Dropbox
to server
server
(=
backup)
The second example is a figure I made for describing the energy fluxes at the ice surface on
a glacier.
\begin{tikzpicture }[>=latex ,scale =0.8, every node /. style ={ scale =0.8}]
\fill[top color=cyan !20, bottom color=black !30]
(0,-1) -- (0,0) -- (10 ,0) -- (10 , -1);
27
\node at (3 ,2.5) [right] {$I_L\ downarrow $};
\draw[decorate ,decoration=snake ,segment length=18,->,red !70! black]
(4,0) -- (4 ,2.9); % Outgoing LW radiation
\node at (4 ,2.5) [right] {$I_L\ uparrow $};
\draw [->] (6.75 ,.15) arc (280:0:.1 cm) -- +(283:0.05 cm); % Turbulence
\draw [->] (6.75 ,1.15) arc (280:0:.15 cm) -- +(283:0.05 cm);
\draw [->] (6.75 ,2.15) arc (280:0:.2 cm) -- +(283:0.05 cm);
\node at (6.75 ,2.8) [gray !50! black] {Turbulence };
\end{tikzpicture}
Turbulence
IS ↓ IS ↑ IL ↓ IL ↑ L H P
Air
G Ice
The examples above require certain tikz libraries to be loaded in the pre-amble. Which are
required depends on what sort of graphic elements are required. The manual details this.
\usetikzlibrary{arrows ,shadows ,positioning}
\usepackage{pgfplots}
\usetikzlibrary{decorations.pathmorphing}
\usetikzlibrary{decorations.shapes}
\usetikzlibrary{patterns}
Although these examples may be daunting, they indicate the flexibility of LATEX.
Do it
• Visit the TEXsample.net site and try out a few examples. If possible try to make changes
to the code to familiarize yourself with the tikz programming.
7.11 xcolor
The xcolor package introduces colour to LATEX. In the hyperref and tikz packages we could
see colour already and and xcolor is in fact loaded already by those packages. The package is
otherwise loaded by
\usepackage{xcolor}
With this package you can access a large number of predefined colours. These are described
in the xcolor package documentation. In addition you can define your own colours using the
\definecolor command. The command takes three arguments, first the name you wish to give
to the colour, second the color space (cmyk, rgb etc.) and third the colour combination that
makes up the colour. The following define the official Stockholm University colour palette in
cmyk space
28
\definecolor{SUBlue }{ cmyk }{1.00 ,0.70 ,0.00 ,0.60}
\definecolor{SUOlive }{ cmyk }{0.25 ,0.10 ,0.60 ,0.20}
\definecolor{SUSky }{ cmyk }{0.35 ,0.00 ,0.10 ,0.00}
\definecolor{SUWater }{ cmyk }{0.40 ,0.15 ,0.00 ,0.05}
\definecolor{SUFire }{ cmyk }{0.00 ,0.65 ,1.00 ,0.00}
\definecolor{SUSilver }{ cmyk }{0.12 ,0.08 ,0.08 ,0.23}
\definecolor{SUGold }{ cmyk }{0.30 ,0.40 ,0.80 ,0.15}
There are also ways to create hues out of the colours by mixing colours using the command
\color{}. To make up a hue we specify how much of each to mix
\color{green !40! red}
In the example the mix will be 40% green and thus 60% red (since they must sum up to
100%). Table 1 shows the official Stockholm University palette defined in CMYK through the
combinations given on the SU web site.
Do it
• Define and use some of your own colours.
7.12 caption
The caption package provides easy tools for changing how the figure and table captions are
formatted but also extends on the native functionality. The package is loaded by
\usepackage{caption}
In the standard layout the the captions start with ‘Figure 1:’ and ‘Table 1:’ Since this part
of the caption is created automatically, you cannot manually change the colon to a period,
which is the format required by most journals, in the text. The following commands changes
the formatting of the caption start:
\renewcommand {\ figurename }{ Figure .}
\renewcommand {\ tablename }{ Table .}
Note that you can enter whatever formatting you want in the second argument. A perhaps
quicker way is to load the package with options for fonts
\usepackage[labelsep=period ,font ={small ,it},justification=justified ]{ caption}
With this you will receive a caption written in ‘small’ size italics font, and with the words
Figure and Table followed by a period. This is shown in ‘Figure’ 1 (which is just a caption).
Please refer to the caption package documentation for more details.
Figure 1. This is a trial caption to see how the different changes will look in the case of a caption in a
float
29
Do it
• Use the caption package to change the look of your captions.
7.13 float
The float package adds a placement option H to the figure and table environment (see section
5). The option is a stronger placement directive the the native options. The package is loaded
by
\usepackage{float}
7.14 amslatex
The amslatex package provides many improvements and extension to LATEX native mathematics
capabilities. The package is loaded by
\usepackage{amslatex}
There is no point to try to describe the package here. You need to carefully look at the
AMSLATEX information at the American Mathematical Society.
7.15 babel
The babel package contains ability to switch many built in features that are language dependent
to a language other than English. If you wish to write a document n Swedish you simply load
the package as
\usepackage[swedish ]{ babel}
The document will now be shown with many small differences to the English version. Certain
headings such as ‘Contents’ and ‘References’ will be in your chosen language, dates will be
written in the standard of your language, etc. Please refer to the babel package documentation
for details.
With babel it is also possible to write multilingual documents and switch between languages
mid-document.
7.16 lipsum
The lipsum package produces a body of dummy text in your document. The text is commonly
used in type setting to assess the look of the layout design and consists of a text body in
improper Latin. By adding a number or range of numbers as an optional argument (1–4 in
the example below) it is possible to display a specific number of paragraphs in your text. the
benefit of this is that you can quickly add some text to see effects of your type setting design
decisions without having to type anything into your document. The package is loaded by
\usepackage{lipsum}
30
8 Managing references
LATEX has the capability to handle literature references and generating reference lists in your
documents. To accomplish there a few points we need to cover.
You need to have a data base of the literature you wish to cite in your documents. This
means that you should start building a data base of references. There are many reference
managers available such as EndNote, RefWorks, Zotero, Mendeley and JabRef to mention a
few. The Comparison of reference management software page provides an overview of available
tools. What you should look for is that the tool can export BibTEX format, can provide a
unique BibTEX ‘cite key’ (see below) for each entry, is continually supported, supports your
platform and, I would suggest, is free and open.
I use and recommend the Open Source Zotero for your reference handling. With this tool
you can save reference information directly into Zotero and quickly build your reference data
base. Zotero works with a cloud based storage that is free up to 300 Mb. You need to install
Zotero and a connector for your web-browser (Chrome/Firefox/Safari). You should also install
the Better-BibTeX for Zotero plugin. Just follow instructions to do so.
Zotero allows you to also store pdf files with your references. this will, however, quickly fill
your free data base space. I personally save only the reference information and at some point
had 2974 references in Zotero which used up 0.3% of my 300 Mb. So the free space will be
sufficient for quite some time as long as you store only the reference information and not pdf
files.
To work with your data base in your document, you also need a package that can handle
author-year referencing, the standard format in Physical geography and related fields, and also
a reference format so that your reference list is correctly formatted.
The goal is to be able to relate any article you reference in your manuscript with an entry
in your data base. We also want all references we added in the document to correspond to a
reference in the reference list. We of course also want the reference list to correspond exactly to
what we want to reference in the text. All this will be accomplished by LATEX with the natbib
package.
active where the author name is part of the text and the year is within parenthesis as in ‘Smith
(2013)’
passive where both the author name and the year are within parenthesis as in ‘(Smith 2013)’
The natbib package provides two commands for this, \citet{} and \citep{}, respectively.
As with other cross-referencing the referencing works through labels or cite keys. Each
reference must therefore have a unique cite key. With Zotero the cite key will by default be
created from the first authors last name, the first word in the title (Ignoring words such as
‘The’ and ‘A’) and the year. A reference such as
Smith AZ, 2013. Bad science – surviving in the jungle. Journal of Long-winded Pseudoscience,
23, 214–523.
will be assigned a cite key Smith_Bad_2013. this means you can reference this article in the text as
either \citet{Smith_Bad_2013} or \citep{Smith_Bad_2013}. Either one of these cite commands
will enable LATEX to add the reference to the reference list. Hence you simply add references
and the reference list is built for you.
The natbib package has several commands for referencing but the most commonly used are
shown here
31
Command Result
\citet{} ‘active’ citation ‘Smith (2013)’
\citep{} ‘passive’ citation (Smith, 2013)
\citeauthor{} cites only author name, not year
\citeyear{} cites only year, not author name
In all cases the BibTEX key should be entered as argument to the commands.
If you need to reference many authors in a passive reference, you simply add them all
as argument separated by a comma. \citep{Smith_Bad_2013,Day_Two_2014,Knight_Three_2015}
will yield (Smith 2013; Day 2014; Knight 2015).
The \citet{} and \citep{} commands can also take optional arguments. If we want
to have a reference that looks like (e.g., Smith 2013; and references therein) we can write
\citep[e.g.,][and references therein]{Smith_Bad_2013}. What we want added before the ref-
erence goes as the first optional argument and what should be placed after the reference goes
in the second. If you do not want one or the other, you just leave the argument empty.
If you make a spelling mistake in the BibTEX key in your document, you will see this as two
question marks in the text (??). This is how LATEX signals such errors. It will also appear as a
warning in your log file.
With these commands you should be able to add references to the text but in order for the
system to work, you need to provide somewhere from which BibTEX can obtain its information
and this is where we have two ways to go, the fully and the semi automated way. I will cover
both but there is little point in making the semi automated system your standard.
The first command \bibliography{} tells BibTEX which .bib file to look for, your bibliography
file. The file name does not need to be written out with the extension .bib and you can add
a path if your bibliography file is not located with your LATEX document file. The second
command tells BibTEX which bibliographic style that should be uses, the name of your .bst
file here exemplified by the CSE.bst (Council of Science Editors).
With all this in place your reference list should be up to date whenever you add a reference
to a new publication in your document with the different cite commands and you should not
need to worry about any discrepancies in the document. As mentioned earlier, a prerequisite
is that the reference you you reference must be in the data base file and all entries in the data
base must have unique BibTEX styles.
Note that if you add references in your data base you will need to export the database again
and replace the earlier .bib file with the new updated version to be able to make use of new
references added to the data base.
32
Do it
• Add a few references to a .bib file and cite them (using natbib citing commands) using
the fully automated method described above.
\end{bibliography}
As you can see the bibliography has its own environment within which you put all your refer-
ences. each reference must start with the command \bibitem[]{} which takes two arguments.
the first argument is the in-text reference, the information you want LATEX/BibTEX to place
in the text. Note that the comma is not a style, it is for LATEX to separate author and year.
The second argument is the BibTEX key that is unique for all references. This is what natbib
uses to link a unique reference in the list with a natbib cite command in the text. After the
bibitem command follows the reference formatted the way it should look according to any
author instructions that may be given for the reference list.
Using the system this way is very simple but has the draw back that while all references in the
text will be matched by a reference in the reference list, there is nothing that prevents you from
adding references in the list that are not matched in the text. This means the cross-referencing
will always be correct but LATEXcannot do anything about the content in the reference list.
33
That will be up to you. You also have to manually type in the references and check that each
gets its unique cite key.
So to sum up, this way of using references in LATEX is useful to know but the fully automated
system, described below, is what you need to aim for.
Do it
• Add some references using the semi-automated method described above and cite them
(using natbib citing commands) in your document.
So if you were writing a manuscript on stable isotopes, you may get really tired of repeating
this over and over. We can then create a new command that types this out for us
\newcommand {\dO }{$\ delta ^{18}$O}
In this case all you need to type in your manuscript i \dO and you will receive δ 18 O.
When you create a new command, it is important not to use an existing command name.
LATEX commands are always in lower case and LATEX is case sensitive. I therefore suggest you
write yours with some capital letters, so called camel case or Pascal case (after the programming
language Pascal). If you, for example, wanted to create a command called ‘do it now’ this would
be written as \DoItNow, that is the first letter in each word is capitalized.
The \newcommand can be used with additional input. Let us look at the new command \Nada
defined by
\newcommand {\ Nada }[3]{\ textsc {#1} \textit {#2}\\ \textbf {#3}}
The first argument defines the command name \Nada. The second tells LATEX that there will
be three arguments. The third argument shows LATEX what to do with the three arguments.
In our case the first given by #1 will be set as small caps, the second as italics and the third on
a new line as bold. With input like
\Nada{What On Earth }{ kind of joke typesetting }{is this ?}
we get
What On Earth kind of joke typesetting
is this?
Even though the example is pointless in content the point that you can automate repetitive
and boring tasks is there. The newcommand can contain up to 9 arguments.
There is also a related command \renewcommand that allows you to use an existing command
name and redefine it. This can be very useful but also quite ‘dangerous’ if you do not know
what you are doing.
Do it
• Create your own new command. Try to replicate
this using the
marginpar (section
3.12) as a starting
point
34
10 Copying documents from Word to LATEX
Why have a section on moving Word content to LATEX? As you probably have understood there
are some significant differences between how Word works and how LATEX works. Most evident
is the fact that while Word does all formatting in the hidden, most such work is upfront in
LATEX. This can cause much grief when trying to copy text originally written and formatted
in Word to LATEX. Since you are likely to encounter persons who do not work with LATEX, you
may find yourself in a situation where most of a document is prepared in Word and left for
you to, for example, transfer into a journal class template. Or, you may have an old favourite
document you wish to move to LATEX. In this section I will provide some hands-on guidelines
for transferring material between the two tools as smoothly as possible.
Before continuing I need to mention that there are tools that translate Word files into LATEX.
The tools are usually good at replicating the look and feel of the Word document in LATEX,
but since that is rarely what we want, we end up with a code that mimics Word documents
well but with a LATEX code that is unnecessarily complicated. I recommend you to try such
tools just to get a sense of what they can do but in the following we will work on the principle
of preparing the word document so that the content can be copied using ‘copy–paste’ between
Word and your LATEX editor.
The first thing we need to realize is that no Word-based formatting will carry over into the
LATEX editor, only the text and the returns indicating end-of-paragraph. What order we make
the following changes is immaterial, each find their own praxis. In a way, one can say that
anything that has required some form of formatting in Word needs to be changed.
The basic strategy I recommend is to ‘LATEXify’ your Word document already in Word before
cutting and pasting it into the LATEX editor.
Paragraph breaks LATEX uses empty lines to identify paragraph breaks, Word does not. You
need to go through and add empty lines between all paragraphs otherwise, you will have
a hard time finding them in the LATEX editor.
Italics and bold face The italics and bold face typesetting will not be carried over. It is
much simpler to go through the Word document and look for your italics and bold text
and use the commands \textit{} and \textbf{} to mark those words in Word than in
your LATEX editor where the formatting will be lost.
Section headings The section headings formatting (levels) will not carry through to LATEX
(unless they are numbered so that you at least can identify them). This means it is easier
to insert the commands \section{}, \subsection{}, and \subsubsection{} in the word file
prior to copying.
Mathematics If you use equations and you have formatted variables with super and subscripts
in the text, you should rewrite these using the mathematical mode already in Word.
Scientific units Mixing text and mathematical mode to produce super and subscripts when
writing scientific units can be quite a mess. I strongly suggest you retype units using the
commands in the siunitx package.
Dashes You need to replace en-dashes in Word with the -- (double dash) format used by
LATEX.
Tables There is no easy way to prepare the tables for LATEX in Word. Just remember that any
fancy formatting will be lost so it is best to keep the table in as simple form as possible.
Complex tables are hard to typeset anywhere so this is where you probably need to spend
some time.
A useful tool to try is excel2latex, a plugin for Excel that allows you to save LATEX code
from a section of an Excel spreadsheet. If you take your tables from Word into Excel then
this tool will yield a good basis for your table, quick and easy. At the time of writing
the macro should work with Excel 2012–2016 (both 32 and 64-bit). In fact if you are
uncertain about the coding of tables, this macro may be a good way to learn by making
a table in excel and then saving it for LATEX.
35
Figures Since you cannot copy graphics from Word into LATEX the only thing that will be
copied is the figure caption. If you have your figures in Word and cannot produce originals
for LATEX you can right-click on the figure and save it as a picture. Use PNG format for
line graphics and JPG for photographs if you do so.
References If you have used EndNote or some other reference manager to produce references
and reference list in your Word document then all such couplings disappear when you copy
the text. Your reference should, however be correct unless you decide to do some serious
editing in LATEX after copying. You basically have two ways to deal with the references.
One is to stick to the manual way and simply manually check for correct cross-referencing.
The other is to load the natbib package and either enter/import references into BibTEX
and use that system or go halfway and use the \bibitem and different \cite{} commands
to produce the cross referencing. Either way this could cost you some time.
Extended type faces Depending on what system you use for compiling your LATEX document,
extended type faces may be come an issue. This stems from the introduction of type faces
that contain a much larger number of characters than used by older computers. XeLATEX
uses these modern type faces and may compile a text containing such extended character
sets correctly while pdfLATEX generally cannot. Switching to XeLATEX may solve issues
and for pdfLATEX there are work arounds (see the pdfLATEX documentation). However,
care should be taken when moving text containing, e.g. greek letters or mathematical
signs to ensure they become type set correctly.
There may be additional details in the Word document that either do not translate well or are
simply lost but the list above should normally cover 99% of a normal scientific document in
Word.
\begin{frame}
\(a=b\)
\end{frame}
\end{document}
What you see is that you need to make sure you use the beamer class. A slide is created by
an new environment called frame. anything you place within the frame environment will be on
your slide. Adding new slides is done by simply adding a new frame environment before or after
the first.
There are of course many things you can add to your basic beamer presentation. The
command \framettitle{} can be placed in a frame environment and will then produce title for
that slide. As with a regular document you can add a title page by providing the commands
\title{} and \author{} in combination with \titlepage (note not \maketitle). A two page
presentation with a title page can thus look as
\documentclass{beamer}
\begin{document}
\begin{frame}
\title{Presentation title}
\author{Your name}
\titlepage
\end{frame}
36
\begin{frame}
\frametitle{The title of the frame}
\(a=b\)
\end{frame}
\end{document}
Beamer comes preloaded with a series of colourful layouts. These can be invoked by using
the \usetheme{} and \usecolortheme{} commands. The themes and colour schemes have specific
names which are described in detail at the Beamer theme gallery. You can also create your
won layouts but that requires a little bit of involvement.
In the end you should consult the Beamer class user’s guide to learn more about all the
possibilities available in Beamer.
Do it
• Make a short Beamer presentation consisting of a title slide and a couple of text and
figure slides.
• Add some colour by using a few ‘beamer themes’.
\usepackage{MyStyle}
\begin{document}
\end{document}
The \usepackage command will then take your file and use its content in order to format the
current document.
It is important to realize a couple of things here. First, you will always need to place a copy
of your style file along with whatever document you are working on. LATEX will not keep track
of it for you. Second, if you enter additional instructions in the preamble, you need to make sure
they do not interfere with your style file. If you add something before the \usepackage{MyStyle},
you run the risk of having whatever you want to do over-ruled by the content in your style and
if you add something after the call the new material may over-rule something you have decided
will be part of your style.
37
It is possible to add some additional safety to the style file so that it will only be used with
appropriate versions of LATEX etc. We can start the style file by adding the following commands
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage {MyStyle }[2016/04/01 my LaTeX style]
This tells LATEX that the latest format of LATEX (LATEX2e) is needed and that this is ‘my’ style
file of such and such date. At the end of the file we can add
\ endinput
which tells LATEX that the style file content is ended. This command means you can add more
material to the file after the \endinput command but which will be ignored. This can be useful
if you add material you are unsure you want to use but do not want to lose.
So a complete style file should look like the following example
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage {MyStyle }[2016/04/01 my LaTeX style]
\ endinput
It is possible to take the style file much further and essentially build your own class. This
is beyond the scope of this text but the document LATEX2e for and package writers provides
much more in depth information on the subject.
LATEX
pdfLATEX PDF file
document
Figure 2. The basic way to generate a pdf file from a LATEX file. (upper work flow) Generic work flow
running LATEX to generate a DVI file followed by running dvi2ps to produce a postscript file from the
DVI and then ps2pdf to generate the pdf from the postscript file. (lower work flow) Work flow running
pdfLATEX to directly generate the pdf file.
Since LATEX in its generic form cannot easily handle system fonts a variant called XeLATEX
has been created. XeLATEX can access system fonts in a more direct way but because there
are internal differences between pdfLATEX and XeLATEX we must be careful when trying to use
certain packages in documents. Some (most) work with pdfLATEX while some require XeLATEX.
38
This is the price paid by maintaining backwards compatibility. However, any problem is easily
handled with some understanding of the two systems and by not overusing packages that we
do not know anything about.
The way LATEX handles information that requires recursive treatment is to store results in
external files (Table 2). This applies to, for example, the table of contents, figure and table
references, reference citations. The first run of LATEX generates lists of all such cross-referencing
information while LATEX type-sets the document. This way the location of each cross-referenced
object becomes known. LATEX then needs a second run to find all references to the objects and
replace these locations with the number of the figure or table or reference of the article. The
result is that the document is compiled, not once, but in fact several times in order for all
cross-referencing information to be properly located. Once this is accomplished you will find
several files generated by this process that contains information from the process.
Table 2. Some of the more common files (extensions) generated when compiling a LATEX document.
Note that some files are generated only when specific implementations are used.
Extension Description
.aux Generic information, mostly cross-referencing
.bib BibTEX reference data base file
.bbl bibliography produced by BibTEX
.bst BibTEX bibliography style file
.blg bibliography (BibTEX) log file
.cls LATEX class file
.dvi device independent file
.lof list of figures
.log complete compilation diagnostics reported by LATEX
.lot list of tables
.out hyperref PDF bookmarks
.sty LATEX package file
.tex LATEX or TEX document file
.toc table of contents
Depending on what you include in your document LATEX will need to be run several times
and maybe also involve other supplementary programs such as BibTEX. As an example, we
can view the series of runs necessary in order to produce a table of contents and a reference list
using the fully automated bibliography (Figure 3).
.bib .bst
BibTEX
data base
ref. style
Figure 3. The pdfLATEX work flow for a document containing a table of contents (generating the .toc
and a reference system based on a a BibTEX data base. Note that pdfLATEX needs to be run twice
after the BibTEX run in order for the cross referencing and reference list to be inserted correctly in the
document. Many, if not all, LATEX editors take care of this work flow automatically.
39
done something wrong. It is therefore useful to lay down a few ground rules to, first, reduce
the numbers of errors and, second, to see how we can solve them. The best way to solve errors
is to make sure they do not happen.
The first rule is thus, be meticulous when you write your document. The by far most common
error comes from having forgotten to pair { and }. The second most common error is that you
misspell a command. A third, concerns mathematical mode; you have either forgotten to switch
back to text mode or you use a mathematical command in text mode. In all cases, the errors
should be quite easy to spot and correct.
The second rule is to write slowly when you are doing more advanced LATEXing. When
you have some complex code you need to enter, do not rush and put a lot in at once. Instead
complete the code bit by bit and make sure each bit works before you continue with the following
parts. A useful tip is to maintain an empty document, I usually call test.tex, where I can build
and test code before pasting it into the main document. This has two advantages, one is that
you are working only on one piece of code in the test document and the other is that a small
document compiles much faster than if you work in your main and most likely much longer
document.
Sometimes, you will come across errors that may be ridiculously difficult to spot and to solve.
Such errors can come about for a multitude of reasons but, remember, you entered something
into the document which did not agree with LATEX, directly or indirectly. Therefore, go back
to what it was you just entered and try to figure out why this may have caused an error. Is
something incompatible? Have you misunderstood how a certain command works? There is no
easy answer as to how to solve these problems, you need to figure out what you did to cause
it. If it is possible, try to remove the part in the document that appears to cause the problem
and put it into a separate file (the test file) and see if you can replicate the error there.
Occasionally, you end up having a recurring problem that just does not seem to go away
and you cannot find a single problem. One detail to remember is the set of files generated
during a LATEX run (Table 2). It sometimes happens that one of these files contain material
that causes the problem. If you have run LATEX and then made some changes that will also
change the content of these files, there may be conflicting information left from earlier runs. It
is therefore useful to make a clean compile of the document by first removing all the temporary
or intermediate files. You need to be careful, however, since they all will have the same main file
name and just differ in their extension. What you should remove are typically the .aux, .bbl,
.blg, .dvi, .lof, .lot, .log, .out, and .toc files; if they exist. You should at all costs avoid to
remove any .tex, .bib, .bst, .cls and .sty files, of course. Many editors can do this for you
safely. In Overleaf this is called a recompile. If the problem persists after such a recompile,
then you unfortunately still have a problem in your document.
With time, and as you have created enough errors to solve, you will improve your problem
solving ability. This may seem as a cumbersome way, but it is the price we pay for the flex-
ibility and power of LATEX, and something quite familiar to those who do programming. As
stated earlier, the best way to avoid errors is to not make them so write slowly and carefully,
particularly when you enter commands., and compile your document frequently to that you see
when an error appears.
Do it
• It is tempting to write here that you should create your own error, but most likely you
have already done so in the process of trying things out. So, try to solve your errors
instead.
40
Appendix
A Running LaTeX on your own computer
This section outlines the basic installations necessary to run LATEX on your own computer. In
order to run LATEX you need an implementation of LATEX, a distribution, and a LATEX-compatible
editor.
A.1 LATEX
Which LATEX-distribution you chose depends on which operating system platform you are on.
For Linux, you most likely already have LATEX already installed. For Mac and Windows, you
definitely need to install it. There is one implementation call TEXLive which can be installed on
all platforms; on Macs using its Mac version MacTEX. The web page provides good instructions
on how to download and install the distribution. For Windows there is also a distribution called
MikTEX. I would recommend installing MikTEX on Windows platforms. MikTEX has utilities
to easily update LATEX. It is also possible to create a portable LATEX-environment by installing
on a memory stick.
A complete distribution of LATEX can be large (1–2 Gb). I would nevertheless recommend
to make a full installation rather than a partial. The reason for this is that LATEX contains a
huge number of so-called packages that simplifies tasks and provides new features to the basic
functionality. If you install the entire distribution, you are sure to have them within reach
if you need them. It is, however, also possible to make minimal installations and have the
LATEX-implementation download packages as necessary (applies at least to MikTEX).
LATEX in its basic form is a command-line driven software. It is thus possible to use it in
command line mode. This is not a very smooth way to use it and so a front-end editor is a
useful complement.
41
A.4 Reference management
LATEX contains its own reference management system called BibTEX. BibTEX is a database
system for references that consists of a standardized database format for reference material.
Many other systems can rad and export to BibTEX, such as EndNote, and may databases
including Web of Science. To manage your database you will need some form of software.
There are two ways forward, either you chose an on-line service such as Zotero or Mendeley, or
you go for a local service installed on your computer.
The online services Zotero and Mendeley provide means to build reference databases by
accessing material directly from the web and is probably the best choice if you have not begun
building such a database with any particular software. These services can provide the necessary
information to LATEX to enable you to reference data from your data base directly in your
document. The data is stored on-line but you also have the option of installing a standalone
version that can be synchronized with the on-line version. This is of course most valuable if
you wish or must to work off-line.
If you want to keep your reference database only on your computer I strongly recommend
JabRef. JabRef is a Java-based reference manager. This also means it works equally well on
all platforms and it is free! JabRef installs through the downloaded installer. Since JabRef is
Java-based, it will also require Java to be installed on the computer. In Windows, you will be
prompted to download it if you try to start your already installed JabRef without Java. Java
installs easily through an interactive installer.
B.2 Mac
The simplest way to install LATEX on the Mac is via MacTEX . The site provides the MacTex.pkg
file to install everything needed for running and maintaining your LATEX installation. There is
also an optional MacTeXtras.zip which provides some additional tools for editing etc. Once
42
installed you will find a Preference Pane for the selection of your TEX distribution (i.e. ver-
sion) but you can ignore this unless you have an older installation on your Mac. The basic
MacTex.pkg installer provides BibDesk, LATEXiT, TEXShop, TEXWorks and Excalibur as well
TEXLive Utility. The TEXLive Utility is used for updating and installing new packages (func-
tions or tools) and can be found under /Applications/TeX/TeX Live Utility.app.
The other tools installed are useful but there are alternative applications available that may
be more to your liking. TextWrangler is a very useful, freeware text editor that can parse TEX
using a set of scripts. Alternatively, Latexian (available through the App Store) is a very clean,
’Mac-like’ program that provides live previews of the compiled text as well as a good navigation
interface.
B.3 Linux
A basic TEX-environment is included in most Linux distributions.
References
Kottwitz, S., 2011. LATEX Beginner’s Guide. Packt Publishing, Birmingham. 336 p.
Mittelbach, F., Goossens, M., Braams, J., Carlisle, D., and Rowley, C., 2008. The LATEX
companion. Second edition. Addison-Wesley, New York. 1090 p.
van Dongen, M.R.C., 2012. LATEX and Friends. Springer, Berlin. 299 p.
Voss, H., 2010. LATEX Quick Reference. UIT Cambridge, Cambridge. 229 p.
Voss, H., 2011. Typesetting tables with LATEX. UIT Cambridge, Cambridge. 208 p.
43
D Revision history
v.3. 15 Oct., 2019 The part on referencing is completely rewritten with notes on Zotero and
Overleaf 2 integration included. Many minor typos and errors in v.2 have also been
corrected throughout the document.
v.2. 19 Sep., 2018 Added appendix on how to install LATEX on a personal computer. Minor
typos in v.1 corrected. Adjusted for Overleaf v2.
v.1. 29 Apr., 2016 First public version
44