Home  |   About  |   Energy  |   Politics  |   Software  |   Music

## 19 March 2014

### An Introduction to LaTeX

Writing my MSc thesis document was one of the most painstaking experiences I ever had in the computer world. Once the document went over four dozen pages it became very unstable and would wreck the formatting almost every time any substantial text was added. I have the feeling I spent as much time correcting the formatting as I did writing. The worse would come at the very end, by some strange reason Word decided to change all occurrences of the word bacia (Portuguese for basin) to bacio (Portuguese for pee pot); I never noticed it in time and the document went that way for printing. Such frustrating experience compelled me to try a different word processing system; I knew some folk at the Faculty were using LaTeX and decided to give it a try. I never used Microsoft Word again, and almost a decade later, could not possibly conceive going back.

Some weeks ago I administered a short introductory course on LaTeX to a few of my colleagues. Most of them had never seen anything other than Word, but it went quite well nonetheless. Here below I reproduce the contents of this course.

LaTeX is a language for the preparation of electronic or printed documents. It provides a series of special commands that layout the contents automatically in a desired support format.

To create a document with LaTeX you start by creating a file with the .tex extension where you type in your contents and layout commands. This file is then interpreted by a compiler that produces a finished document from it, a print ready file usually in PDF or DIV format.

#### Software

As you might have guessed, to use LaTeX you need to install a programme capable of compiling the language. On Linux I use TexLive, for Windows I recommend MiKTeX, which is easier to install in that system.

A compiler does not mean you need to use the command line or learn weird escape sequences. There are plenty of graphical editors that provide an easy and straightforward experience. On Linux I used TexMaker for long and find it flexible enough to suit both beginners and power users (today I use the TeXlipse extension for Eclipse). For Windows I would recommend WinShell (the first LaTeX editor I ever used) for beginners and TeXnicCentre for power users (for a WYSIWYG experience there is Lyx). These are just suggestions, there are loads of good LaTeX software out there (even for Mac). In this introduction you can use TeXworks for convenience, which comes bundled with MiKTeX.

#### Installing

For Linux users things should be fairly easy in distributions with package management systems.

On Windows you can install MiKTeX following this quick guide (adapted from here):
2. Run the installer by double clicking on it.
3. Accept the license agreement and click "Next" three times without changing anything.
4. At the settings tab, choose "A4" for preferred paper size and "Yes" for installing packages on the fly. Click "Next" and then click "Start".
5. Wait for the installer to finish (~15 minutes) and then click "Next" and "Close".
6. A new start menu will show up named MiKTeX, from which you should be able to start TeXworks.
7. Delete the installer file, it is no longer needed.

#### Creating a document

Step by step, you will build a document containing examples of the most common objects found in academic articles.

#### Commands and Environments

In a LaTeX document keywords are distinguished from regular text by being prefixed with the character \. There are two essential kinds of keywords:
• Commands - perform a specific task at the place they are inserted, e.g. \section{Introduction} creates a new document section.

• Environments - declares a structure containing a particular document element, figures and tables are the best examples. They always have an opening keyword, e.g. \begin{document}, and a closing keyword, e.g. \end{document}; as you can see the document is an environment itself.

#### Basic structure

This is your first LaTeX document. Copy the following lines to the editor, save it in a file with the .tex extension in a new folder and compile it:
\documentclass{article}

\begin{document}

Welcome to LaTeX!

\end{document}

Let us give some structure to the document. It can be divided into sections and subsections. Insert the following inside the document environment:
\section{Welcome}

Welcome to LaTeX!

\section{Experimenting}

This is where I will experiment with different types of LaTeX environments.

\subsection{Bullets and Numbering}

\subsection{Figures}

\subsection{Tables}

\subsection{Mathematics}

An article usually has a title, an author and an a abstract. The next piece of code does just that, insert it right after the \begin{document} keyword:
\title{My first LaTeX document}

