2 local t_insert = table.insert;
3 local st = require "util.stanza";
4 local lxp = require "lxp";
5 local setmetatable = setmetatable;
8 local s_gsub = string.gsub;
14 local function process_stanza(stanza, ops)
16 for key, val in pairs(stanza.attr) do
17 if val:match("{[^}]*}") then
18 t_insert(ops, {stanza.attr, key, val});
24 local child = stanza[i];
26 process_stanza(child, ops);
27 elseif child:match("{[^}]*}") then -- text
28 t_insert(ops, {stanza, i, child});
34 local parse_xml = (function()
36 ["http://www.w3.org/XML/1998/namespace"] = "xml";
38 local ns_separator = "\1";
39 local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$";
42 local stanza = st.stanza("root");
43 function handler:StartElement(tagname, attr)
44 local curr_ns,name = tagname:match(ns_pattern);
46 curr_ns, name = "", curr_ns;
54 local ns, nm = k:match(ns_pattern);
58 attr[ns..":"..nm] = attr[k];
63 stanza:tag(name, attr);
65 function handler:CharacterData(data)
66 data = data:gsub("^%s*", ""):gsub("%s*$", "");
69 function handler:EndElement(tagname)
72 local parser = lxp.new(handler, "\1");
73 local ok, err, line, col = parser:parse(xml);
74 if ok then ok, err, line, col = parser:parse(); end
77 return stanza.tags[1];
79 return ok, err.." (line "..line..", col "..col..")";
84 local function create_template(text)
85 local stanza, err = parse_xml(text);
86 if not stanza then error(err); end
88 process_stanza(stanza, ops);
92 function template.apply(data)
93 local newops = st.clone(ops);
96 local t, k, v = op[1], op[2], op[3];
97 t[k] = s_gsub(v, "{([^}]*)}", data);
104 local templates = setmetatable({}, { __mode = 'k' });
105 return function(text)
106 local template = templates[text];
108 template = create_template(text);
109 templates[text] = template;