Debian Codegraph @

texmf-dist/tex/luatex/luaxml/luaxml-domobject.lua

raw
1 --- DOM module for LuaXML
2 -- @module luaxml-domobject
3 -- @author Michal Hoftich <[email protected]
4 local dom = {}
5
6 local xml
7 local handler
8 local css_query
9 local html
10 if kpse then
11 xml = require("luaxml-mod-xml")
12 handler = require("luaxml-mod-handler")
13 css_query = require("luaxml-cssquery")
14 html = require("luaxml-mod-html")
15 else
16 xml = require("luaxml.mod-xml")
17 handler = require("luaxml.mod-handler")
18 css_query = require("luaxml.cssquery")
19 html = require("luaxml.mod-html")
20 end
21
22 local HtmlParser = html.HtmlParser
23
24 local void = {area = true, base = true, br = true, col = true, hr = true, img = true, input = true, link = true, meta = true, param = true}
25
26 -- support also upper case names
27 for k,v in pairs(void) do void[string.upper(k)] = true end
28
29 local escapes = {
30 [">"] = "&gt;",
31 ["<"] = "&lt;",
32 ["&"] = "&amp;",
33 ['"'] = "&quot;",
34 ["'"] = "&#39;",
35 ["`"] = "&#x60;"
36 }
37
38 -- declarations of local functions
39 local html_to_dom
40 local html_parse
41 local parse
42
43
44
45 local function escape(search, text)
46 return text:gsub(search, function(ch)
47 return escapes[ch] or ""
48 end)
49 end
50
51 local function escape_element(text)
52 return escape("([<>&])", text)
53 end
54
55 local function escape_attr(text)
56 return escape("([<>&\"'`])", text)
57 end
58
59 local actions = {
60 TEXT = {text = "%s"},
61 COMMENT = {start = "<!-- ", text = "%s", stop = " -->"},
62 ELEMENT = {start = "<%s%s>", stop = "</%s>", void = "<%s%s />"},
63 DECL = {start = "<?%s %s?>"},
64 PI = {start = "<?%s %s?>"},
65 DTD = {start = "<!DOCTYPE ", text = "%s" , stop=">"},
66 CDATA = {start = "<![CDATA[", text = "%s", stop ="]]>"}
67
68 }
69
70 --- It serializes the DOM object back to the XML.
71 -- This function is mainly used for internal purposes, it is better to
72 -- use the `DOM_Object:serialize()`.
73 -- @param parser DOM object
74 -- @param current Element which should be serialized
75 -- @param level
76 -- @param output
77 -- @return table Table with XML strings. It can be concenated using table.concat() function to get XML string corresponding to the DOM_Object.
78 local function serialize_dom(parser, current,level, output)
79 local output = output or {}
80 local function get_action(typ, action)
81 local ac = actions[typ] or {}
82 local format = ac[action] or ""
83 return format
84 end
85 local function insert(format, ...)
86 table.insert(output, string.format(format, ...))
87 end
88 local function prepare_attributes(attr)
89 local t = {}
90 local attr = attr or {}
91 for k, v in pairs(attr) do
92 t[#t+1] = string.format("%s='%s'", k, escape_attr(v))
93 end
94 -- sort attributes alphabetically. this will ensure that
95 -- their order will not change between several executions of dom:serialize()
96 table.sort(t)
97 if #t == 0 then return "" end
98 -- add space before attributes
99 return " " .. table.concat(t, " ")
100 end
101 local function start(typ, el, attr)
102 local format = get_action(typ, "start")
103 insert(format, el, prepare_attributes(attr))
104 end
105 local function text(typ, text, parent)
106 local parent = parent or {}
107 local format = get_action(typ, "text")
108 if parent.verbatim then
109 insert(format, text)
110 else
111 insert(format, escape_element(text))
112 end
113 end
114 local function stop(typ, el)
115 local format = get_action(typ, "stop")
116 insert(format,el)
117 end
118 local level = level or 0
119 local spaces = string.rep(" ",level)
120 local root= current or parser._handler.root
121 local name = root._name or "unnamed"
122 local xtype = root._type or "untyped"
123 local text_content = root._text or ""
124 local attributes = root._attr or {}
125 -- if xtype == "TEXT" then
126 -- print(spaces .."TEXT : " .. root._text)
127 -- elseif xtype == "COMMENT" then
128 -- print(spaces .. "Comment : ".. root._text)
129 -- else
130 -- print(spaces .. xtype .. " : " .. name)
131 -- end
132 -- for k, v in pairs(attributes) do
133 -- print(spaces .. " ".. k.."="..v)
134 -- end
135 if xtype == "DTD" then
136 text_content = string.format('%s %s "%s" "%s"', name, attributes["_type"] or "", attributes._name, attributes._uri )
137 -- remove unused fields
138 text_content = text_content:gsub('"nil"','')
139 text_content = text_content:gsub('%s*$','')
140 attributes = {}
141 elseif xtype == "ELEMENT" and void[name] and #current._children < 1 then
142 local format = get_action(xtype, "void")
143 insert(format, name, prepare_attributes(attributes))
144 return output
145 elseif xtype == "PI" then
146 -- it contains spurious _text attribute
147 attributes["_text"] = nil
148 elseif xtype == "DECL" and name =="xml" then
149 -- the xml declaration attributes must be in a correct order
150 local encoding = attributes.encoding or "utf-8"
151 insert("<?xml version='%s' encoding='%s' ?>", attributes.version, encoding)
152 return output
153 elseif xtype == "CDATA" then
154 -- return content unescaped
155 insert("<![CDATA[%s]]>", text_content)
156 return output
157 end
158
159 start(xtype, name, attributes)
160 text(xtype,text_content, (current or {})._parent)
161 local children = root._children or {}
162 for _, child in ipairs(children) do
163 output = serialize_dom(parser,child, level + 1, output)
164 end
165 stop(xtype, name)
166 return output
167 end
168
169 --- XML parsing function
170 -- Parse the XML text and create the DOM object.
171 -- @return DOM_Object
172 parse = function(
173 xmltext --- String to be parsed
174 ,voidElements --- hash table with void elements
175 )
176 local domHandler = handler.domHandler()
177 --- @type DOM_Object
178 local DOM_Object = xml.xmlParser(domHandler)
179 -- preserve whitespace
180 DOM_Object.options.stripWS = nil
181 -- don't try to expand entities
182 DOM_Object.options.expandEntities = nil
183 local voidElements = voidElements or void
184 DOM_Object._handler.options.voidElements = voidElements
185 DOM_Object:parse(xmltext)
186 DOM_Object.current = DOM_Object._handler.root
187 DOM_Object.__index = DOM_Object
188 DOM_Object.css_query = css_query()
189
190 local function save_methods(element)
191 setmetatable(element,DOM_Object)
192 local children = element._children or {}
193 for _, x in ipairs(children) do
194 save_methods(x)
195 end
196 end
197 local parser = setmetatable({}, DOM_Object)
198
199 --- Returns root element of the DOM_Object
200 -- @return DOM_Object
201 function DOM_Object:root_node()
202 return self._handler.root
203 end
204
205
206 --- Get current node type
207 -- @param el [optional] node to get the type of
208 function DOM_Object:get_node_type(
209 el --- [optional] element to test
210 )
211 local el = el or self
212 return el._type
213 end
214
215 --- Test if the current node is an element.
216 -- You can pass different element as parameter
217 -- @return boolean
218 function DOM_Object:is_element(
219 el --- [optional] element to test
220 )
221 local el = el or self
222 return self:get_node_type(el) == "ELEMENT" -- @bool
223 end
224
225
226 --- Test if current node is text
227 -- @return boolean
228 function DOM_Object:is_text(
229 el --- [optional] element to test
230 )
231 local el = el or self
232 return self:get_node_type(el) == "TEXT"
233 end
234
235 local lower = string.lower
236
237 --- Return name of the current element
238 -- @return string
239 function DOM_Object:get_element_name(
240 el --- [optional] element to test
241 )
242 local el = el or self
243 return el._name or "unnamed"
244 end
245
246 --- Get value of an attribute
247 -- @return string
248 function DOM_Object:get_attribute(
249 name --- Attribute name
250 )
251 local el = self
252 if self:is_element(el) then
253 local attr = el._attr or {}
254 return attr[name]
255 end
256 end
257
258 --- Set value of an attribute
259 -- @return boolean
260 function DOM_Object:set_attribute(
261 name --- Attribute name
262 , value --- Value to be set
263 )
264 local el = self
265 if self:is_element(el) then
266 el._attr = el._attr or {}
267 el._attr[name] = value
268 return true
269 end
270 end
271
272
273 --- Serialize the current node back to XML
274 -- @return string
275 function DOM_Object:serialize(
276 current --- [optional] element to be serialized
277 )
278 local current = current
279 -- if no current element is added and self is not plain parser object
280 -- (_type is then nil), use the current object as serialized root
281 if not current and self._type then
282 current = self
283 end
284 return table.concat(serialize_dom(self, current))
285 end
286
287 --- Get text content from the node and all of it's children
288 -- @return string
289 function DOM_Object:get_text(
290 current --- [optional] element which should be converted to text
291 )
292 local current = current or self
293 local text = {}
294 if current:is_text() then return current._text or "" end
295 for _, el in ipairs(current:get_children()) do
296 if el:is_text() then
297 text[#text+1] = el._text or ""
298 elseif el._type == "CDATA" then
299 text[#text+1] = el._text or ""
300 elseif el:is_element() then
301 text[#text+1] = el:get_text()
302 end
303 end
304 return table.concat(text)
305 end
306
307
308
309 --- Retrieve elements from the given path.
310 -- The path is list of elements separated by space,
311 -- starting from the top element of the current element
312 -- @return table of elements which match the path
313 function DOM_Object:get_path(
314 path --- path to be traversed
315 , current --- [optional] element which should be traversed. Default element is the root element of the DOM_Object
316 )
317 local function traverse_path(path_elements, current, t)
318 local t = t or {}
319 if #path_elements == 0 then
320 -- for _, x in ipairs(current._children or {}) do
321 -- table.insert(t,x)
322 -- end
323 table.insert(t,current)
324 return t
325 end
326 local current_path = table.remove(path_elements, 1)
327 for _, x in ipairs(self:get_children(current)) do
328 if self:is_element(x) then
329 local name = string.lower(self:get_element_name(x))
330 if name == current_path then
331 t = traverse_path(path_elements, x, t)
332 end
333 end
334 end
335 return t
336 end
337 local current = current or self:root_node() -- self._handler.root
338 local path_elements = {}
339 local path = string.lower(path)
340 for el in path:gmatch("([^%s]+)") do table.insert(path_elements, el) end
341 return traverse_path(path_elements, current)
342 end
343
344 --- Select elements chidlren using CSS selector syntax
345 -- @return table with elements matching the selector.
346 function DOM_Object:query_selector(
347 selector --- String using the CSS selector syntax
348 )
349 local css_query = self.css_query
350 local css_parts = css_query:prepare_selector(selector)
351 return css_query:get_selector_path(self, css_parts)
352 end
353
354 --- Get table with children of the current element
355 -- @return table with children of the selected element
356 function DOM_Object:get_children(
357 el --- [optional] element to be selected
358 )
359 local el = el or self
360 local children = el._children or {}
361 return children
362 end
363
364 --- Get the parent element
365 -- @return DOM_Object parent element
366 function DOM_Object:get_parent(
367 el --- [optional] element to be selected
368 )
369 local el = el or self
370 return el._parent
371 end
372
373 --- Execute function on the current element and all it's children nodes.
374 -- The difference to DOM_Object:traverse_elements() is that it executes the function
375 -- also on text nodes and all other kinds of XML nodes.
376 -- The traversing of child elements of a given node can be disabled when the executed
377 -- function returns false.
378 function DOM_Object:traverse(
379 fn, --- function which will be executed on the current element and all it's children
380 current --- [optional] element to be selected
381 )
382 local current = current or self --
383 -- Following situation may happen when this method is called directly on the parsed object
384 if not current:get_node_type() then
385 current = self:root_node()
386 end
387 local status = true
388 local status = fn(current)
389 if current:is_element() or current:get_node_type() == "ROOT" then
390 -- don't traverse child nodes when the user function return false
391 if status ~= false then
392 for _, child in ipairs(current:get_children()) do
393 self:traverse(fn, child)
394 end
395 end
396 end
397 end
398
399 --- Execute function on the current element and all it's children elements.
400 --- The traversing of child elements of a given node can be disabled when the executed
401 -- function returns false.
402 -- @return nothing
403 function DOM_Object:traverse_elements(
404 fn, --- function which will be executed on the current element and all it's children
405 current --- [optional] element to be selected
406 )
407 local current = current or self --
408 current:traverse(function(node)
409 if node:is_element() or node:get_node_type() == "ROOT" then
410 fn(node)
411 end
412 end)
413 end
414
415 --- Get table with the inner text of an element, every text node is a separate table item.
416 --- @return table
417 function DOM_Object:strings(
418 current --- [optional] element to be selected
419 )
420 local strings = {}
421 local current = current or self
422 current:traverse(function(node)
423 if node:get_node_type() == "TEXT" then
424 table.insert(strings, node._text or "")
425 end
426 end)
427 return strings
428 end
429
430 --- Get table with the inner text of an element - leading and trailing spaces are removed and elements that contain only white space are ignored.
431 -- @return table
432 function DOM_Object:stripped_strings(
433 current --- [optional] element to be selected
434 )
435 local current = current or self
436 local strings = current:strings()
437 local cleaned = {}
438 for k,v in ipairs(strings) do
439 v = v:gsub("^%s*", ""):gsub("%s*$", "")
440 if v ~= "" then
441 table.insert(cleaned, v)
442 end
443 end
444 return cleaned
445 end
446
447
448
449
450 --- Execute function on list of elements returned by DOM_Object:get_path()
451 function DOM_Object:traverse_node_list(
452 nodelist --- table with nodes selected by DOM_Object:get_path()
453 , fn --- function to be executed
454 )
455 local nodelist = nodelist or {}
456 for _, node in ipairs(nodelist) do
457 for _, element in ipairs(node._children) do
458 fn(element)
459 end
460 end
461 end
462
463 --- Replace the current node with new one
464 -- @return boolean, message
465 function DOM_Object:replace_node(
466 new --- element which should replace the current element
467 )
468 local old = self
469 local parent = self:get_parent(old)
470 local id,msg = self:find_element_pos( old)
471 if id then
472 parent._children[id] = new
473 return true
474 end
475 return false, msg
476 end
477
478 -- restore correct links to parent elements
479 local function fix_parents(el)
480 for k,v in ipairs(el._children or {}) do
481 if v:is_element() then
482 v._parent = el
483 fix_parents(v)
484 end
485 end
486 end
487
488
489 --- Add child node to the current node
490 function DOM_Object:add_child_node(
491 child, --- element to be inserted as a current node child
492 position --- [optional] position at which should the node be inserted
493 )
494 local parent = self
495 child._parent = parent
496 fix_parents(child)
497 if position then
498 table.insert(parent._children, position, child)
499 else
500 table.insert(parent._children, child)
501 end
502 end
503
504
505 --- Create copy of the current node
506 -- @return DOM_Object element
507 function DOM_Object:copy_node(
508 element --- [optional] element to be copied
509 )
510 local element = element or self
511 local t = {}
512 for k, v in pairs(element) do
513 if type(v) == "table" and (k~="_parent" and k~="__index") then
514 t[k] = self:copy_node(v)
515 else
516 t[k] = v
517 end
518 end
519 save_methods(t)
520 return t
521 end
522
523
524 --- Create a new element
525 -- @return DOM_Object element
526 function DOM_Object:create_element(
527 name, -- New tag name
528 attributes, -- Table with attributes
529 parent -- [optional] element which should be saved as the element's parent
530 )
531 local parent = parent or self
532 local new = {}
533 new._type = "ELEMENT"
534 new._name = name
535 new._attr = attributes or {}
536 new._children = {}
537 new._parent = parent
538 save_methods(new)
539 return new
540 end
541
542 --- Create new text node
543 -- @return DOM_Object text object
544 function DOM_Object:create_text_node(
545 text, -- string
546 parent -- [optional] element which should be saved as the element's parent
547 )
548 local parent = parent or self
549 local new = {}
550 new._type = "TEXT"
551 new._parent = parent
552 new._text = text
553 save_methods(new)
554 return new
555 end
556
557 --- Delete current node
558 function DOM_Object:remove_node(
559 element -- [optional] element to be removed
560 )
561 local element = element or self
562 local parent = self:get_parent(element)
563 local pos = self:find_element_pos(element)
564 -- if pos then table.remove(parent._children, pos) end
565 if pos then
566 -- table.remove(parent._children, pos)
567 parent._children[pos] = setmetatable({_type = "removed"}, DOM_Object)
568 end
569 end
570
571 --- Find the element position in the current node list
572 -- @return integer position of the current element in the element table
573 function DOM_Object:find_element_pos(
574 el -- [optional] element which should be looked up
575 )
576 local el = el or self
577 local parent = self:get_parent(el)
578 if not self:is_element(parent) and self:get_node_type(parent) ~= "ROOT" then return nil, "The parent isn't element" end
579 for i, x in ipairs(parent._children) do
580 if x == el then return i end
581 end
582 return false, "Cannot find element"
583 end
584
585 --- Get node list which current node is part of
586 -- @return table with elements
587 function DOM_Object:get_siblings(
588 el -- [optional] element for which the sibling element list should be retrieved
589 )
590 local el = el or self
591 local parent = el:get_parent()
592 if parent:is_element() then
593 return parent:get_children()
594 end
595 end
596
597 --- Get sibling node of the current node
598 -- @param change Distance from the current node
599 -- @return DOM_Object node
600 function DOM_Object:get_sibling_node( change)
601 local el = self
602 local pos = el:find_element_pos()
603 local siblings = el:get_siblings()
604 if pos and siblings then
605 return siblings[pos + change]
606 end
607 end
608
609 --- Get next node
610 -- @return DOM_Object node
611 function DOM_Object:get_next_node(
612 el --- [optional] node to be used
613 )
614 local el = el or self
615 return el:get_sibling_node(1)
616 end
617
618 --- Get previous node
619 -- @return DOM_Object node
620 function DOM_Object:get_prev_node(
621 el -- [optional] node to be used
622 )
623 local el = el or self
624 return el:get_sibling_node(-1)
625 end
626
627 --- parse string as HTML or XML and return created elements
628 --- @return table elements
629 function DOM_Object:create_template(
630 str,
631 is_xml
632 )
633 -- <> is a dummy element, we just need to wrap everything in some element
634 str = "<>" .. (str or "") .. "</>"
635 local template = is_xml and parse(str) or parse(str)
636 local root = template:root_node()._children[1]
637 return root
638 end
639
640 --- parse string as HTML or XML and insert it as a child of the current node
641 function DOM_Object:inner_html(
642 str, --- HTML or XML to be inserted
643 is_xml --- [optional] Pass true to parse as XML, otherwise parse as HTML
644 )
645 local el = self
646 local root = self:create_template(str, is_xml)
647 -- replace original children of the current element with children of the dummy element created by parsing
648 el._children = root._children
649 return el
650 end
651
652
653 --- parse string as HTML or XML and insert it before current the element
654 function DOM_Object:insert_before_begin(
655 str, --- HTML or XML to be inserted
656 is_xml --- [optional] Pass true to parse as XML, otherwise parse as HTML
657 )
658 local el = self
659 local root = self:create_template(str, is_xml)
660 local parent = el:get_parent()
661 local current_pos = el:find_element_pos()
662 local children = root:get_children()
663 for i = 1, #children do
664 parent:add_child_node(children[i], current_pos + i - 1)
665 end
666 end
667
668 --- parse string as HTML or XML and insert it at the beginning of the current the element
669 function DOM_Object:insert_after_begin(
670 str, --- HTML or XML to be inserted
671 is_xml --- [optional] Pass true to parse as XML, otherwise parse as HTML
672 )
673 local el = self
674 local root = self:create_template(str, is_xml)
675 local children = root:get_children()
676 for i = 1, #children do
677 el:add_child_node(children[i], i)
678 end
679 end
680
681 --- parse string as HTML or XML and insert it at the end of the current the element
682 function DOM_Object:insert_before_end(
683 str, --- HTML or XML to be inserted
684 is_xml --- [optional] Pass true to parse as XML, otherwise parse as HTML
685 )
686 local el = self
687 local root = self:create_template(str, is_xml)
688 local children = root:get_children()
689 for i = 1, #children do
690 el:add_child_node(children[i])
691 end
692 end
693
694 --- parse string as HTML or XML and insert it after current the element
695 function DOM_Object:insert_after_end(
696 str, --- HTML or XML to be inserted
697 is_xml --- [optional] Pass true to parse as XML, otherwise parse as HTML
698 )
699 local el = self
700 local root = self:create_template(str, is_xml)
701 local parent = el:get_parent()
702 local current_pos = el:find_element_pos()
703 local children = root:get_children()
704 for i = 1, #children do
705 parent:add_child_node(children[i], current_pos + i)
706 end
707 end
708
709
710 -- include the methods to all xml nodes
711 save_methods(parser._handler.root)
712 -- parser:
713 return parser, DOM_Object
714 end
715
716 -- table of elements that should be kept without XML escaping in the DOM serialization
717 local verbatim_elements = {script=true, style=true}
718
719 function html_to_dom(html_object)
720 -- convert parsed HTML DOM to the XML DOM
721 local dom, DOM_Object = parse("") -- use empty text to just initialize the DOM object
722 -- use root of the DOM object as the original parent
723 local current_parent = dom._handler.root
724
725 local function create_node(tbl)
726 -- create node suitable for LuaXML DOM object
727 tbl._children = {}
728 -- this should copy methods from the DOM object to the newly created object
729 tbl.__index = DOM_Object
730 return setmetatable(tbl, DOM_Object)
731 end
732
733 local function build_tree(object)
734 -- convert tree produced by the HTML parser to LuaXML DOM
735 local typ = object._type
736 -- process particular node types from the HTML parser
737 if typ == "doctype" then
738 current_parent:add_child_node(create_node {_name=object.name, _type="DTD"})
739 elseif typ == "comment" then
740 current_parent:add_child_node(create_node {_text=object.text, _type="COMMENT"})
741 elseif typ == "element" then
742 local attributes = {}
743 -- convert attributes to the form expected by the DOM object
744 for _, attr in ipairs(object.attr) do
745 attributes[attr.name] = attr.value
746 end
747 local element = current_parent:create_element(object.tag, attributes)
748 -- disable escaping of text in dom:serialize() for <script> or <style> elements
749 if verbatim_elements[string.lower(object.tag)] then element.verbatim = true end
750 current_parent:add_child_node(element)
751 -- set the current element as parent for the processing of children
752 local old_parent = current_parent
753 current_parent = element
754 -- process children
755 for k,v in ipairs(object.children) do
756 build_tree(v)
757 end
758 -- restore original parent
759 current_parent = old_parent
760 elseif typ == "text" then
761 local text = current_parent:create_text_node(object.text)
762 current_parent:add_child_node(text)
763 else
764 -- for other node types, just process the children
765 for k,v in ipairs(object.children) do
766 build_tree(v)
767 end
768 end
769
770 end
771 build_tree(html_object)
772 return dom
773 end
774
775 --- Parse HTML text as a DOM object.
776 -- It supports all methods as the object returned by the parse() function.
777 -- @param html_str string with the HTML code to be parsed
778 -- @return DOM_Object
779 function html_parse(html_str)
780 local html_obj = HtmlParser:init(html_str)
781 local html_dom = html_obj:parse()
782 return html_to_dom(html_dom)
783 end
784
785
786
787 --- @export
788 return {
789 parse = parse,
790 serialize_dom= serialize_dom,
791 html_parse = html_parse
792 }