CODE FARM
Galaxy background

"The Renaissance was not a revival, but a new birth."

- Walter Pater

TeX and LaTeX: Mathematics and Typesetting

TeX is a text formatting and markup language developed by D. Knuth in the late 1970s and early 1980s, which has become the de facto standard for document preparation in mathematics and certain areas of the physical sciences because of its unsurpassed utility in typesetting mathematical formulae. LaTeX is an extension of TeX, which for purposes of discussion can be thought of as a third-party macro package for TeX to provide a logical system for document preparation, where the author does not have to give specific formatting instructions in order to achieve a particular look; the look is provided by an external document class description. [1] [2]

TeX is named after the Greek letters tau (τ), epsilon (ε), and chi (χ), reflecting the word τέχνη (téchnē), meaning "art," "craft," or "skill" in Greek. It is pronounced "tech" (as in technology), not "teks." LaTeX stands for Lamport TeX, named after its creator, Leslie Lamport. It is pronounced "LAY-tech" or "LAH-tech."

TeX Live is one of the major TeX systems (e.g., MiKTeX and TeX Live) that provides binaries for most flavors of Unix, including GNU/Linux and macOS, and also Windows. It includes the major TeX-related programs, macro packages, and fonts that are free software, including support for many languages around the world. Many Unix/GNU/Linux operating systems provide TeX Live through their own distributions and package managers. TeX Live is supported by the TeX Users Group and many other user groups around the world. [3]

MathJax is an open-source JavaScript display engine for LaTeX, MathML, and AsciiMath notation that works in modern browsers, with built-in support for assistive technology such as screen readers, including automatic speech generation and an expression explorer that can be used to investigate typeset mathematics at a more granular level than the complete expression. [4]
TeXLive.net is a powerful online site to edit TeX snippets, run LaTeX, and display PDF documents or error logs.

On Debian, TeX Live is distributed through modular packages, including core typesetting engines (texlive-latex-base, texlive-xetex), packages and extensions (texlive-latex-recommended, texlive-latex-extra, texlive-science), graphics tools (texlive-pictures), fonts (texlive-fonts-recommended, texlive-fonts-extra), bibliography resources (texlive-bibtex-extra, texlive-publishers), language packs (texlive-lang-*), and supporting utilities. For broader setups, texlive and texlive-full serve as general-purpose and all-inclusive metapackages, respectively.

# Install basic TeX utilities, fonts, core LaTeX system, document classes, and fundamental packages.
sudo apt-get install \
    texlive-base \
    texlive-latex-base

# Extend the minimal installation with commonly used LaTeX packages and additional fonts.
sudo apt-get install \
    texlive-latex-recommended \
    texlive-fonts-recommended

# Install additional packages for sophisticated layouts, mathematical notation, and specialized typesetting.
sudo apt-get install \
    texlive-latex-extra \
    texlive-science

# Install the graphics infrastructure (e.g., PGF/TikZ) along with complementary vector tools and plotting engines.
# The gnuplot metapackage pulls in gnuplot-qt, which can open plot windows; on a machine without a display,
# such as a server, WSL, or CI, install gnuplot-nox instead, which writes files only.
sudo apt-get install \
    texlive-pictures \
    pdf2svg \
    gnuplot-nox

# Install compilation automation engines to simplify multi-pass document building.
sudo apt-get install latexmk

# Install TeXstudio, a full-featured integrated development environment (IDE) for LaTeX.
sudo apt-get install texstudio

A TeX engine is the underlying program responsible for interpreting TeX instructions and performing the typesetting operations, by processing source input, expands macros, evaluates typesetting commands, arranges text and mathematical expressions, and produces an output representation such as PDF or DVI.

  • pdfTeX is a traditional TeX engine that generates PDF output natively and is suitable for conventional documents and mathematical typesetting.

    pdflatex document.tex
  • XeTeX is a TeX engine that supports Unicode and system-installed OpenType and TrueType fonts, making it suitable for multilingual documents and advanced typography.

    xelatex document.tex
  • LuaTeX is an extensible TeX engine that supports Lua scripting, Unicode, and modern font handling.

    lualatex document.tex
  • pdfTeX, XeTeX, and LuaTeX are engines that process TeX input, while pdfLaTeX, XeLaTeX, and LuaLaTeX are LaTeX workflows that use those engines.

    $ tex --version
    TeX 3.141592653
  • latexmk is a make-like build tool for LaTeX: it tracks the files a document depends on, rebuilds only when one of them changes, and reruns the engine, and BibTeX, Biber, or MakeIndex when needed, until cross-references settle.

    latexmk -pdf document.tex        # pdfLaTeX; -xelatex or -lualatex selects another engine
    latexmk -pdf -pvc document.tex   # watches the sources and rebuilds on every save
    latexmk -c                       # removes auxiliary files and keeps the PDF; -C removes the PDF too

1. LaTeX

LaTeX is a document preparation system built on top of TeX, that writes plain-text source file (.tex) that marks up the logical structure of the document, such as titles, sections, lists, equations, figures, and cross-references, and a TeX engine compiles it into typeset output such as PDF. The visual appearance comes from the document class and the loaded packages, so the same source can be restyled without rewriting its content. [1] [5]

1.1. Structures

A LaTeX document consists of a preamble, which configures the document, and a body, which holds the content between \begin{document} and \end{document}.

% hello.tex
\documentclass[11pt,a4paper]{article}   % Selects the document class, which defines the overall layout, with optional settings in square brackets.

\usepackage{amsmath,amssymb}            % Loads packages that add commands and environments; everything before `\begin{document}` is the preamble.
\usepackage{graphicx}
\usepackage{hyperref}

\title{Hello, \LaTeX}                   % Declares the title metadata, which is not printed until `\maketitle` is called.
\author{John Doe}
\date{\today}

\begin{document}                        % Starts the body; only content in the body is typeset.

\maketitle                              % Prints the title block declared in the preamble.

\section{Introduction}\label{sec:intro} % Starts a numbered section and attaches a label to it for cross-referencing.
The Pythagorean theorem states that \(a^2 + b^2 = c^2\).

\begin{equation}\label{eq:euler}        % Typesets a numbered display equation.
  e^{i\pi} + 1 = 0
\end{equation}

% Refers to labels by name; LaTeX fills in the numbers, and `~` is a non-breaking space
% that keeps the number on the same line as its noun.
Equation~\eqref{eq:euler} appears in Section~\ref{sec:intro}.

\end{document}

LaTeX writes intermediate data, such as labels, the table of contents, and citations, to auxiliary files (.aux, .toc, .log) and reads them back on the next run. A document with cross-references therefore needs more than one pass, which latexmk automates.

# Run the engine twice so that \ref and \eqref resolve to numbers.
pdflatex hello.tex
pdflatex hello.tex

# Or let latexmk run as many passes as needed.
latexmk -pdf hello.tex      # -xelatex or -lualatex selects another engine

# Remove the auxiliary files, keeping the PDF.
latexmk -c

The document class determines the available sectioning commands and the default layout:

  • article: short documents such as papers, notes, and reports without chapters.

  • report: longer documents divided into chapters, such as theses and technical reports.

  • book: books with front matter, chapters, and two-sided layout by default.

  • beamer: presentation slides.

  • standalone: a single figure or formula cropped to its content, commonly used to produce TikZ graphics.

1.2. Commands

