#!/usr/bin/env python3 """ Pandoc filter to process code blocks with class "plantuml" into plant-generated images. Needs `plantuml.jar` from http://plantuml.com/. """ import os import sys import subprocess from pandocfilters import toJSONFilter, Para, Image from pandocfilters import get_filename4code, get_caption, get_extension kinds = { 'plantuml': { 'tag': 'plantuml', 'argv': lambda src, dest: [ 'plantuml', '-tsvg', '-o', '.', src, ], 'ext': '.uml', 'prefix': b'@startuml\n', 'suffix': b'\n@enduml\n', }, 'dot': { 'tag': 'dot', 'argv': lambda src, dest: [ 'dot', '-Tsvg', '-o', dest, src, '-Nfontname=Bitstream Charter', '-Nfontsize=10', ], 'ext': '.dot', 'prefix': b'digraph foo {\n', 'suffix': b'}\n', }, } def process_to_svg(kind, ident, classes, keyvals, code, format_): caption, typef, keyvals = get_caption(keyvals) filename = get_filename4code(kind['tag'], code) filetype = get_extension(format_, "png", html="svg", latex="svg") src = filename + kind['ext'] dest = filename + '.' + filetype if not os.path.isfile(dest): txt = code.encode(sys.getfilesystemencoding()) txt = kind['prefix'] + txt + kind['suffix'] with open(src, "wb") as f: f.write(txt) func = kind['argv'] argv = func(src, dest) subprocess.check_call(argv) sys.stderr.write('Created image ' + dest + '\n') return Para([Image([ident, [], keyvals], caption, [dest, typef])]) def combo(key, value, format_, _): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value for tag, kind in kinds.items(): if tag in classes: return process_to_svg( kind, ident, classes, keyvals, code, format_) def main(): toJSONFilter(combo) if __name__ == "__main__": main()