Last active
June 7, 2024 21:31
-
-
Save samueltwallace/afc182d95096be06167662e438ae1383 to your computer and use it in GitHub Desktop.
Tikz Lua Filter for Pandoc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function draw_symbol(i,j,char) | |
if char == '-' then | |
return string.format('\\draw (%s,%s) -- (%s,%s)\n', i-1,j-0.5,i,j-0.5) | |
elseif char == '_' then | |
return string.format('\\draw (%s,%s) -- (%s,%s)\n', i-1,j,i,j) | |
elseif char == '|' then | |
return string.format('\\draw (%s,%s) -- (%s,%s)\n', i-0.5,j-1,i-0.5,j) | |
elseif char == '/' then | |
return string.format('\\draw (%s,%s) -- (%s,%s)\n', i-1,j-1,i,j) | |
elseif char == '\\' then | |
return string.format("\\draw (%s,%s) -- (%s,%s)\n", i-1,j-1,i,j) | |
elseif char == '+' then | |
return string.format('\\draw (%s,%s) -- (%s,%s)\n\\draw (%s,%s) -- \\draw (%s,%s)\n', i-1,j-0.5,i,j-0.5,i-0.5,j-1,i-0.5,j) | |
elseif char == '<' then | |
return string.format('\\draw [<-] (%s,%s) -- (%s,%s)\n', i-1,j-0.5,i,j-0.5) | |
elseif char == '>' then | |
return string.format('\\draw [->] (%s,%s) -- (%s,%s)\n', i-1,j-0.5,i,j-0.5) | |
elseif char == '~' then | |
return string.format('\\draw (%s,%s) -- (%s,%s)\n', i-0.75,j-0.5,i-0.25, j-0.5) | |
elseif char == ':' then | |
return string.format('\\draw (%s,%s) -- (%s,%s)\n \\draw (%s, %s) -- (%s,%s)', i-0.5,j-0.1,i-0.5, j-0.75, i-0.5, j-0.25, i-0.5, j) | |
elseif char == 'v' then | |
return string.format('\\draw [->] (%s,%s) -- (%s, %s)', i - 0.5, j-1, i-0.5,j) | |
elseif char == '^' then | |
return string.format('\\draw [<-] (%s,%s) -- (%s, %s)', i - 0.5, j-1, i-0.5,j) | |
elseif char == "o" then | |
return string.format('\\draw (%s,%s) circle [radius=1pt]' i-0.5,j-0.5) | |
else | |
error('Non-diagram character found: '..char) | |
end | |
end | |
local function draw_tikz (diagram) | |
local i = 1 -- length along a line | |
local j = 1 -- line number | |
local pos = 1 -- position in diagram string | |
local tikz_final = '' -- what we will eventually output | |
while pos <= diagram:len() do | |
if diagram[pos] == '\n' then | |
local j = j+1 | |
local i = 1 | |
local pos = pos+1 | |
else | |
tikz_final = tikz_final..draw_symbol( i,j, diagram[pos]) | |
pos = pos+1 | |
end | |
end | |
return '\\begin{tikzpicture}\n'..tikz_final..'\n\\end{tikzpicture}' | |
end | |
-- only use if going to latex | |
if FORMAT:match 'latex' then | |
function Figure(elem) --use figure elements | |
if elem.attr.Attributes['tikz'] == 'true' then -- require a tikz attribute | |
return pandoc.Figure { pandoc.Str draw_tikz(io.open(elem.content)), elem.caption, elem.attr } -- only modify content | |
else | |
return elem | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment