LaTeX

Overview

  • LaTeX files are plain text files that describe the document’s structure and presentation
  • LaTeX converts source text, combined with markup, into a teypset document
  • LaTeX is similar to HTML

There are several LaTeX engines in modern use: lualatex, xelatex, and pdflatex.

LaTeX itself does not have a GUI, though some LaTeX installations feature a graphical front-end where you can click LaTeX into compiling your input file. Assuming you’re not using one of those:

Open a terminal and navigate to the directory containing your .tex file. Type the command: xelatex hello.tex (The .tex extension is not required, although you can include it if you wish.) Various bits of info about LaTeX and its progress will be displayed. If all went well, the last two lines displayed in the console will be:

Output written on hello.pdf (1 page). Transcript written on hello.log.

Autobuild Systems

Compiling can be quite tricky as soon as you start working on more complex documents. A number of programs exist to automatically read in a LaTeX document and run the appropriate compilers the appropriate number of times. For example, latexmk can generate a PDF from most LaTeX files simply:

$ latexmk -pdf file.tex

Historical versions of LaTeX

Both LaTeX and TeX were created many years before the Portable Document Format (PDF) existed, so the plain LaTeX engine, latex, emits DVI, a format designed by Donald Knuth for device-independent TeX output. This format has fallen out of general use, but can be converted into more common output formats using programs from your LaTeX distribution:

dvips converts .dvi files to .ps (PostScript). dvipdf converts .dvi files to .pdf (dvipdfm is an improved version).

You might also find Ghostscript, a set of free and open-source tools for working with PostScript, useful. Its ps2pdf converts .ps files to .pdf, and pdf2ps does the reverse.

The following diagram shows the relationships between the LaTeX source code and the formats you can create from it:

Ancillary files

The TeX compilers are single-pass processes. It means that there is no way for a compiler to jump around the document, which would be useful for the table of contents and references. Indeed the compiler cannot guess at which page a specific section is going to be printed, so when the table of contents is printed before the upcoming sections, it cannot set the page numbers.

To circumvent this issue, many LaTeX commands which need to jump use ancillary files which usually have the same file name as the current document but a different extension. It stores temporary data into these files and use them for the next compilation. So to have an up-to-date table of contents, you need to compile the document twice. There is no need to re-compile if no section moved.

For example, the temporary file for the table of contents data is filename.toc.

None of these files contains unrecoverable information. It means you can delete them safely, compiling will regenerate them automatically. warning The only important file types are .tex, .cls and .sty, .bib and .bst for BibTeX, these are not temporary and should not be deleted.

When you work with various capabilities of LaTeX (index, glossaries, bibliographies, etc.) you will soon find yourself in a maze of files with various extensions and probably no clue. The following list explains the most common file types you might encounter when working with TeX:

.aux - A file that transports information from one compiler run to the next. Among other things, the .aux file is used to store information associated with cross-references. .bbl - Bibliography file output by BiBTeX and used by LaTeX .bib - Bibliography database file. (where you can store a list of full bibliographic citations) .blg - BiBTeX log file. (errors are logged here) .bst - BiBTeX style file. .cls - Class files define what your document looks like. They are selected with the \documentclass command. .dtx - Documented TeX. This is the main distribution format for LaTeX style files. If you process a .dtx file you get documented macro code of the LaTeX package contained in the .dtx file. .ins - The installer for the files contained in the matching .dtx file. If you download a LaTeX package from the net, you will normally get a .dtx and a .ins file. Run LaTeX on the .ins file to unpack the .dtx file. .fd - Font description file telling LaTeX about new fonts. .dvi - Device Independent File. This is the main result of a LaTeX compile run with latex. You can look at its content with a DVI previewer program or you can send it to a printer with dvips or a similar application. .pdf - Portable Document Format. This is the main result of a LaTeX compile run with pdflatex. You can look at its content or print it with any PDF viewer. .log - Gives a detailed account of what happened during the last compiler run. .toc - Stores all your section headers. It gets read in for the next compiler run and is used to produce the table of contents. .lof - This is like .toc but for the list of figures. .lot - And again the same for the list of tables. .idx - If your document contains an index. LaTeX stores all the words that go into the index in this file. Process this file with makeindex. .ind - The processed .idx file, ready for inclusion into your document on the next compile cycle. .ilg - Logfile telling what makeindex did. .sty - LaTeX Macro package. This is a file you can load into your LaTeX document using the \usepackage command. .tex - LaTeX or TeX input file. It can be compiled with latex. .out - hyperref package file, just one for the master file.

Creating a document

A minimal document:

\documentclass[options]{class}

