LaTeX and KaTeX
Recompile LaTeX documents automatically with latexmk, and write and render maths on web pages with KaTeX.
2 min readUpdated
LaTeX is the standard typesetting system for documents with mathematics. KaTeX renders the same maths notation in a web browser, quickly and without a server round trip. This note covers automatic recompilation of LaTeX documents and the KaTeX syntax and API used on web pages, including this site.
Recompile LaTeX on every save
latexmk runs pdflatex (and BibTeX, makeindex and so on) as many times as a document needs. With -pvc it keeps watching the source files and recompiles whenever one changes:
latexmk -pvc -pdf -view=none document.tex-pvc: preview continuously, that is, watch the files and rebuild after every change. Stop it with Ctrl+C.-pdf: produce a PDF withpdflatex.-view=none: do not open a viewer. Keep the PDF open in a viewer that reloads changed files instead.
In Visual Studio Code, the LaTeX Workshop extension builds with latexmk on save and shows the PDF in a tab next to the source.
Write maths for KaTeX
KaTeX understands most of LaTeX’s maths mode. On pages that enable it, maths between single dollar signs ($...$) is set inline, and maths between double dollar signs ($$...$$) is set as a centred display equation.
An inline equation, the normal distribution, sits in the text: .
The same formula as a display equation:
Its source:
$$P(x)=\frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\sigma ^2}}$$Matrices use the pmatrix environment (round brackets; bmatrix gives square brackets). & separates columns and \\ ends a row:
$$T^{\mu\nu}=\begin{pmatrix}\varepsilon&0&0&0\\0&\varepsilon/3&0&0\\0&0&\varepsilon/3&0\\0&0&0&\varepsilon/3\end{pmatrix}$$The KaTeX documentation has the full list of supported commands and environments.
Render maths in a web page
To render a single expression into an element, call katex.render with the TeX source and the target element:
katex.render(String.raw`P(x)=\frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\sigma ^2}}`, element, { displayMode: true, throwOnError: false});String.rawkeeps the backslashes, so they do not need to be doubled.displayMode: truerenders a centred display equation; the defaultfalserenders inline maths.throwOnError: falseshows invalid TeX in red instead of throwing an exception.
katex.renderToString takes the same arguments without the element and returns the HTML, for rendering on the server or in a static site generator.
To render every formula on a page, load the auto-render extension and call renderMathInElement. It searches the text of the element for the delimiters you list:
renderMathInElement(document.body, { delimiters: [ { left: '$$', right: '$$', display: true }, { left: '$', right: '$', display: false }, { left: '\\(', right: '\\)', display: false }, { left: '\\[', right: '\\]', display: true } ], throwOnError: false});Both need the KaTeX stylesheet and script on the page; the KaTeX documentation gives the current CDN links.