Comparison

util/stanza.lua @ 10717:05e4645fc9b3

util.stanza: Add method returning stanza with added indentation Adds indentation and line breaks to stanzas, to make stanzas easier to read for humans.
author Kim Alvefur <zash@zash.se>
date Sun, 12 Apr 2020 17:03:05 +0200
parent 10503:e25a1a9a6e7e
child 11082:c26599a78fae
comparison
equal deleted inserted replaced
10716:29575fe64860 10717:05e4645fc9b3
509 -- Sorry, fresh out of colours for you guys ;) 509 -- Sorry, fresh out of colours for you guys ;)
510 stanza_mt.pretty_print = stanza_mt.__tostring; 510 stanza_mt.pretty_print = stanza_mt.__tostring;
511 stanza_mt.pretty_top_tag = stanza_mt.top_tag; 511 stanza_mt.pretty_top_tag = stanza_mt.top_tag;
512 end 512 end
513 513
514 function stanza_mt.indent(t, level, indent)
515 if #t == 0 or (#t == 1 and type(t[1]) == "string") then
516 -- Empty nodes wouldn't have any indentation
517 -- Text-only nodes are preserved as to not alter the text content
518 -- Optimization: Skip clone of these since we don't alter them
519 return t;
520 end
521
522 indent = indent or "\t";
523 level = level or 1;
524 local tag = clone(t, true);
525
526 for child in t:children() do
527 if type(child) == "string" then
528 -- Already indented text would look weird but let's ignore that for now.
529 if child:find("%S") then
530 tag:text("\n" .. indent:rep(level));
531 tag:text(child);
532 end
533 elseif is_stanza(child) then
534 tag:text("\n" .. indent:rep(level));
535 tag:add_direct_child(child:indent(level+1, indent));
536 end
537 end
538 -- before the closing tag
539 tag:text("\n" .. indent:rep((level-1)));
540
541 return tag;
542 end
543
514 return { 544 return {
515 stanza_mt = stanza_mt; 545 stanza_mt = stanza_mt;
516 stanza = new_stanza; 546 stanza = new_stanza;
517 is_stanza = is_stanza; 547 is_stanza = is_stanza;
518 preserialize = preserialize; 548 preserialize = preserialize;