\begin{document}
Hello
\end{document}

Whitespace characters such as space and tab are treated uniformly as space i.e. multiple spaces/tabs are converted to one space

An empty line starts a new paragraph

  • A document class file defines the formatting standard to follow,
  • The area between \documentclass{…} and \begin{document} is called the preamble. It normally contains commands that affect the entire document.
  • the text of your document is enclosed between \begin{} and \end{} which identify the beginning and end of the actual document:
  • A useful side-effect of marking the end of the document text is that you can store comments or temporary text underneath the \end{document} in the knowledge that LaTeX will never try to typeset them:

Document Classes

article For articles in scientific journals, presentations, short reports, program documentation, invitations, … IEEEtran For articles with the IEEE Transactions format. proc A class for proceedings based on the article class. report For longer reports containing several chapters, small books, thesis, … book For real books. slides For slides. The class uses big sans serif letters. memoir For changing sensibly the output of the document. It is based on the book class, but you can create any kind of document with it [1] letter For writing letters. beamer For writing presentations (see LaTeX/Presentations).

Document Class Options

10pt, 11pt, 12pt Sets the size of the main font in the document. If no option is specified, 10pt is assumed. a4paper, letterpaper,… Defines the paper size. The default size is letterpaper; However, many European distributions of TeX now come pre-set for A4, not Letter, and this is also true of all distributions of pdfLaTeX. Besides that, a5paper, b5paper, executivepaper, and legalpaper can be specified. fleqn Typesets displayed formulas left-aligned instead of centered. leqno Places the numbering of formulas on the left hand side instead of the right. titlepage, notitlepage Specifies whether a new page should be started after the document title or not. The article class does not start a new page by default, while report and book do. twocolumn Instructs LaTeX to typeset the document in two columns instead of one. twoside, oneside Specifies whether double or single sided output should be generated. The classes article and report are single sided and the book class is double sided by default. Note that this option concerns the style of the document only. The option twoside does not tell the printer you use that it should actually make a two-sided printout. landscape Changes the layout of the document to print in landscape mode. openright, openany Makes chapters begin either only on right hand pages or on the next page available. This does not work with the article class, as it does not know about chapters. The report class by default starts chapters on the next page available and the book class starts them on right hand pages. draft makes LaTeX indicate hyphenation and justification problems with a small square in the right-hand margin of the problem line so they can be located quickly by a human. It also suppresses the inclusion of images and shows only a frame where they would normally occur.

Reserved Characters

# $ % ^ & _ { } ~ \

Escape these with a single backslash \

Use \backslash in math mode

In some circumstances square brackets can be considered reserved characters ([ and ]).

LaTeX Groups

Use { and } to control scope or \bgroup and \egroup when braces can’t be used.

LaTeX Environments

Environments are similar to commands, but also have a wider effect

\begin{envname}
...
\end{envname}
  • you can put other commands inside environments and nest environments
  • the mechanism for environments defines a group internal to the environments

LaTeX Commands

Commands start with \ and then have a name consisting of letters only

  • terminated by a space a number or other non-letters

Or consist of \ and one non-letters

Some commands need an argument, which is placed in { and } after the command name. Some commands support optional parameters which are placed after the command name in brackets i.e. [ and ]

\backslashtext commandname[option1,option1,...]{arg1}{arg2}...

Most LaTeX commands have a switch equivalent. Switches have no arguments, but apply to the rest of the scope. Switches are easily confused with commands

\emph{emphasized text} % command
{\em emphasized text}  % switch

Comment with %

Packages

If you want to include graphics, colored text or source code from a file into your document, you need to enhance the capabilities of LaTeX. Such enhancements are called packages. Some packages come with the LaTeX base distribution. Others are provided separately. Modern TeX distributions come with a large number of packages pre-installed. The command to use a package is pretty simple: \usepackage:

\documentclass{report}
\usepackage[options]{packagename}

\begin{document}
...
\end{document}

Top Matter

At the beginning of most documents there will be information about the document itself, such as the title and date, and also information about the authors, such as name, address, email etc. All of this type of information within LaTeX is collectively referred to as top matter.

\documentclass[11pt,a4paper]{report}

\begin{document}
\title{How to Structure a LaTeX Document}
\author{Andrew Roberts}
\date{December 2004}
\maketitle
\end{document}

MathJax

Inline LaTeX:

$\text{LaTeX}$

Block-style LaTeX:

$$
\text{LaTeX}
$$

Chemistry

Code Rendering Description
\ce{H^+} $\ce{H^+}$ chemical equation
\ce{H_2(l) \rightleftharpoons H^+ (aq) + OH^-(aq)} $\ce{H_2(l) \rightleftharpoons H^+ (aq) + OH^-(aq)}$ chemical reaction both ways