\author{ Lu\'{i}s de Sousa }

\maketitle

\begin{abstract}
This is my first LaTeX document. In the future I can use it as a template, or
as a guide by example to the main components of the language.
\end{abstract}


Exercise 1: replace my name by yours.

#### Writing with LaTeX

With LaTeX you do not need to worry with line breaks, the compiler will do that for you. All the text in the same line is cast on the same paragraph; to create a new paragraph you must leave an empty line:
This is the first paragraph. It does not have much text.

This is the second paragraph. I might have a bit more text
to exemplify how the compiler breaks lines for you. Add
more random text here to see the effect.


Exercise 2: Copy the first two paragraphs from this web page and add them to the Welcome section. Try creating a subsection for it.

Bold text is made using the \textbf command; for italics there is the \textit command. Copy the following code to the Welcome section to see how it works:
\textbf{This is a sentence in bold}. And here is
an example of word in \textit{italics}.

Sometimes it may be useful to leave notes or comments in the .tex file that you may not wish to see in the final document. This is achieved with the % character: all that appears afterwards in the same line is ignored. Try the following still in the Welcome section:
% This is a comment.
There is a comment above this line that will be ignored
by the compiler. % This bit will also be ignored.

Commented out lines are also commonly used to visually separate code sections, i.e.:
% ------------------------------------------------------ %
\section{A new section}


#### Bullets and numbering

This is a common feature in documents, that LaTeX provides with the itemize environment. Copy the following code to the Bullets and Numbering section and see the effect:
My first item list:

\begin{itemize}
\item This is the first item.
\item And this is the second.
\item There's even a third item.
\end{itemize}


Tags or numbers can be attributed to each item using a suffix between []:
\begin{itemize}
\item[a)] Create a file with a .tex extension.
\item[b)] Open the the file and write your document.
\item[c)] Save the file and compile it.
\end{itemize}

To create a simple numbered list there is the enumerate environment:
\begin{enumerate}
\item Create a file with a .tex extension.
\item Open the the file and write your document.
\item Save the file and compile it.
\end{enumerate}

Item lists can also be nested by opening a new itemize environment after an item command.

Exercise 3: Modify the numbered item list to make it look like this:

#### Packages

To do particular tasks the compiler needs specific pieces of code called packages. To make the compiler aware of their need, packages must be declared at the begin of the document, between the \documentclass command and the document environment. In the following section we will need to import images to the document, for such we need the graphix package, that can be included with the following command:
\usepackage{graphicx}

A common feature that needs a special package is the euro symbol (€) - LaTeX long pre-dates the common currency. This is the package:
\usepackage{eurosym}

And an usage example (add it to the document):
A train ride back to Esch city costs 0.40 \euro{}.


#### Figures

Figures are another important component of a document, that in LaTeX are created with the figure environment. Inside this environment it is possible to import an image file to the document and attribute a caption to it. The figure environment keeps these assets together, instructing the compiler to use them as a single object. The centering command is useful to align all these assets inside the figure environment.

\begin{figure}[ht]
\centering
\includegraphics[scale=0.5]{LaTeX.jpeg}
\caption{LaTeX Figure.}
\end{figure}

Note that LaTeX automatically numbered the figure. Another thing it kindly does for you.

#### Tables

Tables are created within the tabular environment and can be grouped with a caption in a table environment. Vertical lines are set with the character | in a particular command group within the tabular environment; among these is defined the text alignment for each column, using the characters l (left), c (centred) and r (right). Horizontal lines are created with the \hline command, which is used bordering each text row. Text cells in each row are separated by the & character and terminated with the \\ sequence. The of number cells in each row must match the number of columns defined in the beginning of the tabular environment.

Copy the following table to the Tables section and study it carefully.
\begin{table}[ht]
\caption{My first LaTeX table.}
\centering
\begin{tabular}{|l|c|r|}
\hline
\textbf{Left} & \textbf{Centered} & \textbf{Right} \\
\hline
First Row & Something & 99.9 \\
\hline
Second Row & Some other & 1001.1 \\
\hline
\end{tabular}
\end{table}


Exercise 5: Produce a table resembling this image:

#### References

Most LaTeX objects can be labelled with an identifier using the \label command; sections, tables, figures, etc, can all be tagged this way. These labels can then be used in the text to refer to these objects, without any worries regarding their numbering or positioning.

Add the following label to the first figure, inside the figure environment:
\label{fig:First}

Labels are referenced in the text with the \ref command. Add the following paragraph to the Images section:
In Figure \ref{fig:First} you can see something very important.

Sometimes the compiler can break the line between the "Figure" word and the number generated by the \ref command. To avoid this there is a special character, ~, that informs the compiler the two elements should be kept together:
In Figure~\ref{fig:First}


Exercise 6: Add labels for all the sections, images and tables you have created so far. Create a new paragraph in the Welcome section referring to various of these objects.

#### Mathematics

