LaTeX: Writing Mathematics and Documents

Updated 20 min read Beginner Baca dalam Bahasa Indonesia

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 .tex file; compiling it with pdflatex gives a PDF.
  • Mathematics lives in math mode: $...$ inside a sentence, \[ ... \] on its own line. Scripts take one character unless braced: x^{10}, not x^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 as equation, align, pmatrix and itemize always 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 sequence is a misspelled command or a missing package, Missing $ inserted is mathematics outside math mode (a ^ in text, or a lone $), Missing } inserted is 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 with latex(), 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:

main.tex: the smallest 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. amsmath gives the better equation environments, amssymb extra symbols, graphicx pictures, booktabs nicer table rules, geometry the margins, and hyperref clickable links (load it last).
  • \title, \author, \date: the front matter, printed by \maketitle.
  • \section, \subsection: headings (a report or book also has \chapter).
  • abstract: a short summary, in the article and report classes (a book has 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 wantYou typeYou get
a superscriptx^2x^2
a subscripta_na_n
bothx_i^2x_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.

Formulas in a document: inline, displayed and numbered
% 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, \gamma for lowercase and \Gamma, \Delta, \Omega for capitals (only the capitals that differ from Latin letters exist: there is no \Alpha, because it would be an A). \epsilon and \varepsilon are two shapes of the same letter, as are \phi and \varphi, and \theta and \vartheta.
  • Relations are abbreviated: \leq and \geq (less or equal, greater or equal), \neq, \approx, \equiv, \sim, \propto, \in, \subset.
  • Negations are made with \not in front of a relation, and many have a name of their own: \notin is ∉, \neq is ≠.
  • Arrows are \to, \mapsto, \Rightarrow (⇒), \Leftrightarrow (⇔).
  • Big operators \sum, \prod, \int grow 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 the amssymb (or amsfonts) 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.

Aligned equations and a matrix (amsmath)
\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. itemize makes bullets and enumerate numbers, with one \item per 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 \textbackslash for the backslash itself, \textasciitilde for the tilde and \textasciicircum for 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. tabular takes a column specification, l, c and r for left, centered and right, and rows separated by \\ with cells separated by &. \hline draws rules (or \toprule, \midrule, \bottomrule with booktabs). Wrap it in table to give it a caption and a label.
  • Figures. \includegraphics[width=0.6\textwidth]{file.png} (from graphicx) inside a figure environment with \caption and \label.
  • References inside the text. \label{tab:prices} right after the caption and Table~\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.

A list, a table and a figure
\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 and its use in main.tex
% 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 (\mathbb without amssymb).
  • Missing $ inserted: mathematics was used outside math mode (a ^ or _ in text, or a symbol such as \alpha without dollar signs), or a dollar sign is unmatched.
  • Missing } inserted and Extra }, 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 or align; 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 in plt.title(r"$\alpha^2
    quot;)
    (the r means 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 and String.raw in 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.

Python: LaTeX from SymPy
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)}
Python: escape text and write a table
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}
JavaScript: String.raw and escaping
const special = { '\\': '\\textbackslash{}', '&': '\\&', '%': '\\%', $: '\\
  

, '#': '\\#', _: '\\_', '{': '\\{', '}': '\\}', '~': '\\textasciitilde{}', '^': '\\textasciicircum{}' }
const escapeLatex = (text) => Array.from(text, (c) => special[c] ?? c).join('')
escapeLatex('50% of $5 & #1_a')                      // '50\\% of \\$5 \\& \\#1\\_a'  (each \\ is one backslash)

// build formulas with ordinary strings: every backslash is written twice
const frac = (a, b) => '\\frac{' + a + '}{' + b + '}'
const sum = (v, from, to, body) => '\\sum_{' + v + '=' + from + '}^{' + to + '} ' + body
frac('a+b', 2)                                      // '\\frac{a+b}{2}'
sum('i', 1, 'n', 'i^2')                             // '\\sum_{i=1}^{n} i^2'

// a single backslash starts an escape: '\f' is a form feed, not a backslash followed by f
'\frac'.length                                      // 4: the form feed, r, a, c
// String.raw in front of a template literal keeps every backslash, so you can write each one once
C++: escape the special characters and print a fraction
#include <iostream>
#include <cstdio>
using namespace std;

int main() {
  char text[] = "50% of $5 & #1_a";
  for (int i = 0; text[i] != 0; i++) {
    char c = text[i];
    if (c == '%' || c == '&' || c == '
  

 || c == '#' || c == '_' || c == '{' || c == '}') printf("\\%c", c);   // a backslash in front
    else printf("%c", c);
  }
  printf("\n");

  int a = 3, b = 4;
  printf("\\frac{%d}{%d} = %.2f\n", a, b, (double)a / b);   // in C++ source too, every backslash is written twice
  return 0;
}

/* output:
50\% of \$5 \& \#1\_a
\frac{3}{4} = 0.75
*/

Where does LaTeX come from?

LaTeX grew out of one mathematician's dislike of how his book looked.

  • 1976–1977. Donald Knuth, finishing the second edition of volume 2 of The Art of Computer Programming, was dismayed by the proofs, which had been typeset by a new photographic process and looked far worse than the earlier metal type. He decided to write a system that would typeset mathematics as well as the best printers, and began TeX in 1977.
  • 1978–1982. The first TeX (TeX78) was followed by the stable TeX82, together with the METAFONT language and the Computer Modern typefaces designed with it. Knuth documented the result in The TeXbook (1984).
  • 1984–1985. Leslie Lamport wrote LaTeX, a set of macros on top of TeX that describes the structure of a document (sections, lists, equations) instead of the details of its layout; his book LaTeX: A Document Preparation System appeared in 1986.
  • 1992 and 1996. The CTAN archive collected the packages in one place, and TeX Live began as a complete distribution.
  • 1994. LaTeX2e, the version in use today, was released by a team led by Frank Mittelbach, and is still developed.
  • 1997–2007. New engines followed: pdfTeX (PDF output directly, by Hàn Thế Thành), XeTeX (Unicode and system fonts, by Jonathan Kew, 2004) and LuaTeX (2007, scriptable in Lua).
  • 2009–2014. MathJax (2009) and KaTeX (2014) brought LaTeX mathematics to web pages; Overleaf (2012) put the whole system in a browser.
  • 2021. Knuth made the last scheduled update of TeX, version 3.141592653. The version number of TeX gets closer to π with every update, and Knuth has said it will become π at his death, when the program is to be frozen. For decades he has paid a reward, starting at 2.56 US dollars and doubling every year up to 327.68, for every error found in his programs.

What mistakes do beginners make in LaTeX?

The most common beginner mistakes in LaTeX are the nine below, each with the correct statement.

MistakeCorrect
❌ Write x^10 for tenA script takes one character: write x^{10}, and e^{-x} rather than e^-x.
❌ Type a percent sign, ampersand, hash or underscore in text as it isThey are special: write \%, \&, \#, \_ (and escape text that comes from outside).
❌ Leave a blank line inside a formulaA blank line ends the paragraph and the formula with it: delete it, or put the pieces in align.
❌ Use double dollar signs for displayed equationsUse \[ ... \] or an equation environment: they space the formula correctly.
❌ Use \\ or several blank lines to add spaceA blank line makes a paragraph and LaTeX spaces it; use \vspace only for a deliberate gap.
❌ Put \usepackage after \begin{document}Packages are loaded in the preamble, before \begin{document}.
❌ Compile once and wonder about the "??"References and citations need several runs: pdflatex, bibtex, pdflatex, pdflatex, or latexmk.
❌ Type straight quotes around a wordOpen with two backticks and close with two apostrophes, so the quotes face the right way.
❌ Write sin x or lim as plain letters in a formulaUse \sin x and \lim: the commands give upright names with the right spacing.

Practice: test your understanding

These questions mix everything above. A wrong answer costs nothing here: read the hint and try again.

True or false?

Decide whether each statement is True or False.

  • A LaTeX document is a plain-text file that a compiler turns into a PDF.
  • A blank line in the source starts a new paragraph.
  • x^10 produces x to the power ten.
  • \usepackage may be written anywhere in the document.
  • References and citations may need more than one compilation.
  • Every \left( needs a matching \right.

Special characters

Which of these characters is special in LaTeX text and must be escaped with a backslash to print itself? Choose all that apply.

  • %
  • &
  • #
  • @
  • :

A square root

Which code gives the square root of x+1, the whole sum under the root?

  • \sqrt{x+1}
  • \sqrt x+1
  • sqrt(x+1)
  • \root{x+1}

A minus in an exponent

What does e^-x produce?

  • e with only the minus sign raised, followed by x
  • e to the power -x
  • an error
  • e to the power x, negated

Arguments of a fraction

How many arguments does \frac take?

Runs of pdflatex

How many times is pdflatex run to build a document with a BibTeX bibliography?

An error message

LaTeX says that \begin{pmatrix} was "ended by \end{matrix}". What is wrong?

  • the names of the beginning and the end of the environment differ
  • pmatrix does not exist
  • the matrix has too many rows
  • amsmath is not installed

Where do packages go?

Where must \usepackage{amsmath} be written?

  • in the preamble, before \begin{document}
  • right before the first equation
  • after \end{document}
  • it is loaded automatically

Count the special characters

How many characters have a special meaning in LaTeX text?

Formulas on a web page

You want LaTeX formulas drawn in a web page. What do you use?

  • KaTeX or MathJax
  • BibTeX
  • pdflatex in the browser tab
  • the \maketitle command

Limits of a sum

In \sum_{i=1}^{n} i, what does _{i=1} set?

  • the lower limit: the index starts at i=1
  • the upper limit
  • a subscript on the letter i only
  • the number of terms

Columns of a matrix

How many & are in each row of a matrix with 4 columns?

Summary: LaTeX at a glance

  • What it is: plain text with commands, compiled by pdflatex into a PDF; TeX (Knuth) is the engine and LaTeX (Lamport) the commands.
  • Document: \documentclass, a preamble with \usepackage, and \begin{document} ... \end{document}.
  • Math mode: $...$ inline, \[ ... \] displayed, equation for numbered; scripts take one character, so use braces: x^{10}.
  • Commands: \frac{a}{b}, \sqrt[n]{x}, \sum_{i=1}^{n}, \int_a^b, \left( ... \right), Greek letters by name, \sin and \lim for functions.
  • Environments: pmatrix, cases, align, itemize, tabular, figure: & separates cells, \\ ends a row.
  • Special characters: # $ % & _ { } ~ ^ \ must be escaped; escape text that comes from outside.
  • Builds: several runs for labels and citations; pdflatex, bibtex, pdflatex, pdflatex, or latexmk and Overleaf.
  • Errors: read the first one; undefined control sequence, missing $, unbalanced braces; compile often and use a minimal example.
  • Elsewhere: KaTeX and MathJax on the web, SymPy latex(), raw strings for backslashes.

Glossary: key terms

LaTeX
A system of commands on top of TeX for writing documents, in which you describe the structure and a compiler produces the layout.
TeX
The typesetting engine written by Donald Knuth, which LaTeX is built on.
Compiler
The program, such as pdflatex, that reads the source file and produces the PDF.
Preamble
The part of a LaTeX file before the begin document line, where the class, packages and settings are given.
Package
An add-on loaded with the usepackage command that provides new commands or changes how the document is built, such as amsmath.
Environment
A block between a begin command and an end command with the same name, such as equation, itemize or pmatrix.
Math mode
The state in which LaTeX reads formulas: between dollar signs inside text, or in a displayed equation.
BibTeX
A program that turns a bib file of sources into the formatted list of references cited in a document.
Escape character
The backslash that turns a special character into an ordinary one, as in the percent escape, so that it prints itself.

Frequently asked questions

What is LaTeX used for?

It is used to write documents with a lot of mathematics or structure: research papers, theses, textbooks, problem sets and slides. It sets formulas well, numbers sections and equations automatically, manages citations, and keeps the style consistent.

Is LaTeX a programming language?

LaTeX is a markup language built from macros, and the TeX engine underneath it is capable of real computation. In practice you write documents, not programs, and you can ignore the programming side.

What is the difference between TeX and LaTeX?

TeX is the typesetting engine written by Donald Knuth. LaTeX is a set of commands on top of it, by Leslie Lamport, that lets you describe a document by its structure, with sections, lists and equations, instead of its layout.

How do you write a fraction, a square root or a sum in LaTeX?

Use frac with two braced arguments for a fraction, sqrt with one for a root, and sum with an underscore and a caret for the limits, all inside math mode between dollar signs.

How do you compile a LaTeX document?

Save it as main.tex and run pdflatex main, or press Compile on Overleaf. If the document has references or a bibliography, run it again, with bibtex in between for citations, or let latexmk repeat the steps.

Why does LaTeX say "Undefined control sequence"?

LaTeX met a command it does not know. Either the name is misspelled, or the package that defines it is not loaded in the preamble, as with mathbb without amssymb. Fix the first such error, since the others often follow from it.

How do you write LaTeX in Markdown or on a website?

Many Markdown tools, Jupyter notebooks and wikis draw formulas written between single or double dollar signs. On your own page, include KaTeX or MathJax, which read the same code and draw it in the browser.

How does LaTeX compare with a word processor?

A word processor shows the page as you type; LaTeX makes you describe the content and builds the page after. LaTeX wins for formulas, long documents and references; a word processor is quicker for short, visual, collaborative notes.

References

  1. Leslie Lamport (1994). LaTeX: A Document Preparation System (2nd ed.). Addison-Wesley.
  2. Donald E. Knuth (1984). The TeXbook. Addison-Wesley.
  3. Tobias Oetiker, Hubert Partl, Irene Hyna, Elisabeth Schlegl (2021). The Not So Short Introduction to LaTeX2e. CTAN (lshort).
  4. Frank Mittelbach, Michel Goossens (2004). The LaTeX Companion (2nd ed.). Addison-Wesley.
  5. Donald E. Knuth (1999). Digital Typography. CSLI Publications.
  6. American Mathematical Society (2002). User's Guide for the amsmath Package. AMS.