Math

Code Rendering Description
\cancel{3} $\cancel{3}$ cancel something out
\text{not italicised} $\text{not italicised}$ text
\\ $\\$ newline
\{ $\{$ left curly brace
\} $\}$ right curly brace
\left\{ $\left\{$ autofit brace
\right\{ $\right\{$ autofit brace
\langle $\langle$ left angle bracket
\rangle $\rangle$ right angle bracket
| $\|$ pipe
\mid $\mid$ pipe
\underbrace{x}_{b} $\underbrace{x}_{b}$ under brace
\underbracket{x}_{b} $\underbracket{x}_{b}$ under bracket
\mathop{\text{max}}_{i} $\mathop{\text{max}}_{i}$ centered subscript
\overbrace{x + y}^{\text{equation for } x + y} $\overbrace{x + y}^{\text{equation for } x + y}$ over brace
\overset{a}{b} $\overset{a}{b}$ place a above b
\overset\leftrightarrow{a} $\overset\leftrightarrow{a}$ left right arrow above a
\xrightarrow{c} $\xrightarrow{c}$ c above right arrow
\underset{b}{a} $\underset{b}{a}$ b under a
\left( $\left($ auto fit
\right) $\right)$ auto fit
( \big( \Big( \bigg( \Bigg(   % sizes in ascending order

Special Letters

Code Rendering Description
\ell $\ell$ ’l’ used for loss function
\sigma $\sigma$ example lower case Greek letter
\Sigma $\Sigma$ example upper case Greek letter

Calculus

Code Rendering Description
\frac{\partial Q}{\partial t} = \frac{\partial s}{\partial t} $\frac{\partial Q}{\partial t} = \frac{\partial s}{\partial t}$ partial derivative
\nabla $\nabla$ gradient

Piecewise Functions

$$ \begin{gather} f(x) = \left\{ \begin{array}{lr} x^2 & : x < 0\\ x^3 & : x \ge 0 \end{array} \right. \end{gather} $$$$ \begin{gather} f(x) = \left\{ \begin{array}{lr} 1, & \text{ if } x = \pi \\ 0, & \text{ if } x = 3 \end{array} \right. \end{gather} $$
f(x)
= \left\{
  \begin{array}{lr}
  x^2 & : x < 0\\
  x^3 & : x \ge 0
  \end{array}
\right.

f(x)
= \left\{
\begin{array}{lr}
1, & \text{ if } x = \pi \\
0, & \text{ if } x = 3
\end{array}
\right.
Code Rendering Description
x^{y} $x^{y}$ x superscript y
h^* $h^*$ an optimal function
x^\circ $x^\circ$ x with degree symbol
' $'$ prime symbol
'' $''$ double prime symbol
\dot x $\dot x$ Newton’s notation for derivatives
x_{y} $x_{y}$ x subscript y
x_{y_z} $x_{y_z}$ x subscript y subscript z
3.\overline{3} $3.\overline{3}$ repeating decimal
\bar{x} $\bar{x}$ over bar?
\frac{n}{d} $\frac{n}{d}$ fraction with numerator n and denominator d
\frac nd $\frac nd$ shorthand
\sum{} $\sum{}$ sum with upper case sigma
\displaystyle\sum $\displaystyle\sum$ variation where subscript is directly below, and superscript directly above
\sqrt{} $\sqrt{}$ square root
\sqrt[p]{} $\sqrt[p]{}$ p root
\div $\div$ division symbol
\cdot $\cdot$ multiplication dot
\dots $\dots$ ellipses
\cdots $\cdots$ center of line ellipses
\vdots $\vdots$ same, but vertical
\ddots $\ddots$ same, but diagonal
\leq $\leq$ less than or equal to
< $<$ less than
\ll $\ll$ very less than
\geq $\geq$ greater than or equal to
> $>$ greater than
\gg $\gg$ very greater than
\lesseqqgtr $\lesseqqgtr$ less than, equal to, or greater than
\lessgtr $\lessgtr$ less than or greater than
\ne $\ne$ not equal to
\approx $\approx$ approximately equal
\lessapprox $\lessapprox$ less approximately
\gtrapprox $\gtrapprox$ greater approximately
\simeq $\simeq$ similar equal
\sim $\sim$ similarity in geometry
\triangleq $\triangleq$ estimates; ‘defined to be equal’
:= $:=$ same
\overset{\text{def}}{=}} $\overset{\text{def}}{=}$ same
\doteq $\doteq$ by definition, equals
\pm $\pm$ plus or minus
\mid $\mid$ absolute value line
\pi $\pi$ pi
\infty $\infty$ infinity

Set Theory

\{x \mid \x \text{ is positive and even} \}
Code Rendering Description
\{2, 4, 6, 8, \dots \} $\{2, 4, 6, 8, \dots \}$ set with ellipses
\rightarrow $\rightarrow$ right arrow
\leftarrow $\leftarrow$ left arrow
\Rightarrow $\Rightarrow$ implies
\Leftarrow $\Leftarrow$ ?
\downarrow $\downarrow$ down arrow
x \in X $x \in X$ x is a member of set X
x \notin X $x \notin X$ x is not a member of set X
X \ni x $X \ni x$ set X has member x
A \cup B $A \cup B$ union of 2 sets (2 sets combined)
\bigcup $\bigcup$ union of many sets
\bigcup\limits_{i=1}^{\infty} $\bigcup\limits_{i=1}^{\infty}$ with limits
A \cap B $A \cap B$ intersection of 2 sets (values common to both sets)
\bigcap $\bigcap$ intersection of many sets
\bigcap\limits_{i=1}^{\infty} $\bigcap\limits_{i=1}^{\infty}$ with limits
A \setminus B $A \setminus B$ set difference
S \subset T $S \subset T$ S is proper subset of T
S \subseteq T $S \subseteq T$ S is subset of T
S \nsubseteq T $S \nsubseteq T$ S is not a subset of T
T \supset S $T \supset S$ T is a superset of S
\emptyset $\emptyset$ empty/null set
A \times B $A \times B$ cartesian product A with B
\mathcal{P}(S) $\mathcal{P}(S)$ Power set of set S

Logic

Code Rendering Description
\forall $\forall$ universal quantifier
\exists $\exists$ existential quantifier
\exists! $\exists!$ uniqueness quantifier
\exists_1 $\exists_1$ same
\top $\top$ top (“true”)
\bot $\bot$ bottom (“false”)
\models $\models$ interpretation evaluates to “true”; entailment
\not\models $\not\models$ interpretation evaluates to “false”
\triangleleft $\triangleleft interpretation update

Proof

$$ \begin{align} \begin{array}{rl} & p \\ & \underline{p \to q} \\ \therefore & q \end{array} \end{align} $$
$$
\begin{align}
\begin{array}{rl}
& p \\
& \underline{p \to q} \\
\therefore & q
\end{array}
\end{align}
$$

Tables

\begin{center}
\begin{tabular}{ | m{5em} | m{1cm}| m{1cm} | }
\hline
cell1 dummy text dummy text dummy text& cell2 & cell3 \\
\hline
cell1 dummy text dummy text dummy text & cell5 & cell6 \\
\hline
cell7 & cell8 & cell9 \\
\hline
\end{tabular}
\end{center}
\begin{array}{ | c | c | c | c | c | c | }
\hline
x & 1 & 2 & 3 & 4 & 5\\
\hline
f(x) & 2 & 4 & 6 & 9 & 12\\
\hline
\end{array}
  • With no outer border and line under columns
\begin{array}{ c | c }
x & y = 2^x\\
\hline
3 & 8\\
3.1 & 8.5742\\
3.14 & 8.8152\\
3.141 & 8.8214\\
\end{array}

Special fonts

Code Rendering Description
\mathbb{R} $\mathbb{R}$ double-lined font e.g. all real numbers
\mathcal{P} $\mathcal{P}$ fancy writing e.g. set of polynomials
\mathbf{a} $\mathbf{a}$ bold e.g. vectors
\mathbf{A} $\mathbf{A}$ e.g. matrices
\mathscr{E} $\mathscr{E}$ cursive and upper case epsilon?
\mathfrak{R} $\mathfrak{R}$ ?

Spacing

Code Rendering Description
\qquad $\qquad$ 2 em
\quad $\quad$ 1 em
\: $\:$ single space
\, $\,$ thin space

Misc format

Code Rendering Description
\fbox{my text} $\fbox{my text}$ enclose in a box

Alignment

\begin{align*}
&    % aligned to left
     % aligned to right
\end{align*}

\begin{flushleft}
\end{flushleft}

Functions

Code Rendering Description
:= $:=$ defined as
(f \circ g)(x) $(f \circ g)(x)$ f composed with g

Long Division

\begin{array}{l}
{\qquad\:\: 4??}\\
364\overline{)160476}\\
{\quad\,\underline{-1456}}\\
{\quad\quad 0148}\\
\end{array}

Logarithms

Code Rendering Description
\log_base exponent $\log_base exponent$ logarithm
\log_{\frac{n}{d}} $\log_{\frac{n}{d}}$ exponent
\ln exponent $\ln exponent$ natural logarithm
\log exponent $\log exponent$ base 10 logarithm

Trigonometry

Code Rendering Description
\triangle $\triangle$ triangle
\sin $\sin$ sine
\cos $\cos$ cosine
\tan $\tan$ tangent
\csc $\csc$ cosecant
\sec $\sec$ secant
\cot $\cot$ cotangent

Limits

|\lim_{x \to 1} y|$\lim_{x \to 1} y$| limit of $y$ as $x$ approaches $1$|

Logic2

Code Rendering Description
\neg $\neg$ negation
\land $\land$ logical and (conjunction)
\lor $\lor$ logical or (disjunction)
\oplus $\oplus$ exclusive or
\ominus $\ominus$ generalized difference
\odot $\odot$ boolean product
\to $\to$ conditional statement (if-then)
\leftrightarrow $\leftrightarrow$ biconditionality (if-then both ways)
p \equiv q $p \equiv q$ means p \leftrightarrow is true in all cases, $p$ congruent to $q$
p \Leftrightarrow q $p \Leftrightarrow q$ same?
p \not\equiv q $p \not\equiv q$ not equivalent
I \mapsto J $I \mapsto J$ I maps to J
x \leadsto y $x \leadsto y$ x maps to y
i: K_3 \xhookrightarrow H $i: K_3 \xhookrightarrow H$ inclusion map, an identity function from K_3 to H
\therefore $\therefore$ conclusion to proof
\ni $\ni$ there
\blacksquare $\blacksquare$ QED, the halmos, indicates end of proof

Logical Argument

$$		% logic argument
\begin{array}{rl}
& p \\
& \underline{p \to q} \\
\therefore & q
\end{array}
$$

Combinatorics

Code Rendering Description
{n \choose k} ${n \choose k}$ “n choose k”
Code Rendering Description
\lfloor n \rfloor $\lfloor n \rfloor$ floor n
\lceil n \rceil $\lceil n \rceil$ ceiling n
a \mod m $a \mod m$ remainder of a divided by m, “a modulo m”
d $a$ d a there is no remainder resulting from a/d, “d divides a”
d\not $ a$ d\not a “d does not divide a”
{}_n C_r ${}_n C_r$ subscript n before Cr

Geometry

Code Rendering Description
L \perp M $L \perp M$ line L is perpendicular to line M
L \parallel M $L \parallel M$ line L is parallel to line M

Partially ordered sets

Code Rendering Description
\prec $\prec$
\succ $\succ$
\preccurlyeq $\preccurlyeq$
\succcurlyeq $\succcurlyeq$

Matrices

Plain Matrix

\begin{matrix}
    3 & 2 & 1\\
    2 & 4 & 7\\
    1 & 7 & 5
\end{matrix}

Block matrix (block braces)

\begin{bmatrix}
    3 & 2 & 1\\
    2 & 4 & 7\\
    1 & 7 & 5
\end{bmatrix}

Adjacency Matrix (parentheses)

\begin{pmatrix}
    3 & 2 & 1\\
    2 & 4 & 7\\
    1 & 7 & 5
\end{pmatrix}

\top for matrix transpose, e.g. $\mathbf{M}\top$.

Code Rendering Description
\propto $\propto$ proportional to; polynomial time reduction

Summation

Code Rendering Description
\sum_{i = 0}^k i $\sum_{i = 0}^k i$ summation
\prod_{i = 0)^k i $\prod_{i = 0)^k i$ product summation

Isomorphism

Code Rendering Description
V \simeq W $V \simeq W$ the vector spaces V and W are isomorphic
V \cong W $V \cong W$ same (also symbol for congruence)

Comparison

Code Rendering Description
a \ll b $a \ll b$ a is much smaller than b
a \gg b $a \gg b$ a is much greater than b
\tilde{T} $\tilde{T}$ a linear map “tilde T” different form T
\vec{v} \bot \vec{u} $\vec{v} \bot \vec{u}$ vector v is orthogonal to vector u (up tack or falsum)

Relational Theory

Code Rendering Description
\bowtie $\bowtie$ joins
\Join $\Join$ joins
\overset{\circ}{\Join} $\overset{\circ}{\Join}$ outer joins
\perp $\perp$ null
\bigtimes $\product$ cross-product

Geometry

Code Rendering Description
\overline{AB} $\overline{AB}$ line segment

Operators

Code Rendering Description
\underset{x}{\operatorname{argmax}} $\underset{x}{\operatorname{argmax}}$ argmax

Sources