Mathjax on Github Pages
Mathjax is a cross-browser JavaScript library that displays mathematical notation in web browers. Specifically, Mathjax enables LaTeX syntax to write math equations Markdown and show on Github Pages.
The support for TeX and LaTeX in MathJax consists of two parts
-
the
tex2jax
processorIt looks for mathmatics within your web page (indicated by math delimiters like
$$...$$
) and marks the mathematics for later processing by MathJax. -
the TeX input processor
It converts the TeX notation into MathJax’s internal format (which is essentially MathML).
The current version, as of 2023 when this blog was written, is V3.0. See official documents here.
The latest document for V3 may not be stable, some parts are missing. Refer to the document for V2 for a complete version.
The configuration, loading, and startup processes for MathJax version 3 are different from those of version 2 in a number of ways.
Where version 2 had several different methods for configuring MathJax, version 3 streamlines the process and has only one, as described below.
In version 2, you always loaded MathJax.js
, and added a config=...
parameter to provide a combined configuration file, but in version 3 you load one of several different files, depending on your needs (so you can avoid multiple file transfers, and also use MathJax synchronously, which was not possible in version 2).
Version 3
In-line Configuration for Mathjax
Q: Where to put the configuration data?
A: Add the following codes to the end of the file _layouts/base.html
. This loads MathJax
automatically for all posts.
The easiest way to configure MathJax is to place the MathJax object in a <script>
tag just before the script that loads MathJax itself.
In-line configuration puts the configuration options within the web page itself. The use of in-line configuration with MathJax requires two separate <script>
tags:
- one for specifying the configuration settings and
- one for loading of MathJax.
Because MathJax starts its configuration process as soon as it is loaded, the configuration script must come before the script tag that loads MathJax.js
itself.
<!-- inline config -->
<script>
MathJax = {
tex: {
inlineMath: [ // start/end delimiter pairs for in-line math
['$', '$'],
['\\(', '\\)']
],
displayMath: [ // start/end delimiter pairs for display math
['$$', '$$'],
['\\[', '\\]']
],
processEscapes: true, // use \$ to produce a literal dollar sign
macros: {
RR: "{\\bf R}",
bold: ["{\\bf #1}", 1],
indep: "{\\perp \\!\\!\\! \\perp}",
},
tags: 'ams',
packages: {'[-]': ['noundefined', 'autoload'], '[+]': ['enclose']},
},
svg: {
fontCache: 'global'
},
};
</script>
<!-- load MathJax -->
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
The first script defines a global object named MathJax
that contains configuration data for the various components of MathJax.
The MathJax
has to be put before the script that loads MathJax
itself.
The MathJax
object defined above means:
-
tex
to configure the TeX input processor component. Check HERE for a full list of options. Commonly used options are:-
inlineMath
allows you to use single dollar signs ($
) as in-line math delimiters, in addition to the usual\\(...\\)
.LaTeX uses brackets and parentheses as math delimiters; TeX use dollar signs. By default, MathJax supports brackets and parentheses, but not dollar signs. You need to enable them if you want to use TeX delimiters.
Note that when you use brackets and prarentheses, you need double backslashes (
\\(...\\)
or\\[...\\]
) to escape backslashes. -
displayMath
an array of pairs of strings that are to be used as delimiters for displayed/block equations.MathJax processes all environments when wrapped inside math delimiters, even those like
\begin{equation}...\end{equation}
that are supposed to be used to initiate math mode.This feature is useful to enable Typora preview of equations while make sure MathJax can render it correctly.
Typora doesn’t support LaTeX delimiters (brackets and parentheses). In order to ensure compatibility, use double signs and add one empty line before and after for displayed eqns.
-
The default for
processEscapes
has changed fromfalse
in version 2 totrue
in version 3.-
When set to
true
, you may use\$
to represent a literal dollar sign, rather than using it as a math delimiter, and\\
to represent a literal backslash (so that you can use\\\$
to get a literal\$
or\\$...$
to get a backslash just before in-line math). -
When
false
,\$
will not be altered, and its dollar sign may be considered part of a math delimiter. Typically this is set to true if you enable the$ ... $
in-line delimiters, so you can type\$
and MathJax will convert it to a regular dollar sign in the rendered document.
-
-
macros
allows you to define your own commands.macro
is given as aname: value
pair, where thename
is the name of the control sequence (without the backslash) that you are defining, andvalue
is either the replacement string for the macro (when there are no arguments) or an array consisting of the replacement string followed by the number of arguments for the macro and, optionally, default values for optional arguments.Note that the replacement string is given as a javascript string literal, and the backslash has special meaning in javascript strings. So to get an actual backslash in the string you must double it, as in the examples above.
Just include your macro definitions in the
macros
section of thetex
blocks of your configuration. The code above would define\RR
to produce a bold-faced “R”, and\bold{...}
to put its argument into bold face,\indep
($\indep$) to show double perpendicular sign to represent independence,
tags: 'ams'
tells the TeX input processor to use the AMSmath package numbering rules.- Only certain environments (
\begin{equation}
) produce numbered equations, as they would be in LaTeX. tags: 'none'
: auto-numbering was not performed.tags: 'all'
: numbering for every displayed equation.
- Only certain environments (
packages: ['base']
lists the names of the packages that should be initialized by the TeX input processor.- add new packages using
'[+]': ['enclose', ...]
. - remove packages from the default list using
'[-]': ['noundefined', 'autoload']
.
- add new packages using
-
-
svg
output component specifies a global font cache for all expressions on the page, rather than a separate cache for each expression on the page.svg
is a Scalable Vector Graphics; it is scalable, high quality at any resolution.- Other benifts of using
svg
: It won’t get pixelated at different screen sizes, like a raster image would.
Now that you have configured MathJax, you can then load the MathJax component file that you want to use. Here, we use the following.
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
Using a Local File for Configuration
If you are using the same MathJax configuration over multiple pages, you may find it convenient to store your configuration in a separate JavaScript file that you load into the page. For example, you could create a file called mathjax-config.js
that contains
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
},
svg: {
fontCache: 'global'
}
};
and then use
<script src="mathjax-config.js" defer></script>
<script type="text/javascript" id="MathJax-script" defer
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js">
</script>
to first load your configuration file, and then load the tex-svg
component from the jsdelivr
CDN.
Note that here we use the defer
attribute on both scripts so that they will execute in order, but still not block the rest of the page while the files are being downloaded to the browser.
If the async
attribute were used, there is no guarantee that the configuration would run first, and so you could get instances where MathJax doesn’t get properly configured, and they would seem to occur randomly.
General Guidelines
-
Since MathJax renders for the web and TeX is a print layout engine, there are natural limitations of which parts of TeX can be supported in a reasonable way.
By default, the tex2jax preprocessor defines the LaTeX math delimiters, which are
\(...\)
for in-line math, and\[...\]
for displayed equations.It also defines the TeX delimiters
$$...$$
for displayed equations, but it does not define$...$
as in-line math delimiters. If you want to use$...$
as in-line math delimiter, you need to configure it in thetex
component.The default settings are as follows.
MathJax = { tex: { inlineMath: [ // start/end delimiter pairs for in-line math ['$', '$'], ['\\(', '\\)'] ], displayMath: [ // start/end delimiter pairs for display math ['$$', '$$'], ['\\[', '\\]'] ], processEscapes: true, // use \$ to produce a literal dollar sign }, };
This is an example of inline equations: \(y = x’\beta + \varepsilon \) (
\\(y = x'\beta + \varepsilon \\)
).This is an example of block equations. \[ y = x’\beta + \varepsilon \]
\\[ y = x'\beta + \varepsilon \\]
Note that you need to use double backslash followed by brackets or parentheses. The only problem with that is some markdown editor won’t provide a preview for equations using the default delimiter for TeX.
-
Must add a blank line before and after a block equation so that it is rendered correctly.
-
When print
|
vertical bar in inline equations, must use\vert
otherwise, will be recognized as a table column separator.
Cross References to Eqns
Refer to an eqn on the same page
-
add
\tag{}
andlabel{}
\tag
is the number that shows at the end of the equation. Note that\tag
will interrupt the numbering continuity within a document. Do not use\tag
to insert numbers. Use this to add labels like(*)
, symbols to denote equations.\label
is the internal identifier that you use for cross references.\label{myequation} \tag{4.1}
-
refer using simple html links.
"<a href="http://www.mysite.com/mypage#myequation"> 4.1 </a>"
Or using
\ref{myequation}
(this does not add parentheses).\eqref{myequation}
(this adds parenthese around the label automatically) [Recommended ✅]- Note that references can come before the corresponding formula as well as after them.
See Eq (\ref{myequation}) or Eq \eqref{myequation}.
Example
Distributive law for multiplication (from product of sums to double sums).
\begin{equation} \label{multiplication} \sum_{i=1}^k a_i \cdot \sum_{j=1}^m b_j = \sum_{i=1}^k \left(\sum_{j=1}^m a_ib_j\right) \end{equation}
\begin{equation} \label{multiplication}
\sum_{i=1}^k a_i \cdot \sum_{j=1}^m b_j = \sum_{i=1}^k \left(\sum_{j=1}^m a_ib_j\right)
\end{equation}
Refer to the equation
- using
\eqref{multiplication}
: Eq \eqref{multiplication}. - using
\ref{multiplication}
: Eq (\ref{multiplication}).
What does \tag*
do?
\tag{2.1}
puts2.1
in parentheses.\tag*{2.1}
suppress the parentheses.
See examples.
\[v = a\cdot t \tag{2.1}\]v = a\cdot t \tag{2.1}
Without parentheses.
\[d = \frac {1}{2}\cdot a \cdot t^2 \tag*{2.2}\]d = \frac {1}{2}\cdot a \cdot t^2 \tag*{2.2}
Refer to an equation in a different page with Mathjax
Automatic equation numbering
The TeX input processing in MathJax can be configured to add equation numbers to displayed equations automatically. This functionality is turned off by default, but it is easy to configure MathJax to produce automatic equation numbers by adding:
MathJax = {
tex: {
tags: 'ams'
},
};
to tell the TeX input processor to use the AMS numbering rules.
With the configuration tag:'ams'
you need to wrap the equation with \begin{equation}
and \end{equation}
.
The unstarred versions produce equation numbers (when tags
is set to 'ams'
) and the starred ones don’t.
You can use \notag
or \nonumber
to prevent individual equations from being numbered, and \tag{}
can be used to override the usual equation number with your own symbol instead (or to add an equation tag even when automatic numbering is off).
Numbered equation:
\begin{equation} E = mc^2 \end{equation}
\begin{equation}
E = mc^2
\end{equation}
Unnumbered equation:
\[\begin{equation*} e^{\pi i} + 1 = 0 \end{equation*}\]$$
\begin{equation*}
e^{\pi i} + 1 = 0
\end{equation*}
$$
- Note that for unnumbered equations, the
\begin{equation*}...\end{equation*}
needs to be enclosed in$$
so that it is rendered correctly.
Numbered equation again.
\begin{equation} \int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15} \label{eq:sample} \end{equation}
\begin{equation}
\int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15}
\label{eq:sample}
\end{equation}
See Eq \eqref{eq:sample} (\eqref{eq:sample}
) for an integral example.
Useful Tricks Typesetting Eqns
Color eqns
Must enclose the part you want to color in braces {...}
, otherwise everything behind the \color
will be colored.
{\color{red} x} + {\color{blue} y}
The code show a formula as follows
\[{\color{red} x} + {\color{blue} y}.\]Curly braces $\\{Z_t\\}$
have to use double backslashes. First escape the backslash from Jekyll, then mathjax.
QED at the End of Equations
Several options you can choose from.
- Use
\tag*{\(\blacksquare\)}
.\[e^{x+y}=e^xe^y. \tag*{\(\blacksquare\)}\]$$ e^{x+y}=e^xe^y. \tag*{\(\blacksquare\)} $$
Multi-lined eqn: Use
\begin{align*}
and put\tag*{\(\blacksquare\)}
at the end of the last equality, then close the environment with\end{align*}
.\[\begin{align*} \mathbb{E}(Y) &= \sum_j y_j P(Y=y_j) \\ &= \sum_j y_j \left[P(Y=y_j|X_1)P(X_1) + P(Y=y_j|X_2)P(X_2) + \cdots + P(Y=y_j|X_n)P(X_n) \right] \\ &= \sum_j y_j \left[ \sum_{i} P(Y=y_j | X_i) P(X_i) \right] \\ &= \sum_i \left[\sum_j y_j\,P(Y=y_j | X_i)\right] P(X_i) \\ &= \sum_i \mathbb E\left[Y|X_i\right] P(X_i) \\ &= \mathbb{E}\left[\mathbb{E}(Y|X)\right] \tag*{\(\blacksquare\)} \end{align*}\]$$ \begin{align*} \mathbb{E}(Y) &= \sum_j y_j P(Y=y_j) \\ &= \sum_j y_j \left[P(Y=y_j|X_1)P(X_1) + P(Y=y_j|X_2)P(X_2) + \cdots + P(Y=y_j|X_n)P(X_n) \right] \\ &= \sum_j y_j \left[ \sum_{i} P(Y=y_j | X_i) P(X_i) \right] \\ &= \sum_i \left[\sum_j y_j\,P(Y=y_j | X_i)\right] P(X_i) \\ &= \sum_i \mathbb E\left[Y|X_i\right] P(X_i) \\ &= \mathbb{E}\left[\mathbb{E}(Y|X)\right] \tag*{\(\blacksquare\)} \end{align*} $$
- Use
\tag*{\(\square\)}
for white squares.\[e^{x+y}=e^xe^y. \tag*{\(\square\)}\]$$ e^{x+y}=e^xe^y. \tag*{\(\square\)} $$
- Use
margin-top:-2em; float:right
to set the alignment to float to the right and move upward so that it is in the same line as the equation block.$$ \begin{aligned} f(x) &\approx f(0) + f'(0)(x-0) \\ &= \ln(1) + 1\cdot x \\ &= x. \end{aligned} $$ <span style='margin-top:-2em; float:right'>$\square$</span>
If the equation is long, don’t need to float to the right. The $\square$ will append to the end of the equation. You can add
\quad
to add whitespaces if needed.-
\begin{aligned}[b]
option[b]</> is needed as we need it to align at the bottom.
$$ \begin{aligned}[b] P(r_t>0) &= P(\mu+e_t>0) \\ &= P(e_t>-\mu) \quad\quad\quad (\sigma>0, \text{dividing by a pos. number, inequality unchanged}) \\ &= P\left( \frac{e_t}{\sigma} > -\frac{\mu}{\sigma}\right) \quad\;\; e_t\sim N(0, \sigma^2), \text{ then } \frac{e_t}{\sigma}\sim N(0,1) \\ &= P \left( \frac{e_t}{\sigma} < \frac{\mu}{\sigma} \right) \\ &= \Phi \left(\frac{\mu}{\sigma} \right) \end{aligned} \square $$
-
References: