LaTeX: Writing Mathematics and Documents
Fundamentals Computing Python JavaScript
Quick answer
LaTeX is a typesetting system: you write a plain-text file with commands such as \frac{a}{b} and \section{Introduction}, and a program turns it into a cleanly formatted PDF. It is the standard for mathematics, science and computing papers because it sets formulas beautifully, numbers pages, equations and citations automatically, and keeps the look of a document separate from its content. Mathematics goes between dollar signs, as in $x^2+y^2=r^2$.
Key takeaways
- LaTeX is marked-up text: you type the content and say what each part is (a section, a formula, a list), and the compiler chooses the typography. A document is a
.texfile; compiling it withpdflatexgives a PDF. - Mathematics lives in math mode:
$...$inside a sentence,\[ ... \]on its own line. Scripts take one character unless braced:x^{10}, notx^10. Fractions, roots and sums are\frac{a}{b},\sqrt{x}and\sum_{i=1}^{n}. - Every document has a
\documentclass, a preamble where the packages are loaded (\usepackage{amsmath}), and a body between\begin{document}and\end{document}. Environments such asequation,align,pmatrixanditemizealways come in\begin{...}and\end{...}pairs. - Ten characters are special in LaTeX text:
# % & _ { } ~ ^ \and the dollar sign. To print one, escape it (\%,\&,\_) or use a command such as\textbackslash. Labels and citations need several compilations:pdflatex,bibtex,pdflatex,pdflatex. - Read errors from the first one down:
Undefined control sequenceis a misspelled command or a missing package,Missing $ insertedis mathematics outside math mode (a^in text, or a lone$),Missing } insertedis an unbalanced brace. A linter can find most of them before you compile. - LaTeX is also the notation of the web and of code: MathJax and KaTeX draw it in browsers, Markdown and Jupyter notebooks accept
$...$, Python's SymPy prints it withlatex(), and Overleaf compiles documents online without installing anything.
What is LaTeX?
LaTeX is a system for preparing documents in which you write the text and mark up its structure, and a program called a compiler lays it out and produces a PDF. You do not drag a formula into place or choose a font size for a heading. You type \section{Results} and LaTeX decides how a section heading looks, how much space surrounds it, what number it gets and where it appears in the table of contents. This is "what you mean is what you get", as opposed to the "what you see is what you get" of a word processor.
Why people use it.
- Mathematics. Formulas are written in text and set with the care of a professional typesetter: the right spacing around operators, brackets that grow with their contents, and fractions and scripts of the correct sizes.
- Automatic numbering and references. Sections, equations, figures and tables are numbered for you, and \ref and \cite keep every cross-reference and citation correct when you add or move something.
- Stability. A source file is plain text: it opens anywhere, works with version control, and still compiles years later.
- Consistency. The look is a property of the document class and the packages, so a thesis, a paper and a set of slides keep a uniform style, and a journal can supply a class that formats your paper the way it wants.
The names. TeX (pronounced "tech", from the Greek letters τ ε χ) is the typesetting engine written by Donald Knuth. LaTeX (say "lah-tech" or "lay-tech") is a layer of commands on top of TeX, written by Leslie Lamport, that makes it easy to describe documents. People say "LaTeX" for both the system and the language. Overleaf is a website that compiles LaTeX in the browser; TeX Live and MiKTeX are the distributions you install on your own computer.
The workflow. You write main.tex, run the compiler (pdflatex main), and open main.pdf. The compiler also writes a .log file with its messages and a .aux file where it remembers numbers for the next run. Here is the smallest complete document:
\documentclass{article}
\begin{document}
Hello, \LaTeX! The area of a circle of radius $r$ is $A = \pi r^2$.
\end{document}The first line chooses the document class (article, report, book, beamer for slides, and so on). Everything between \begin{document} and \end{document} is the document. Anything before \begin{document} is the preamble: settings and packages, which you will meet next. A blank line starts a new paragraph; several spaces or a single line break count as one space.
How do you write and compile your first LaTeX document?
Write a .tex file with a document class, a preamble and a body, then compile it with pdflatex; the quickest start is Overleaf, which needs no installation. Either install a distribution (TeX Live on Linux, macOS and Windows; MiKTeX on Windows) and an editor, or make a free project on Overleaf, where the Compile button runs everything for you.
The skeleton of a real document. A paper has a title, an author, the \maketitle command, sections, and usually an abstract:
\documentclass[11pt,a4paper]{article}: the class, with options for the font size and the paper.\usepackage{...}: one line per package, in the preamble only.amsmathgives the better equation environments,amssymbextra symbols,graphicxpictures,booktabsnicer table rules,geometrythe margins, andhyperrefclickable links (load it last).\title,\author,\date: the front matter, printed by\maketitle.\section,\subsection: headings (areportorbookalso has\chapter).abstract: a short summary, in thearticleandreportclasses (abookhas none).
How many times to compile. A cross-reference such as \ref{eq:main} is resolved from the .aux file written on the previous run, so the first compilation prints "??" and the second prints the number. A bibliography needs the sequence pdflatex, bibtex, pdflatex, pdflatex. The tool latexmk -pdf main.tex (and Overleaf) repeats the steps for you until nothing changes.
Assemble one below. Choose the class, packages and parts, and read the source; it also lists the commands to compile it and the rules the page applied (for example, that hyperref goes last and that a book has no abstract).
Interactive: assemble a LaTeX document
Choose the class, font size, paper, packages, margins and parts (abstract, equation, table, figure, bibliography) and get a complete main.tex with the commands to compile it and the rules that were applied.
How do you write mathematics in LaTeX?
Put the mathematics in math mode: between single dollar signs inside a sentence, or between \[ and \] for a formula on its own line. In math mode letters are italic variables, spaces are ignored (LaTeX spaces the operators itself), and commands start with a backslash. The ones you use constantly:
| You want | You type | You get |
|---|---|---|
| a superscript | x^2 | x^2 |
| a subscript | a_n | a_n |
| both | x_i^2 | x_i^2 |
| a fraction | \frac{a}{b} | a/b |
| a square root | \sqrt{x} | √x |
| an nth root | \sqrt[3]{x} | x^(1/3) |
| a Greek letter | \alpha \beta \pi | α β π |
| a function name | \sin x | \sin x |
| a sum | \sum_{i=1}^{n} i | \sum_i=1^n i |
| an integral | \int_0^1 x\,dx | \int_0^1 x dx |
| a limit | \lim_{x\to 0} | \lim_x→ 0 |
Braces group. A superscript or subscript takes one character. So x^10 is x^1 followed by a zero, and e^-x puts only the minus sign up. Write x^{10} and e^{-x} to raise the whole group. Braces also delimit the arguments of \frac, \sqrt and the other commands. What the operations themselves mean is explained in exponents and radicals and in algebraic fractions.
Brackets that fit. \left( and \right) make brackets grow to the height of what is between them, as in \left( \frac{a}{b} \right). Every \left needs a \right (write \right. for an invisible one).
Words, spacing and functions. Text inside a formula goes in \text{...}, as in x > 0 \text{ and } y > 0. Add a small space with \,, a larger one with \quad. Write \sin, \log, \lim and \max for function names: typed as plain letters, sin would be the product s i n of three variables set in italics, with the wrong spacing.
Numbering. The equation environment numbers a formula, and \label{eq:name} lets you cite it with \eqref{eq:name} (from amsmath). Without a number, use \[ ... \] or the starred form equation*.
The editor below draws a formula as you type and, like a careful teacher, points at the usual mistakes: a missing brace, x^10, a mismatched environment, an undefined command. Click the broken examples to see what it says.
Interactive: type LaTeX and see the formula
Type a formula in LaTeX and watch it appear, with a linter that points at the usual mistakes (a missing brace, x^10, a mismatched environment, an undefined command) in the words LaTeX itself would use.
% in the preamble: \usepackage{amsmath}
The roots of $ax^2 + bx + c = 0$ are given by the formula
\[
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}.
\]
\begin{equation}
\label{eq:euler}
e^{i\pi} + 1 = 0
\end{equation}
Equation~\eqref{eq:euler} is Euler's identity. Functions are upright:
$\sin^2 x + \cos^2 x = 1$, and $\lim_{x \to 0} \frac{\sin x}{x} = 1$.Where do you find the command for a symbol?
Most symbols are named after what they are: \alpha is α, \leq is ≤, \infty is ∞, \rightarrow (or \to) is →. The names follow a few patterns that make them easy to guess:
- Greek letters are spelled out:
\alpha,\beta,\gammafor lowercase and\Gamma,\Delta,\Omegafor capitals (only the capitals that differ from Latin letters exist: there is no\Alpha, because it would be an A).\epsilonand\varepsilonare two shapes of the same letter, as are\phiand\varphi, and\thetaand\vartheta. - Relations are abbreviated:
\leqand\geq(less or equal, greater or equal),\neq,\approx,\equiv,\sim,\propto,\in,\subset. - Negations are made with
\notin front of a relation, and many have a name of their own:\notinis ∉,\neqis ≠. - Arrows are
\to,\mapsto,\Rightarrow(⇒),\Leftrightarrow(⇔). - Big operators
\sum,\prod,\intgrow in display style and take limits with_and^. - Blackboard letters for the number sets come from
\mathbb{R},\mathbb{N},\mathbb{Z},\mathbb{Q},\mathbb{C}and need theamssymb(oramsfonts) package.
A few symbols need a package: \therefore and \because need amssymb, and \lVert and \rVert (norm bars) need amsmath. If a symbol gives "Undefined control sequence", a missing package is the first suspect.
When you cannot remember the name, look it up in the table below, which lists more than a hundred, or draw the symbol in a recognition tool such as Detexify, or search the Comprehensive LaTeX Symbol List, a PDF that lists thousands.
Interactive: find the command for a symbol
Search more than a hundred symbols by name, in English or Indonesian, or by part of the command, filter by kind (Greek letters, relations, arrows, brackets) and see which ones need the amsmath or amssymb package.
How do you write matrices, aligned equations and piecewise functions?
Larger structures are environments: a block between \begin{name} and \end{name}, inside which & separates columns and \\ ends a row. The same pattern builds matrices, piecewise definitions and aligned equations.
Matrices. The amsmath environments pmatrix (round brackets), bmatrix (square brackets) and vmatrix (vertical bars, a determinant) differ only in the brackets:
\begin{pmatrix} a & b \\ c & d \end{pmatrix} gives \beginpmatrix a & b \ c & d \endpmatrix, and vmatrix with the same entries gives the determinant \beginvmatrix a & b \ c & d \endvmatrix. Use \cdots, \vdots and \ddots for the dots inside a large matrix.
Piecewise functions use cases: each row has the value, &, and the condition:
f(x) = \begincases x^2 & x \ge 0 \ -x & x < 0 \endcases
Aligned equations. Several lines that should line up at the equals signs go in align (numbered) or align* (unnumbered); put & just before the sign to align on it:
(a+b)^2 &= a^2 + 2ab + b^2 \\(a-b)^2 &= a^2 - 2ab + b^2
The aligned environment does the same inside a larger formula. Do not use \\ or blank lines to space equations: leave that to LaTeX.
The builder below fills in the code for the structures people look up most. Choose one, change the fields, and copy the result; the linter checks that the code is well formed.
Interactive: build a formula from a form
Fill in the fields of a fraction, root, power, sum, product, integral, limit, matrix or piecewise function and get the LaTeX code and the drawn result, ready to copy, with the linter checking it.
\begin{align}
(a+b)^2 &= a^2 + 2ab + b^2 \\
(a-b)^2 &= a^2 - 2ab + b^2
\end{align}
\[
A = \begin{bmatrix}
1 & 2 \\
3 & 4
\end{bmatrix},
\qquad
\det A = \begin{vmatrix} 1 & 2 \\ 3 & 4 \end{vmatrix} = -2.
\]How do you write text, lists, tables and figures?
Everything that is not a formula follows the same idea: say what the thing is, and let LaTeX lay it out.
- Paragraphs and lines. A blank line starts a new paragraph.
\\forces a line break and is rarely needed outside tables. - Emphasis.
\emph{word}is italic (it switches back to upright inside italics),\textbf{word}is bold,\texttt{code}is monospace. - Lists.
itemizemakes bullets andenumeratenumbers, with one\itemper entry; they nest. - Special characters. Ten characters are commands in disguise:
#, the dollar sign,%(a comment: the rest of the line is ignored),&(a column separator),_and^(scripts, only in math),{,}(groups),~(a non-breaking space) and the backslash. To print one, escape it with a backslash (\%,\&,\#,\_,\{,\}), or use\textbackslashfor the backslash itself,\textasciitildefor the tilde and\textasciicircumfor the caret. - Quotes and dashes. Open a quotation with two backticks and close it with two apostrophes (the typewriter quote
"closes the wrong way); a hyphen is-, a range uses two hyphens (10--20) and a dash in a sentence uses three (---). - Tables.
tabulartakes a column specification,l,candrfor left, centered and right, and rows separated by\\with cells separated by&.\hlinedraws rules (or\toprule,\midrule,\bottomrulewithbooktabs). Wrap it intableto give it a caption and a label. - Figures.
\includegraphics[width=0.6\textwidth]{file.png}(fromgraphicx) inside afigureenvironment with\captionand\label. - References inside the text.
\label{tab:prices}right after the caption andTable~\ref{tab:prices}in the sentence. The tilde is a non-breaking space, so "Table" and its number are never split across lines.
The code below shows a list, a table and a figure with their labels.
\begin{enumerate}
\item Write the source.
\item Compile it \emph{twice} so that the references resolve.
\end{enumerate}
\begin{table}[ht]
\centering
\begin{tabular}{lr}
\hline
Item & Price (Rp) \\
\hline
Notebook & 12\,500 \\
Pen \& ink & 4\,000 \\
\hline
\end{tabular}
\caption{Two prices.}
\label{tab:prices}
\end{table}
Table~\ref{tab:prices} lists them; the ink costs 50\% less.
\begin{figure}[ht]
\centering
\includegraphics[width=0.6\textwidth]{graph.png}
\caption{A graph.}
\label{fig:graph}
\end{figure}How do citations and bibliographies work?
Keep your sources in a .bib file, cite them by key with \cite, and let BibTeX or biblatex build the reference list. Each source is one entry with a key you choose:
% references.bib
@book{knuth1984,
author = {Donald E. Knuth},
title = {The {\TeX}book},
publisher = {Addison-Wesley},
year = {1984}
}
% main.tex, in the text:
TeX was described by Knuth~\cite{knuth1984}.
% main.tex, where the list should appear (usually at the end):
\bibliographystyle{plain}
\bibliography{references}The build is a small pipeline. The first pdflatex run notes every \cite in the .aux file; bibtex main reads the .bib file and writes the formatted list; the next two pdflatex runs put the list in the document and fix the numbers. Keys are case-sensitive and must be unique. The braces in {\TeX} protect capital letters from being lowercased by the style. The newer biblatex with the biber program replaces BibTeX in many projects (the steps are pdflatex, biber, pdflatex), and gives more control over styles such as APA. latexmk and Overleaf run the right sequence automatically.
What do the common LaTeX errors mean?
LaTeX reports a problem with a message and a line number; the first error is the one to fix, because later ones are often its echoes. Read the line it names and the one before it. The most common messages:
Undefined control sequence: a command is misspelled (\fraq), or the package that defines it is not loaded (\mathbbwithoutamssymb).Missing $ inserted: mathematics was used outside math mode (a^or_in text, or a symbol such as\alphawithout dollar signs), or a dollar sign is unmatched.Missing } insertedandExtra }, or forgotten $: the braces do not balance; count the opening and closing braces of the line.Runaway argument: a brace was never closed, so an argument ran on to the end of a paragraph.\begin{...} ended by \end{...}: the names of an environment pair differ, or an inner environment was not closed.File ended while scanning use of...: the same kind of problem, found at the end of the file.Misplaced alignment tab character &: an ampersand outside a table, matrix oralign; write\&to print one.LaTeX Error: File 'x.sty' not found: a package is not installed; install it from your distribution, or use Overleaf.Overfull \hbox: a warning, not an error: a line is too wide by the amount shown.
Habits that make them easy to find.
- Compile often, after each paragraph or formula, so a new error can only be in the new text.
- Write \begin{...} and \end{...} together, then fill in between.
- When stuck, make a minimal working example: delete everything that is not needed to reproduce the error. Half the time the mistake appears in the process, and if not, it is a perfect post for a forum.
- Check formulas with the linter in the editor above before compiling: it finds unbalanced braces, \left without \right, mismatched environments, scripts like x^10 and unknown commands.
How do you use LaTeX from Python, JavaScript and Markdown?
LaTeX math is the common notation of the web and of scientific code: you can write it by hand, generate it from objects, or let a library draw it.
- Markdown, notebooks and the web. In Jupyter notebooks, Markdown renderers, many wikis and Wikipedia,
$...$and$...$are drawn as formulas. In your own web pages, include KaTeX (fast, a subset of LaTeX) or MathJax (more complete) and write the same code. - Python. SymPy turns expressions into LaTeX with
latex(); Matplotlib draws it in labels, as inplt.title(r"$\alpha^2quot;)(thermeans raw string, so the backslash is kept); Pandoc converts Markdown with formulas into a PDF through LaTeX. - Strings and backslashes. In Python and JavaScript a backslash starts an escape, so
"\frac"contains a form-feed character (\f) and"\alpha"is wrong. Use raw strings:r"\frac"in Python andString.rawin JavaScript. - User text. Text that comes from outside (names, titles, file contents) must be escaped before it goes into a LaTeX document, or a
%or&in it breaks the build.
The first Python program asks SymPy for the LaTeX of some expressions (as printed by SymPy 1.14), and the second one escapes text and writes a table. The JavaScript program builds formulas as strings and shows the form-feed trap, and the C++ program escapes characters and prints a fraction.
from sympy import symbols, Integral, Sum, Rational, sqrt, oo, Matrix, latex, sin, pi, exp
x, k, n = symbols("x k n")
print(latex(Integral(x ** 2, (x, 0, 1))))
print(latex(Sum(1 / k ** 2, (k, 1, oo))))
print(latex(sqrt(x ** 2 + 1) / 2))
print(latex(Matrix([[1, 2], [3, 4]])))
print(latex(Rational(3, 4) * pi))
print(latex(exp(-x ** 2) * sin(x)))
# \int\limits_{0}^{1} x^{2}\, dx
# \sum_{k=1}^{\infty} \frac{1}{k^{2}}
# \frac{\sqrt{x^{2} + 1}}{2}
# \left[\begin{matrix}1 & 2\\3 & 4\end{matrix}\right]
# \frac{3 \pi}{4}
# e^{- x^{2}} \sin{\left(x \right)}SPECIAL = {
"\\": r"\textbackslash{}", "&": r"\&", "%": r"\%", "quot;: r"\quot;, "#": r"\#",
"_": r"\_", "{": r"\{", "}": r"\}", "~": r"\textasciitilde{}", "^": r"\textasciicircum{}",
}
def escape_latex(text):
"""Write the ten special characters so that LaTeX prints them as themselves."""
return "".join(SPECIAL.get(ch, ch) for ch in text)
def latex_table(header, rows):
"""A tabular environment from a header and a list of rows of text."""
cols = "l" + "r" * (len(header) - 1)
lines = [r"\begin{tabular}{" + cols + "}", r" \hline"]
lines.append(" " + " & ".join(escape_latex(h) for h in header) + r" \\")
lines.append(r" \hline")
for row in rows:
lines.append(" " + " & ".join(escape_latex(str(c)) for c in row) + r" \\")
lines += [r" \hline", r"\end{tabular}"]
return "\n".join(lines)
print(escape_latex("50% of $5 & #1_a"))
print(latex_table(["Item", "Price (Rp)"], [["Notebook", 12500], ["Pen & ink", 4000]]))
print(r"\frac{%s}{%s}" % ("a+b", 2))
# 50\% of \$5 \& \#1\_a
# \begin{tabular}{lr}
# \hline
# Item & Price (Rp) \\
# \hline
# Notebook & 12500 \\
# Pen \& ink & 4000 \\
# \hline
# \end{tabular}
# \frac{a+b}{2}const special = { '\\': '\\textbackslash{}', '&': '\\&', '%': '\\%', $: '\\