Daniel Rotter
Daniel Rotter

Reputation: 2056

Integrate graphviz into pandoc

I am trying to integrate graphviz using the dot command into pandoc markdown, and I am wondering what the easiest way is to do this. Currently I am creating separate .dot files, create images from them using the dot command manually on the command line into a separate file, and finally add that file using the image syntax of markdown:

![](./path/to/image.png)

But since the dot syntax is similar easy to read than markdown, I would prefer to have dot integrated in markdown. It feels like this should be possible, because in the pandoc filters page this is given as an example. It is just that I don't want to code that on my own, but would like to use some package that is ready to use. Does something like that exist?

Upvotes: 4

Views: 3147

Answers (1)

Daniel Rotter
Daniel Rotter

Reputation: 2056

tarleb posted a link to https://github.com/pandoc/lua-filters/tree/master/diagram-generator#graphviz in the comments, which was a great help. Using a lua-filter is really. Adapted the linked script a bit to match my needs.

The script now looks like the following:

-- insprired from https://github.com/pandoc/lua-filters/blob/5686d96/diagram-generator/diagram-generator.lua

local dotPath = os.getenv("DOT") or "dot"

local filetype = "svg"
local mimetype = "image/svg+xml"

local function graphviz(code, filetype)
    return pandoc.pipe(dotPath, {"-T" .. filetype}, code)
end

function CodeBlock(block)
    local converters = {
        graphviz = graphviz,
    }

    local img_converter = converters[block.classes[1]]
    if not img_converter then
      return nil
    end

    local success, img = pcall(img_converter, block.text, filetype)

    if not success then
        io.stderr:write(tostring(img))
        io.stderr:write('\n')
        error 'Image conversion failed. Aborting.'
    end

    return pandoc.RawBlock('html', img)
end

return {
    {CodeBlock = CodeBlock},
}

The pandoc option --lua-filter can then be used to add this filter to the conversion:

pandoc\
    slides.md\
    -o slides.html\
    --lua-filter=codeblock-filter.lua

Also added more explanation in my blog.

Upvotes: 5

Related Questions