computable-pandoc/src/literate.lua

108 lines
2.4 KiB
Lua

----------------------------------- LITERATE ----------------------------------
-- Types functions extensions
function string:linearize()
return self:gsub("\n", "\\\\n")
end
-- Variable for all literate stuff
local lit = {}
-- Error collector
lit.e = {}
-- Grammars
lit.g = {}
-- Lexical elements
lit.newline = lpeg.P"\r"^-1 * lpeg.P"\n"
lit.space = lpeg.S" \t"
lit.anyspace = lpeg.S" \t\r\n"
lit.spot = (1 - lit.anyspace)
lit.any = (lit.spot + lit.space)
lit.yaml_header = lit.space^0 * lpeg.P"---" * lit.space^0 * lit.newline
lit.yaml_footer = lit.space^0 * lpeg.P"..." * lit.space^0 * lit.newline^-1
lit.yaml_body = -lit.yaml_footer * lit.any^0 * lit.newline
lit.id = lpeg.R("az", "AZ") * lpeg.R("az", "AZ", "09")^0
lit.ref = lpeg.P"#" * lit.id
-- Blocks grammar
lit.g.block = lpeg.P {
"Block";
Block = lpeg.Ct(lpeg.V"YAML" * lpeg.V"Code", "name");
YAML = lpeg.C(lit.yaml_header * lit.yaml_body^0 * lit.yaml_footer);
Code = lpeg.C((lit.any + lit.newline)^0);
}
-- Evals Lisp code
--[[
function lit.eval(code)
local is_passed, out = pcall (
function () return fennel.eval(code) end,
function (e) return e end
)
local lua = ""
local out = tostring(out)
local preview = out:gsub("\n.*", "")
if is_passed then
lua = fennel.compileString(code)
end
return {is_passed = is_passed, preview = preview, out = out, lua = lua}
end
]]--
function lit.debug_level(str)
if str == "ERROR" then
return 2
elseif str == "WARNING" then
return 1
else
return 0
end
end
function lit.puts(msg, level)
local verbosity = lit.debug_level(PANDOC_STATE.verbosity)
level = lit.debug_level(level)
if level >= verbosity then
print("[" .. PANDOC_STATE.verbosity .. "] " .. msg)
end
end
function lit.add_error(err)
end
function lit.check_yaml(raw_yaml)
local yaml = io.popen("pandoc -t json <<<\"" .. raw_yaml .. "\" 2>&1")
if yaml:read("*l"):sub(1, 1) == "{" then
yaml = pandoc.read(raw_yaml)
return yaml
else
lit.add_error(err)
return nil
end
end
function lit.check_block(parsed)
lit.puts("Parsing " .. table.concat(parsed, "\n"):linearize())
local yaml = lit.check_yaml(parsed[1])
return "TODO"
end
function lit.parse_blocks(codeblock)
local parsed = lpeg.match(lit.g.block, codeblock.text)
local valid = (parsed ~= nil and lit.check_block(parsed) or false)
return codeblock
end
function lit.parse_inserts(code)
-- print(code)
return code
end
return lit