March 27, 2017

Typesetting math equations with Anki

Anki is a tool I use daily to remember things better. Below are the things I have learned about typesetting math equations in Anki using both MathJax and raw LaTeX. Hopefully these notes can save you some time.

Update [2020-04-17]

Anki 2.1+ now has built-in support for MathJax. This is now the best approach to math typesetting, since it removes the dependency on LaTeX being installed on your computer. Besides being a pain in the ass to configure, this also required a bunch of configurations that you had to keep track of if you regularly use multiple computers with Anki. As a bonus, the MathJax syntax is cleaner, and you can now edit expressions on AnkiDroid and they will render immediately.

How to convert existing LaTeX in Anki to MathJax

If you have already been using a full installation of LaTeX and have a bunch of anki cards that you want to convert to Mathjax, the process is relatively easy.

First, make sure you back up your entire Anki database. In the card browser, select the cards you want to convert and go to Menu → Edit → Find and Replace. Make sure Treat input as regular expression_ is checked, and then run the following input/output pairs. It’s a good idea to test on a couple cards first.

Find Replace
\\[\\$\\] \\\(
\\[\\/\\$\\] \\\)
\\[\$\$\] \\\[
\\[\\/\\\$\\\$\\] \\\]
\\[latex\\] \\\[
\\[\\/latex\\] \\\]

You could probably combine these into a lesser number of more complex regular expressions, but I didn’t want to mess around too much, since Anki’s preview-less and undo-less Find & Replace tool made me somewhat nervous.

Depending on what sort of syntax you used, you may need to convert or remove some additional strings which are not recognized by MathJax. For me, this included replacing the align* environment with aligned and removing in-equation tags (using regex: \\tag{\d}).

After running the above pairs, review a few cards to ensure everything looks okay. Then run Tools → Check Media and sync. Both operations may take a while (30-60 seconds) depending on how many LaTeX expressions you had previously. I had 3010 rendered LaTeX images which took up a total of 32.6 MB.

Using LaTeX with Anki

Hazards ☠

Anki’s official documentation on LaTeX support is excellent, and deserves a careful readthrough, since it covers many typical problems. I will highlight two problems I did not pay enough attention to when starting

  • You can only put LaTeX tags inside fields, not inside the card template itself. Otherwise it breaks the logic used by the “update media references” process.
  • If you are using cloze deletion and have a nested LaTeX expression, put a space between curly brackets } } to avoid confusing Anki between cloze brackets and latex code.

Understand the difference between inline and display equations

Latex has two different ways to render math equations: inline and display.

Their primary difference in full latex documents is that inline equations are smaller and do not cause a line break, so they can be used within a flowing paragraph, while display appear as a larger, centered equation with a line break before and after. Since anki renders latex figures indvidiually as png files and inserts them into your template, this spacing does not apply to us.

The secondary difference is that inline has tighter formatting on a variety of symbols, most notably on summations, integrals, etc.

Outputting high-resolution PNG files

I was not satisfied with the default rendering settings, which were generating images with noticable aliasing. The following settings render equations at 800 DPI with a transparent background and medium compression. The files are not much bigger in the end, due to hte compression.

  1. Install the Edit LaTeX build process addon.

  2. Open latex_build_process.py and modify it as follows:

   newLaTeX = \
   [
       ["latex", "-interaction=nonstopmode", "tmp.tex"],
       ["dvipng", "-D", "800", "-T", "tight", "-bg", "Transparent", "tmp.dvi", "-z", "6", "-o", "tmp.png"]
   ]
   
   # make the changes
   import anki.latex
   anki.latex.latexCmds = newLaTeX
  1. In your card template CSS, put .latex { zoom: 14%; } to return the images to a reasonable size.

Center-align rendered LaTeX images

If your inline LaTeX equations seem not to be aligned with the surrounding text, you can add the following to your card CSS.

img[src*="latex"] {
    vertical-align: middle;
}

Making display equations larger than inline equations

Annoyingly, there is no way to automatically display png files rendered from display math as larger than inline math. So the best way I have found to do achieve this is to add a conditional field to the template and run a snippet of javascript code to modify the CSS on the fly.

  1. Add a field to your note template, I used the name _latex_displaymath and set the text size to 10, so that it takes up minimal space in the anki browser.

  2. Add the following to your note CSS

   .display-math .latex {
       zoom: 80%;
       display: block;
       margin: 0 auto;
       padding: 30px;
   }
  1. Add the following to your card HTML
   <script>
   
   var displayMath = "{{_latex_displaymath}}"
   if (displayMath.length > 0) {
   	document.getElementById("answer").classList.add('display-math');
   }
   
   </script>

© Geoff Ruddock 2020