Skip to content

Instantly share code, notes, and snippets.

@jdiez17
Last active October 6, 2015 10:59
Show Gist options
  • Save jdiez17/acadccd35c6555780831 to your computer and use it in GitHub Desktop.
Save jdiez17/acadccd35c6555780831 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Pandoc filter to process code blocks with class "graphviz" into
graphviz-generated images.
"""
import pygraphviz
import hashlib
import os
import sys
from pandocfilters import toJSONFilter, Str, Para, Image
def sha1(x):
return hashlib.sha1(x.encode(sys.getfilesystemencoding())).hexdigest()
imagedir = "graphviz-images"
def graphviz(key, value, format, meta):
if key == 'CodeBlock':
[[ident, classes, keyvals], code] = value
caption = "caption"
if "graphviz" in classes:
G = pygraphviz.AGraph(string=code, strict=False, directed=True)
G.layout(prog='dot')
filename = sha1(code)
if format == "html":
filetype = "png"
elif format == "latex":
filetype = "pdf"
else:
filetype = "png"
alt = Str(caption)
src = imagedir + '/' + filename + '.' + filetype
if not os.path.isfile(src):
try:
os.mkdir(imagedir)
sys.stderr.write('Created directory ' + imagedir + '\n')
except OSError:
pass
G.draw(src)
sys.stderr.write('Created image ' + src + '\n')
tit = ""
return Para([Image([alt], [src, tit])])
if __name__ == "__main__":
toJSONFilter(graphviz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment