aboutsummaryrefslogtreecommitdiff
path: root/pandoc/filters/tikz2svg.lua
blob: f5a8c29ace96c36339eeb361ff4d7d16f34b4ee2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
local system = require 'pandoc.system'

local tikz_doc_template = [[
\documentclass{standalone}
\usepackage{xcolor}
\usepackage{tikz}
%s
\begin{document}
\nopagecolor
%s
\end{document}
]]

local function tikz2image(src, outfile, before)
  system.with_temporary_directory('tikz2image', function (tmpdir)
    system.with_working_directory(tmpdir, function()
      local f = io.open('tikz.tex', 'w')
      local tex = tikz_doc_template:format(before, src)
      if not f then return end
      f:write(tex)
      f:close()
      os.execute('pdflatex tikz.tex')
      os.execute('pdf2svg tikz.pdf ' .. outfile)
    end)
  end)
end

function CodeBlock(el)
  if not el.classes:includes('tikz') then
    return el
  end

  local fbasename = pandoc.sha1(el.text) .. '.svg'
  local fname = system.get_working_directory() .. '/.build/' .. fbasename
  tikz2image(el.text, fname, el.attributes.before)
  el.attributes.before = nil
  local img = pandoc.Image({}, fname)
  img.attributes = el.attributes
  return img
end