• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lunarmodules / Penlight / 603

29 Dec 2025 10:36PM UTC coverage: 89.269% (+0.4%) from 88.862%
603

push

appveyor

Tieske
chore(example): fix Lua 5.5 compat

5482 of 6141 relevant lines covered (89.27%)

165.46 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.6
/lua/pl/xml.lua
1
--- XML LOM Utilities.
2
--
3
-- This implements some useful things on [LOM](http://matthewwild.co.uk/projects/luaexpat/lom.html) documents, such as returned by `lxp.lom.parse`.
4
-- In particular, it can convert LOM back into XML text, with optional pretty-printing control.
5
-- It is based on stanza.lua from [Prosody](http://hg.prosody.im/trunk/file/4621c92d2368/util/stanza.lua)
6
--
7
--     > d = xml.parse "<nodes><node id='1'>alice</node></nodes>"
8
--     > = d
9
--     <nodes><node id='1'>alice</node></nodes>
10
--     > = xml.tostring(d,'','  ')
11
--     <nodes>
12
--        <node id='1'>alice</node>
13
--     </nodes>
14
--
15
-- Can be used as a lightweight one-stop-shop for simple XML processing; a simple XML parser is included
16
-- but the default is to use `lxp.lom` if it can be found.
17
-- <pre>
18
-- Prosody IM
19
-- Copyright (C) 2008-2010 Matthew Wild
20
-- Copyright (C) 2008-2010 Waqas Hussain--
21
-- classic Lua XML parser by Roberto Ierusalimschy.
22
-- modified to output LOM format.
23
-- http://lua-users.org/wiki/LuaXml
24
-- </pre>
25
-- See @{06-data.md.XML|the Guide}
26
--
27
-- Dependencies: `pl.utils`
28
--
29
-- Soft Dependencies: `lxp.lom` (fallback is to use basic Lua parser)
30
-- @module pl.xml
31

32
local utils = require 'pl.utils'
8 ✔
33
local split         =   utils.split
8 ✔
34
local t_insert      =  table.insert
8 ✔
35
local t_concat      =  table.concat
8 ✔
36
local t_remove      =  table.remove
8 ✔
37
local s_match       =  string.match
8 ✔
38
local tostring      =      tostring
8 ✔
39
local setmetatable  =  setmetatable
8 ✔
40
local getmetatable  =  getmetatable
8 ✔
41
local pairs         =         pairs
8 ✔
42
local ipairs        =        ipairs
8 ✔
43
local type          =          type
8 ✔
44
local next          =          next
8 ✔
45
local print         =         print
8 ✔
46
local unpack        =  utils.unpack
8 ✔
47
local s_gsub        =   string.gsub
8 ✔
48
local s_sub         =    string.sub
8 ✔
49
local s_find        =   string.find
8 ✔
50
local pcall         =         pcall
8 ✔
51
local require       =       require
8 ✔
52

53

54
utils.raise_deprecation {
16 ✔
55
  source = "Penlight " .. utils._VERSION,
8 ✔
56
  message = "the contents of module 'pl.xml' has been deprecated, please use a more specialized library instead",
8 ✔
57
  version_removed = "2.0.0",
8 ✔
58
  deprecated_after = "1.11.0",
8 ✔
59
  no_trace = true,
8 ✔
60
}
61

62

63

64
local _M = {}
8 ✔
65
local Doc = { __type = "doc" };
8 ✔
66
Doc.__index = Doc;
8 ✔
67

68

69
local function is_text(s) return type(s) == 'string' end
4,152 ✔
70
local function is_tag(d) return type(d) == 'table' and is_text(d.tag) end
1,380 ✔
71

72

73

74
--- create a new document node.
75
-- @tparam string tag the tag name
76
-- @tparam[opt={}] table attr attributes (table of name-value pairs)
77
-- @return the Node object
78
-- @see xml.elem
79
-- @usage
80
-- local doc = xml.new("main", { hello = "world", answer = "42" })
81
-- print(doc)  -->  <main hello='world' answer='42'/>
82
function _M.new(tag, attr)
8 ✔
83
  if type(tag) ~= "string" then
800 ✔
84
    error("expected 'tag' to be a string value, got: " .. type(tag), 2)
4 ✔
85
  end
86
  attr = attr or {}
796 ✔
87
  if type(attr) ~= "table" then
796 ✔
88
    error("expected 'attr' to be a table value, got: " .. type(attr), 2)
4 ✔
89
  end
90

91
  local doc = { tag = tag, attr = attr, last_add = {}};
792 ✔
92
  return setmetatable(doc, Doc);
792 ✔
93
end
94

95

96
--- parse an XML document. By default, this uses lxp.lom.parse, but
97
-- falls back to basic_parse, or if `use_basic` is truthy
98
-- @param text_or_filename  file or string representation
99
-- @param is_file whether text_or_file is a file name or not
100
-- @param use_basic do a basic parse
101
-- @return a parsed LOM document with the document metatatables set
102
-- @return nil, error the error can either be a file error or a parse error
103
function _M.parse(text_or_filename, is_file, use_basic)
8 ✔
104
  local parser,status,lom
105
  if use_basic then
84 ✔
106
    parser = _M.basic_parse
80 ✔
107
  else
108
    status,lom = pcall(require,'lxp.lom')
4 ✔
109
    if not status then
4 ✔
110
      parser = _M.basic_parse
4 ✔
111
    else
112
      parser = lom.parse
×
113
    end
114
  end
115

116
  if is_file then
84 ✔
117
    local text, err = utils.readfile(text_or_filename)
4 ✔
118
    if not text then
4 ✔
119
      return nil, err
×
120
    end
121
    text_or_filename = text
4 ✔
122
  end
123

124
  local doc, err = parser(text_or_filename)
84 ✔
125
  if not doc then
84 ✔
126
    return nil, err
×
127
  end
128

129
  if lom then
84 ✔
130
    _M.walk(doc, false, function(_, d)
8 ✔
131
      setmetatable(d, Doc)
60 ✔
132
    end)
133
  end
134
  return doc
84 ✔
135
end
136

137

138
--- Create a Node with a set of children (text or Nodes) and attributes.
139
-- @tparam string tag a tag name
140
-- @tparam table|string items either a single child (text or Node), or a table where the hash
141
-- part is the attributes and the list part is the children (text or Nodes).
142
-- @return the new Node
143
-- @see xml.new
144
-- @see xml.tags
145
-- @usage
146
-- local doc = xml.elem("top", "hello world")                -- <top>hello world</top>
147
-- local doc = xml.elem("main", xml.new("child"))            -- <main><child/></main>
148
-- local doc = xml.elem("main", { "this ", "is ", "nice" })  -- <main>this is nice</main>
149
-- local doc = xml.elem("main", { xml.new "this",
150
--                                xml.new "is",
151
--                                xml.new "nice" })          -- <main><this/><is/><nice/></main>
152
-- local doc = xml.elem("main", { hello = "world" })         -- <main hello='world'/>
153
-- local doc = xml.elem("main", {
154
--   "prefix",
155
--   xml.elem("child", { "this ", "is ", "nice"}),
156
--   "postfix",
157
--   attrib = "value"
158
-- })   -- <main attrib='value'>prefix<child>this is nice</child>postfix</main>"
159
function _M.elem(tag, items)
8 ✔
160
  local s = _M.new(tag)
536 ✔
161
  if is_text(items) then items = {items} end
536 ✔
162
  if is_tag(items) then
536 ✔
163
    t_insert(s,items)
4 ✔
164
  elseif type(items) == 'table' then
532 ✔
165
    for k,v in pairs(items) do
984 ✔
166
      if is_text(k) then
676 ✔
167
        s.attr[k] = v
96 ✔
168
        t_insert(s.attr,k)
96 ✔
169
      else
170
        s[k] = v
580 ✔
171
      end
172
    end
173
  end
174
  return s
536 ✔
175
end
176

177

178
--- given a list of names, return a number of element constructors.
179
-- If passing a comma-separated string, then whitespace surrounding the values
180
-- will be stripped.
181
--
182
-- The returned constructor functions are a shortcut to `xml.elem` where you
183
-- no longer provide the tag-name, but only the `items` table.
184
-- @tparam string|table list a list of names, or a comma-separated string.
185
-- @return (multiple) constructor functions; `function(items)`. For the `items`
186
-- parameter see `xml.elem`.
187
-- @see xml.elem
188
-- @usage
189
-- local new_parent, new_child = xml.tags 'mom, kid'
190
-- doc = new_parent {new_child 'Bob', new_child 'Annie'}
191
-- -- <mom><kid>Bob</kid><kid>Annie</kid></mom>
192
function _M.tags(list)
8 ✔
193
  local ctors = {}
20 ✔
194
  if is_text(list) then
20 ✔
195
    list = split(list:match("^%s*(.-)%s*$"),'%s*,%s*')
16 ✔
196
  end
197
  for i,tag in ipairs(list) do
88 ✔
198
    local function ctor(items)
199
      return _M.elem(tag,items)
120 ✔
200
    end
201
    ctors[i] = ctor
68 ✔
202
  end
203
  return unpack(ctors)
20 ✔
204
end
205

206

207
--- Adds a document Node, at current position.
208
-- This updates the last inserted position to the new Node.
209
-- @tparam string tag the tag name
210
-- @tparam[opt={}] table attrs attributes (table of name-value pairs)
211
-- @return the current node (`self`)
212
-- @usage
213
-- local doc = xml.new("main")
214
-- doc:addtag("penlight", { hello = "world"})
215
-- doc:addtag("expat")  -- added to 'penlight' since position moved
216
-- print(doc)  -->  <main><penlight hello='world'><expat/></penlight></main>
217
function Doc:addtag(tag, attrs)
8 ✔
218
  local s = _M.new(tag, attrs)
96 ✔
219
  self:add_child(s)
96 ✔
220
  t_insert(self.last_add, s)
96 ✔
221
  return self
96 ✔
222
end
223

224

225
--- Adds a text node, at current position.
226
-- @tparam string text a string
227
-- @return the current node (`self`)
228
-- @usage
229
-- local doc = xml.new("main")
230
-- doc:text("penlight")
231
-- doc:text("expat")
232
-- print(doc)  -->  <main><penlightexpat</main>
233
function Doc:text(text)
8 ✔
234
  self:add_child(text)
72 ✔
235
  return self
72 ✔
236
end
237

238

239
--- Moves current position up one level.
240
-- @return the current node (`self`)
241
function Doc:up()
8 ✔
242
  t_remove(self.last_add)
72 ✔
243
  return self
72 ✔
244
end
245

246

247
--- Resets current position to top level.
248
-- Resets to the `self` node.
249
-- @return the current node (`self`)
250
function Doc:reset()
8 ✔
251
  local last_add = self.last_add
4 ✔
252
  for i = 1,#last_add do
16 ✔
253
    last_add[i] = nil
12 ✔
254
  end
255
  return self
4 ✔
256
end
257

258

259
--- Append a child to the current Node (ignoring current position).
260
-- @param child a child node (either text or a document)
261
-- @return the current node (`self`)
262
-- @usage
263
-- local doc = xml.new("main")
264
-- doc:add_direct_child("dog")
265
-- doc:add_direct_child(xml.new("child"))
266
-- doc:add_direct_child("cat")
267
-- print(doc)  -->  <main>dog<child/>cat</main>
268
function Doc:add_direct_child(child)
8 ✔
269
  t_insert(self, child)
252 ✔
270
  return self
252 ✔
271
end
272

273

274
--- Append a child at the current position (without changing position).
275
-- @param child a child node (either text or a document)
276
-- @return the current node (`self`)
277
-- @usage
278
-- local doc = xml.new("main")
279
-- doc:addtag("one")
280
-- doc:add_child(xml.new("item1"))
281
-- doc:add_child(xml.new("item2"))
282
-- doc:add_child(xml.new("item3"))
283
-- print(doc)  -->  <main><one><item1/><item2/><item3/></one></main>
284
function Doc:add_child(child)
8 ✔
285
  (self.last_add[#self.last_add] or self):add_direct_child(child)
236 ✔
286
  return self
236 ✔
287
end
288

289

290
--accessing attributes: useful not to have to expose implementation (attr)
291
--but also can allow attr to be nil in any future optimizations
292

293

294
--- Set attributes of a document node.
295
-- Will add/overwrite values, but will not remove existing ones.
296
-- Operates on the Node itself, will not take position into account.
297
-- @tparam table t a table containing attribute/value pairs
298
-- @return the current node (`self`)
299
function Doc:set_attribs(t)
8 ✔
300
  -- TODO: keep array part in sync
301
  for k,v in pairs(t) do
40 ✔
302
    self.attr[k] = v
24 ✔
303
  end
304
  return self
16 ✔
305
end
306

307

308
--- Set a single attribute of a document node.
309
-- Operates on the Node itself, will not take position into account.
310
-- @param a attribute
311
-- @param v its value, pass in `nil` to delete the attribute
312
-- @return the current node (`self`)
313
function Doc:set_attrib(a,v)
8 ✔
314
  -- TODO: keep array part in sync
315
  self.attr[a] = v
8 ✔
316
  return self
8 ✔
317
end
318

319

320
--- Gets the attributes of a document node.
321
-- Operates on the Node itself, will not take position into account.
322
-- @return table with attributes (attribute/value pairs)
323
function Doc:get_attribs()
8 ✔
324
  return self.attr
4 ✔
325
end
326

327

328

329
local template_cache do
8 ✔
330
  local templ_cache = {}
8 ✔
331

332
  -- @param templ a template, a string being valid xml to be parsed, or a Node object
333
  function template_cache(templ)
6 ✔
334
    if is_text(templ) then
48 ✔
335
      if templ_cache[templ] then
44 ✔
336
        -- cache hit
337
        return templ_cache[templ]
×
338

339
      else
340
        -- parse and cache
341
        local ptempl, err = _M.parse(templ,false,true)
44 ✔
342
        if not ptempl then
44 ✔
343
          return nil, err
×
344
        end
345
        templ_cache[templ] = ptempl
44 ✔
346
        return ptempl
44 ✔
347
      end
348
    end
349

350
    if is_tag(templ) then
4 ✔
351
      return templ
4 ✔
352
    end
353

354
    return nil, "template is not a document"
×
355
  end
356
end
357

358

359
do
360
  local function is_data(data)
361
    return #data == 0 or type(data[1]) ~= 'table'
8 ✔
362
  end
363

364

365
  local function prepare_data(data)
366
    -- a hack for ensuring that $1 maps to first element of data, etc.
367
    -- Either this or could change the gsub call just below.
368
    for i,v in ipairs(data) do
8 ✔
369
      data[tostring(i)] = v
×
370
    end
371
  end
372

373
  --- create a substituted copy of a document,
374
  -- @param template may be a document or a string representation which will be parsed and cached
375
  -- @param data a table of name-value pairs or a list of such tables
376
  -- @return an XML document
377
  function Doc.subst(template, data)
8 ✔
378
    if type(data) ~= 'table' or not next(data) then
4 ✔
379
      return nil, "data must be a non-empty table"
×
380
    end
381

382
    if is_data(data) then
4 ✔
383
      prepare_data(data)
×
384
    end
385

386
    local templ, err = template_cache(template)
4 ✔
387
    if err then
4 ✔
388
      return nil, err
×
389
    end
390

391
    local function _subst(item)
392
      return _M.clone(templ, function(s)
16 ✔
393
        return s:gsub('%$(%w+)', item)
56 ✔
394
      end)
395
    end
396

397
    if is_data(data) then
4 ✔
398
      return _subst(data)
×
399
    end
400

401
    local list = {}
4 ✔
402
    for _, item in ipairs(data) do
12 ✔
403
      prepare_data(item)
8 ✔
404
      t_insert(list, _subst(item))
8 ✔
405
    end
406

407
    if data.tag then
4 ✔
408
      list = _M.elem(data.tag,list)
×
409
    end
410
    return list
4 ✔
411
  end
412
end
413

414

415
--- Return the first child with a given tag name (non-recursive).
416
-- @param tag the tag name
417
-- @return the child Node found or `nil` if not found
418
function Doc:child_with_name(tag)
8 ✔
419
  for _, child in ipairs(self) do
12 ✔
420
    if child.tag == tag then
12 ✔
421
      return child
4 ✔
422
    end
423
  end
424
end
425

426

427
do
428
  -- @param self document node to traverse
429
  -- @param tag tag-name to look for
430
  -- @param list array table to add the matching ones to
431
  -- @param recurse if truthy, recursively search the node
432
  local function _children_with_name(self, tag, list, recurse)
433
    -- TODO: protect against recursion
434
    for _, child in ipairs(self) do
324 ✔
435
      if type(child) == 'table' then
184 ✔
436
        if child.tag == tag then
128 ✔
437
          t_insert(list, child)
28 ✔
438
        end
439
        if recurse then
128 ✔
440
          _children_with_name(child, tag, list, recurse)
128 ✔
441
        end
442
      end
443
    end
444
  end
445

446
  --- Returns all elements in a document that have a given tag.
447
  -- @tparam string tag a tag name
448
  -- @tparam[opt=false] boolean dont_recurse optionally only return the immediate children with this tag name
449
  -- @return a list of elements found, list will be empty if none was found.
450
  function Doc:get_elements_with_name(tag, dont_recurse)
8 ✔
451
    local res = {}
12 ✔
452
    _children_with_name(self, tag, res, not dont_recurse)
12 ✔
453
    return res
12 ✔
454
  end
455
end
456

457

458

459
--- Iterator over all children of a document node, including text nodes.
460
-- This function is not recursive, so returns only direct child nodes.
461
-- @return iterator that returns a single Node per iteration.
462
function Doc:children()
8 ✔
463
  local i = 0;
8 ✔
464
  return function (a)
465
    i = i + 1
20 ✔
466
    return a[i];
20 ✔
467
  end, self, i;
8 ✔
468
end
469

470

471
--- Return the first child element of a node, if it exists.
472
-- This will skip text nodes.
473
-- @return first child Node or `nil` if there is none.
474
function Doc:first_childtag()
8 ✔
475
  if #self == 0 then
8 ✔
476
    return
×
477
  end
478
  for _, t in ipairs(self) do
20 ✔
479
    if is_tag(t) then
16 ✔
480
      return t
4 ✔
481
    end
482
  end
483
end
484

485

486
--- Iterator that matches tag names, and a namespace (non-recursive).
487
-- @tparam[opt=nil] string tag tag names to return. Returns all tags if not provided.
488
-- @tparam[opt=nil] string xmlns the namespace value ('xmlns' attribute) to return. If not
489
-- provided will match all namespaces.
490
-- @return iterator that returns a single Node per iteration.
491
function Doc:matching_tags(tag, xmlns)
8 ✔
492
  -- TODO: this doesn't make sense??? namespaces are not "xmnls", as matched below
493
  -- but "xmlns:name"... so should be a string-prefix match if anything...
494
  xmlns = xmlns or self.attr.xmlns;
495
  local tags = self
×
496
  local next_i = 1
×
497
  local max_i = #tags
×
498
  local node
499
  return function ()
500
      for i = next_i, max_i do
×
501
        node = tags[i];
502
        if (not tag or node.tag == tag) and
×
503
           (not xmlns or xmlns == node.attr.xmlns) then
×
504
          next_i = i + 1
×
505
          return node
×
506
        end
507
      end
508
    end, tags, next_i
×
509
end
510

511

512
--- Iterator over all child tags of a document node. This will skip over
513
-- text nodes.
514
-- @return iterator that returns a single Node per iteration.
515
function Doc:childtags()
8 ✔
516
  local i = 0;
12 ✔
517
  return function (a)
518
    local v
519
      repeat
520
        i = i + 1
32 ✔
521
        v = self[i]
32 ✔
522
        if v and type(v) == 'table' then
32 ✔
523
          return v
20 ✔
524
        end
525
      until not v
12 ✔
526
    end, self[1], i;
16 ✔
527
end
528

529

530
--- Visit child Nodes of a node and call a function, possibly modifying the document.
531
-- Text elements will be skipped.
532
-- This is not recursive, so only direct children will be passed.
533
-- @tparam function callback a function with signature `function(node)`, passed the node.
534
-- The element will be updated with the returned value, or deleted if it returns `nil`.
535
function Doc:maptags(callback)
8 ✔
536
  local i = 1;
8 ✔
537

538
  while i <= #self do
48 ✔
539
    if is_tag(self[i]) then
40 ✔
540
      local ret = callback(self[i]);
24 ✔
541
      if ret == nil then
24 ✔
542
        -- remove it
543
        t_remove(self, i);
12 ✔
544

545
      else
546
        -- update it
547
        self[i] = ret;
12 ✔
548
        i = i + 1;
12 ✔
549
      end
550
    else
551
      i = i + 1
16 ✔
552
    end
553
  end
554

555
  return self;
8 ✔
556
end
557

558

559
do
560
  local escape_table = {
8 ✔
561
    ["'"] = "&apos;",
8 ✔
562
    ['"'] = "&quot;",
8 ✔
563
    ["<"] = "&lt;",
8 ✔
564
    [">"] = "&gt;",
8 ✔
565
    ["&"] = "&amp;",
8 ✔
566
  }
567

568
  --- Escapes a string for safe use in xml.
569
  -- Handles quotes(single+double), less-than, greater-than, and ampersand.
570
  -- @tparam string str string value to escape
571
  -- @return escaped string
572
  -- @usage
573
  -- local esc = xml.xml_escape([["'<>&]])  --> "&quot;&apos;&lt;&gt;&amp;"
574
  function _M.xml_escape(str)
8 ✔
575
    return (s_gsub(str, "['&<>\"]", escape_table))
332 ✔
576
  end
577
end
578
local xml_escape = _M.xml_escape
8 ✔
579

580
do
581
  local escape_table = {
8 ✔
582
    quot = '"',
8 ✔
583
    apos = "'",
8 ✔
584
    lt = "<",
8 ✔
585
    gt = ">",
8 ✔
586
    amp = "&",
8 ✔
587
  }
588

589
  --- Unescapes a string from xml.
590
  -- Handles quotes(single+double), less-than, greater-than, and ampersand.
591
  -- @tparam string str string value to unescape
592
  -- @return unescaped string
593
  -- @usage
594
  -- local unesc = xml.xml_escape("&quot;&apos;&lt;&gt;&amp;")  --> [["'<>&]]
595
  function _M.xml_unescape(str)
8 ✔
596
    return (str:gsub( "&(%a+);", escape_table))
640 ✔
597
  end
598
end
599
local xml_unescape = _M.xml_unescape
8 ✔
600

601
-- pretty printing
602
-- if indent, then put each new tag on its own line
603
-- if attr_indent, put each new attribute on its own line
604
local function _dostring(t, buf, parentns, block_indent, tag_indent, attr_indent)
605
  local nsid = 0
592 ✔
606
  local tag = t.tag
592 ✔
607

608
  local lf = ""
592 ✔
609
  if tag_indent then
592 ✔
610
    lf = '\n'..block_indent
72 ✔
611
  end
612

613
  local alf = " "
592 ✔
614
  if attr_indent then
592 ✔
615
    alf = '\n'..block_indent..attr_indent
×
616
  end
617

618
  t_insert(buf, lf.."<"..tag)
592 ✔
619

620
  local function write_attr(k,v)
621
    if s_find(k, "\1", 1, true) then
128 ✔
622
      nsid = nsid + 1
×
623
      local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$")
×
624
      t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'")
×
625

626
    elseif not (k == "xmlns" and v == parentns) then
128 ✔
627
      t_insert(buf, alf..k.."='"..xml_escape(v).."'");
128 ✔
628
    end
629
  end
630

631
  -- it's useful for testing to have predictable attribute ordering, if available
632
  if #t.attr > 0 then
592 ✔
633
    -- TODO: the key-value list is leading, what if they are not in-sync
634
    for _,k in ipairs(t.attr) do
72 ✔
635
      write_attr(k,t.attr[k])
40 ✔
636
    end
637
  else
638
    for k, v in pairs(t.attr) do
648 ✔
639
      write_attr(k,v)
88 ✔
640
    end
641
  end
642

643
  local len = #t
592 ✔
644
  local has_children
645

646
  if len == 0 then
592 ✔
647
    t_insert(buf, attr_indent and '\n'..block_indent.."/>" or "/>")
256 ✔
648

649
  else
650
    t_insert(buf, ">");
336 ✔
651

652
    for n = 1, len do
892 ✔
653
      local child = t[n]
556 ✔
654

655
      if child.tag then
556 ✔
656
        has_children = true
356 ✔
657
        _dostring(child, buf, t.attr.xmlns, block_indent and block_indent..tag_indent, tag_indent, attr_indent)
356 ✔
658

659
      else
660
        -- text element
661
        t_insert(buf, xml_escape(child))
200 ✔
662
      end
663
    end
664

665
    t_insert(buf, (has_children and lf or '').."</"..tag..">");
336 ✔
666
  end
667
end
668

669
--- Function to pretty-print an XML document.
670
-- @param doc an XML document
671
-- @tparam[opt] string|int b_ind an initial block-indent (required when `t_ind` is set)
672
-- @tparam[opt] string|int t_ind an tag-indent for each level (required when `a_ind` is set)
673
-- @tparam[opt] string|int a_ind if given, indent each attribute pair and put on a separate line
674
-- @tparam[opt] string|bool xml_preface force prefacing with default or custom <?xml...>, if truthy then `&lt;?xml version='1.0'?&gt;` will be used as default.
675
-- @return a string representation
676
-- @see Doc:tostring
677
function _M.tostring(doc, b_ind, t_ind, a_ind, xml_preface)
8 ✔
678
  local buf = {}
236 ✔
679

680
  if type(b_ind) == "number" then b_ind = (" "):rep(b_ind) end
236 ✔
681
  if type(t_ind) == "number" then t_ind = (" "):rep(t_ind) end
236 ✔
682
  if type(a_ind) == "number" then a_ind = (" "):rep(a_ind) end
236 ✔
683

684
  if xml_preface then
236 ✔
685
    if type(xml_preface) == "string" then
4 ✔
686
      buf[1] = xml_preface
×
687
    else
688
      buf[1] = "<?xml version='1.0'?>"
4 ✔
689
    end
690
  end
691

692
  _dostring(doc, buf, nil, b_ind, t_ind, a_ind, xml_preface)
236 ✔
693

694
  return t_concat(buf)
236 ✔
695
end
696

697

698
Doc.__tostring = _M.tostring
8 ✔
699

700

701
--- Method to pretty-print an XML document.
702
-- Invokes `xml.tostring`.
703
-- @tparam[opt] string|int b_ind an initial indent (required when `t_ind` is set)
704
-- @tparam[opt] string|int t_ind an indent for each level (required when `a_ind` is set)
705
-- @tparam[opt] string|int a_ind if given, indent each attribute pair and put on a separate line
706
-- @tparam[opt="&lt;?xml version='1.0'?&gt;"] string xml_preface force prefacing with default or custom <?xml...>
707
-- @return a string representation
708
-- @see xml.tostring
709
function Doc:tostring(b_ind, t_ind, a_ind, xml_preface)
8 ✔
710
  return _M.tostring(self, b_ind, t_ind, a_ind, xml_preface)
152 ✔
711
end
712

713

714
--- get the full text value of an element.
715
-- @return a single string with all text elements concatenated
716
-- @usage
717
-- local doc = xml.new("main")
718
-- doc:text("one")
719
-- doc:add_child(xml.elem "two")
720
-- doc:text("three")
721
--
722
-- local t = doc:get_text()    -->  "onethree"
723
function Doc:get_text()
8 ✔
724
  local res = {}
36 ✔
725
  for i,el in ipairs(self) do
80 ✔
726
    if is_text(el) then t_insert(res,el) end
44 ✔
727
  end
728
  return t_concat(res);
36 ✔
729
end
730

731

732
do
733
  local function _copy(object, kind, parent, strsubst, lookup_table)
734
    if type(object) ~= "table" then
256 ✔
735
      if strsubst and is_text(object) then
156 ✔
736
        return strsubst(object, kind, parent)
88 ✔
737
      else
738
        return object
68 ✔
739
      end
740
    end
741

742
    if lookup_table[object] then
100 ✔
743
      error("recursion detected")
4 ✔
744
    end
745
    lookup_table[object] = true
96 ✔
746

747
    local new_table = {}
96 ✔
748
    lookup_table[object] = new_table
96 ✔
749

750
    local tag = object.tag
96 ✔
751
    new_table.tag = _copy(tag, '*TAG', parent, strsubst, lookup_table)
96 ✔
752

753
    if object.attr then
96 ✔
754
      local res = {}
96 ✔
755
      for attr, value in pairs(object.attr) do
136 ✔
756
        if type(attr) == "string" then
40 ✔
757
          res[attr] = _copy(value, attr, object, strsubst, lookup_table)
20 ✔
758
        end
759
      end
760
      new_table.attr = res
96 ✔
761
    end
762

763
    for index = 1, #object do
208 ✔
764
      local v = _copy(object[index], '*TEXT', object, strsubst, lookup_table)
116 ✔
765
      t_insert(new_table,v)
112 ✔
766
    end
767

768
    return setmetatable(new_table, getmetatable(object))
92 ✔
769
  end
770

771
  --- Returns a copy of a document.
772
  -- The `strsubst` parameter is a callback with signature `function(object, kind, parent)`.
773
  --
774
  -- Param `kind` has the following values, and parameters:
775
  --
776
  -- - `"*TAG"`: `object` is the tag-name, `parent` is the Node object. Returns the new tag name.
777
  --
778
  -- - `"*TEXT"`: `object` is the text-element, `parent` is the Node object. Returns the new text value.
779
  --
780
  -- - other strings not prefixed with `*`: `kind` is the attribute name, `object` is the
781
  --   attribute value, `parent` is the Node object. Returns the new attribute value.
782
  --
783
  -- @tparam Node|string doc a Node object or string (text node)
784
  -- @tparam[opt] function strsubst an optional function for handling string copying
785
  -- which could do substitution, etc.
786
  -- @return copy of the document
787
  -- @see Doc:filter
788
  function _M.clone(doc, strsubst)
8 ✔
789
    return _copy(doc, nil, nil, strsubst, {})
24 ✔
790
  end
791
end
792

793

794
--- Returns a copy of a document.
795
-- This is the method version of `xml.clone`.
796
-- @see xml.clone
797
-- @name Doc:filter
798
-- @tparam[opt] function strsubst an optional function for handling string copying
799
Doc.filter = _M.clone -- also available as method
8 ✔
800

801
do
802
  local function _compare(t1, t2, recurse_check)
803

804
    local ty1 = type(t1)
232 ✔
805
    local ty2 = type(t2)
232 ✔
806

807
    if ty1 ~= ty2 then
232 ✔
808
      return false, 'type mismatch'
8 ✔
809
    end
810

811
    if ty1 == 'string' then
224 ✔
812
      if t1 == t2 then
52 ✔
813
        return true
48 ✔
814
      else
815
        return false, 'text '..t1..' ~= text '..t2
4 ✔
816
      end
817
    end
818

819
    if ty1 ~= 'table' or ty2 ~= 'table' then
172 ✔
820
      return false, 'not a document'
4 ✔
821
    end
822

823
    if recurse_check[t1] then
168 ✔
824
      return false, "recursive document"
4 ✔
825
    end
826
    recurse_check[t1] = true
164 ✔
827

828
    if t1.tag ~= t2.tag then
164 ✔
829
      return false, 'tag  '..t1.tag..' ~= tag '..t2.tag
4 ✔
830
    end
831

832
    if #t1 ~= #t2 then
160 ✔
833
      return false, 'size '..#t1..' ~= size '..#t2..' for tag '..t1.tag
4 ✔
834
    end
835

836
    -- compare attributes
837
    for k,v in pairs(t1.attr) do
239 ✔
838
      local t2_value = t2.attr[k]
91 ✔
839
      if type(k) == "string" then
91 ✔
840
        if t2_value ~= v then return false, 'mismatch attrib' end
59 ✔
841
      else
842
        if t2_value ~= nil and t2_value ~= v then return false, "mismatch attrib order" end
32 ✔
843
      end
844
    end
845
    for k,v in pairs(t2.attr) do
216 ✔
846
      local t1_value = t1.attr[k]
72 ✔
847
      if type(k) == "string" then
72 ✔
848
        if t1_value ~= v then return false, 'mismatch attrib' end
52 ✔
849
      else
850
        if t1_value ~= nil and t1_value ~= v then return false, "mismatch attrib order" end
20 ✔
851
      end
852
    end
853

854
    -- compare children
855
    for i = 1, #t1 do
300 ✔
856
      local ok, err = _compare(t1[i], t2[i], recurse_check)
168 ✔
857
      if not ok then
168 ✔
858
        return ok, err
12 ✔
859
      end
860
    end
861
    return true
132 ✔
862
  end
863

864
  --- Compare two documents or elements.
865
  -- Equality is based on tag, child nodes (text and tags), attributes and order
866
  -- of those (order only fails if both are given, and not equal).
867
  -- @tparam Node|string t1 a Node object or string (text node)
868
  -- @tparam Node|string t2 a Node object or string (text node)
869
  -- @treturn boolean `true` when the Nodes are equal.
870
  function _M.compare(t1,t2)
8 ✔
871
    return _compare(t1, t2, {})
64 ✔
872
  end
873
end
874

875

876
--- is this value a document element?
877
-- @param d any value
878
-- @treturn boolean `true` if it is a `table` with property `tag` being a string value.
879
-- @name is_tag
880
_M.is_tag = is_tag
8 ✔
881

882

883
do
884
  local function _walk(doc, depth_first, operation, recurse_check)
885
    if not depth_first then operation(doc.tag, doc) end
260 ✔
886
    for _,d in ipairs(doc) do
556 ✔
887
      if is_tag(d) then
304 ✔
888
        assert(not recurse_check[d], "recursion detected")
204 ✔
889
        recurse_check[d] = true
200 ✔
890
        _walk(d, depth_first, operation, recurse_check)
200 ✔
891
      end
892
    end
893
    if depth_first then operation(doc.tag, doc) end
252 ✔
894
  end
895

896
  --- Calls a function recursively over Nodes in the document.
897
  -- Will only call on tags, it will skip text nodes.
898
  -- The function signature for `operation` is `function(tag_name, Node)`.
899
  -- @tparam Node|string doc a Node object or string (text node)
900
  -- @tparam boolean depth_first visit child nodes first, then the current node
901
  -- @tparam function operation a function which will receive the current tag name and current node.
902
  function _M.walk(doc, depth_first, operation)
8 ✔
903
    return _walk(doc, depth_first, operation, {})
60 ✔
904
  end
905
end
906

907

908
local html_empty_elements = { --lists all HTML empty (void) elements
8 ✔
909
    br      = true,
8 ✔
910
    img     = true,
8 ✔
911
    meta    = true,
8 ✔
912
    frame   = true,
8 ✔
913
    area    = true,
8 ✔
914
    hr      = true,
8 ✔
915
    base    = true,
8 ✔
916
    col     = true,
8 ✔
917
    link    = true,
8 ✔
918
    input   = true,
8 ✔
919
    option  = true,
8 ✔
920
    param   = true,
8 ✔
921
    isindex = true,
8 ✔
922
    embed = true,
8 ✔
923
}
924

925
--- Parse a well-formed HTML file as a string.
926
-- Tags are case-insensitive, DOCTYPE is ignored, and empty elements can be .. empty.
927
-- @param s the HTML
928
function _M.parsehtml(s)
8 ✔
929
    return _M.basic_parse(s,false,true)
12 ✔
930
end
931

932
--- Parse a simple XML document using a pure Lua parser based on Robero Ierusalimschy's original version.
933
-- @param s the XML document to be parsed.
934
-- @param all_text  if true, preserves all whitespace. Otherwise only text containing non-whitespace is included.
935
-- @param html if true, uses relaxed HTML rules for parsing
936
function _M.basic_parse(s, all_text, html)
8 ✔
937
    local stack = {}
96 ✔
938
    local top = {}
96 ✔
939

940
    local function parseargs(s)
941
      local arg = {}
680 ✔
942
      s:gsub("([%w:%-_]+)%s*=%s*([\"'])(.-)%2", function (w, _, a)
1,360 ✔
943
        if html then w = w:lower() end
356 ✔
944
        arg[w] = xml_unescape(a)
356 ✔
945
      end)
946
      if html then
680 ✔
947
        s:gsub("([%w:%-_]+)%s*=%s*([^\"']+)%s*", function (w, a)
96 ✔
948
          w = w:lower()
8 ✔
949
          arg[w] = xml_unescape(a)
8 ✔
950
        end)
951
      end
952
      return arg
680 ✔
953
    end
954

955
    t_insert(stack, top)
96 ✔
956
    local ni,c,label,xarg, empty, _, istart
957
    local i = 1
96 ✔
958
    local j
959
    -- we're not interested in <?xml version="1.0"?>
960
    _,istart = s_find(s,'^%s*<%?[^%?]+%?>%s*')
96 ✔
961
    if not istart then -- or <!DOCTYPE ...>
96 ✔
962
        _,istart = s_find(s,'^%s*<!DOCTYPE.->%s*')
92 ✔
963
    end
964
    if istart then i = istart+1 end
96 ✔
965
    while true do
966
        ni,j,c,label,xarg, empty = s_find(s, "<([%/!]?)([%w:%-_]+)(.-)(%/?)>", i)
1,240 ✔
967
        if not ni then break end
1,240 ✔
968
        if c == "!" then -- comment
1,144 ✔
969
            -- case where there's no space inside comment
970
            if not (label:match '%-%-$' and xarg == '') then
8 ✔
971
                if xarg:match '%-%-$' then -- we've grabbed it all
8 ✔
972
                    j = j - 2
4 ✔
973
                end
974
                -- match end of comment
975
                _,j = s_find(s, "-->", j, true)
8 ✔
976
            end
977
        else
978
            local text = s_sub(s, i, ni-1)
1,136 ✔
979
            if html then
1,136 ✔
980
                label = label:lower()
88 ✔
981
                if html_empty_elements[label] then empty = "/" end
88 ✔
982
            end
983
            if all_text or not s_find(text, "^%s*$") then
1,136 ✔
984
                t_insert(top, xml_unescape(text))
272 ✔
985
            end
986
            if empty == "/" then  -- empty element tag
1,136 ✔
987
                t_insert(top, setmetatable({tag=label, attr=parseargs(xarg), empty=1},Doc))
224 ✔
988
            elseif c == "" then   -- start tag
912 ✔
989
                top = setmetatable({tag=label, attr=parseargs(xarg)},Doc)
456 ✔
990
                t_insert(stack, top)   -- new level
456 ✔
991
            else  -- end tag
992
                local toclose = t_remove(stack)  -- remove top
456 ✔
993
                top = stack[#stack]
456 ✔
994
                if #stack < 1 then
456 ✔
995
                    error("nothing to close with "..label..':'..text)
×
996
                end
997
                if toclose.tag ~= label then
456 ✔
998
                    error("trying to close "..toclose.tag.." with "..label.." "..text)
×
999
                end
1000
                t_insert(top, toclose)
456 ✔
1001
            end
1002
        end
1003
        i = j+1
1,144 ✔
1004
    end
1005
    local text = s_sub(s, i)
96 ✔
1006
    if all_text or  not s_find(text, "^%s*$") then
96 ✔
1007
        t_insert(stack[#stack], xml_unescape(text))
×
1008
    end
1009
    if #stack > 1 then
96 ✔
1010
        error("unclosed "..stack[#stack].tag)
×
1011
    end
1012
    local res = stack[1]
96 ✔
1013
    return is_text(res[1]) and res[2] or res[1]
96 ✔
1014
end
1015

1016
do
1017
  local match do
8 ✔
1018

1019
    local function empty(attr) return not attr or not next(attr) end
756 ✔
1020

1021
    local append_capture do
8 ✔
1022
      -- returns the key,value pair from a table if it has exactly one entry
1023
      local function has_one_element(t)
1024
          local key,value = next(t)
144 ✔
1025
          if next(t,key) ~= nil then return false end
144 ✔
1026
          return key,value
88 ✔
1027
      end
1028

1029
      function append_capture(res,tbl)
6 ✔
1030
          if not empty(tbl) then -- no point in capturing empty tables...
144 ✔
1031
              local key
1032
              if tbl._ then  -- if $_ was set then it is meant as the top-level key for the captured table
144 ✔
1033
                  key = tbl._
88 ✔
1034
                  tbl._ = nil
88 ✔
1035
                  if empty(tbl) then return end
88 ✔
1036
              end
1037
              -- a table with only one pair {[0]=value} shall be reduced to that value
1038
              local numkey,val = has_one_element(tbl)
144 ✔
1039
              if numkey == 0 then tbl = val end
144 ✔
1040
              if key then
144 ✔
1041
                  res[key] = tbl
88 ✔
1042
              else -- otherwise, we append the captured table
1043
                  t_insert(res,tbl)
56 ✔
1044
              end
1045
          end
1046
      end
1047
    end
1048

1049
    local function make_number(pat)
1050
        if pat:find '^%d+$' then -- $1 etc means use this as an array location
348 ✔
1051
            pat = tonumber(pat)
136 ✔
1052
        end
1053
        return pat
348 ✔
1054
    end
1055

1056
    local function capture_attrib(res,pat,value)
1057
        pat = make_number(pat:sub(2))
288 ✔
1058
        res[pat] = value
288 ✔
1059
        return true
288 ✔
1060
    end
1061

1062
    function match(d,pat,res,keep_going)
6 ✔
1063
        local ret = true
740 ✔
1064
        if d == nil then d = '' end --return false end
740 ✔
1065
        -- attribute string matching is straight equality, except if the pattern is a $ capture,
1066
        -- which always succeeds.
1067
        if is_text(d) then
740 ✔
1068
            if not is_text(pat) then return false end
312 ✔
1069
            if _M.debug then print(d,pat) end
312 ✔
1070
            if pat:find '^%$' then
312 ✔
1071
                return capture_attrib(res,pat,d)
288 ✔
1072
            else
1073
                return d == pat
24 ✔
1074
            end
1075
        else
1076
        if _M.debug then print(d.tag,pat.tag) end
428 ✔
1077
            -- this is an element node. For a match to succeed, the attributes must
1078
            -- match as well.
1079
            -- a tagname in the pattern ending with '-' is a wildcard and matches like an attribute
1080
            local tagpat = pat.tag:match '^(.-)%-$'
428 ✔
1081
            if tagpat then
428 ✔
1082
                tagpat = make_number(tagpat)
60 ✔
1083
                res[tagpat] = d.tag
60 ✔
1084
            end
1085
            if d.tag == pat.tag or tagpat then
428 ✔
1086

1087
                if not empty(pat.attr) then
372 ✔
1088
                    if empty(d.attr) then ret =  false
144 ✔
1089
                    else
1090
                        for prop,pval in pairs(pat.attr) do
328 ✔
1091
                            local dval = d.attr[prop]
184 ✔
1092
                            if not match(dval,pval,res) then ret = false;  break end
184 ✔
1093
                        end
1094
                    end
1095
                end
1096
                -- the pattern may have child nodes. We match partially, so that {P1,P2} shall match {X,P1,X,X,P2,..}
1097
                if ret and #pat > 0 then
372 ✔
1098
                    local i,j = 1,1
260 ✔
1099
                    local function next_elem()
1100
                        j = j + 1  -- next child element of data
544 ✔
1101
                        if is_text(d[j]) then j = j + 1 end
544 ✔
1102
                        return j <= #d
544 ✔
1103
                    end
1104
                    repeat
1105
                        local p = pat[i]
392 ✔
1106
                        -- repeated {{<...>}} patterns  shall match one or more elements
1107
                        -- so e.g. {P+} will match {X,X,P,P,X,P,X,X,X}
1108
                        if is_tag(p) and p.repeated then
392 ✔
1109
                            local found
1110
                            repeat
1111
                                local tbl = {}
152 ✔
1112
                                ret = match(d[j],p,tbl,false)
152 ✔
1113
                                if ret then
152 ✔
1114
                                    found = false --true
144 ✔
1115
                                    append_capture(res,tbl)
144 ✔
1116
                                end
1117
                            until not next_elem() or (found and not ret)
152 ✔
1118
                            i = i + 1
40 ✔
1119
                        else
1120
                            ret = match(d[j],p,res,false)
352 ✔
1121
                            if ret then i = i + 1 end
352 ✔
1122
                        end
1123
                    until not next_elem() or i > #pat -- run out of elements or patterns to match
392 ✔
1124
                    -- if every element in our pattern matched ok, then it's been a successful match
1125
                    if i > #pat then return true end
260 ✔
1126
                end
1127
                if ret then return true end
156 ✔
1128
            else
1129
                ret = false
56 ✔
1130
            end
1131
            -- keep going anyway - look at the children!
1132
            if keep_going then
100 ✔
1133
                for child in d:childtags() do
8 ✔
1134
                    ret = match(child,pat,res,keep_going)
8 ✔
1135
                    if ret then break end
8 ✔
1136
                end
1137
            end
1138
        end
1139
        return ret
100 ✔
1140
    end
1141
  end
1142

1143
  --- does something...
1144
  function Doc:match(pat)
8 ✔
1145
      local err
1146
      pat,err = template_cache(pat)
44 ✔
1147
      if not pat then return nil, err end
44 ✔
1148
      _M.walk(pat,false,function(_,d)
88 ✔
1149
          if is_text(d[1]) and is_tag(d[2]) and is_text(d[3]) and
148 ✔
1150
            d[1]:find '%s*{{' and d[3]:find '}}%s*' then
40 ✔
1151
            t_remove(d,1)
40 ✔
1152
            t_remove(d,2)
40 ✔
1153
            d[1].repeated = true
40 ✔
1154
          end
1155
      end)
1156

1157
      local res = {}
44 ✔
1158
      local ret = match(self,pat,res,true)
44 ✔
1159
      return res,ret
44 ✔
1160
  end
1161
end
1162

1163

1164
return _M
8 ✔
1165

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc