Skip to content

Instantly share code, notes, and snippets.

@mnm364
Last active April 27, 2019 14:53
Show Gist options
  • Save mnm364/6b378a094f864c7908cec1fb429cf0be to your computer and use it in GitHub Desktop.
Save mnm364/6b378a094f864c7908cec1fb429cf0be to your computer and use it in GitHub Desktop.
Pandoc: Convert DOT to TikZ

Pandoc: Convert DOT to TikZ

Using Pandoc's Lua AST manipulation, we can convert DOT blocks into TikZ during compile time, and then have LaTeX generate a graph rendering.

Running

An example command that uses this filter

pandoc --pdf-engine=xelatex --lua-filter ./dot2tex.lua -o out.pdf in.md

Dependencies

You must have dot2text

Usage

Simply include the DOT in a dot attributed code block

```dot
digraph graphname {
    a -> b -> c;
    b -> d;
}
```

And the LaTeX output will include the following picture:

Dot Example

--- Converts DOT block to TikZ
-- @author Michael Miller
-- Scans for dot attributed code blocks and converts them into representative
-- tikz using the dot2tex tool.
-- see https://pandoc.org/lua-filters.html for documentation on pandoc filters
-- see https://dot2tex.readthedocs.io/en/latest/ for documentation on doc2tex
-- @return TikZ represenation of DOT
function CodeBlock(block)
if block.classes[1] == "dot" then
-- Write dot data to temporary file location.
unique = tostring(block):gsub("table: ", "")
filename = "/tmp/dot2tex_"..unique..".dot"
fp = io.open(filename, "w")
dot = block.text
fp:write(dot)
fp:close()
-- Run dot2tex over temporary dot file.
cmd = "dot2tex --preproc "..filename.." | dot2tex --figonly --codeonly"
fp = io.popen(cmd)
tikz = "\\begin{center}\\begin{tikzpicture}[>=latex',line join=bevel,]"..fp:read("*a").."\\end{tikzpicture}\\end{center}"
fp:close()
-- Remove temporary file.
os.remove(filename)
return pandoc.RawBlock("latex", tikz)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment