Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

Preserve block boundaries inside preformatted content

kevin810420641248
diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs
index d34b687e4..76a45ae7d 100644
--- a/moli-html2md/src/machine.rs
+++ b/moli-html2md/src/machine.rs
@@ -14,6 +14,7 @@ enum Task<'a, Id> {
EndList(usize),
EndItem(String),
RawChildren(Option<Id>, usize, bool),
+ EndRawBlock,
EndCode,
EndPre(Option<&'a str>),
TableCell,
@@ -130,6 +131,11 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
self.writer().block(item.into(), separation, separation);
}
Task::RawChildren(Some(node), depth, inline) => self.raw_node(node, depth, inline),
+ Task::EndRawBlock => {
+ if !self.raw.ends_with('\n') {
+ self.raw.push('\n');
+ }
+ }
Task::EndCode => {
let text = std::mem::take(&mut self.raw);
let preformatted = self.options.preformatted_code;
@@ -393,6 +399,14 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
// breaks without converting descendant formatting into Markdown.
NodeKind::Element("br") if inline => self.raw.push('\n'),
NodeKind::Document | NodeKind::Element(_) if depth + 1 < self.options.max_depth => {
+ if !inline
+ && matches!(self.dom.node_kind(node), NodeKind::Element(tag) if is_block(tag))
+ {
+ if !self.raw.is_empty() && !self.raw.ends_with('\n') {
+ self.raw.push('\n');
+ }
+ self.tasks.push(Task::EndRawBlock);
+ }
self.tasks.push(Task::RawChildren(
self.dom.first_child(node),
depth + 1,
diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs
index 7b547f627..47081f92f 100644
--- a/moli-html2md/tests/regressions.rs
+++ b/moli-html2md/tests/regressions.rs
@@ -158,6 +158,17 @@ fn adjacent_code_elements_keep_distinct_values() {
);
}
+#[test]
+fn preformatted_block_children_keep_text_boundaries() {
+ let html = "<pre><div>ts</div><div><code>function identity() {}</code></div></pre>";
+ let output = markdown(html, false);
+ assert_eq!(output, "```\nts\nfunction identity() {}\n```");
+ assert_eq!(
+ rendered_html(&output),
+ "<pre><code>ts\nfunction identity() {}\n</code></pre>\n"
+ );
+}
+
#[test]
fn attribute_newlines_remove_indentation_without_joining_words() {
for separator in ["\n ", "\r\n\t", "\n \n \t "] {