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
= r"(\\begin{[^}]+}.+?\\end{[^}]+})"
LATEX_BLOCK = r"(\\$.+?\\$)"
LATEX_EXPR
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
'mathjaxblocks', HtmlPattern(LATEX_BLOCK, md), '<escape')
md.inlinePatterns.add('mathjaxexprs', HtmlPattern(LATEX_EXPR, md), '<escape') md.inlinePatterns.add(
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:
- Those brackets around the expression? Those are important. The way that the regular expression processing works is that it messes with your regex a bit, and then uses capturing group \(2\) as the output (\(1\) will be everything in the current block prior to the start of your regex). This means that if you must use groups in your regex, make them named groups.
- For reasons I haven’t fully understood and have chosen not to bother understanding because the current behaviour is correct for my needs, despite allegedly being an HTML block, this extension does seem to do entity escaping on the contents of your MathJax.