A command is a backslash followed by a name, with optional arguments in square brackets and mandatory arguments in curly braces: \name[optional]{mandatory}.

  • A command name (called a control word) begins with a backslash (\) followed by one or more case-sensitive letters.

    \LaTeX  % predefined
    \latex  % undefined
  • A single non-letter with a leading backslash (\) forms a control symbol.

    Character Typeset Output Character Typeset Output

    %

    \%

    %

    $

    \$

    $

    &

    \&

    &

    #

    \#

    #

    _

    \_

    _

    {

    \{

    {

    }

    \}

    }

    ~

    \textasciitilde

    ~

    ^

    \textasciicircum

    ^

    \

    \textbackslash

    \

  • A command ignores the spaces immediately following its name, so use empty braces \LaTeX{} or insert an explicit space \LaTeX\ .

  • A command is either a TeX primitive built into the engine, such as \hbox or \def, or a predefined macro, such as \section, \textbf, or user-defined with \newcommand.

    \newcommand{\R}{\mathbb{R}}                          % no argument: \R
    \newcommand{\norm}[1]{\left\lVert #1 \right\rVert}   % one argument: \norm{x}
    \[\boxed{\text{LaTeX source} \rightarrow \text{macro expansion} \rightarrow \text{TeX primitives} \rightarrow \text{typesetting} \rightarrow \text{PDF}}\]

1.3. Environments

An environment is a structured block of content enclosed between two commands: \begin{name} and \end{name}.

\begin{itemize}
    \item Mathematics
    \item Physics
    \item Chemistry
\end{itemize}
\begin{equation}
    E = mc^2
\end{equation}
\begin{figure}
    \centering
    \includegraphics{image.png}
    \caption{An example figure}
\end{figure}
  • In LaTeX, certain formatting changes apply only within a particular environment and are automatically restored when that environment ends, like curly braces {...} which creates a group and establishes a local scope for certain changes.

    Normal text.
    
    \begin{large}
        This text is larger.
    \end{large}
    
    Normal text again.
  • A new environment can be defined with \newenvironment{name}{begin-definition}{end-definition}.

    \newenvironment{mybox}
    {
        \begin{center}
        \bfseries
    }
    {
        \end{center}
    }
    \begin{mybox}
        Welcome to LaTeX!
    \end{mybox}

1.4. Packages

Packages extend LaTeX with new commands and environments and are loaded in the preamble with \usepackage[options]{name}. TeX Live ships thousands of packages, and the following are found in most mathematical documents:

Package Purpose

amsmath

Mathematical environments and commands such as align, gather, cases, pmatrix, \text, \dfrac, and \boxed.

amssymb

Additional mathematical symbols and fonts such as \mathbb{R}.

graphicx

Includes external images with \includegraphics.

geometry

Sets page size and margins, such as \usepackage[margin=2cm]{geometry}.

hyperref

Turns cross-references, citations, and URLs into hyperlinks; load it last because it patches other packages.

tikz, pgfplots

Draws vector graphics and plots, as described in Graphics.

Many environments used in the Mathematics section, such as aligned, gather, pmatrix, and cases, require amsmath in a LaTeX document. MathJax provides them by default, so they work in the browser without loading any package.

1.5. Mathematics

LaTeX allows two writing modes for mathematical expressions: the inline math mode and display math mode: [6]

  • inline math mode is used to write formulas that are part of a paragraph:

    The Pythagorean theorem is \(a^2 + b^2 = c^2\).

    The Pythagorean theorem is \(a^2 + b^2 = c^2\).

  • display math mode is used to write expressions that are not part of a paragraph, and are therefore put on separate lines

    The quadratic formula is:
    
    \[
    x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}
    \]

    The quadratic formula is:

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

1.5.1. Rules

  • Use curly braces {} when an exponent contains more than one character.

    LaTeX Result LaTeX Result

    x^{a+b}

    \(x^{a+b}\)

    x^a+b

    \(x^a+b\)

  • Use a backslash (\) followed by a command name to enter LaTeX symbols and expressions.

    LaTeX Result LaTeX Result LaTeX Result

    \frac{a}{b}

    \(\frac{a}{b}\)

    \sqrt{x}

    \(\sqrt{x}\)

    x^2

    \(x^2\)

    \alpha

    \(\alpha\)

    \infty

    \(\infty\)

    75\%

    \(75\%\)

    \text{hello}

    \(\text{hello}\)

    \textit{hello}

    \(\textit{hello}\)

    \textbf{hello}

    \(\textbf{hello}\)

    \underline{x}

    \(\underline{x}\)

    \overline{x}

    \(\overline{x}\)

    \vec{x}

    \(\vec{x}\)

    \quad

    \(a \quad b\)

    \times

    \(a \times b\)

    \leq

    \(a \leq b\)

    \text{for all } x>0

    \(\text{for all } x>0\)

    \neq

    \(a \neq b\)

    \pm

    \(a \pm b\)

  • Use spacing commands to control the horizontal space between mathematical symbols and expressions.

    LaTeX Purpose Example Result LaTeX Purpose Example Result

    \!

    Negative thin space

    a\!b

    \(a\!b\)

    \

    Normal space

    a\ b

    \(a\ b\)

    \,

    Thin space

    a\,b

    \(a\,b\)

    \:

    Medium space

    a\:b

    \(a\:b\)

    \;

    Thick space

    a\;b

    \(a\;b\)

    \quad

    Wide space

    a\quad b

    \(a\quad b\)

    \qquad

    Extra-wide space

    a\qquad b

    \(a\qquad b\)

    \hspace{1em}

    Custom horizontal space

    a\hspace{1em}b

    \(a\hspace{1em}b\)

    \\[pt]

    Line break

    \a\\b

    \(a\\b\)

    \a\\[6pt]b

    \(a\\[6pt]b\)

  • Use environment that starts with \begin{...} and ends with \end{...} to format or arrange the content inside it.

    Environment Purpose LaTeX Result

    equation

    A single numbered equation

    \begin{equation}
    E = mc^2
    \end{equation}

    \(E = mc^2\) (numbered)

    aligned

    Multiple aligned equations

    \begin{aligned}
    x + y &= 5 \\
    x - y &= 1
    \end{aligned}

    \(\begin{aligned}x+y&=5\\x-y&=1\end{aligned}\)

    gather

    Multiple centered equations

    \begin{gather}
    x + y = 5 \\
    x - y = 1
    \end{gather}

    \(\begin{gather}x+y=5\\x-y=1\end{gather}\)

    matrix

    Matrix elements without surrounding brackets

    \begin{matrix}
    a & b \\
    c & d
    \end{matrix}

    \(\begin{matrix}a&b\\c&d\end{matrix}\)

    pmatrix

    Matrix elements surrounded by parentheses

    \begin{pmatrix}
    a & b \\
    c & d
    \end{pmatrix}

    \(\begin{pmatrix}a&b\\c&d\end{pmatrix}\)

    bmatrix

    Matrix elements surrounded by square brackets

    \begin{bmatrix}
    a & b \\
    c & d
    \end{bmatrix}

    \(\begin{bmatrix}a&b\\c&d\end{bmatrix}\)

    cases

    Piecewise-defined functions

    f(x) = \begin{cases}
    x^2 & x \geq 0 \\
    -x & x < 0
    \end{cases}

    \(f(x)=\begin{cases}x^2&x\geq0\\-x&x<0\end{cases}\)

1.5.2. Superscripts and subscripts

LaTeX Result Meaning

x^2

\(x^2\)

\(x\) squared

x^10

\(x^{10}\)

\(x\) to the tenth power

a_i

\(a_i\)

Subscript \(i\)

x_i^2

\(x_i^2\)

Subscript and superscript

x^{n+1}

\(x^{n+1}\)

A multi-character exponent

a_{i,j}

\(a_{i,j}\)

A multi-character subscript

1.5.3. Fractions and binomials

LaTeX Result LaTeX Result LaTeX Result

\frac{a}{b}

\(\frac{a}{b}\)

\dfrac{a}{b}

\(\dfrac{a}{b}\)

\dfrac{x + 1}{x + 2}

\(\dfrac{x + 1}{x + 2}\)

\binom{n}{k}

\(\binom{n}{k}\)

\dbinom{n}{k}

\(\dbinom{n}{k}\)

\dbinom{n+1}{k-1}

\(\dbinom{n+1}{k-1}\)

P(n,r) = \dfrac{n!}{(n-r)!}

\(P(n,r) = \dfrac{n!}{(n-r)!}\)

C(n,r) = \dbinom{n}{r} = \dfrac{n!}{r!(n-r)!}

\(C(n,r) = \dbinom{n}{r} = \dfrac{n!}{r!(n-r)!}\)

1.5.4. Greek letters

LaTeX Result LaTeX Result LaTeX Result

\alpha, A

\(\alpha, A\)

\beta, B

\(\beta, B\)

\gamma, \Gamma

\(\gamma, \Gamma\)

\delta, \Delta

\(\delta, \Delta\)

\epsilon, \varepsilon, E

\(\epsilon, \varepsilon, E\)

\zeta, Z

\(\zeta, Z\)

\eta, H

\(\eta, H\)

\theta, \vartheta, \Theta

\(\theta, \vartheta, \Theta\)

\iota, I

\(\iota, I\)

\kappa, K

\(\kappa, K\)

\lambda, \Lambda

\(\lambda, \Lambda\)

\mu, M

\(\mu, M\)

\nu, N

\(\nu, N\)

\xi, \Xi

\(\xi, \Xi\)

o, O

\(o, O\) (omicron)

\pi, \varpi, \Pi

\(\pi, \varpi, \Pi\)

\rho, \varrho, P

\(\rho, \varrho, P\)

\sigma, \varsigma, \Sigma

\(\sigma, \varsigma, \Sigma\)

\tau, T

\(\tau, T\)

\upsilon, \Upsilon

\(\upsilon, \Upsilon\)

\phi, \varphi, \Phi

\(\phi, \varphi, \Phi\)

\chi, X

\(\chi, X\)

\psi, \Psi

\(\psi, \Psi\)

\omega, \Omega

\(\omega, \Omega\)

1.5.5. Mathematical operators and symbols

LaTeX Result Meaning LaTeX Result Meaning

+

\(+\)

Addition

-

\(-\)

Subtraction

\times

\(\times\)

Multiplication

\div

\(\div\)

Division

\pm

\(\pm\)

Plus or minus

\mp

\(\mp\)

Minus or plus

=

\(=\)

Equal to

\neq

\(\neq\)

Not equal to

<

\(<\)

Less than

>

\(>\)

Greater than

\leq

\(\leq\)

Less than or equal to

\geq

\(\geq\)

Greater than or equal to

\approx

\(\approx\)

Approximately equal to

\equiv

\(\equiv\)

Equivalent to; identically equal to

\propto

\(\propto\)

Proportional to

\infty

\(\infty\)

Infinity

\sqrt{x}

\(\sqrt{x}\)

Square root

\sum

\(\sum\)

Summation

\in

\(\in\)

Is an element of

\notin

\(\notin\)

Is not an element of

\subseteq

\(\subseteq\)

Is a subset of

\supseteq

\(\supseteq\)

Is a superset of

\cup

\(\cup\)

Union of sets

\cap

\(\cap\)

Intersection of sets

\emptyset

\(\emptyset\)

Empty set

\mathbb{R}

\(\mathbb{R}\)

Set of real numbers

\forall

\(\forall\)

For all

\exists

\(\exists\)

There exists

\land

\(\land\)

Logical AND

\lor

\(\lor\)

Logical OR

\neg

\(\neg\)

Logical NOT

\Rightarrow

\(\Rightarrow\)

Implies

\Leftrightarrow, \iff

\(\iff\)

If and only if

\partial

\(\partial\)

Partial derivative symbol

Use \mathbb{} (bb stands for blackboard bold) to typeset common number sets in blackboard bold.

LaTeX Result Meaning LaTeX Result Meaning

\mathbb{N}

\(\mathbb{N}\)

Natural numbers

\mathbb{Z}

\(\mathbb{Z}\)

Integers

\mathbb{Q}

\(\mathbb{Q}\)

Rational numbers

\mathbb{R}

\(\mathbb{R}\)

Real numbers

\mathbb{C}

\(\mathbb{C}\)

Complex numbers

\mathbb{R}^n

\(\mathbb{R}^n\)

\(n\)-dimensional real coordinate space

1.5.6. Summations, products, and integrals

LaTeX Result Remark

\sum_{i=1}^{n} i

\(\sum_{i=1}^{n} i\)

Summation from \(i=1\) to \(i=n\).

\sum_{k=0}^{n} k^2

\(\sum_{k=0}^{n} k^2\)

Sum of the squares of the integers from \(0\) to \(n\).

\prod_{i=1}^{n} i

\(\prod_{i=1}^{n} i\)

Product of the integers from \(1\) to \(n\).

\lim_{n\to\infty} \sum_{i=1}^{n} \frac{1}{i}

\(\lim_{n\to\infty} \sum_{i=1}^{n} \frac{1}{i}\)

Limit of a sequence of partial sums.

\int x^2\,dx

\(\int x^2\,dx\)

Indefinite integral; \, adds a small space before the differential.

\int_0^1 x^2\,dx

\(\int_0^1 x^2\,dx\)

Definite integral from \(0\) to \(1\).

\iint_D f(x,y)\,dx\,dy

\(\iint_D f(x,y)\,dx\,dy\)

Double integral over a region \(D\).

\iiint_V f(x,y,z)\,dx\,dy\,dz

\(\iiint_V f(x,y,z)\,dx\,dy\,dz\)

Triple integral over a volume \(V\).

\oint_C F(z)\,dz

\(\oint_C F(z)\,dz\)

Contour integral over a closed curve \(C\).

\frac{1}{2\pi i}\oint_C \frac{f(z)}{z-a}\,dz

\(\frac{1}{2\pi i}\oint_C \frac{f(z)}{z-a}\,dz\)

Example of a contour integral from complex analysis.

1.5.7. Brackets and parentheses

Left delimiter Right delimiter LaTeX Result

\left(

\right)

\left( x \right)

\(\left( x \right)\)

\left[

\right]

\left[ x \right]

\(\left[ x \right]\)

\left\{

\right\}

\left\{ x \right\}

\(\left\{ x \right\}\)

\left\lvert

\right\rvert

\left\lvert x \right\rvert

\(\left\lvert x \right\rvert\)

\left\lVert

\right\rVert

\left\lVert \mathbf{x} \right\rVert

\(\left\lVert \mathbf{x} \right\rVert\)

\left\langle

\right\rangle

\left\langle x \right\rangle

\(\left\langle x \right\rangle\)

\left.

\right|

\left. F(x) \right|_a^b

\(\left. F(x) \right| _a^b \)

\left|

\right.

\left| x \right.

\(\left| x \right.\)

Every \left must have a corresponding \right within the same mathematical expression.

\left\{\frac{1}{n}:n\in\mathbb{N}\right\}

\[ \left\{\frac{1}{n}:n\in\mathbb{N}\right\} \]

To make one side invisible, use a dot (.) as the delimiter, which is useful for evaluating a function at a boundary.

\[
\left. \text{expression} \right|
\]

\[
\left| \text{expression} \right.
\]

\[ \left. \text{expression} \right| \]

\[ \left| \text{expression} \right. \]

1.5.8. Matrices and equations

LaTeX Result LaTeX Result
\begin{matrix}
a & b \\
c & d
\end{matrix}

\[ \begin{matrix} a & b \\ c & d \end{matrix} \]

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

\[ \begin{bmatrix} a & b \\ c & d \end{bmatrix} \]

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

\[ \begin{pmatrix} a & b \\ c & d \end{pmatrix} \]

\begin{vmatrix}
a & b \\
c & d
\end{vmatrix}

\[ \begin{vmatrix} a & b \\ c & d \end{vmatrix} \]

\begin{align*}
x+y &= 10 \\
x-y &= 2
\end{align*}

\[ \begin{align*} x+y &= 10 \\ x-y &= 2 \end{align*} \]

\begin{split}
A & = \frac{\pi r^2}{2} \\
 & = \frac{1}{2} \pi r^2
\end{split}

\(\begin{split}A &= \frac{\pi r^2}{2} \\ &= \frac{1}{2} \pi r^2\end{split}\)

1.5.9. Functions and named operators

LaTeX Result LaTeX Result LaTeX Result

\sin x

\(\sin x\)

\cos x

\(\cos x\)

\tan x

\(\tan x\)

\cot x

\(\cot x\)

\sec x

\(\sec x\)

\csc x

\(\csc x\)

\arcsin x

\(\arcsin x\)

\arccos x

\(\arccos x\)

\arctan x

\(\arctan x\)

\sinh x

\(\sinh x\)

\cosh x

\(\cosh x\)

\tanh x

\(\tanh x\)

\log x

\(\log x\)

\ln x

\(\ln x\)

\log_{a} x

\(\log_a x\)

\exp x

\(\exp x\)

\sqrt{x}

\(\sqrt{x}\)

\sqrt[n]{x}

\(\sqrt[n]{x}\)

\lim_{x\to 0}

\(\lim_{x\to 0}\)

\lim_{x\to\infty}

\(\lim_{x\to\infty}\)

\infty

\(\infty\)

\max(a,b)

\(\max(a,b)\)

\min(a,b)

\(\min(a,b)\)

\sup A

\(\sup A\)

\inf A

\(\inf A\)

\det A

\(\det A\)

\dim V

\(\dim V\)

\gcd(a,b)

\(\gcd(a,b)\)

\arg z

\(\arg z\)

\ker T

\(\ker T\)

\Pr(A)

\(\Pr(A)\)

\sin^2 x

\(\sin^2 x\)

\cos^2 x

\(\cos^2 x\)

1.6. Graphics

LaTeX produces graphics in two ways: including an image file created by another program, or drawing the graphic natively from TeX code, so that its fonts, sizes, and mathematical notation match the surrounding text.

Approach Tool Best for

Include a file

graphicx

Photos, screenshots, and plots exported by other programs.

Draw natively

TikZ (on PGF)

Diagrams, geometric constructions, vectors, and annotations.

Plot natively

PGFPlots

Function plots and small to medium data sets.

Plot externally

gnuplot

Heavy numerical computation, large data sets, and 3-D surfaces.

1.6.1. Including images and figures

The graphicx package provides \includegraphics[options]{file}, which inserts an image and optionally resizes or rotates it.

pdfLaTeX, XeLaTeX, and LuaLaTeX accept PDF, PNG, and JPG files; prefer PDF for vector graphics, PNG for screenshots, and JPG for photos. The file extension may be omitted, in which case LaTeX searches for a supported format.
Option Effect

width=0.7\textwidth

Scales the image to 70% of the text width, keeping the aspect ratio.

height=4cm

Scales the image to a fixed height, keeping the aspect ratio.

scale=0.5

Scales the image by a factor.

angle=90

Rotates the image counterclockwise by the given degrees.

  • An image is usually placed inside a figure environment, which adds a numbered caption and makes the figure a float: LaTeX may move it to the top or bottom of a page, or to the next page, to avoid awkward page breaks.

    \begin{figure}[htbp]                      % placement preference: here, top, bottom, page
      \centering
      \includegraphics[width=0.7\textwidth]{diagram.pdf}
      \caption{A diagram included from an external file.}
      \label{fig:diagram}                     % must follow \caption to get the figure number
    \end{figure}
    
    Figure~\ref{fig:diagram} shows the overall structure.
  • The subcaption package places several images side by side in one figure, each with its own sub-caption and label, so that \ref{fig:before} prints a reference such as 1a, while the command \listoffigures prints a list of all figure captions, and \caption[short]{long} supplies a shorter entry for that list.

    \usepackage{subcaption}                   % in the preamble
    
    \begin{figure}[htbp]
      \centering
      \begin{subfigure}{0.45\textwidth}
        \centering
        \includegraphics[width=\linewidth]{before.pdf}
        \caption{Before}
        \label{fig:before}
      \end{subfigure}
      \hfill                                  % pushes the two subfigures apart
      \begin{subfigure}{0.45\textwidth}
        \centering
        \includegraphics[width=\linewidth]{after.pdf}
        \caption{After}
        \label{fig:after}
      \end{subfigure}
      \caption{Two images side by side.}
      \label{fig:compare}
    \end{figure}

1.6.2. Drawing with TikZ

PGF (Portable Graphics Format) is a low-level system for drawing vector graphics in TeX, and TikZ (TikZ ist kein Zeichenprogramm, "TikZ is not a drawing program") is the high-level language built on top of it.

  • A drawing lives in a tikzpicture environment, where each statement builds a path through coordinates and ends with a semicolon (;).

  • A coordinate is written as (x,y) in centimeters by default, or as (angle:radius) in polar form.

    \begin{tikzpicture}
      \draw[thick] (0,0) -- (4,0) -- (2,3) -- cycle;
      \node at (2,-0.3) {Triangle};
    \end{tikzpicture}
    tikz triangle
Syntax Effect

\draw, \fill, \filldraw

Strokes, fills, or both strokes and fills a path.

\node at (x,y) {text}

Places text, which may contain math, at a coordinate.

(a) -- (b)

Draws a straight line from a to b.

-- cycle

Closes the path back to its starting point.

(a) rectangle (b)

Draws a rectangle with opposite corners a and b.

(c) circle (r)

Draws a circle with center c and radius r.

(c) ellipse (rx and ry)

Draws an ellipse with center c, horizontal radius rx, and vertical radius ry.

(a) .. controls (c1) and (c2) .. (b)

Draws a cubic Bézier curve from a to b that bends toward the control points c1 and c2; with a single control point, .. controls (c) .. (b), both control points are c.

(a) arc (start:end:r)

Draws an arc of radius r from angle start to angle end, beginning at a.

(a) grid (b)

Draws a grid in the rectangle with corners a and b.

node[pos] {text}

Attaches text to the current point of a path, positioned with above, below, left, right, or combinations such as above right.

  • Options in square brackets set the style of a path, such as line width (thick), pattern (dashed), color (red, or a mix such as blue!20 for 20% blue), and arrow tips (->).

    % vector.tex
    \documentclass{article}
    \usepackage{tikz}
    
    \begin{document}
    \begin{tikzpicture}
      % Axes with arrow tips and labels
      \draw[->] (-0.5,0) -- (3.5,0) node[right] {$x$};
      \draw[->] (0,-0.5) -- (0,2.5) node[above] {$y$};
    
      % Reference grid
      \draw[help lines, dashed] (0,0) grid (3,2);
    
      % Vector from the origin, labelled at its tip
      \draw[thick, blue, ->] (0,0) -- (3,2) node[above right] {$\vec{v} = (3,2)$};
    
      % Angle between the vector and the x-axis
      \draw (0.8,0) arc (0:33.7:0.8);
      \node at (1.1,0.3) {$\theta$};
    
      % Filled point with a label
      \fill[red] (3,0) circle (2pt) node[below] {$(3,0)$};
    \end{tikzpicture}
    \end{document}
    tikz options
  • Larger drawings rely on a few more techniques, which name and reuse points and styles instead of repeating raw coordinates:

    Syntax Effect

    \coordinate (A) at (1,2);

    Names a point, which later paths refer to as (A).

    \node[draw, circle] (B) at (3,0) {text};

    Creates a named node; draw adds its border, and lines drawn to (B) stop at that border. Anchors such as (B.north) and (B.east) refer to points on it.

    ++(1,0), +(1,0)

    Gives a coordinate relative to the current point; ++ also moves the current point, whereas + does not.

    (a) -| (b), (a) |- (b)

    Connects two points with a horizontal then vertical line, or a vertical then horizontal line.

    \foreach \x in {0,...,4} { ... }

    Repeats a command for each value, such as tick marks or a row of shapes.

    [dot/.style={circle, fill}]

    Defines a reusable style for one picture; \tikzset{...} in the preamble defines it for the whole document.

    scale=2, shift={(1,0)}, rotate=30

    Transforms a whole picture or a single path.

  • TikZ keeps optional features in libraries, which are loaded in the preamble with \usetikzlibrary{...}:

    Library Purpose

    positioning

    Places nodes relative to each other, such as right=of A or below=1cm of A.

    arrows.meta

    Provides configurable arrow tips, such as -{Stealth} and -{Latex[length=3mm]}.

    calc

    Computes coordinates, such as the midpoint $(A)!0.5!(B)$ or the offset $(A)+(1,0)$.

    shapes.geometric

    Adds node shapes such as diamond, ellipse, and regular polygon.

    The following flowchart combines named nodes, styles, libraries, and relative coordinates:

    % flowchart.tex
    \documentclass{article}
    \usepackage{tikz}
    \usetikzlibrary{positioning, arrows.meta, shapes.geometric}
    
    \begin{document}
    \begin{tikzpicture}[
        node distance = 8mm and 10mm,         % vertical and horizontal gaps
        box/.style = {draw, rounded corners, minimum height=8mm, align=center},
        decision/.style = {draw, diamond, aspect=2, align=center},
        arrow/.style = {-{Stealth}, thick},
      ]
      \node[box] (src) {Source\\\texttt{.tex}};
      \node[box, right=of src] (engine) {TeX engine};
      \node[decision, right=of engine] (refs) {References\\resolved?};
      \node[box, right=of refs] (pdf) {PDF};
    
      \draw[arrow] (src) -- (engine);
      \draw[arrow] (engine) -- (refs);
      \draw[arrow] (refs) -- node[above] {yes} (pdf);
      \draw[arrow] (refs.south) -- ++(0,-0.8) -| node[pos=0.25, below] {no, rerun} (engine.south);
    \end{tikzpicture}
    \end{document}
    tikz options features

    \foreach and calc handle repetition and computed positions:

    \usetikzlibrary{calc}
    
    \begin{tikzpicture}[dot/.style={circle, fill, inner sep=1.5pt}]
      \draw[->] (-0.5,0) -- (5.5,0) node[right] {$x$};
      \foreach \x in {0,...,5}
        \draw (\x,0.1) -- (\x,-0.1) node[below] {$\x$};
    
      \coordinate (A) at (1,1);
      \coordinate (B) at (4,2);
      \draw[thick] (A) node[dot] {} -- (B) node[dot] {};
      \node[dot, red, label=above:midpoint] at ($(A)!0.5!(B)$) {};   % requires \usetikzlibrary{calc}
    \end{tikzpicture}
    tikz foreach calc
The TikZ and PGF manual covers the full language, including decorations, matrices, and 3-D drawing. [7]

1.6.3. Plotting with PGFPlots

PGFPlots is a plotting package built on TikZ. A plot is an axis environment inside a tikzpicture, and each \addplot command draws one data series, either from a mathematical expression evaluated over a domain with a given number of samples, or from data points.

% plot.tex
\documentclass{article}
\usepackage{pgfplots}       % loads TikZ as well
\pgfplotsset{compat=1.18}   % pins the behavior to a specific version for stable output

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
      axis lines = middle,
      xlabel = $x$,
      ylabel = $y$,
      domain = -2.5:2.5,
      samples = 100,
      grid = major,
      legend pos = outer north east,
  ]
    \addplot[blue, thick] {x^3 - 3*x};
    \addlegendentry{$x^3 - 3x$}

    \addplot[red, thick, dashed] {exp(x/2) - 2};
    \addlegendentry{$e^{x/2} - 2$}
  \end{axis}
\end{tikzpicture}
\end{document}
Diagram

Data can be given inline or read from a file whose columns are separated by whitespace and whose first row names the columns:

\addplot coordinates {(0,0) (1,1) (2,4) (3,9)};

\addplot table[x=t, y=v] {data.dat};

Options on the axis environment control the whole plot, while options on \addplot style a single series:

Option Effect

xmin, xmax, ymin, ymax

Fixes the visible range instead of fitting it to the data.

xtick, xticklabels

Sets tick positions and their labels, such as xtick={-pi,0,pi} with xticklabels={$-\pi$,$0$,$\pi$}.

width, height

Sets the size of the plot.

axis lines

Draws the axes through the origin (middle), around the plot (box), or on the left and bottom (left).

title, xlabel, ylabel, legend pos

Adds a title, axis labels, and positions the legend.

mark=*, only marks, no markers, smooth

Per-series options: draws markers, draws markers without lines, draws lines without markers, or smooths the line through the points.

The following snippets of common plots assume the preamble of plot.tex, and each one is the body of a tikzpicture.

