| 1 |
--[[ |
| 2 |
This file returns an anonymous function |
| 3 |
with the arguments element, indent, version, which |
| 4 |
write the mathml tree through the here defined write_elem(tree, indent) |
| 5 |
function to a file or to a stream. |
| 6 |
|
| 7 |
Used by luamml-tex as write_xml in save_result. |
| 8 |
--]] |
| 9 |
|
| 10 |
-- FIXME: Not sure yet if this will be needed |
| 11 |
local function escape_name(name) |
| 12 |
return name |
| 13 |
end |
| 14 |
|
| 15 |
local escapes = { |
| 16 |
['"'] = """, |
| 17 |
['<'] = "<", |
| 18 |
['>'] = ">", |
| 19 |
['&'] = "&", |
| 20 |
} |
| 21 |
local function escape_text(text) |
| 22 |
return string.gsub(string.gsub(tostring(text), '["<>&]', escapes), '[\x00-\x08\x0B\x0C\x0E-\x1F]', function(x) |
| 23 |
return string.format('^^%02x', string.byte(x)) |
| 24 |
end) |
| 25 |
end |
| 26 |
|
| 27 |
local attrs = {} |
| 28 |
local function write_elem(tree, indent) |
| 29 |
if not tree[0] then print('ERR', require'inspect'(tree)) end |
| 30 |
local escaped_name = escape_name(assert(tree[0])) |
| 31 |
local i = 0 |
| 32 |
for attr, val in next, tree do if type(attr) == 'string' then |
| 33 |
if not string.find(attr, ':', 1, true) then |
| 34 |
-- if string.byte(attr) ~= 0x3A then |
| 35 |
i = i + 1 |
| 36 |
attrs[i] = string.format(' %s="%s"', escape_name(attr), escape_text(val)) |
| 37 |
end |
| 38 |
end end |
| 39 |
table.sort(attrs) |
| 40 |
local out = string.format('%s<%s%s', indent or '', escaped_name, table.concat(attrs)) |
| 41 |
for j = 1, i do attrs[j] = nil end |
| 42 |
if not tree[1] then |
| 43 |
return out .. '/>' |
| 44 |
end |
| 45 |
out = out .. '>' |
| 46 |
-- Never indent the content if it's purely text. |
| 47 |
if #tree == 1 and type(tree[1]) == 'string' then |
| 48 |
indent = nil |
| 49 |
end |
| 50 |
local inner_indent = indent and indent .. ' ' |
| 51 |
local is_string |
| 52 |
for _, elem in ipairs(tree) do |
| 53 |
if type(elem) == 'string' then |
| 54 |
if inner_indent and not is_string then |
| 55 |
out = out .. inner_indent |
| 56 |
end |
| 57 |
out = out .. escape_text(elem) |
| 58 |
is_string = true |
| 59 |
else |
| 60 |
out = out .. write_elem(elem, inner_indent) |
| 61 |
is_string = nil |
| 62 |
end |
| 63 |
end |
| 64 |
if indent then out = out .. indent end |
| 65 |
return out .. '</' .. escaped_name .. '>' |
| 66 |
end |
| 67 |
|
| 68 |
return function(element, indent, version) |
| 69 |
return (version == '11' and '<?xml version="1.1"?>' or '') .. |
| 70 |
write_elem(element, indent and '\n' or nil) |
| 71 |
end |