diff --git a/crates/leaf-core/src/doc/delete.rs b/crates/leaf-core/src/doc/delete.rs
index aeeb29df..897961c4 100644
--- a/crates/leaf-core/src/doc/delete.rs
+++ b/crates/leaf-core/src/doc/delete.rs
@@ -62,6 +62,9 @@ impl Doc {
if self.view != View::Source && self.backspace_verse() {
return;
}
+ if self.view != View::Source && self.backspace_html_empty_paragraph() {
+ return;
+ }
if self.view != View::Source && self.backspace_joins_block() {
return;
}
@@ -353,6 +356,58 @@ impl Doc {
}
}
+ /// Backspace in an HTML document in an empty `
= self
+ .nodes()
+ .into_iter()
+ .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
+ .collect();
+ let content = |n: &FlatNode| n.content_span.clone().unwrap_or_else(|| n.span.clone());
+ let Some(here) = blocks.iter().find(|n| content(n).start == caret) else {
+ return false;
+ };
+ let Some(above) = blocks
+ .iter()
+ .filter(|n| n.span.end <= here.span.start)
+ .max_by_key(|n| n.span.end)
+ else {
+ return false;
+ };
+ if !self.source[above.span.end..here.span.start]
+ .trim()
+ .is_empty()
+ {
+ return false;
+ }
+ let empty =
+ |n: &FlatNode| n.kind == Kind::Para && self.source[content(n)].trim().is_empty();
+ let (range, land) = if empty(here) {
+ (above.span.end..here.span.end, content(above).end)
+ } else if empty(above) {
+ let range = above.span.start..here.span.start;
+ (range.clone(), caret - range.len())
+ } else {
+ return false;
+ };
+ if self.splice(range.start, range.end, "", EditKind::Delete) {
+ self.caret = land.min(self.source.len());
+ self.record_caret();
+ }
+ true
+ }
+
/// Delete at the end of a block's content: join the block after it into
/// this one — [`backspace_joins_block`](Self::backspace_joins_block)'s
/// mirror, and the same twig gesture aimed at the next block. The caret
diff --git a/crates/leaf-core/src/doc/newline.rs b/crates/leaf-core/src/doc/newline.rs
index 46136fbc..300000a3 100644
--- a/crates/leaf-core/src/doc/newline.rs
+++ b/crates/leaf-core/src/doc/newline.rs
@@ -83,6 +83,23 @@ impl Doc {
self.verse_newline();
return;
}
+ // HTML keeps neither a blank line nor a newline in running text, so
+ // the whitespace the branches below write is whitespace its page does
+ // not have. In prose Enter writes elements instead; a list, a quote
+ // and a table keep the branches below. See `html_newline`.
+ if self.format == Format::Html
+ && ![
+ Kind::ListItem,
+ Kind::TaskListItem,
+ Kind::BlockQuote,
+ Kind::Table,
+ ]
+ .into_iter()
+ .any(has)
+ {
+ self.html_newline();
+ return;
+ }
// An *empty* list item exits the list — the standard double-Enter — which
// `split_block` reports as an error rather than a split (there is no
// content to part), so it stays leaf's. `list_marker_on_line` is itself
@@ -173,6 +190,157 @@ impl Doc {
self.split_block_here();
}
+ /// Enter in an HTML document's prose, which writes elements where
+ /// Markdown writes whitespace.
+ ///
+ /// - at the end of a paragraph or heading, or in an empty one → an
+ /// empty `` after it, the caret inside
+ /// - at the start of one → an empty `` before it, the caret
+ /// staying with the text
+ /// - between two blocks, on the whitespace that separates them → an
+ /// empty `` there
+ /// - inside a paragraph in [`LineFlow::Preserve`] → a `
`, the soft
+ /// line that flow's Enter makes
+ /// - inside one otherwise → two elements, parted at the caret
+ /// ([`split_html_block`](Self::split_html_block))
+ ///
+ /// At a paragraph's end Preserve flow opens a paragraph too: a `
`
+ /// with nothing after it in its block draws no line in a browser.
+ ///
+ /// The paragraph break Markdown writes at a block's edge went inside the
+ /// element, `I cry\n\n
`, which the view drew as an empty paragraph
+ /// and a browser does not draw at all; Preserve flow's lone `\n` drew
+ /// nothing anywhere.
+ fn html_newline(&mut self) {
+ let caret = self.caret.min(self.source.len());
+ let block = self.editor.nodes().ok().and_then(|nodes| {
+ nodes
+ .iter()
+ .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
+ .filter(|n| {
+ let content = n.content_span.clone().unwrap_or_else(|| n.span.clone());
+ content.start <= caret && caret <= content.end
+ })
+ .min_by_key(|n| n.span.len())
+ .cloned()
+ });
+ let Some(block) = block else {
+ let at_line_start = caret == 0 || self.source.as_bytes()[caret - 1] == b'\n';
+ let (text, inside) = if at_line_start {
+ ("\n", "".len())
+ } else {
+ ("\n
", "\n".len())
+ };
+ self.open_html_paragraph(caret, text, caret + inside);
+ return;
+ };
+ let drawn: Vec> = self
+ .editor
+ .subtree(block.id)
+ .map(|nodes| {
+ nodes
+ .iter()
+ .filter(|n| {
+ matches!(n.kind, Kind::Image | Kind::HardBreak)
+ || n.text.as_deref().is_some_and(|t| !t.trim().is_empty())
+ })
+ .map(|n| n.span.clone())
+ .collect()
+ })
+ .unwrap_or_default();
+ let before = drawn.iter().any(|s| s.start < caret);
+ let after = drawn.iter().any(|s| s.end > caret);
+ if !after {
+ let at = block.span.end;
+ self.open_html_paragraph(at, "\n", at + "\n".len());
+ } else if !before {
+ let text = "
\n";
+ self.open_html_paragraph(block.span.start, text, caret + text.len());
+ } else if self.line_flow == LineFlow::Preserve && block.kind == Kind::Para {
+ self.splice(caret, caret, "
", EditKind::Other);
+ } else {
+ self.split_html_block(&block);
+ }
+ }
+
+ /// Part the HTML paragraph or heading `block` at the caret, which has text
+ /// on both sides of it: each element open there is closed and opened
+ /// again, so `a bo|ld
` becomes `a bo
` over
+ /// `ld
`, each paragraph keeping the tag it was written
+ /// with. A heading's second half is a paragraph, as in every format.
+ ///
+ /// twig's split wrote a Markdown paragraph break, `\n\n`, inside the
+ /// element, which HTML reads as one space.
+ fn split_html_block(&mut self, block: &FlatNode) {
+ let caret = self.caret.min(self.source.len());
+ let Some(content) = block.content_span.clone() else {
+ return;
+ };
+ // The inline elements around the caret, outermost first. At one's
+ // edge the caret is outside it, and the split goes outside it too.
+ let mut inline: Vec = self
+ .editor
+ .subtree(block.id)
+ .map(|nodes| {
+ nodes
+ .into_iter()
+ .filter(|n| n.span != block.span)
+ .filter(|n| {
+ n.content_span
+ .as_ref()
+ .is_some_and(|c| c.start <= caret && caret <= c.end && *c != n.span)
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ inline.sort_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)));
+ let mut at = caret;
+ let mut open = Vec::new();
+ for n in inline {
+ let c = n.content_span.clone().unwrap_or_else(|| n.span.clone());
+ if caret == c.start {
+ at = n.span.start;
+ break;
+ }
+ if caret == c.end {
+ at = n.span.end;
+ break;
+ }
+ open.push(n);
+ }
+ let tag = |r: Range| self.source.get(r).unwrap_or("").to_string();
+ let opening =
+ |n: &FlatNode| n.span.start..n.content_span.as_ref().map_or(n.span.start, |c| c.start);
+ let closing =
+ |n: &FlatNode| n.content_span.as_ref().map_or(n.span.end, |c| c.end)..n.span.end;
+ let (second_open, second_close) = if block.kind == Kind::Heading {
+ ("".to_string(), "
".to_string())
+ } else {
+ (tag(opening(block)), tag(closing(block)))
+ };
+ let mut text: String = open.iter().rev().map(|n| tag(closing(n))).collect();
+ text += &tag(closing(block));
+ text.push('\n');
+ text += &second_open;
+ text.extend(open.iter().map(|n| tag(opening(n))));
+ let caret = at + text.len();
+ text += &self.source[at..content.end];
+ text += &second_close;
+ if self.splice(at, block.span.end, &text, EditKind::Other) {
+ self.caret = caret.min(self.source.len());
+ self.record_caret();
+ }
+ }
+
+ /// Write `text` at `at` and stand the caret at `caret`, an offset in the
+ /// edited source.
+ fn open_html_paragraph(&mut self, at: usize, text: &str, caret: usize) {
+ if self.splice(at, at, text, EditKind::Other) {
+ self.caret = caret.min(self.source.len());
+ self.record_caret();
+ }
+ }
+
/// Where Enter writes to open an empty paragraph above the paragraph or
/// heading the caret starts, and what — `None` when the caret does not
/// start one.
diff --git a/crates/leaf-core/src/doc/tests/enter.rs b/crates/leaf-core/src/doc/tests/enter.rs
index 73b64428..fd012a2e 100644
--- a/crates/leaf-core/src/doc/tests/enter.rs
+++ b/crates/leaf-core/src/doc/tests/enter.rs
@@ -201,9 +201,8 @@ fn enter_and_backspace_anywhere_show_what_they_write_and_undo_in_one_step() {
"{data-line-height=\"2\"}\nI cry\n\n{data-line-height=\"2\"}\nknees to nose\n",
),
(Format::Djot, "# Title\n\na\n\n* * *\n\nb\n"),
- // HTML is not here: Enter writes blank lines there, which the
- // view draws and HTML does not keep. See
- // docs/tasks/enter-in-html-writes-whitespace.md.
+ (Format::Html, "I talk to myself
\nI cry
\n"),
+ (Format::Html, "Title
\na bold b
\n"),
];
let mut failures = Vec::new();
for &(format, body) in cases {
@@ -851,3 +850,124 @@ fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
"the rule belongs to the quote it was asked for"
);
}
+
+#[test]
+fn enter_in_html_writes_elements_and_backspace_takes_them_back() {
+ // HTML keeps neither a blank line nor a newline in running text. Enter
+ // wrote them anyway, `I cry\n\n
`, which the view drew as an empty
+ // paragraph a browser does not have, and Preserve flow's lone `\n`,
+ // which nothing drew. Enter writes elements instead.
+ let src = "I cry
\nknees
\n";
+ let after_cry = src.find("
").unwrap();
+ let at_knees = src.find("knees").unwrap();
+ let mid = src.find("cry").unwrap();
+ let opened = "I cry
\n\nknees
\n";
+ let cases = [
+ // At a paragraph's end, an empty paragraph after it, in both flows:
+ // a `
` with nothing after it draws no line in a browser.
+ (
+ LineFlow::Fold,
+ src,
+ after_cry,
+ opened,
+ opened.find("\nk").unwrap(),
+ ),
+ (
+ LineFlow::Preserve,
+ src,
+ after_cry,
+ opened,
+ opened.find("
\nk").unwrap(),
+ ),
+ // At its start, an empty paragraph before it, the caret staying
+ // with the text.
+ (
+ LineFlow::Fold,
+ src,
+ at_knees,
+ opened,
+ opened.find("knees").unwrap(),
+ ),
+ // Inside it, Preserve flow's soft line is a `
`.
+ (
+ LineFlow::Preserve,
+ src,
+ mid,
+ "
I
cry
\nknees
\n",
+ mid + 4,
+ ),
+ ];
+ for (flow, body, at, want, caret) in cases {
+ let mut d = Doc::from_source(body.into(), Format::Html).unwrap();
+ d.view = View::Wysiwyg;
+ d.set_line_flow(flow);
+ d.build_visual(80);
+ d.caret = at;
+ d.newline();
+ assert_eq!(d.source, want, "{flow:?} at {at}");
+ assert_eq!(d.caret, caret, "{flow:?} at {at}: {:?}", d.source);
+ d.build_visual(80);
+ let (row, _) = d.vmap.pos_of_offset(d.caret);
+ assert!(
+ !d.vmap.rows[row].decoration,
+ "{flow:?} at {at}: the caret's row is a line"
+ );
+ // One Backspace takes back what Enter wrote.
+ d.backspace();
+ assert_eq!(d.source, body, "{flow:?} at {at}: backspace");
+ assert_eq!(d.caret, at, "{flow:?} at {at}: backspace");
+ }
+
+ // Fold parts the element. Backspace there is twig's join, which spells
+ // the join as a newline, a space to HTML; one Undo takes the split back.
+ let mut d = Doc::from_source(src.into(), Format::Html).unwrap();
+ d.view = View::Wysiwyg;
+ d.build_visual(80);
+ d.caret = mid;
+ d.newline();
+ assert_eq!(d.source, "I
\ncry
\nknees
\n");
+ assert_eq!(d.caret, mid + "\n".len());
+ d.undo();
+ assert_eq!(d.source, src);
+
+ // The empty paragraph draws, and what is typed there is its text.
+ let mut d = Doc::from_source(src.into(), Format::Html).unwrap();
+ d.view = View::Wysiwyg;
+ d.build_visual(80);
+ d.caret = after_cry;
+ d.newline();
+ d.build_visual(80);
+ let (row, _) = d.vmap.pos_of_offset(d.caret);
+ assert!(d.vmap.rows[row].glyphs.is_empty(), "{:?}", drawn(&d));
+ d.insert("x");
+ assert_eq!(d.source, "
I cry
\nx
\nknees
\n");
+
+ // A split closes and reopens the inline elements around the caret, and
+ // a heading's second half is a paragraph.
+ for (body, at, want) in [
+ (
+ "a bold b
\n",
+ "a bo".len(),
+ "
a bo
\nld b
\n",
+ ),
+ (
+ "Title
\n",
+ "Ti".len(),
+ "Ti
\n
tle
\n",
+ ),
+ ] {
+ let mut d = Doc::from_source(body.into(), Format::Html).unwrap();
+ d.view = View::Wysiwyg;
+ d.build_visual(80);
+ d.caret = at;
+ d.newline();
+ assert_eq!(d.source, want);
+ assert!(
+ d.source[d.caret..].starts_with(&body[at..at + 2]),
+ "{:?}",
+ d.caret
+ );
+ d.undo();
+ assert_eq!(d.source, body);
+ }
+}
diff --git a/crates/leaf-core/src/wysiwyg/builder/blocks.rs b/crates/leaf-core/src/wysiwyg/builder/blocks.rs
index d5d16eba..9f431bc5 100644
--- a/crates/leaf-core/src/wysiwyg/builder/blocks.rs
+++ b/crates/leaf-core/src/wysiwyg/builder/blocks.rs
@@ -829,9 +829,28 @@ impl Builder<'_> {
let pres = self.presentation.under(&node.attrs, &self.faces);
let glyphs =
self.inline_children_with_trailing(id, pres.over(Style::default()));
- if !glyphs.is_empty() {
+ // An empty `` is an empty paragraph on the page,
+ // and the one HTML's Enter opens: one glyphless row, its
+ // home between the tags, as an empty heading's is past
+ // its `#`. A paragraph is that shape when markup opens
+ // and closes it around no content. Elsewhere a block
+ // with nothing to draw draws no row.
+ let home = if !glyphs.is_empty() {
+ Some(node.span.start)
+ } else {
+ node.content_span
+ .as_ref()
+ .filter(|c| {
+ node.kind == Kind::Para
+ && c.is_empty()
+ && node.span.start < c.start
+ && c.end < node.span.end
+ })
+ .map(|c| c.start)
+ };
+ if let Some(home) = home {
let first = self.rows.len();
- self.emit_wrapped(glyphs, node.span.start, pf, pc);
+ self.emit_wrapped(glyphs, home, pf, pc);
for row in &mut self.rows[first..] {
row.align = pres.align;
row.line_height = pres.line_height;
diff --git a/docs/tasks/enter-in-html-writes-whitespace.md b/docs/tasks/enter-in-html-writes-whitespace.md
index d54b116e..eb2d300c 100644
--- a/docs/tasks/enter-in-html-writes-whitespace.md
+++ b/docs/tasks/enter-in-html-writes-whitespace.md
@@ -1,11 +1,32 @@
---
-status: open
+status: done
created: 2026-09-23
-updated: 2026-09-23
+updated: 2026-10-21
part_of: '[Tasks](/docs/tasks/tasks.md)'
---
# Enter in an HTML document writes whitespace
+**Status: done.** In an HTML document's prose, `Doc::newline` writes
+elements (`html_newline`). At a paragraph's or heading's end, or in an
+empty paragraph, it writes an empty `` after it. At a block's start,
+or on the whitespace between two blocks, the `` goes there instead.
+Inside a paragraph, Preserve flow writes a `
` and Fold parts the element
+at the caret, closing and reopening the inline elements around it. A
+heading's second half is a paragraph. Preserve flow opens a paragraph at a
+paragraph's end too, because a `
` with nothing after it in its block
+draws no line in a browser. The map draws an empty `` as an empty
+paragraph row. Backspace in one, or at the start of a block under one,
+takes it whole, the inverse of the Enter that opened it: twig's join had
+left a newline in the element. Lists, quotes and tables keep their own
+branches.
+`enter_and_backspace_anywhere_show_what_they_write_and_undo_in_one_step`
+runs two HTML documents, and
+`enter_in_html_writes_elements_and_backspace_takes_them_back` pins the
+rest. What is still open: Backspace between two paragraphs of text is
+twig's join, which spells it as a newline, a space to HTML, drawn as a line
+break in Preserve flow. Hand-written whitespace between or inside elements
+is still drawn as Markdown would draw it.
+
**Where.** `crates/leaf-core`: `Doc::newline` and the visual map.
**What.** In an HTML document, Enter writes what it writes in Markdown: