/
markdown.py
84 lines (59 loc) · 1.7 KB
/
markdown.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
76
77
78
79
80
81
82
83
84
import re
import mistune
from fluffy.app import app
from fluffy.component.highlighting import guess_lexer
from fluffy.component.highlighting import PygmentsHighlighter
class HtmlCommentsInlineLexerMixin:
"""Strip HTML comments inside lines."""
def enable_html_comments(self):
self.rules.html_comment = re.compile(
'^<!--(.*?)-->',
)
self.default_rules.insert(0, 'html_comment')
def output_html_comment(self, m):
return ''
class HtmlCommentsBlockLexerMixin:
"""Strip blocks which consist entirely of HTML comments."""
def enable_html_comments(self):
self.rules.html_comment = re.compile(
'^<!--(.*?)-->',
)
self.default_rules.insert(0, 'html_comment')
def parse_html_comment(self, m):
pass
class CodeRendererMixin:
"""Render highlighted code."""
def block_code(self, code, lang):
return PygmentsHighlighter(
guess_lexer(code, lang, None, opts={'stripnl': True}),
).highlight(code)
class FluffyMarkdownRenderer(
CodeRendererMixin,
mistune.Renderer,
):
pass
class FluffyMarkdownInlineLexer(
mistune.InlineLexer,
HtmlCommentsInlineLexerMixin,
):
pass
class FluffyMarkdownBlockLexer(
mistune.BlockLexer,
HtmlCommentsBlockLexerMixin,
):
pass
_renderer = FluffyMarkdownRenderer(
escape=True,
hard_wrap=False,
)
_inline = FluffyMarkdownInlineLexer(_renderer)
_inline.enable_html_comments()
_block = FluffyMarkdownBlockLexer(mistune.BlockGrammar())
_block.enable_html_comments()
@app.template_filter()
def markdown(text):
return mistune.Markdown(
renderer=_renderer,
inline=_inline,
block=_block,
)(text)