The PGFPlots manual describes every option, plot type, and library. [8]
  • Radians: PGFPlots evaluates trigonometric functions in degrees, so a plot over radians either converts each argument with deg, as in sin(deg(x)), or sets trig format plots=rad, which makes sin, cos, and tan take radians inside \addplot. Tick positions accept expressions such as pi/2, and xticklabels prints them as multiples of \(\pi\).

    \begin{axis}[
        trig format plots = rad,      % only \addplot expressions; \draw coordinates are unaffected
        axis lines = middle,
        domain = -2*pi:2*pi,
        samples = 200,
        xtick = {-2*pi, -pi, 0, pi, 2*pi},
        xticklabels = {$-2\pi$, $-\pi$, $0$, $\pi$, $2\pi$},
    ]
      \addplot[blue, thick] {sin(x)};          % without the option: sin(deg(x))
      \addplot[red, thick, dashed] {cos(x)};
    \end{axis}
    Diagram
  • Piecewise function: the conditional operator condition ? a : b, or its function form ifthenelse(condition, a, b), selects a branch per sample.

    \begin{axis}[axis lines = middle, domain = -2:2, samples = 101]
      \addplot[blue, thick] {x < 0 ? -x : x^2};
      % \addplot[blue, thick] {ifthenelse(x < 0), -x, x^2)};
    \end{axis}
    svg
    A single \addplot connects consecutive samples, so a conditional across a jump draws a false vertical segment at the jump.
  • Piecewise function with a jump: one \addplot per piece, each with its own domain, leaves the gap open; a filled marker shows the endpoint that belongs to the function, and a hollow marker (fill=white) the one that does not.

    \begin{axis}[axis lines = middle, samples = 100, ymin = -1.5, ymax = 4.5]
      \addplot[blue, thick, domain=-2:1] {x^2};
      \addplot[blue, thick, domain=1:3]  {x - 2};
      \addplot[blue, only marks, mark=*] coordinates {(1,1)};                % f(1) = 1
      \addplot[blue, only marks, mark=*, fill=white] coordinates {(1,-1)};   % excluded
    \end{axis}
    Diagram
  • Vertical asymptotes: near a pole such as \(x = 0\) in \(\dfrac{1}{x}\), samples on both sides would be joined by a near-vertical line.

    • restrict y to domain discards samples outside a y-range, including the infinite value at the pole, and unbounded coords=jump breaks the line at each discarded sample instead of bridging it.

      \begin{axis}[
          axis lines = middle,
          domain = -4:4,
          samples = 201,                    % odd count, so x = 0 is sampled and discarded
          restrict y to domain = -10:10,    % wider than the visible range, so the curve reaches the edge
          unbounded coords = jump,
          ymin = -6, ymax = 6,
      ]
        \addplot[blue, thick] {1/x};
      \end{axis}
      Diagram
    • Inside an axis, \draw uses data coordinates, so a dashed line marks an asymptote, such as tan(x):

      \begin{axis}[
          trig format plots = rad,
          axis lines = middle,
          domain = -1.5*pi:1.5*pi,
          samples = 301,
          restrict y to domain = -5:5,
          unbounded coords = jump,
          ymin = -4, ymax = 4,
          xtick = {-pi/2, pi/2},
          xticklabels = {$-\frac{\pi}{2}$, $\frac{\pi}{2}$},
      ]
        \addplot[blue, thick] {tan(x)};
        \draw[gray, dashed] (-pi/2,-4) -- (-pi/2,4);
        \draw[gray, dashed] (pi/2,-4) -- (pi/2,4);
      \end{axis}
      Diagram
  • Area under a curve: the fillbetween library shades the region between two named paths, which illustrates a definite integral; soft clip limits the shading to the interval of integration.

    \usepgfplotslibrary{fillbetween}      % in the preamble
    
    \begin{axis}[
        axis lines = middle,
        xlabel = $x$,
        ylabel = $y$,
        xmin = -0.2, xmax = 1.4,
        ymin = -0.2, ymax = 1.6,
        samples = 100,
    ]
      \addplot[name path=f, blue, thick, domain=-0.2:1.2] {x^2};
      \path[name path=xaxis] (0,0) -- (1,0);
      \addplot[blue!20] fill between[of=f and xaxis, soft clip={domain=0:1}];
      \node at (0.4,1.2) {$\int_0^1 x^2\,dx = \frac{1}{3}$};
    \end{axis}
    Diagram
  • Named functions: declare function defines functions once per axis, or for the whole document inside \pgfplotsset{...}, so that several plots reuse them. Parameters are written as macros such as \x.

    \begin{axis}[
        axis lines = middle,
        domain = -3:3,
        samples = 100,
        declare function = {
          f(\x) = exp(-\x^2/2);
          g(\x) = 1/(1 + \x^2);
        },
    ]
      \addplot[blue, thick] {f(x)};
      \addlegendentry{$e^{-x^2/2}$}
      \addplot[red, thick] {g(x)};
      \addlegendentry{$\frac{1}{1+x^2}$}
    \end{axis}
    Diagram
  • Parametric curve: a coordinate pair ({x(t)}, {y(t)}) in parentheses plots \(x\) and \(y\) as functions of one parameter, named with variable=t; the braces protect commas and parentheses inside each expression, and axis equal keeps the units on both axes the same length.

    \begin{axis}[axis lines = middle, axis equal, trig format plots = rad]
      \addplot[blue, thick, domain=0:2*pi, samples=200, variable=t]
        ({cos(3*t)}, {sin(2*t)});         % Lissajous curve
      \addplot[red, thick, domain=0:2*pi, samples=200, variable=t]
        ({cos(t)}, {sin(t)});             % x^2 + y^2 = 1
    \end{axis}
    Diagram
  • Polar curve: the polar library’s polaraxis environment reads x as the angle in degrees and the expression as the radius \(r\).

    \usepgfplotslibrary{polar}            % in the preamble
    
    \begin{polaraxis}
      \addplot[blue, thick, domain=0:180, samples=300] {cos(3*x)};   % three-petal rose
    \end{polaraxis}
    Diagram
  • Logarithmic axes: ymode=log, xmode=log, or the semilogyaxis and loglogaxis environments scale an axis logarithmically, which turns exponential growth into a straight line.

    \begin{axis}[ymode = log, axis lines = left, domain = 0:5, samples = 50, grid = major]
      \addplot[blue, thick] {exp(x)};
      \addlegendentry{$e^x$}
      \addplot[red, thick] {x^3};
      \addlegendentry{$x^3$}
    \end{axis}
    Diagram
  • Surface: \addplot3 plots a function of two variables, and the surf option draws it as a colored surface; view={azimuth}{elevation} sets the viewing angle.

    \begin{axis}[view={60}{30}, xlabel=$x$, ylabel=$y$, zlabel=$z$]
      \addplot3[surf, domain=-2:2, samples=25] {exp(-x^2-y^2)};
    \end{axis}
    Diagram

1.6.4. External plots with gnuplot

gnuplot is an external, command-driven plotting program that generates two- and three-dimensional plots from mathematical expressions or numerical data. Commands are typed at the interactive gnuplot> prompt or collected in a script that runs with gnuplot plot.gnu. A script typically configures the plot with set commands and then draws it with plot for two dimensions or splot for three.

The terminal selects the output format, and set output names the file to write; without them, gnuplot draws in an interactive window if its build supports one.

Terminal Output

qt, wxt, x11

An interactive window, and the default when no terminal is set. Debian’s gnuplot-nox package has no window terminals, so a script must set a file terminal such as pdfcairo.

pdfcairo

A PDF file, for inclusion in LaTeX documents with \includegraphics.

pngcairo

A PNG bitmap, for web pages and slides.

svg

An SVG vector image, for web pages.

cairolatex

A PDF with the graphics and a .tex file with the labels, so that LaTeX typesets the text.

The following commands appear in most scripts:

Command Effect

set terminal pdfcairo size 12cm,8cm

