Skip to content

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.rb
index ebf4ea2a364..14faf07670c 100644
--- a/lib/html_to_markdown.rb
+++ b/lib/html_to_markdown.rb
@@ -12,6 +12,7 @@ class HtmlToMarkdown
remove_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 HtmlToMarkdown
LISTS.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}"
end
end
diff --git a/spec/lib/html_to_markdown_spec.rb b/spec/lib/html_to_markdown_spec.rb
index 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>" do
expect(html_to_markdown("<li>I'm alone</li>")).to eq("- I'm alone")
end