A platform for community discussion. Free, open, simple.
FIX: Nest sublists that Word emits as siblings of their list item (#42104)
RΓ©gis Hanole5bf97e22edb
diff --git a/lib/html_to_markdown.rb b/lib/html_to_markdown.rbindex ebf4ea2a364..14faf07670c 100644--- a/lib/html_to_markdown.rb+++ b/lib/html_to_markdown.rb@@ -12,6 +12,7 @@ class HtmlToMarkdownremove_not_allowed!(@doc)remove_hidden!(@doc)+ nest_sibling_lists!(@doc)hoist_line_breaks!(@doc)remove_whitespaces!(@doc)end@@ -44,6 +45,15 @@ class HtmlToMarkdown@doc.css("img[height]").each { |n| n.remove if n["height"].to_i <= 0 }end+ def nest_sibling_lists!(doc)+ doc+ .css("ul > ul, ul > ol, ol > ul, ol > ol")+ .each do |list|+ previous = list.previous_element+ previous.add_child(list) if previous&.name == "li"+ end+ end+# When there's a <br> inside an inline element, split the inline element around the <br>def hoist_line_breaks!(doc)klass = "_" + SecureRandom.hex@@ -310,7 +320,8 @@ class HtmlToMarkdownLISTS.each do |tag|define_method("visit_#{tag}") do |node|prefix = block?(node.previous_element) ? "" : "\n"- suffix = node.ancestors("ul, ol, li").size > 0 ? "" : "\n"+ nested = node.ancestors("ul, ol, li").present?+ suffix = nested && node.next_element.nil? ? "" : "\n""#{prefix}#{traverse(node)}#{suffix}"endenddiff --git a/spec/lib/html_to_markdown_spec.rb b/spec/lib/html_to_markdown_spec.rbindex 7d59392bee5..ffc6db2ceed 100644--- a/spec/lib/html_to_markdown_spec.rb+++ b/spec/lib/html_to_markdown_spec.rb@@ -399,6 +399,35 @@ RSpec.describe HtmlToMarkdown do)end+ it "nests lists that are siblings of the <li> they belong to" do+ expect(html_to_markdown(<<-HTML)).to eq(+ <ul>+ <li>Fruits</li>+ <ul>+ <li>π</li>+ <li>π</li>+ <li>π</li>+ </ul>+ <li>Vegetables</li>+ <ul>+ <li>π</li>+ <li>π </li>+ <li>π</li>+ </ul>+ </ul>+ HTML+ "- Fruits\n - π\n - π\n - π\n- Vegetables\n - π\n - π \n - π",+ )++ expect(html_to_markdown("<ol><li>π</li><ol><li>π </li></ol><li>π</li></ol>")).to eq(+ "1. π\n 1. π \n1. π",+ )+ end++ it "separates a nested list from the <li> that follows it" do+ expect(html_to_markdown("<ul><ol><li>π</li></ol><li>π</li></ul>")).to eq("1. π\n- π")+ end+it "supports bare <li>" doexpect(html_to_markdown("<li>I'm alone</li>")).to eq("- I'm alone")end