graphviz.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env python3
  2. # Licensed BSD-3-Clause: https://spdx.org/licenses/BSD-3-Clause.html
  3. """
  4. Pandoc filter to process code blocks with class "graphviz" into
  5. SVG based graphviz-generated images.
  6. Needs pygraphviz
  7. """
  8. # Based on https://github.com/jgm/pandocfilters/blob/master/examples/graphviz.py
  9. import sys, os, pygraphviz
  10. from pandocfilters import toJSONFilter, Para, Image, RawBlock, get_filename4code, get_caption, get_extension, get_value
  11. # https://pandoc.org/lua-filters.html
  12. def graphviz (key, value, frmat, _):
  13. if key == 'CodeBlock':
  14. [[ident, classes, keyvals], code] = value
  15. if "graphviz" in classes:
  16. # sys.stderr.write ('Debug: ' + str (value) + '\n')
  17. caption, typef, keyvals = get_caption (keyvals)
  18. prog, keyvals = get_value (keyvals, u"prog", u"dot")
  19. force, keyvals = get_value (keyvals, u"force", u"false")
  20. filetype = get_extension (frmat, "svg", html ="svg", latex ="pdf")
  21. dest = get_filename4code ("graphviz", str (value), filetype)
  22. if force != u"false" or not os.path.isfile (dest):
  23. g = pygraphviz.AGraph (string = code)
  24. g.layout ()
  25. g.draw (dest, prog = prog)
  26. sys.stderr.write ('Create image: ' + dest + '\n')
  27. if dest.endswith ('.svg'):
  28. return RawBlock (u'html', '<object type="image/svg+xml" data="%s"></object>' % dest)
  29. return Para ([Image ([ident, [], keyvals], caption, [dest, typef])])
  30. if __name__ == "__main__":
  31. toJSONFilter (graphviz)