-
Notifications
You must be signed in to change notification settings - Fork 27
/
pandoc_plantuml_filter.py
executable file
·88 lines (64 loc) · 2.65 KB
/
pandoc_plantuml_filter.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
85
86
87
88
#!/usr/bin/env python
"""
Pandoc filter to process code blocks with class "plantuml" into
plant-generated images.
Needs `plantuml.jar` from http://plantuml.com/.
"""
import os
import subprocess
import sys
from pandocfilters import Image, Para, get_caption, get_extension, get_filename4code, toJSONFilter
PLANTUML_BIN = os.environ.get("PLANTUML_BIN", "plantuml")
def rel_mkdir_symlink(src, dest):
dest_dir = os.path.dirname(dest)
if dest_dir and not os.path.exists(dest_dir):
os.makedirs(dest_dir)
if os.path.exists(dest):
os.remove(dest)
src = os.path.relpath(src, dest_dir)
os.symlink(src, dest)
def calculate_filetype(format_, plantuml_format):
if plantuml_format:
# File-type is overwritten via cli
# --metadata=plantuml-format:svg
if plantuml_format["t"] == "MetaString":
return get_extension(format_, plantuml_format["c"])
# File-type is overwritten in the meta data block of the document
# ---
# plantuml-format: svg
# ---
elif plantuml_format["t"] == "MetaInlines":
return get_extension(format_, plantuml_format["c"][0]["c"])
# Default per output-type eg. output-type: html -> file-type: svg
return get_extension(format_, "png", html="svg", latex="png")
def plantuml(key, value, format_, meta):
if key == "CodeBlock":
[[ident, classes, keyvals], code] = value
if "plantuml" in classes:
caption, typef, keyvals = get_caption(keyvals)
filename = get_filename4code("plantuml", code)
filetype = calculate_filetype(format_, meta.get("plantuml-format"))
src = filename + ".uml"
dest = filename + "." + filetype
# Generate image only once
if not os.path.isfile(dest):
txt = code.encode(sys.getfilesystemencoding())
if not txt.startswith(b"@start"):
txt = b"@startuml\n" + txt + b"\n@enduml\n"
with open(src, "wb") as f:
f.write(txt)
subprocess.check_call([*PLANTUML_BIN.split(), "-t" + filetype, src])
sys.stderr.write("Created image " + dest + "\n")
# Update symlink each run
for ind, keyval in enumerate(keyvals):
if keyval[0] == "plantuml-filename":
link = keyval[1]
keyvals.pop(ind)
rel_mkdir_symlink(dest, link)
dest = link
break
return Para([Image([ident, [], keyvals], caption, [dest, typef])])
def main():
toJSONFilter(plantuml)
if __name__ == "__main__":
main()