mathml/luamml-xmlwriter.lua

51 lines
1.4 KiB
Lua
Raw Normal View History

2021-04-18 15:19:52 +02:00
-- FIXME: Not sure yet if this will be needed
local function escape_name(name)
return name
end
local escapes = {
['"'] = """,
['<'] = "&lt;",
['>'] = "&gt;",
['&'] = "&amp;",
}
local function escape_text(text)
2021-04-19 13:30:54 +02:00
return string.gsub(tostring(text), '("<>&)', escapes)
2021-04-18 15:19:52 +02:00
end
2021-04-26 16:01:57 +02:00
local attrs = {}
2021-04-19 13:30:54 +02:00
local function write_elem(tree, indent)
2021-04-18 15:19:52 +02:00
if not tree[0] then print('ERR', require'inspect'(tree)) end
local escaped_name = escape_name(assert(tree[0]))
2021-04-26 16:01:57 +02:00
local i = 0
for attr, val in next, tree do if type(attr) == 'string' and string.byte(attr) ~= 0x3A then
2021-04-26 16:01:57 +02:00
i = i + 1
attrs[i] = string.format(' %s="%s"', escape_name(attr), escape_text(val))
2021-04-18 15:19:52 +02:00
end end
2021-04-26 16:01:57 +02:00
table.sort(attrs)
local out = string.format('%s<%s%s', indent or '', escaped_name, table.concat(attrs))
for j = 1, i do attrs[j] = nil end
2021-04-18 15:19:52 +02:00
if not tree[1] then
return out .. '/>'
end
out = out .. '>'
2021-04-19 13:30:54 +02:00
local inner_indent = indent and indent .. ' '
2021-04-18 15:19:52 +02:00
for _, elem in ipairs(tree) do
if type(elem) == 'string' then
2021-04-19 13:30:54 +02:00
if inner_indent then
out = out .. inner_indent
end
2021-04-18 15:19:52 +02:00
out = out .. escape_text(elem)
else
2021-04-19 13:30:54 +02:00
out = out .. write_elem(elem, inner_indent)
2021-04-18 15:19:52 +02:00
end
end
2021-04-19 13:30:54 +02:00
if indent then out = out .. indent end
2021-04-18 15:19:52 +02:00
return out .. '</' .. escaped_name .. '>'
end
2021-04-23 02:58:07 +02:00
return function(element, indent, version)
return (version == '11' and '<?xml version="1.1"?>' or '') ..
write_elem(element, indent and '\n' or nil)
2021-04-23 02:58:07 +02:00
end