Skip to content
This repository was archived by the owner on Nov 12, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions crates/leaf-core/src/doc/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -353,6 +356,58 @@ impl Doc {
}
}

/// Backspace in an HTML document in an empty `<p></p>`, or at the start of
/// a block under one: the empty paragraph goes whole, with the whitespace
/// that parts it from its neighbour, which is the inverse of the Enter
/// that opened it (`html_newline`). twig's join reads the two as
/// paragraphs of text and joins them on a newline, and that newline stayed
/// in the element: a space in HTML, and a line in Preserve flow.
///
/// Returns whether it acted.
fn backspace_html_empty_paragraph(&mut self) -> bool {
if self.format != Format::Html {
return false;
}
let caret = self.caret;
let blocks: Vec<FlatNode> = 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
Expand Down
168 changes: 168 additions & 0 deletions crates/leaf-core/src/doc/newline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 `<p></p>` after it, the caret inside
/// - at the start of one → an empty `<p></p>` before it, the caret
/// staying with the text
/// - between two blocks, on the whitespace that separates them → an
/// empty `<p></p>` there
/// - inside a paragraph in [`LineFlow::Preserve`] → a `<br>`, 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 `<br>`
/// 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, `<p>I cry\n\n</p>`, 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 {
("<p></p>\n", "<p>".len())
} else {
("\n<p></p>", "\n<p>".len())
};
self.open_html_paragraph(caret, text, caret + inside);
return;
};
let drawn: Vec<Range<usize>> = 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<p></p>", at + "\n<p>".len());
} else if !before {
let text = "<p></p>\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, "<br>", 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 `<p>a <b>bo|ld</b></p>` becomes `<p>a <b>bo</b></p>` over
/// `<p><b>ld</b></p>`, 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<FlatNode> = 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<usize>| 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 {
("<p>".to_string(), "</p>".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.
Expand Down
126 changes: 123 additions & 3 deletions crates/leaf-core/src/doc/tests/enter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, "<p>I talk to myself</p>\n<p>I cry</p>\n"),
(Format::Html, "<h1>Title</h1>\n<p>a <b>bold</b> b</p>\n"),
];
let mut failures = Vec::new();
for &(format, body) in cases {
Expand Down Expand Up @@ -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, `<p>I cry\n\n</p>`, 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 = "<p>I cry</p>\n<p>knees</p>\n";
let after_cry = src.find("</p>").unwrap();
let at_knees = src.find("knees").unwrap();
let mid = src.find("cry").unwrap();
let opened = "<p>I cry</p>\n<p></p>\n<p>knees</p>\n";
let cases = [
// At a paragraph's end, an empty paragraph after it, in both flows:
// a `<br>` with nothing after it draws no line in a browser.
(
LineFlow::Fold,
src,
after_cry,
opened,
opened.find("</p>\n<p>k").unwrap(),
),
(
LineFlow::Preserve,
src,
after_cry,
opened,
opened.find("</p>\n<p>k").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 `<br>`.
(
LineFlow::Preserve,
src,
mid,
"<p>I <br>cry</p>\n<p>knees</p>\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, "<p>I </p>\n<p>cry</p>\n<p>knees</p>\n");
assert_eq!(d.caret, mid + "</p>\n<p>".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, "<p>I cry</p>\n<p>x</p>\n<p>knees</p>\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 [
(
"<p>a <b>bold</b> b</p>\n",
"<p>a <b>bo".len(),
"<p>a <b>bo</b></p>\n<p><b>ld</b> b</p>\n",
),
(
"<h1>Title</h1>\n",
"<h1>Ti".len(),
"<h1>Ti</h1>\n<p>tle</p>\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);
}
}
Loading
Loading