DRMacIver's Notebook

Mathjax and Python Markdown

Mathjax and Python Markdown

I’ve been having an interesting time of things with this notebook and getting Python markdown and Mathjax to play well with each other. In particular I have not been enjoying the markdown extension API at all.

Anyway, it turns out that it is easy to do what I need, just slightly undocumented and with some annoyingly silent failure modes.

Here is the (slightly simplified) code from this notebook that makes MathJax work correctly:

from markdown.inlinepatterns import HtmlPattern

LATEX_BLOCK = r"(\\begin{[^}]+}.+?\\end{[^}]+})"
LATEX_EXPR  = r"(\\$.+?\\$)"


class MathJaxAlignExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        # Needs to come before escape so that markdown doesn't break use of \ in LaTeX
        md.inlinePatterns.add('mathjaxblocks', HtmlPattern(LATEX_BLOCK, md), '<escape')
        md.inlinePatterns.add('mathjaxexprs', HtmlPattern(LATEX_EXPR, md), '<escape')

The HtmlPattern class takes an expression and treats anything matching that expression as something that the markdown processor should not touch further.

Some caveats to note: