This repository has been archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
md_mermaid.py
84 lines (63 loc) · 2.63 KB
/
md_mermaid.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
"""
Mermaid Extension for Python-Markdown
========================================
Adds mermaid parser (like github-markdown) to standard Python-Markdown code blocks.
Original code Copyright 2018-2020 [Olivier Ruelle].
License: GNU GPLv3
"""
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
from PyQt6.QtCore import QUrl
import re
import os
MermaidRegex = re.compile(r"^(?P<mermaid_sign>[\~\`]){3}[\ \t]*[Mm]ermaid[\ \t]*$")
# ------------------ The Markdown Extension -------------------------------
class MermaidPreprocessor(Preprocessor):
def run(self, lines):
new_lines = []
mermaid_sign = ""
m_start = None
m_end = None
in_mermaid_code = False
is_mermaid = False
old_line = ""
js_file = os.path.join(os.path.dirname(__file__), "node_modules", "mermaid", "dist", "mermaid.js")
new_lines.append('<meta charset="utf-8">')
new_lines.append('<script src="{}"></script>'.format(QUrl.fromLocalFile(js_file).toString()))
new_lines.append('<script>mermaid.initialize({startOnLoad:true});</script>')
for line in lines:
# Wait for starting line with MermaidRegex (~~~ or ``` following by [mM]ermaid )
if not in_mermaid_code:
m_start = MermaidRegex.match(line)
else:
m_end = re.match(r"^["+mermaid_sign+"]{3}[\ \t]*$", line)
if m_end:
in_mermaid_code = False
if m_start:
in_mermaid_code = True
mermaid_sign = m_start.group("mermaid_sign")
if not re.match(r"^[\ \t]*$", old_line):
new_lines.append("")
if not is_mermaid:
is_mermaid = True
new_lines.append('<div class="mermaid">')
m_start = None
elif m_end:
new_lines.append('</div>')
new_lines.append("")
m_end = None
elif in_mermaid_code:
new_lines.append(line.strip())
else:
new_lines.append(line)
old_line = line
return new_lines
class MermaidExtension(Extension):
""" Add source code hilighting to markdown codeblocks. """
def extendMarkdown(self, md, md_globals):
""" Add HilitePostprocessor to Markdown instance. """
# Insert a preprocessor before ReferencePreprocessor
md.preprocessors.register(MermaidPreprocessor(md), 'mermaid', 35)
md.registerExtension(self)
def makeExtension(**kwargs): # pragma: no cover
return MermaidExtension(**kwargs)