-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdx_alerts.py
75 lines (62 loc) · 2 KB
/
mdx_alerts.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import re
from textwrap import dedent
from markdown import Extension
from markdown.preprocessors import Preprocessor
SNIPPET = '''<div class="alert alert-{level}" role="alert">
<h4 class="alert-heading"><strong>{heading}</strong></h4>
{alert}
</div>'''
HEADINGS = {
"primary": "",
"secondary": "Note",
"success": "Congratulations!",
"danger": "Caution!",
"warning": "Warning",
"info": "Info",
"light": "Note",
"dark": "Note",
}
class AlertExtension(Extension):
def __init__(self, **kwargs):
self.config = {}
super().__init__(**kwargs)
def extendMarkdown(self, md):
md.registerExtension(self)
md.preprocessors.register(
AlertBlockProcessor(md, self.getConfigs()
), 'alert_block', 25)
class AlertBlockProcessor(Preprocessor):
ALERT_BLOCK_RE = re.compile(
dedent(r'''
:: (?P<level>[^\[\s+]+)( heading=["'](?P<heading>[^"']+)["'])?
(?P<alert>[\s\S]*?)
::
'''),
)
def __init__(self, md, config):
super().__init__(md)
self.config = config
def run(self, lines):
text = "\n".join(lines)
while 1:
m = self.ALERT_BLOCK_RE.search(text)
if m:
level = 'debug'
if m.group('level'):
level = m.group('level')
heading = HEADINGS.get(level, "Note")
if m.group("heading"):
heading = m.group("heading")
alert = self.md.convert(m.group("alert"))
snippet = SNIPPET.format(level=level, alert=alert, heading=heading)
placeholder = self.md.htmlStash.store(snippet)
text = '{}\n{}\n{}'.format(
text[:m.start()],
placeholder,
text[m.end():],
)
else:
break
return text.split("\n")
def makeExtension(**kwargs): # pragma: no cover
return AlertExtension(**kwargs)