Rendering $\LaTeX$ Using $\KaTeX$

by Subhomoy Haldar

Table of Contents
Introduction
Basic Structure
Adding $\KaTeX$ to our Project
Configuring $\KaTeX$
Conclusion
Links

Introduction

For anyone remotely interested in anything related to science or mathematics, equations are an integral part of our lives. It may be in the form of chemical formulae - providing us information about the (literal) atomic components of a compound, or the mathematical representation of a law - providing us an explanation that transcends linguistic barriers. Typesetting scientific equations and formulae is therefore, very important for science communicators. Even though I veer towards programming and development, I will often talk about mathematical ideas and present formulae. In that case, my blog must be able to display such content properly. What options do I have to render equations?

Equations on a black board
➣ Science and Mathematics without equations is probably not very intuitive - Photo by Roman Mager on Unsplash

HTML by itself, supports superscripts and subscripts. With a little more difficulty, we can manage fractions. However, it quickly becomes cumbersome for more complicated content, such as aligned equation arrays or matrices. Enter $\TeX$$^1$, an open-source typesetting system made by Donald Knuth.$^2$ It is a very stable software in extensive use in academia to generate high quality documents with a myriad of equations and symbols embedded in them. The most popular variant is $\LaTeX$$^3$, by Leslie Lamport.$^4$

The syntax for general markup in $\TeX$ or $\LaTeX$ is usually cumbersome, but it is one of the best ways of representing non-trivial mathematical constructs and symbols. A lot of people had the idea to recreate the mathematical rendering capabilities of $\LaTeX$ in the browser. One popular project is MathJax$^5$. I have used it in the past, but have found the performance to be unsatisfactory. I came across a better, faster solution instead: $\KaTeX$$^6$ by Khan Academy.$^7$

Now I’ve written a rather lengthy introduction without a lot of substance. So here are some examples to back up my claim about $\KaTeX$ being useful:

  • Time Dilation formula due to Special Relativity: $$t'=t\frac{1}{\sqrt{1 - \frac{v^2}{c^2}}}$$
  • The Callan-Symanzik equation: $$\left[M\frac{\partial }{\partial M}+\beta(g)\frac{\partial }{\partial g}+n\gamma\right] G^{(n)}(x_1,x_2,\ldots,x_n;M,g)=0$$
  • Euler’s identity: $e^{i\pi}+1=0$

There are some limitations to $\KaTeX$ though. Supposedly, it has lesser coverage of mathematical $\LaTeX$ syntax than MathJax, but I do not feel limited in any manner. At least not yet. It’s time we test a minimum viable setup that can show how to use the library.

Basic Structure

Any webpage has three components:

  • The content written in a markup language like HTML, Markdown.
  • Style/visual information in a style language like CSS.
  • Scripting or executable information in a scripting language like JavaScript.

We will make use of three languages (two directly, one indirectly) in our project. We can proceed:

  1. Create an empty folder in a suitable location.
  2. Create an index.html or any appropriately named HTML file.
  3. Type out or copy the following boiler plate content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0, shrink-to-fit=no" name="viewport"/>
<title>Minimal Katex Example</title>
</head>
<body>
</body>
</html>
  1. Inside the body tags, we create a paragraph tag pair <p></p> and type in the formula we want to render: $e^{i\pi}+1=0$. So the code now looks like:
...
<body>
 <p>
     $e^{i\pi}+1=0$
 </p>
</body>
...

Adding $\KaTeX$ to our Project

We have the basic structure ready to add functionality to. All that we have to do now is add the links to the CDN hosted source code.

  1. Navigate to the Browser$^8$ section of the Installation instructions in the $\KaTeX$ documentation. Find the link and source tags with CDN links to the regular (or minified) versions of katex.css (or katex.min.css), katex.js (or katex.min.js) and auto-render.js (or auto-render.min.js). As of writing, the relevant tags are:
<!-- #1 Link to the stylesheet: KaTeX CSS -->
<link rel="stylesheet"
 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
 integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq"
 crossorigin="anonymous" />
<!-- #2 Link to the main JS library: KaTeX JS -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"
 crossorigin="anonymous"
 integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz">
</script>
<!-- #3 Link to the Auto Render extension. -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js"
 crossorigin="anonymous"
 integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI">
</script>

Make sure you use updated links if the version of $\KaTeX$ available is different.

  1. Put the link to the stylesheet (#1) in the head area. Put the script tags (#2 and #3) inside the body, after everything else. Make sure it’s just before the ending </body> tag. The update code is now:
<!DOCTYPE html>
<html>
<head>
...
<!-- #1 -->
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
    integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq"
    crossorigin="anonymous">
</head>
<body>
...
<!-- #2 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"
    crossorigin="anonymous"
    integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz">
</script>
<!-- #3 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js"
    crossorigin="anonymous"
    integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI">
</script>
</body>
</html>

Configuring $\KaTeX$

If you save the file and open it in the browser, you notice that nothing happens yet. This is because the rendering starts when triggered by a script that we have to write ourselves. And we also have to mention the options we want for rendering. Specifically, we want $\KaTeX$ to know that we want the content between the dollar symbols ($) to be processed. This piece of code will follow the previously added script tags:

<!-- Initialize KaTeX Rendering -->
<script>
document.addEventListener("DOMContentLoaded", function() {
    renderMathInElement(document.body, {
        delimiters: [
            {left: '$$', right: '$$', display: true},
            {left: "\\[", right: "\\]", display: true},
            {left: "$", right: "$", display: false},
            {left: "\\(", right: "\\)", display: false},
        ]
    });
});
</script>

It is imperative to note that the options for display mode, i.e. block-level, full-line or centred content delimiters (those with display: true) must appear first. If the order breaks, then the rendering does not work. Keep this in mind when you want to add custom delimiters to show rendering regions. It would have been better if this behaviour was better documented. However, it was relatively simple to figure it out. I mention my findings here to save everyone else some time.

We’re technically done. Although we have only explicitly written code in 2 out of the 3 language categories I mentioned. This does not mean that our project is devoid of CSS, however. In the head, we’ve linked to the $\KaTeX$ stylesheet: katex.min.css, besides the two javascript files. Here’s the minimal source code for a one-file project:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta content="width=device-width, initial-scale=1.0, shrink-to-fit=no" name="viewport"/>
    <title>Minimal Katex Example</title>

    <!-- #1 -->
    <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
        integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq"
        crossorigin="anonymous">
</head>
<body>
    <p>
        $e^{i\pi}+1=0$
    </p>

    <!-- #2 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"
        crossorigin="anonymous"
        integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz">
    </script>
    <!-- #3 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js"
        crossorigin="anonymous"
        integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI">
    </script>

    <!-- Initialize KaTeX Rendering -->
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            renderMathInElement(document.body, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: "\\[", right: "\\]", display: true},
                    {left: "$", right: "$", display: false},
                    {left: "\\(", right: "\\)", display: false},
                ]
            });
        });
    </script>
</body>
</html>

I encourage you to add more content to the body, maybe in a div. Perhaps a few lines of CSS. I have provided a solid base for people to build upon so you’re welcome to test your creativity! Here are some examples that you can try out to ensure that your installation of $\KaTeX$ works:

CodeStyleOutput
$\sum_{n=0}^{\infty}{\frac{x^n}{n!}}$Inline$\sum_{n=0}^{\infty}{\frac{x^n}{n!}}$
$$\sum_{n=0}^{\infty}{\frac{x^n}{n!}}$$Display$$\sum_{n=0}^{\infty}{\frac{x^n}{n!}}$$
$$x=\frac{3+y}{1+4z^2}$$Display$$x=\frac{3+y}{1+4z^2}$$
\\[\frac{1}{\displaystyle 1+\frac{1}{\displaystyle 2+\frac{1}{\displaystyle 3+x}}} + \frac{1}{1+\frac{1}{2+\frac{1}{3+x}}}\\]Display$$\frac{1}{\displaystyle 1+\frac{1}{\displaystyle 2+ \frac{1}{\displaystyle 3+x}}} + \frac{1}{1+\frac{1}{2+\frac{1}{3+x}}}$$

Conclusion

In this post I’ve summarised Math rendering technologies that exist. I outline my reason for choosing $\KaTeX$. I then explain the basic structure of a project that supports rendering mathematical expressions with $\KaTeX$. Finally, I provided some sample code for some expressions. Hopefully, this post proves to be useful for you. If you face any problems, contact me.$^9$


Links

  1. $\TeX$ - short for $\Tau\Epsilon\Chi\Nu\Iota\Chi$ (greek for technique) - a document typesetting system by Donald Knuth.
  2. Donald Knuth - the author of The Art of Computer Programming series, creator of $\TeX$ and my favourite computer scientist.
  3. $\LaTeX$ - the most popular variant of $\TeX$.
  4. Leslie Lamport - the creator of $\LaTeX$.
  5. MathJax - A popular JavaScript library that has probably the best coverage of $\LaTeX$ math syntax.
  6. $\KaTeX$ - “The fastest math typesetting library for the web." according to its website. It was created by Khan Academy.
  7. Khan Academy - A website that offers free, personalised learning resources for all ages. They are a nonprofit organisation that have made several contributions to the field of Open Source Software, as well as the education industry as a whole.
  8. Installation for the Browser - Obtain the CDN links to the regular or minified versions.
  9. Contact me if you need any assistance, or have any feedback.

Spot an Error?

Contact me with the details. I’ll update the post at the earliest. Make sure to include the following details:

  1. Post name - and the link too.
  2. The type of error - typographical error or conceptual or anything else.
  3. Suggested fix - if you can supply it, the update will be quicker.