# latex

> the commands, environments, and packages for everyday documents and math, with the math rendered.

source: https://learning.anthnydas.com/tools/latex/

## tl;dr

you write the content and its structure as plain text. tex does the typesetting.

- **reserved:** 10 (characters that need escaping)
- **engine:** pdflatex (xelatex or lualatex for opentype fonts)
- **math:** amsmath (align, cases, matrices)
- **build:** latexmk (reruns until the references settle)
- **reach for it:** papers and reports, math-heavy notes, anything with equations, documents you keep in git

latex is a document preparation system: you write the content and mark its structure in plain text, and tex, the typesetting program underneath, works out how the page looks.[^latex] leslie lamport wrote it in the early 1980s as a set of macros for donald knuth's tex.[^lamport][^tex]

> **interactive figure:** a latex editor and the page latex.js renders from it, updated as you type. five examples to start from: an article, math, lists, text and symbols, and a resume. an error shows under the editor with its line, and the last page that worked stays up.

the playground runs latex.js, a latex to html translator written in javascript, in your browser.[^latexjs] it handles the core: sections, text, lists, and math between `$...$` or `\[...\]`. tables, figures, footnotes, custom commands, and the `equation` and `align` environments need a real latex install.

## document structure

a file is a class, a preamble, and a body. `\documentclass` comes first and sets the kind of document. everything between it and `\begin{document}` is the preamble, where packages load. the body is what gets typeset.

```latex
\documentclass{article}      % or report, book, letter
\usepackage{amsmath}         % packages load in the preamble

\title{a short paper}
\author{your name}
\date{\today}                % \date{} leaves the date off

\begin{document}
\maketitle                   % prints the title block

\section{introduction}       % 1 introduction
text of the section.

\subsection{background}      % 1.1 background
\section*{thanks}            % starred: no number, not in the table of contents

% a comment runs to the end of the line
\end{document}
```

the levels go `\part`, `\chapter`, `\section`, `\subsection`, `\subsubsection`, `\paragraph`, `\subparagraph`. `article` has no `\chapter`. `report` and `book` do.[^structure]

## text

```latex
\emph{emphasis}, \textbf{bold}, \texttt{monospace}
{\small smaller} and {\Large larger}    % a size lasts until its group ends

``double quotes'' and `single quotes'
pages 12--14                            % en dash, for ranges
a pause---like this---in a sentence     % em dash
well-known                              % hyphen

\# \$ \% \& \_ \{ \}                     % backslash in front
\textasciitilde{} \textasciicircum{} \textbackslash{}

a claim.\footnote{its note, at the foot of the page.}

one line\\
the next line, same paragraph

a blank line starts a new paragraph.
```

ten characters mean something to latex: `#`, `$`, `%`, `&`, `_`, `{`, `}`, `~`, `^`, and `\`. seven print with a backslash in front. the last three need commands of their own: `\\` is a line break, and `\~` and `\^` put an accent on the next letter.[^special]

quotes open with backticks and close with apostrophes, not straight quotes. one hyphen joins words, two make an en dash for ranges, three an em dash. sizes, smallest to largest: `\tiny`, `\scriptsize`, `\footnotesize`, `\small`, `\normalsize`, `\large`, `\Large`, `\LARGE`, `\huge`, `\Huge`.[^text]

`\\` ends a line but not the paragraph. a blank line ends the paragraph, and several blank lines count as one. for extra space, use `\vspace{1em}`, not a stack of `\\`. `\footnote` puts a numbered note at the bottom of the page.[^text]

## lists

```latex
\begin{itemize}              % bullets
  \item a point
  \item another
  \begin{enumerate}          % lists nest, up to four deep
    \item numbered
    \item and counted
  \end{enumerate}
\end{itemize}

\begin{description}
  \item[term] its meaning. the label prints in bold.
\end{description}
```

every entry starts with `\item`.[^lists] the enumitem package takes options for the labels and the spacing:[^enumitem]