Selects the output format and the image size.

set output "plot.pdf"

Names the output file; unset output closes it so that the file is complete.

set title "...", set xlabel "...", set ylabel "..."

Adds a title and axis labels.

set xrange [-pi:pi], set yrange [-1.5:1.5]

Fixes the visible range instead of fitting it to the data.

set xtics 1, set xtics ("-π" -pi, "0" 0, "π" pi)

Sets the tick interval, or explicit tick positions with labels.

set grid

Draws grid lines at the major ticks.

set key top left, unset key

Positions or hides the legend, which gnuplot calls the key.

set samples 200

Sets the number of points at which functions are evaluated.

f(x) = a*x + b

Defines a user function; a = 2 defines a variable.

plot, splot, replot

Draws a 2-D plot, draws a 3-D plot, or redraws the last plot after settings change.

Expressions use x as the variable in plot and x and y in splot, ** for powers, and built-in functions such as sin, cos, exp, log, sqrt, and abs, with the constant pi. Trigonometric functions take radians.

Division of two integers is integer division, so 1/2 evaluates to 0; write 1.0/2 to get 0.5.

A plot command lists one or more series separated by commas, each followed by modifiers that select the data and its style:

Modifier Effect

using 1:2, u 1:2

Takes x from column 1 and y from column 2 of a data file; using 1:($2*100) computes a value from a column.

title "...", notitle

Sets or suppresses the series' entry in the legend.

with lines, with points, with linespoints, with boxes, with yerrorbars

Draws the series as lines, markers, both, bars, or points with error bars; abbreviated as w l, w p, w lp.

lw 2, lc rgb "blue", dt 2, pt 7

Sets the line width, line color, dash type, and point type.

The following script plots two functions and saves them as a PDF:

# plot.gnu
set terminal pdfcairo size 12cm,8cm
set output "gnuplot-graph.pdf"

set xlabel "x"
set ylabel "y"
set xrange [-2*pi:2*pi]
set yrange [-1.5:1.5]
set xtics ("-2π" -2*pi, "-π" -pi, "0" 0, "π" pi, "2π" 2*pi)
set grid
set key top right

plot sin(x) title "sin(x)" with lines lw 2 lc rgb "blue", \
     cos(x) title "cos(x)" with lines lw 2 lc rgb "red" dt 2

unset output
gnuplot two functions

A data file holds whitespace-separated columns, and lines starting with # are comments. The fit command adjusts the parameters of a function to the data by least squares, prints the results, and appends them to fit.log in the current directory; set fit quiet nolog suppresses both:

# fit.gnu
# data.dat:
#   # x   y     error
#     1   2.1   0.2
#     2   3.9   0.3
#     3   6.2   0.3
#     4   7.8   0.4
#     5   10.1  0.4

set terminal pdfcairo
set output "fit.pdf"

f(x) = a*x + b
fit f(x) "data.dat" using 1:2 via a, b

set key top left
plot "data.dat" using 1:2:3 title "measured" with yerrorbars pt 7, \
     f(x) title sprintf("fit: y = %.2fx %+.2f", a, b) with lines lw 2

unset output
gnuplot fit data file

splot draws a function of x and y as a surface, and set pm3d colors it by height:

# surface.gnu
set terminal pdfcairo
set output "surface.pdf"

set xrange [-2:2]
set yrange [-2:2]
set isosamples 40          # grid density of the surface
set pm3d                   # color the surface by its z value
set view 60, 30            # elevation and azimuth in degrees

splot exp(-x**2 - y**2) notitle with pm3d

unset output
gnuplot pm3d

Run the script, then include the PDF in the document like any other image:

gnuplot plot.gnu          # writes gnuplot-graph.pdf
latexmk -pdf graphics.tex
\begin{figure}[htbp]
  \centering
  \includegraphics[width=0.7\textwidth]{gnuplot-graph.pdf}
  \caption{A plot generated by gnuplot.}
  \label{fig:gnuplot}
\end{figure}

The labels in a pdfcairo plot use gnuplot’s fonts rather than the document’s. The cairolatex terminal instead writes the graphics to a PDF and the labels to a .tex file, which the document loads with \input so that LaTeX typesets the text, including math:

# latex-plot.gnu
set terminal cairolatex pdf size 12cm,8cm
set output "latex-plot.tex"          # also writes latex-plot.pdf

set xlabel '$x$'                     # single quotes keep the backslashes literal
set ylabel '$f(x)$'
set xrange [-2*pi:2*pi]
set xtics ('$-2\pi$' -2*pi, '$-\pi$' -pi, '$0$' 0, '$\pi$' pi, '$2\pi$' 2*pi)
set key top right

plot sin(x) title '$\sin x$' with lines lw 2

unset output
\begin{figure}[htbp]
  \centering
  \input{latex-plot.tex}               % requires the graphicx and xcolor packages
  \caption{A plot whose labels are typeset by LaTeX.}
  \label{fig:latex-plot}
\end{figure}

For web pages, compile a graphic on its own with the standalone class, which crops the page to its content, and convert the PDF to SVG with pdf2svg, which preserves the visual appearance but not the document semantics. [Graphics with Asciidoctor Diagram] automates these steps.

pdflatex triangle.tex     # \documentclass[tikz]{standalone}
pdf2svg triangle.pdf triangle.svg

2. Asciidoctor

Asciidoctor renders LaTeX in two different ways: mathematical expressions pass through to the HTML output and are typeset in the browser by MathJax, whereas TikZ graphics are compiled by a local TeX installation into image files when the document is converted.

2.1. Mathematics

Asciidoctor supports mathematical notation through STEM (Science, Technology, Engineering, and Mathematics) processing. It supports both AsciiMath and LaTeX-style mathematical expressions. When generating HTML, Asciidoctor can prepare STEM expressions for rendering by a JavaScript-based mathematics engine such as MathJax. [9]

2.1.1. Enabling STEM support

A document-level attribute can override the global setting when necessary.

To enable STEM processing, set the stem attribute in the document header or configure the stem attribute globally in the site’s _config.yml file for using the Jekyll Asciidoc plugin:

asciidoctor:
  attributes:
    stem: latexmath

The value latexmath selects LaTeX syntax as the default for STEM expressions. If no notation is specified, Asciidoctor defaults to AsciiMath.

2.1.2. Rendering mathematics with MathJax

Asciidoctor processes STEM macros during document conversion, but HTML output generally requires a mathematics renderer to display the expressions as formatted mathematics in the browser. MathJax is a JavaScript library that can render LaTeX mathematics in HTML. [10]

<script>
  window.MathJax = { (1)
    options: {
      ignoreHtmlClass: 'nostem|nolatexmath' (2)
    },
    tex: {
      inlineMath: [['\\(', '\\)']], (3)
      displayMath: [['\\[', '\\]']], (4)
      tags: 'none' (5)
    },
  };
</script>
<script defer
    src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/4.1.3/tex-chtml.min.js" (6)
    integrity="sha512-kO24RkUwCpSCXtdV9p2FM/5isVLi06qQPGlE+AsOx8kN9MTc6Mk7qlZBSEh/b7bvCr2vEWlZLAdp20QLkB/qPg=="
    crossorigin="anonymous"
    referrerpolicy="no-referrer">
