util/stanza.lua

changeset 626
cf1d26fd4d6f
parent 519
cccd610a0ef9
child 628
f0a4498ae996
equal deleted inserted replaced
610:d98106902f74 626:cf1d26fd4d6f
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 -- 18 --
19 19
20 20
21 local t_insert = table.insert; 21 local t_insert = table.insert;
22 local t_concat = table.concat;
22 local t_remove = table.remove; 23 local t_remove = table.remove;
23 local s_format = string.format; 24 local s_format = string.format;
24 local tostring = tostring; 25 local tostring = tostring;
25 local setmetatable = setmetatable; 26 local setmetatable = setmetatable;
26 local pairs = pairs; 27 local pairs = pairs;
27 local ipairs = ipairs; 28 local ipairs = ipairs;
28 local type = type; 29 local type = type;
29 local next = next; 30 local next = next;
30 local print = print; 31 local print = print;
31 local unpack = unpack; 32 local unpack = unpack;
32 local s_gsub = string.gsub; 33 local s_gsub = string.gsub;
33 local os = os; 34 local os = os;
34 35
35 local do_pretty_printing = not os.getenv("WINDIR"); 36 local do_pretty_printing = not os.getenv("WINDIR");
114 function xml_escape(s) return s_gsub(s, "['&<>\"]", xml_entities); end 115 function xml_escape(s) return s_gsub(s, "['&<>\"]", xml_entities); end
115 end 116 end
116 117
117 local xml_escape = xml_escape; 118 local xml_escape = xml_escape;
118 119
120 local function dostring(t, buf, self)
121 t_insert(buf, "<");
122 t_insert(buf, t.name);
123 if t.attr then
124 for k, v in pairs(t.attr) do if type(k) == "string" then
125 t_insert(buf, " ");
126 t_insert(buf, k);
127 t_insert(buf, "='");
128 t_insert(buf, (xml_escape(tostring(v))));
129 t_insert(buf, "'");
130 end end
131 end
132 t_insert(buf, ">");
133 for n, child in ipairs(t) do
134 if child.name then
135 self(child, buf, self);
136 else
137 t_insert(buf, (xml_escape(child)));
138 end
139 end
140 t_insert(buf, "</");
141 t_insert(buf, t.name);
142 t_insert(buf, ">");
143 end
144
119 function stanza_mt.__tostring(t) 145 function stanza_mt.__tostring(t)
120 local children_text = ""; 146 local buf = {};
121 for n, child in ipairs(t) do 147 dostring(t, buf, dostring);
122 if type(child) == "string" then 148 return t_concat(buf);
123 children_text = children_text .. xml_escape(child);
124 else
125 children_text = children_text .. tostring(child);
126 end
127 end
128
129 local attr_string = "";
130 if t.attr then
131 for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, xml_escape(tostring(v))); end end
132 end
133 return s_format("<%s%s>%s</%s>", t.name, attr_string, children_text, t.name);
134 end 149 end
135 150
136 function stanza_mt.top_tag(t) 151 function stanza_mt.top_tag(t)
137 local attr_string = ""; 152 local attr_string = "";
138 if t.attr then 153 if t.attr then

mercurial