```latex
\usepackage{enumitem}                 % preamble

\begin{enumerate}[label=(\alph*)]     % (a), (b), (c)
  \item first
  \item second
\end{enumerate}

\begin{itemize}[nosep]                % no extra space between items
  \item tight
  \item list
\end{itemize}
```

## math

inline math goes between dollar signs, like $\pi r^2$ in this sentence. display math gets a line of its own: `\[...\]`. you'll also see `$$...$$`. that's plain tex: in latex it spaces displays inconsistently and breaks the `fleqn` option, so use `\[...\]`.[^dollars]

`equation` numbers a display. amsmath adds `equation*` without the number, and `align` for several lines: `&` goes before the symbol to line up on, `\\` ends every line but the last, and each line gets a number (`align*` for none). a blank line anywhere inside math is an error.[^amsmath]

```latex
the area is $\pi r^2$.            % inline. \( \pi r^2 \) works too

\[ e^{i\pi} + 1 = 0 \]            % display, no number

\begin{equation}                  % display, numbered
  E = mc^2 \label{eq:energy}      % \ref{eq:energy} prints its number
\end{equation}

\begin{align}                     % lined up at the &, one number per line
  f(x) &= (x + 1)^2 \\
       &= x^2 + 2x + 1
\end{align}
```

$$
\begin{align}
  f(x) &= (x + 1)^2 \\
       &= x^2 + 2x + 1
\end{align}
$$

### examples

each one as you'd type it in a `.tex` file, then rendered. the rendering on this page is katex, a library that typesets tex math as html when the site builds. it does math only, not whole documents.[^katex]

a fraction and a square root:

```latex
\[ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]
```

$$
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
$$

a sum with limits. `_` sets the bottom, `^` the top, and in a display they sit below and above the sigma:[^amsmath]

```latex
\[ \sum_{i=1}^{n} i = \frac{n(n+1)}{2} \]
```

$$
\sum_{i=1}^{n} i = \frac{n(n+1)}{2}
$$

an integral. `\infty` is infinity, and `\,` puts a thin space before the $dx$:[^amsmath]

```latex
\[ \int_0^\infty e^{-x} \, dx = 1 \]
```

$$
\int_0^\infty e^{-x} \, dx = 1
$$

a matrix. `&` splits the columns and `\\` the rows. `pmatrix` draws parentheses, `bmatrix` brackets:[^amsmath]

```latex
\[ A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} \]
```

$$
A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}
$$

cases, for a function defined piece by piece. `\text` sets words inside math:[^amsmath]

```latex
\[
  |x| = \begin{cases}
    x  & \text{if } x \geq 0 \\
    -x & \text{otherwise}
  \end{cases}
\]
```

$$
|x| = \begin{cases}
  x  & \text{if } x \geq 0 \\
  -x & \text{otherwise}
\end{cases}
$$

### symbols

a few of each. capital greek letters only have commands where they look different from latin ones, like `\Delta` and `\Omega`. `\to` is short for `\rightarrow`.[^symbols]

| greek      | command    | greek         | command       |
| ---------- | ---------- | ------------- | ------------- |
| $\alpha$   | `\alpha`   | $\beta$       | `\beta`       |
| $\gamma$   | `\gamma`   | $\delta$      | `\delta`      |
| $\epsilon$ | `\epsilon` | $\varepsilon$ | `\varepsilon` |
| $\theta$   | `\theta`   | $\lambda$     | `\lambda`     |
| $\mu$      | `\mu`      | $\pi$         | `\pi`         |
| $\sigma$   | `\sigma`   | $\phi$        | `\phi`        |
| $\omega$   | `\omega`   | $\Omega$      | `\Omega`      |
| $\Delta$   | `\Delta`   | $\Sigma$      | `\Sigma`      |

| relation  | command   | relation    | command     |
| --------- | --------- | ----------- | ----------- |
| $\leq$    | `\leq`    | $\geq$      | `\geq`      |
| $\neq$    | `\neq`    | $\approx$   | `\approx`   |
| $\equiv$  | `\equiv`  | $\sim$      | `\sim`      |
| $\in$     | `\in`     | $\notin$    | `\notin`    |
| $\subset$ | `\subset` | $\subseteq$ | `\subseteq` |

| operator | command  | operator   | command    |
| -------- | -------- | ---------- | ---------- |
| $\times$ | `\times` | $\cdot$    | `\cdot`    |
| $\pm$    | `\pm`    | $\div$     | `\div`     |
| $\sum$   | `\sum`   | $\prod$    | `\prod`    |
| $\int$   | `\int`   | $\partial$ | `\partial` |
| $\nabla$ | `\nabla` | $\sqrt{x}$ | `\sqrt{x}` |
| $\cup$   | `\cup`   | $\cap$     | `\cap`     |

| arrow             | command           | arrow        | command      |
| ----------------- | ----------------- | ------------ | ------------ |
| $\to$             | `\to`             | $\leftarrow$ | `\leftarrow` |
| $\Rightarrow$     | `\Rightarrow`     | $\Leftarrow$ | `\Leftarrow` |
| $\Leftrightarrow$ | `\Leftrightarrow` | $\iff$       | `\iff`       |
| $\mapsto$         | `\mapsto`         | $\uparrow$   | `\uparrow`   |

## tables

```latex
\begin{tabular}{l c r}       % one letter per column: left, center, right
  \hline
  item  & count & price \\   % & between cells, \\ ends a row
  \hline
  apple & 3     & 1.20  \\
  pear  & 12    & 0.80  \\
  \hline
\end{tabular}
```

column letters are `l`, `c`, `r`, and `p{3cm}` for a column of wrapped text that wide. a `|` between them draws a vertical line. `\hline` draws a rule under a row.[^tabular]

booktabs replaces `\hline` with three rules, heavier at the top and bottom, with more space around them. its manual gives two guidelines: no vertical lines, and no double lines.[^booktabs]

```latex
\usepackage{booktabs}        % preamble

\begin{tabular}{l r}
  \toprule
  item  & price \\
  \midrule
  apple & 1.20  \\
  pear  & 0.80  \\
  \bottomrule
\end{tabular}
```

## figures and images

```latex
\usepackage{graphicx}                         % preamble

\begin{figure}[htbp]                          % here, top, bottom, or a page of floats
  \centering
  \includegraphics[width=0.8\textwidth]{plot} % finds plot.pdf or plot.png
  \caption{error against step size.}
  \label{fig:plot}                            % after the caption
\end{figure}

figure~\ref{fig:plot} shows the error.        % ~ is a space that won't break
```

a figure floats: latex puts it where it fits, which can be a page or more away from where it sits in the source. `width`, `height`, `scale`, and `angle` size and turn the image.[^floats] `\label` goes after `\caption`, inside the figure.[^xref]

## custom commands

```latex
\usepackage{amsmath, amssymb}                 % for \lVert and \mathbb

\newcommand{\R}{\mathbb{R}}                   % no arguments
\newcommand{\norm}[1]{\lVert #1 \rVert}       % one argument, used as #1

$f \colon \R^n \to \R$ and $\norm{x - y}$     % in the body
```

name a piece of notation once, and changing it later is one edit. `\newcommand` stops with an error if the name is taken. `\renewcommand` replaces one on purpose. a command takes up to nine arguments, `#1` to `#9`.[^newcommand] the `\norm` definition comes from the amsmath guide.[^amsmath]

## packages worth knowing

one line each, from the package's page on ctan, the tex archive.

- [geometry](https://ctan.org/pkg/geometry): page size and margins. it knows the standard paper sizes and centers the text block.
- [amsmath](https://ctan.org/pkg/amsmath): the math above: `align`, `equation*`, `cases`, the matrices, `\text`. it ships with latex.
- [enumitem](https://ctan.org/pkg/enumitem): labels and spacing for `itemize`, `enumerate`, and `description`.
- [hyperref](https://ctan.org/pkg/hyperref): turns cross-references into links in the pdf, and adds `\url` and `\href`. load it after your other packages.[^hyperref]
- [graphicx](https://ctan.org/pkg/graphicx): `\includegraphics`, with options like `width` and `angle`.
- [booktabs](https://ctan.org/pkg/booktabs): `\toprule`, `\midrule`, and `\bottomrule`, for tables like the ones in books and journals.
- [xcolor](https://ctan.org/pkg/xcolor): colors by name, plus tints, shades, and mixes, for `\textcolor` and the rest.

## compiling

- `pdflatex paper.tex`: writes a pdf directly.[^engines]
- `xelatex paper.tex`: unicode input and opentype fonts.[^engines]
- `lualatex paper.tex`: unicode and opentype too, with lua built in. it grew out of pdftex.[^engines]
- `latexmk -pdf paper.tex`: runs latex, and bibtex when needed, as many times as the references take. `-xelatex` and `-lualatex` switch the engine.[^latexmk]
- `tectonic paper.tex`: one self-contained program, built on xetex and tex live. it downloads packages as it needs them and reruns until done.[^tectonic]
- tex live: the full tex system, for linux, macos, and windows. mactex is all of tex live for macos, plus a few mac apps.[^texlive]
- overleaf: latex in the browser, with nothing to install.[^overleaf]

## pitfalls

- **unescaped special characters.** `_` and `^` outside math are errors. a bare `&` belongs in tables and alignments, and in text it stops the build with `Misplaced alignment tab character &`. write `\_`, `\^{}`, and `\&`.[^special][^amp]
- **`%` eats the rest of the line.** `50% off` loses everything after the `%`, with no error. write `50\% off`.[^special]
- **spaces after commands.** a command spelled with letters, like `\LaTeX`, swallows the space after it, so `\LaTeX is` prints as one word. write `\LaTeX{} is` or `\LaTeX\ is`.[^space]
- **overfull `\hbox` warnings.** tex couldn't break a line well, so it left one too wide, running into the margin. reword the sentence first, or load microtype. `\sloppy` trades the warning for loose word spacing.[^overfull]
- **`??` instead of a number.** latex writes labels to the `.aux` file and reads them back on the next run, so the first run can't fill them in. run it twice, or let latexmk count.[^xref]

[^latex]: [about latex](https://www.latex-project.org/about/) on the latex project's site: a document preparation system, and why it isn't a word processor.

[^lamport]: leslie lamport's [note on latex](https://lamport.azurewebsites.net/pubs/pubs.html#latex) in his list of writings: in the early 80s he needed macros for a book he planned, and knuth had started releasing the current version of tex.

[^tex]: [computers & typesetting](https://www-cs-faculty.stanford.edu/~knuth/abcde.html), knuth's page for the texbook and the rest of the series that documents tex.

[^latexjs]: [latex.js](https://latex.js.org/) by michael brade (mit), its [source](https://github.com/michael-brade/LaTeX.js), and its [limitations](https://latex.js.org/limitations.html) page: it parses latex with a peg grammar and writes html, with css that imitates latex's output. it can't define new macros, and a package only works once its macros are rewritten in javascript.

[^structure]: the unofficial latex2e reference manual on [document classes](https://latexref.xyz/Document-classes.html), [sectioning](https://latexref.xyz/Sectioning.html), and [`\maketitle`](https://latexref.xyz/_005cmaketitle.html).

[^special]: [reserved characters](https://latexref.xyz/Special-characters.html) and [printing them](https://latexref.xyz/Printing-special-characters.html) in the unofficial latex2e reference manual.

[^text]: the unofficial latex2e reference manual on [text symbols](https://latexref.xyz/Text-symbols.html) (quotes and dashes), [font sizes](https://latexref.xyz/Font-sizes.html), [`\\`](https://latexref.xyz/_005c_005c.html), [`\par`](https://latexref.xyz/_005cpar.html), and [`\footnote`](https://latexref.xyz/_005cfootnote.html).

[^lists]: [itemize](https://latexref.xyz/itemize.html) and [description](https://latexref.xyz/description.html) in the unofficial latex2e reference manual.

[^enumitem]: the [enumitem manual](https://mirrors.ctan.org/macros/latex/contrib/enumitem/enumitem.pdf): the `label` key with `\alph*`, and `nosep`.

[^dollars]: [l2tabu](https://ctan.org/pkg/l2tabu-english), section 1.6, and the tex faq on [why to use `\[...\]`](https://texfaq.org/FAQ-dolldoll).

[^amsmath]: the [amsmath user's guide](https://mirrors.ctan.org/macros/latex/required/amsmath/amsldoc.pdf): limits on sums (section 2), displayed equations (3), matrices (4.1), spacing like `\,` (4.2), the `\norm` command (4.14), and `\text` (6).

[^katex]: [katex](https://katex.org/) and its list of [supported functions](https://katex.org/docs/supported.html).

[^symbols]: [greek letters](https://latexref.xyz/Greek-letters.html) and [arrows](https://latexref.xyz/Arrows.html) in the unofficial latex2e reference manual.

[^tabular]: [tabular](https://latexref.xyz/tabular.html) in the unofficial latex2e reference manual.

[^booktabs]: the [booktabs manual](https://mirrors.ctan.org/macros/latex/contrib/booktabs/booktabs.pdf), sections 2 and 3.

[^floats]: the unofficial latex2e reference manual on [floats](https://latexref.xyz/Floats.html), for the placement letters and why a float drifts, and [`\includegraphics`](https://latexref.xyz/_005cincludegraphics.html).

[^xref]: the [cross-referencing lesson](https://www.learnlatex.org/en/lesson-09) on learnlatex.org, and [cross references](https://latexref.xyz/Cross-references.html) in the unofficial latex2e reference manual.

[^newcommand]: [`\newcommand` and `\renewcommand`](https://latexref.xyz/_005cnewcommand-_0026-_005crenewcommand.html) in the unofficial latex2e reference manual.

[^hyperref]: the [hyperref manual](https://mirrors.ctan.org/macros/latex/contrib/hyperref/doc/hyperref-doc.html): why it loads last, and `\href` and `\url`.

[^engines]: ctan's pages for [pdftex](https://ctan.org/pkg/pdftex), [xetex](https://ctan.org/pkg/xetex), and [luatex](https://ctan.org/pkg/luatex).

[^latexmk]: [latexmk](https://ctan.org/pkg/latexmk) on ctan, and the `-pdf`, `-xelatex`, and `-lualatex` options in [its manual](https://mirrors.ctan.org/support/latexmk/latexmk.txt).

[^tectonic]: [tectonic](https://tectonic-typesetting.github.io/en-US/), on its own site.

[^texlive]: ctan's pages for [tex live](https://ctan.org/pkg/texlive) and [mactex](https://ctan.org/pkg/mactex).

[^overleaf]: [overleaf](https://www.overleaf.com/), on its own site.

[^amp]: overleaf's page on the [misplaced alignment tab character](https://www.overleaf.com/learn/latex/Errors/Misplaced_alignment_tab_character_%26) error.

[^space]: [backslash-space](https://latexref.xyz/_005c_0028SPACE_0029.html) in the unofficial latex2e reference manual: why a command eats the space after it.

[^overfull]: the tex faq on [overfull boxes](https://texfaq.org/FAQ-overfull), and [l2tabu](https://ctan.org/pkg/l2tabu-english), section 1.8, on `\sloppy`.

## related

- https://learning.anthnydas.com/tools/git.md
