forked from mitya57/python-markdown-math
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmdx_math.py
More file actions
56 lines (44 loc) · 1.82 KB
/
mdx_math.py
File metadata and controls
56 lines (44 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# -*- coding: utf-8 -*-
'''
Math extension for Python-Markdown
==================================
Adds support for displaying math formulas using MathJax / KaTeX
Copyright 2019-2020 Gautam Iyer <gi1242+mdxmath@gmail.com>
Based on code originally written by Dmitry Shachnev <mitya57@gmail.com>
'''
from markdown.inlinepatterns import InlineProcessor
from markdown.extensions import Extension
class inlineMathProcessor( InlineProcessor ):
def handleMatch( self, m, data ):
# MathJAX handles all the math. Just set the uses_math flag, and
# protect the contents from markdown expansion.
self.md.uses_math = True
return m.group(0), m.start(0), m.end(0)
class MathExtension(Extension):
def __init__(self, *args, **kwargs):
self.config = {
'enable_dollar_delimiter':
[False, 'Enable single-dollar delimiter'],
}
super(MathExtension, self).__init__(*args, **kwargs)
def extendMarkdown(self, md):
md.registerExtension(self)
mathRegExps = [
r'(?<!\\)\\\((.+?)\\\)', # \( ... \)
r'(?<!\\)\$\$.+?\$\$', # $$ ... $$
r'(?<!\\)\\\[.+?\\\]', # \[ ... \]
r'(?<!\\)\\begin{([a-z]+?\*?)}.+?\\end{\1}',
]
if self.getConfig('enable_dollar_delimiter'):
md.ESCAPED_CHARS.append('$')
mathRegExps.append( r'(?<!\\|\$)\$.+?\$' ) # $ ... $
for i, pattern in enumerate(mathRegExps):
# we should have higher priority than 'escape' which has 180
md.inlinePatterns.register(
inlineMathProcessor( pattern, md ), f'math-inline-{i}', 185)
md.uses_math = False
self.md = md
def reset(self):
self.md.uses_math = False
def makeExtension(*args, **kwargs):
return MathExtension(*args, **kwargs)