</script>
1 Defines the MathJax configuration before the library loads.
2 Excludes HTML elements whose class matches nostem or nolatexmath from MathJax processing.
3 Sets \(…​\) as the delimiters for inline mathematics.
4 Sets \[…​\] as the delimiters for display mathematics.
5 Disables automatic equation numbering.
6 Loads the MathJax TeX-to-Common-HTML component. The tex-chtml.min.js filename indicates TeX input processing, Common HTML output, and a minified JavaScript file.

2.1.3. STEM macros versus MathJax delimiters

There are two main ways to include mathematical expressions in an AsciiDoc document: using Asciidoctor’s STEM macros or writing LaTeX expressions directly between delimiters recognized by MathJax.

Method Example Processing

STEM macro

stem:[y = mx + c]

Asciidoctor recognizes the macro and processes the expression according to the configured STEM notation.

Explicit LaTeX macro

latexmath:[\frac{a}{b}]

Asciidoctor recognizes the macro and interprets its content as LaTeX notation.

Raw MathJax delimiters

\( \frac{a}{b} \)

MathJax processes the delimiters in the generated HTML, provided they are preserved and recognized by its configuration.

The distinction matters because Asciidoctor processes STEM macros during document conversion, whereas MathJax normally renders mathematical expressions in the browser after the HTML has been generated. The two approaches can coexist, but their processing pipelines should be configured consistently.

For a Jekyll site using Asciidoctor, prefer stem:[...] for inline mathematics and [stem] blocks for display mathematics to make the source more explicit and avoid relying on MathJax to recognize raw delimiters throughout the generated HTML.
  • Use the stem inline macro to include a mathematical expression within a paragraph:

    The equation of a straight line is stem:[y = mx + c].

    The equation of a straight line is \(y = mx + c\).

    To specify LaTeX notation explicitly, use the latexmath macro:

    The quadratic equation is latexmath:[ax^2 + bx + c = 0].

    The square brackets delimit the macro’s content. Unlike raw MathJax delimiters, the Asciidoctor STEM macro does not require wrapping the expression in \(...\) or $...$.

  • For a standalone equation, use a delimited STEM block:

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

    Because the document header specifies :stem: latexmath, the expression is interpreted as LaTeX and rendered as a display equation:

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

    Alternatively, explicitly specify the notation (e.g., LaTeX) on the block:

    [latexmath]
    ++++
    \int_0^1 x^2\,dx = \frac{1}{3}
    ++++

2.2. Graphics

Asciidoctor Diagram is a set of Asciidoctor extensions that turns diagram source code written in a document, such as TikZ, gnuplot, Graphviz, or PlantUML, into images. When the document is converted, the extension runs the external tool for each diagram block, writes the image next to the output, and replaces the block with an image reference. [11]

A diagram block names the tool as its style, followed by the image file name and format:

[tikz, triangle, svg]      // tool, file name without extension, output format
----
...diagram source...
----

Only the tool is required. Without a file name, the image is named after a hash of the block’s content, such as diag-tikz-md5-<hash>.svg; without a format, the tool’s default applies, which is svg for TikZ and png for gnuplot. To set the format alone, leave the name empty, as in [gnuplot, , svg], or name the attribute, as in [gnuplot, format=svg].

  • Install the external tools that the diagram blocks call: TeX Live and pdf2svg for TikZ, and gnuplot for gnuplot blocks (or gnuplot-nox on a machine without a display).

    sudo apt install \
        texlive-latex-base \
        texlive-latex-extra \
        texlive-pictures \
        pdf2svg \
        gnuplot-nox
  • Install the asciidoctor-diagram gem, either directly or through Bundler.

    gem install asciidoctor-diagram
    # Gemfile
    gem "asciidoctor-diagram", "~> 3.0"
    bundle install
  • Load the extension when invoking Asciidoctor; without it, diagram blocks render as plain listings.

    asciidoctor -r asciidoctor-diagram graphics.adoc
    Asciidoctor Diagram caches generated images in .asciidoctor/diagram and regenerates an image only when its source changes; add the folder to .gitignore.
  • Jekyll’s cleanup deletes every file in _site that Jekyll did not generate, including diagram images. [12] Preserve them in one of two ways:

    • Per page: images land in each page’s folder, so names need only be unique within a post. Per-page folders cannot be listed in keep_files; disable cleanup in the plugin file instead:

      # _plugins/jekyll-ext.rb
      class Jekyll::Cleaner
        def cleanup!; end
      end

      Cleanup is then off site-wide: delete _site after renaming or removing pages, or their stale files get published.

    • Shared folder: an imagesdir starting with / writes every image to one folder under _site; list that folder in keep_files to keep cleanup active for the rest of the site:

      # _config.yml
      keep_files:
        - images
      asciidoctor:
        attributes:
          imagesdir: /images

      All posts share one namespace: keep diagram names unique site-wide, or images overwrite each other.

      Relative paths, such as include:: targets and plot "data.dat", resolve from Jekyll’s working directory, normally the site root. Set base_dir: :docdir under asciidoctor: to resolve them from the post’s folder; add safe: unsafe only when they reach outside it.

2.2.1. TikZ

The tikz block wraps its content in a standalone LaTeX document, compiles it with pdfLaTeX, and converts the result to SVG with pdf2svg; the supported formats are svg and pdf. [13]

[tikz, triangle, svg]
----
\begin{tikzpicture}
\draw[thick] (0,0) -- (4,0) -- (2,3) -- cycle;
\node at (2,-0.3) {Triangle};
\end{tikzpicture}
----

Packages such as PGFPlots are loaded through the preamble option, and a line containing only ~~~~ separates the preamble from the drawing code.

[tikz, parabola, svg, preamble]
----
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
~~~~
\begin{tikzpicture}
    \begin{axis}[
        axis lines=middle,
        xlabel=$x$,
        ylabel=$y$,
        grid=major
    ]
        \addplot[blue, thick, domain=-2:2, samples=100]
            {x^2};
    \end{axis}
\end{tikzpicture}
----

The generated LaTeX document is based on the following template:

\documentclass[border=2bp, tikz]{standalone}
\usepackage{tikz}
<preamble>
\begin{document}
\begingroup
\tikzset{every picture/.style={scale=1}}
<TikZ code>
\endgroup
\end{document}

2.2.2. Gnuplot

The gnuplot block passes its content to gnuplot as a script and captures the plot that gnuplot writes to its standard output; the supported formats are svg, png, gif, and txt, which renders the plot as ASCII art in a literal block. [14]

The extension selects the terminal itself by prepending a set terminal command that matches the block’s format, so the script contains only the plot settings.

[gnuplot, trig, svg, width=640, height=400]
----
set xrange [-2*pi:2*pi]
set yrange [-1.5:1.5]
set xtics ("-2π" -2*pi, "-π" -pi, "0" 0, "π" pi, "2π" 2*pi)
set grid
set key top right

plot sin(x) title "sin(x)" with lines lw 2, \
     cos(x) title "cos(x)" with lines lw 2 dt 2
----
Do not use set terminal or set output in the block: the extension reads the image from gnuplot’s standard output, so redirecting the output to a file leaves the block without an image.

The block accepts attributes that the extension appends to its set terminal command:

Attribute Effect

width, height

Sets the image size in pixels; both must be given.

font, fontscale

Sets the font, such as font="Arial,12", and scales all text.

background, transparent

Sets the background color, or makes the background transparent with transparent=true.

crop

Crops the image to its content with crop=true; supported by the png and gif terminals.