-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathplugin.py
More file actions
106 lines (86 loc) · 2.98 KB
/
Copy pathplugin.py
File metadata and controls
106 lines (86 loc) · 2.98 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import re
import os
import shlex
import textwrap
from mkdocs.plugins import BasePlugin
from codeinclude.resolver import select
from codeinclude.languages import get_lang_class
RE_START = r"""(?x)
^
(?P<leading_space>\s*)
<!--codeinclude-->
(?P<ignored_trailing_space>\s*)
$
"""
RE_END = r"""(?x)
^
(?P<leading_space>\s*)
<!--/codeinclude-->
(?P<ignored_trailing_space>\s*)
$
"""
RE_SNIPPET = r"""(?x)
^
(?P<leading_space>\s*)
\[(?P<title>[^\]]*)\]\((?P<filename>[^)]+)\)
([\t ]+(?P<params>.*))?
(?P<ignored_trailing_space>\s*)
$
"""
def get_substitute(page, title, filename, lines, block, inside_block):
page_parent_dir = os.path.dirname(page.file.abs_src_path)
import_path = os.path.join(page_parent_dir, filename)
with open(import_path) as f:
content = f.read()
selected_content = select(
content, lines=lines, block=block, inside_block=inside_block
)
dedented = textwrap.dedent(selected_content)
lang_code = get_lang_class(filename)
return f'''
```{lang_code} tab="{title}"
{dedented}
```
'''
class CodeIncludePlugin(BasePlugin):
def on_page_markdown(self, markdown, page, config, site_navigation=None, **kwargs):
"Provide a hook for defining functions from an external module"
active = False
results = ""
for line in markdown.splitlines():
boundary = False
# detect end
if active and re.match(RE_END, line):
active = False
boundary = True
# handle each line of a codeinclude zone
if active:
snippet_match = re.match(RE_SNIPPET, line)
if snippet_match:
title = snippet_match.group("title")
filename = snippet_match.group("filename")
indent = snippet_match.group("leading_space")
raw_params = snippet_match.group("params")
if raw_params:
params = dict(token.split(":") for token in shlex.split(raw_params))
lines = params.get("lines", "")
block = params.get("block", "")
inside_block = params.get("inside_block", "")
else:
lines = ""
block = ""
inside_block = ""
code_block = get_substitute(
page, title, filename, lines, block, inside_block
)
# re-indent
code_block = re.sub("^", indent, code_block, flags=re.MULTILINE)
results += code_block
# detect start
if re.match(RE_START, line):
active = True
boundary = True
# outside a codeinclude zone and ignoring the boundaries
if not active and not boundary:
results += line + "\n"
return results