This is one of the most powerful features of LaTeX and used even by users of different text editors. Within the text, mathematical expressions can be inserted between a pair of $ characters; the equation environment provides the appropriate space for formulas. An example: $$y = mx + b$$  Equation environments are another class of objects automatically numbered. The symbols +, -, /, =, < and > have the usual meaning; for multiplications there is \cdot. For "less than or equal", there is \le and \ge for the converse. Superscripts are indicated with the ^ character as prefix, while subscripts are prefixed with _ : The value of$n_{t}$is consistently higher than that of$w^e\$.

Square roots are generated with the \sqrt command:
$$z = \sqrt{x^2+y^2}$$

Fractions are described with the \frac command, using brackets to separate the numerator from the denominator.
$$\frac{x}{y - 1}$$

Sums are obtained with the \sum command, combined with subscripts and superscripts:
$$\sum_{k=1}^n k = \frac{n(n+1)}{2}$$

The logic is similar for integrals, obtained with the \int command (note also the usage of the \infty command for infinity):
$$\int_{0}^\infty k = \frac{n(n+1)}{2}$$

For limits there is \lim:
$$\lim_{x \to \infty} \exp(-x) = 0$$

An example of basic logic:
$$\forall x \in X, \quad \exists y \leq \epsilon$$


Exercise 7: copy these snippets one by into the Mathematics section and observe the results.

This is just a glimpse of what can be done with mathematics commands, there is much more, support for matrices, set theory and more. It is a whole world that you can easily explore further in one of the many tutorials out there in the web.

Exercise 8: Produce an expression like:

Exercise 9: Produce an expression like:

#### Bibliography

To have a bibliography in your document you need to create a special database. This is nothing more than a text file with the suffix .bib, including the description of each article/book/report/document you wish to cite. This description must respect a special format called BibTeX for the compiler to understand.

Create a new file on the same folder of your document and name it myBiblio.bib. Open it and copy in the following content:
@inproceedings{deSousa2012iguess,
title={iGUESS - A web based system integrating Urban Energy
Planning and Assessment Modelling for multi-scale spatial
decision making},
author={de Sousa, Lu{\'\i}s and Eykamp, Christopher and Leopold,
Ulrich and Baume, Olivier and Braun, Christian},
booktitle={Procedings of the International Congress on Environmental
Modelling and Software (iEMSs)},
year={2012},
organization={International Modelling and Software Society}
}

This is the definition of a single article. Looks complicated? Don't worry, all you need to know for now is the document key, the first string after the very first {, in this case: deSousa2012iguess.

Most scientific databases out there already have the BibTeX description available for each article, such as Google Scholar. All you need to do is copy in the BibTeX of each article and simply use its key.

In the text you refer to an entry in your BibTeX database using the \cite command and the key. Insert the following in the Bibliography section:
iGUESS \cite{deSousa2012iguess} is a great system.

Finally you must tell the compiler which database you wish to use, for that employing the \bibliography and \bibliographystyle commands. They are usually cast at the very end of the document environment.
\bibliographystyle{plain}
\bibliography{myBiblio}


Exercise 10: Copy the BibTeX of two of your articles from Google Scholar into your database. Expand the Bibliography section with some random text referencing these articles of yours.

Bibliography in LaTeX is another world of its own. There are programmes solely dedicated to the management of databases and many different citation styles that you can use. Perhaps a topic for another session altogether.

#### Use case

LaTeX becomes really useful when you have to submit an article to a journal or a conference. You will usually have a LaTeX template ready with the outlet style, no worries whatsoever with formatting. The templates themselves usually provide useful guidelines on how to use LaTeX.

Exercise 11: Download the Elsevier template file into a new folder. Extract it and give a look at the .tex file. Correctly apply your name and affiliation and type in some random abstract. Create new section(s) and add some of the objects you created before, at least a picture, a table and a mathematical expression.

Exercise 12: Knowing that you are an open access supporter here I leave a link to the Frontiers template. It is a bit more complex, but the logic is pretty much the same; see what you can do with it.

#### Enjoy LaTeX

This introduction was very light but provides you the basic tools and concepts underpinning LaTeX. In the beginning you might need to study a bit further to find out how to create less common objects. But the more you use LaTeX the easier it will become, each time you achieve some particular task you can always employ it the same way in future documents. Your knowledge will be constantly expanding.

There is information aplenty on LaTeX on the web, tutorials, guides, even web based compilers. There are also very good community based help centres like the LaTeX Forum and TeX.StackExchange.

And you can always ask help from a colleague :) .