A platform for community discussion. Free, open, simple.
FIX: Improve HTML to Markdown conversion (#9231)
Dan Ungureanu1393950dbc44
diff --git a/lib/html_to_markdown.rb b/lib/html_to_markdown.rbindex a17a78eb2b0..a3eb5e8aaeb 100644--- a/lib/html_to_markdown.rb+++ b/lib/html_to_markdown.rb@@ -31,7 +31,7 @@ class HtmlToMarkdowndef remove_whitespaces!@doc.traverse do |node|- if node.is_a? Nokogiri::XML::Text+ if node.is_a?(Nokogiri::XML::Text) && node.parent.name != "pre"node.content = node.content.gsub(/\A[[:space:]]+/, "") if node.previous_element&.description&.block?node.content = node.content.gsub(/\A[[:space:]]+/, "") if node.previous_element.nil? && node.parent.description&.block?node.content = node.content.gsub(/[[:space:]]+\z/, "") if node.next_element&.description&.block?@@ -220,10 +220,21 @@ class HtmlToMarkdownenddef visit_text(node)+ top_block = @stack[-1]++ if top_block.name == "pre"+ top_block.markdown << node.text+ return+ end+node.content = node.content.gsub(/\A[[:space:]]+/, "") if node.previous_element.nil? && EMPHASIS.include?(node.parent.name)- indent = node.text[/^\s+/] || ""++ if top_block.markdown.present? && indent = node.text[/^\s+/]+ top_block.markdown << indent+ end+text = node.text.gsub(/^\s+/, "").gsub(/\s{2,}/, " ")- @stack[-1].markdown << [indent, text].join("")+ top_block.markdown << textenddef format_blockdiff --git a/spec/components/html_to_markdown_spec.rb b/spec/components/html_to_markdown_spec.rbindex aa89ac351c7..266e875aca6 100644--- a/spec/components/html_to_markdown_spec.rb+++ b/spec/components/html_to_markdown_spec.rb@@ -204,6 +204,7 @@ describe HtmlToMarkdown doexpect(html_to_markdown("<pre>var foo = 'bar';</pre>")).to eq("```\nvar foo = 'bar';\n```")expect(html_to_markdown("<pre><code>var foo = 'bar';</code></pre>")).to eq("```\nvar foo = 'bar';\n```")expect(html_to_markdown(%Q{<pre><code class="lang-javascript">var foo = 'bar';</code></pre>})).to eq("```javascript\nvar foo = 'bar';\n```")+ expect(html_to_markdown("<pre> function f() {\n console.log('Hello world!');\n }</pre>")).to eq("```\n function f() {\n console.log('Hello world!');\n }\n```")endit "supports <pre> inside <blockquote>" do@@ -220,6 +221,7 @@ describe HtmlToMarkdown doit "handles <p>" doexpect(html_to_markdown("<p>1st paragraph</p><p>2nd paragraph</p>")).to eq("1st paragraph\n\n2nd paragraph")+ expect(html_to_markdown("<body><p>1st paragraph</p>\n <p> 2nd paragraph\n 2nd paragraph</p>\n<p>3rd paragraph</p></body>")).to eq("1st paragraph\n\n2nd paragraph\n2nd paragraph\n\n3rd paragraph")endit "handles <div>" do