mdx_mathjax.py 950 Bytes
Newer Older
Piotr Mitros committed
1 2 3
# Source: https://github.com/mayoff/python-markdown-mathjax

import markdown
4 5 6 7 8 9
try:
    # Markdown 2.1.0 changed from 2.0.3. We try importing the new version first,
    # but import the 2.0.3 version if it fails
    from markdown.util import etree, AtomicString
except:
    from markdown import etree, AtomicString
Piotr Mitros committed
10

11

Piotr Mitros committed
12 13 14 15 16 17
class MathJaxPattern(markdown.inlinepatterns.Pattern):

    def __init__(self):
        markdown.inlinepatterns.Pattern.__init__(self, r'(?<!\\)(\$\$?)(.+?)\2')

    def handleMatch(self, m):
18 19 20
        el = etree.Element('span')
        el.text = AtomicString(m.group(2) + m.group(3) + m.group(2))
        return el
Piotr Mitros committed
21

22

Piotr Mitros committed
23 24 25 26 27
class MathJaxExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        # Needs to come before escape matching because \ is pretty important in LaTeX
        md.inlinePatterns.add('mathjax', MathJaxPattern(), '<escape')

28

Piotr Mitros committed
29 30 31
def makeExtension(configs=None):
    return MathJaxExtension(configs)