diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2a428fb6..172ce996 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -6192,24 +6192,21 @@ impl NoteCraftApp { let Some(block) = ed.blocks.get(caret.block) else { return }; let Some(caret) = ed.caret.as_mut() else { return }; let Some((text, selection)) = caret.paint(block, &held.style) else { - self.say(crate::tl_id!("ui.inline_mark_whole_line")); return; }; - if text != caret.text { - Self::remember_step(ed); - let Some(caret) = ed.caret.as_mut() else { return }; - caret.text = text; - caret.selection = selection; - caret.place = Some(selection.0); - caret.focus = true; - if let Some(block) = ed.blocks.get_mut(caret.block) { - caret.write(block); - } - ed.pending_format = None; - ed.rebuild_body(); - Self::mark_dirty_from_blocks(ed); - Self::remember_edit(ed); + Self::remember_step(ed); + let Some(caret) = ed.caret.as_mut() else { return }; + caret.text = text; + caret.selection = selection; + caret.place = Some(selection.0); + caret.focus = true; + if let Some(block) = ed.blocks.get_mut(caret.block) { + caret.write(block); } + ed.pending_format = None; + ed.rebuild_body(); + Self::mark_dirty_from_blocks(ed); + Self::remember_edit(ed); if !held.sticky { self.painter = None; } @@ -6238,13 +6235,8 @@ impl NoteCraftApp { let Some(caret) = ed.caret.as_mut() else { return }; let Some(block) = ed.blocks.get(caret.block) else { return }; let Some((text, selection)) = caret.format(block, format) else { - self.status = crate::tl_id!("ui.inline_mark_whole_line").into(); - self.status_is_error = false; return; }; - if text == caret.text { - return; - } Self::remember_step(ed); let Some(caret) = ed.caret.as_mut() else { return }; caret.text = text; @@ -7101,7 +7093,8 @@ impl NoteCraftApp { return; }; let (lo, hi) = (caret.selection.0.min(caret.selection.1), caret.selection.0.max(caret.selection.1)); - let (range, text, address, editing) = match pageedit::link_at(&caret.text, lo, hi) { + let found = ed.blocks.get(caret.block).and_then(|block| pageedit::link_at_caret(block, caret)); + let (range, text, address, editing) = match found { Some((start, end, words, address)) => ((start, end), words, address, true), None => ((lo, hi), caret.text.chars().skip(lo).take(hi - lo).collect(), String::new(), false), }; @@ -7138,18 +7131,12 @@ impl NoteCraftApp { } Self::remember_step(ed); let Some(caret) = ed.caret.as_mut() else { return }; - let chars: Vec = caret.text.chars().collect(); - let (a, b) = (range.0.min(chars.len()), range.1.min(chars.len())); - let mut text: String = chars[..a].iter().collect(); - text.push_str(replacement); - let at = text.chars().count(); - text.extend(&chars[b..]); - caret.text = text; - caret.selection = (at, at); - caret.place = Some(at); - caret.focus = true; - // Read again from the words, so the new link is a link and not text that looks like one. - caret.inline = None; + let (a, b) = (range.0.min(range.1), range.0.max(range.1)); + // On the spans, not the text: removing a link leaves the same words behind, and a + // text diff could never tell the link's words from plain ones. + if let Some(block) = ed.blocks.get(block) { + caret.replace_range(block, (a, b), replacement); + } if let Some(b) = ed.blocks.get_mut(block) { caret.write(b); } diff --git a/crates/ui-egui/src/pageedit.rs b/crates/ui-egui/src/pageedit.rs index 9ac0b13c..b959cb33 100644 --- a/crates/ui-egui/src/pageedit.rs +++ b/crates/ui-egui/src/pageedit.rs @@ -12,6 +12,7 @@ use crate::pagetext; use crate::preview; use crate::theme::Tokens; +use egui::text::LayoutJob; use egui::{Key, Sense, Ui, vec2}; use notecraft_formats::markdown::{Block, Span, parse_inline}; mod inline_edit; @@ -80,6 +81,13 @@ impl Caret { } else { self.ensure_inline(block).write(block, &text); } + // The parse may have consumed markup the caller put in (a wrap, a pasted link), so + // the caret's text is always the canonical visible projection of the spans. + if let Some(inline) = self.inline.as_ref() { + self.text = inline.text().to_owned(); + } + let len = self.text.chars().count(); + self.selection = (self.selection.0.min(len), self.selection.1.min(len)); } pub fn parse(&self, block: &Block, text: &str) -> Vec { @@ -104,6 +112,19 @@ impl Caret { } } + /// Dialog edits (links, video): replace the visible characters `range` with + /// `replacement`, which may carry markup. Done on the spans because the words before + /// and after can look identical in the visible text while meaning something else. + pub fn replace_range(&mut self, block: &Block, range: (usize, usize), replacement: &str) { + let inline = self.ensure_inline(block); + inline.replace(range.0..range.1, replacement); + self.text = inline.text().to_owned(); + let end = (range.0.min(range.1) + markup_visible_len(replacement)).min(self.text.chars().count()); + self.selection = (end, end); + self.place = Some(end); + self.focus = true; + } + /// Clear only the active text/cell and hydrate the same editing target afterwards. pub fn clear_marks(&mut self, block: &mut Block) { self.write(block); @@ -122,7 +143,12 @@ impl Caret { pub fn format(&mut self, block: &Block, format: InlineFormat) -> Option<(String, (usize, usize))> { let (text, selection) = (self.text.clone(), self.selection); - self.ensure_inline(block).format(&text, selection, format) + let inline = self.ensure_inline(block); + let before = inline.spans().to_vec(); + let out = inline.format(&text, selection, format)?; + // Formatting leaves the visible words where they were, so the text alone cannot + // say whether anything changed; the spans can. + (inline.spans() != before.as_slice()).then_some(out) } pub fn fonts(&self, block: &Block) -> Option { @@ -137,7 +163,10 @@ impl Caret { /// Gives the selected words `style`, for the Format Painter. pub fn paint(&mut self, block: &Block, style: &Span) -> Option<(String, (usize, usize))> { let (text, selection) = (self.text.clone(), self.selection); - self.ensure_inline(block).paint(&text, selection, style) + let inline = self.ensure_inline(block); + let before = inline.spans().to_vec(); + let out = inline.paint(&text, selection, style)?; + (inline.spans() != before.as_slice()).then_some(out) } } @@ -188,6 +217,33 @@ pub fn char_at( // The lines of a paragraph that was given a least height (issue #275), so the click is // measured against the lines that were drawn. pagetext::floor_lines(ui.ctx(), &mut job, crate::bidi::current_floor()); + char_at_laid(ui, job, text, offset) +} + +/// [`char_at`] against a job built from the block's spans, so the measurement sees the same +/// formatted words the editor shows — and an inline image as its one object character. +fn char_at_spans( + ui: &Ui, + spans: &[Span], + size: f32, + strong: bool, + t: &Tokens, + width: f32, + offset: egui::Vec2, + page: Option, +) -> usize { + // The tag marker is drawn beside the line, not inside the measured words. + let spans = preview::tagged(spans).map(|(_, stripped)| stripped).unwrap_or_else(|| spans.to_vec()); + let edit = InlineEdit::from_spans(&spans); + let text = edit.text().to_owned(); + let colour = if strong { t.strong } else { t.text }; + let mut job = preview::edit_job(ui, edit.spans(), size, colour, t, page, width.max(1.0)); + pagetext::floor_lines(ui.ctx(), &mut job, crate::bidi::current_floor()); + char_at_laid(ui, job, &text, offset) +} + +/// The character of `text` a click at `offset` lands on in `job`'s galley. +fn char_at_laid(ui: &Ui, job: LayoutJob, text: &str, offset: egui::Vec2) -> usize { let galley = ui.fonts_mut(|f| f.layout_job(job)); let chars = text.chars().count(); // Two things have to be undone for a right-to-left line, both measured in @@ -1347,9 +1403,19 @@ fn table( if here == Some(cell) && picked.is_none() { let Some(caret) = caret.as_mut() else { return }; caret.ensure_inline(block); - let previous_selection = caret.selection; let id = ui.make_persistent_id(("table-cell", i, r, c)); changed.mark = formatting_key(ui, id); + // The cell's words are drawn with their formatting, the way + // the finished cell beside them is; the buffer stays the + // visible text. + let mut live = caret.inline.clone().unwrap_or_default(); + let strong = r == 0; + let colour = if strong { t.strong } else { ui.style().visuals.text_color() }; + let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, width: f32| { + live.parse(text.as_str()); + let job = preview::edit_job(ui, live.spans(), 14.5 * zoom, colour, t, page, width.max(1.0)); + ui.fonts_mut(|f| f.layout_job(job)) + }; let at = (i, caret.text.clone(), caret.selection); let out = steady_blink(ui, (at.0, &at.1, at.2), |ui| { egui::TextEdit::singleline(&mut caret.text) @@ -1358,6 +1424,7 @@ fn table( .horizontal_align(halign) .desired_width(inner) .font(egui::FontId::proportional(14.5 * zoom)) + .layouter(&mut layouter) .show(ui) }); if caret.focus { @@ -1368,9 +1435,6 @@ fn table( caret.selection = (range.primary.index.0, range.secondary.index.0); } if out.response.changed() { - if let Some(inline) = caret.inline.as_mut() { - inline.update_at(&caret.text, previous_selection, caret.selection); - } action = Some(Action::SetCell(i, cell, caret.text.clone())); } } else { @@ -1622,9 +1686,11 @@ pub fn set_caret_text(block: &mut Block, text: &str) { InlineEdit::new(block, true).write(block, text); } -/// Puts edited text back into a block, keeping what the block is. +/// Puts edited text back into a block, keeping what the block is. `text` is the serialized +/// source (`block_text`), so tags, direction marks and kind changes keep their literal +/// identity. pub fn set_block_text(block: &mut Block, text: &str) { - let spans = InlineEdit::new(block, false).parse(text); + let spans = InlineEdit::new(block, false).parse_source(text); match block { Block::Heading { spans: s, .. } | Block::Paragraph(s) | Block::Quote(s) | Block::Item { spans: s, .. } => *s = spans, Block::Code { text: t, .. } => *t = text.to_string(), @@ -1713,7 +1779,7 @@ fn cell_spans_mut(block: &mut Block, (row, column): (usize, usize)) -> Option<&m } pub fn cell_text(block: &Block, cell: (usize, usize)) -> Option { - Some(spans_to_editor(cell_spans(block, cell)?)) + Some(InlineEdit::from_spans(cell_spans(block, cell)?).text().to_owned()) } pub fn set_cell_text(block: &mut Block, cell: (usize, usize), text: &str) { @@ -1722,6 +1788,28 @@ pub fn set_cell_text(block: &mut Block, cell: (usize, usize), text: &str) { } } +/// How many visible characters serialized inline markup stands for once parsed: the words +/// a `[text](address)` link or a `**bold**` wrap shows, without its marks. +pub fn markup_visible_len(text: &str) -> usize { + InlineEdit::from_spans(&parse_inline(text)).text().chars().count() +} + +/// The link the caret or selection sits in, as the Link dialog needs it: where it starts +/// and ends in the caret's visible characters, its words and its address. `None` when the +/// caret is not on a link. For a table cell the cell's spans answer, not the block's. +pub fn link_at_caret(block: &Block, caret: &Caret) -> Option<(usize, usize, String, String)> { + if matches!(block, Block::Code { .. } | Block::MathBlock(_)) { + return None; + } + let edit = caret + .inline + .clone() + .or_else(|| caret.cell.and_then(|cell| cell_spans(block, cell)).map(InlineEdit::from_spans)) + .unwrap_or_else(|| InlineEdit::new(block, true)); + let at = caret.selection.0.min(caret.selection.1); + inline_edit::link_span(edit.spans(), at) +} + /// A link written `[text](address)` in a line's editable text that the caret or selection /// (`lo..hi`, in characters) is in: where it starts and ends, in characters, its text and its /// address. A picture (`![...](...)`) is not a link. For the Link dialog (issue #163). @@ -2128,13 +2216,24 @@ pub fn show_blocks( let size = size * zoom; let Some(c) = caret.as_mut() else { continue }; c.ensure_inline(&block); - let previous_selection = c.selection; let inline = c.inline.clone().unwrap_or_default(); // The least line height this paragraph was given, so the words keep their lines // while they are written in as they have when they are read (issue #275). let floor = f32::from(justified.spacing_of(i).unwrap_or_default().line) * zoom; + // The buffer is the visible text; the spans it stands for are laid out with the + // same formatting the finished block uses, re-parsed each frame so the galley + // always matches what is in the box. Code and equations keep their own plain + // source look. + let rich = spans_of(&block).is_some(); + let mut live = inline.clone(); + let colour = if strong { t.strong } else { t.text }; let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, width: f32| { - let mut job = inline.layout(text.as_str(), |text| pagetext::inline_job_with_fonts(ui.ctx(), text, size, strong, t, width, page)); + let mut job = if rich { + live.parse(text.as_str()); + preview::edit_job(ui, live.spans(), size, colour, t, page, width) + } else { + pagetext::inline_job_with_fonts(ui.ctx(), text.as_str(), size, strong, t, width, page) + }; pagetext::floor_lines(ui.ctx(), &mut job, floor); ui.fonts_mut(|f| f.layout_job(job)) }; @@ -2179,10 +2278,7 @@ pub fn show_blocks( action = Some(Action::SetTask(i, done)); } if wrote_changed { - let typed = c.text.clone(); if let Some(b) = blocks.get_mut(i) { - let selection = c.selection; - c.ensure_inline(b).update_at(&typed, previous_selection, selection); c.write(b); } changed.blocks = true; @@ -2425,7 +2521,7 @@ pub fn show_blocks( && ui.input(|i| i.modifiers.command) && !matches!(block, Block::Code { .. } | Block::MathBlock(_)) && let Some((a, _)) = selection - && let Some(href) = pagetext::link_at(&c.text, a) + && let Some((_, _, _, href)) = c.inline.as_ref().and_then(|inline| inline_edit::link_span(inline.spans(), a)) { changed.link = Some(href); } @@ -2459,10 +2555,7 @@ pub fn show_blocks( if resp.changed() { // What was typed goes into the block at once, so the page and the file // follow the caret without waiting for it to leave the block. - let typed = c.text.clone(); if let Some(b) = blocks.get_mut(i) { - let selection = c.selection; - c.ensure_inline(b).update_at(&typed, previous_selection, selection); c.write(b); } changed.blocks = true; @@ -2720,9 +2813,14 @@ pub fn copied_span(blocks: &[Block], across: Across) -> Option> { Block::Code { lang, .. } => Block::Code { lang: lang.clone(), text: picked.to_owned() }, Block::MathBlock(_) => Block::MathBlock(picked.to_owned()), _ => { + // The covering bytes are serialized-source offsets; the spans' selection is + // in visible characters. let a = text.get(..a)?.chars().count(); let b = text.get(..b)?.chars().count(); - Block::Paragraph(InlineEdit::new(block, false).selected(&text, a..b)?) + let edit = InlineEdit::new(block, false); + let prefix = text.chars().count() - Tag::split(&text).1.chars().count(); + let range = edit.visible_pos_of_source(a).saturating_sub(prefix)..edit.visible_pos_of_source(b).saturating_sub(prefix); + Block::Paragraph(edit.slice(range).spans().to_vec()) } }; result.push(fragment); @@ -2740,13 +2838,19 @@ pub fn delete_span(blocks: &mut Vec, across: Across) -> (usize, usize) { let ((first, from), (last, to)) = across.ends(); let head = blocks.get(first).map(block_text).unwrap_or_default(); let tail = blocks.get(last).map(block_text).unwrap_or_default(); - let kept_head = head.get(..from.min(head.len())).unwrap_or("").to_string(); let kept_tail = tail.get(to.min(tail.len())..).unwrap_or("").to_string(); - let at = kept_head.chars().count(); - let mut kept = blocks.get(first).map(|b| InlineEdit::new(b, false)).unwrap_or_default().slice(0..at); - let tail_start = tail.chars().count().saturating_sub(kept_tail.chars().count()); - let end = blocks.get(last).map(|b| InlineEdit::new(b, false)).unwrap_or_default(); - kept.join(end.slice(tail_start..tail.chars().count())); + // The cuts arrive as bytes of the serialized source; the caret's text is the visible + // projection, so they are carried across the spans' own mapping, less the tag marker. + let visible_cut = |block: Option<&Block>, text: &str, source_chars: usize| { + let Some(block) = block else { return 0 }; + let prefix = text.chars().count() - Tag::split(text).1.chars().count(); + InlineEdit::new(block, false).visible_pos_of_source(source_chars).saturating_sub(prefix) + }; + let at = visible_cut(blocks.get(first), &head, chars_of(&head, from.min(head.len()))); + let tail_start = visible_cut(blocks.get(last), &tail, tail.chars().count().saturating_sub(kept_tail.chars().count())); + let mut kept = blocks.get(first).map(|b| InlineEdit::new(b, true)).unwrap_or_default().slice(0..at); + let end = blocks.get(last).map(|b| InlineEdit::new(b, true)).unwrap_or_default(); + kept.join(end.slice(tail_start..end.text().chars().count())); if let Some(b) = blocks.get_mut(first) { let text = kept.text().to_owned(); kept.write(b, &text); @@ -2760,31 +2864,38 @@ pub fn delete_span(blocks: &mut Vec, across: Across) -> (usize, usize) { } /// `covering`'s bytes of `block_text` as bytes of the block's drawn words, which is what -/// the preview's selection bands measure in: the editable text carries marks and the tag -/// marker the drawn line never shows. +/// the preview's selection bands measure in: the drawn line is the visible text minus the +/// tag marker, and neither shows an image or an equation's dollars. fn drawn_covering(block: &Block, a: usize, b: usize) -> Option<(usize, usize)> { - spans_of(block)?; + let spans = spans_of(block)?; + if spans.iter().any(|s| s.math || s.image.is_some()) { + return None; + } let whole = block_text(block); let range = chars_of(&whole, a)..chars_of(&whole, b); - InlineEdit::new(block, false).drawn_range(range) + let edit = InlineEdit::new(block, false); + let (v0, v1) = (edit.visible_pos_of_source(range.start), edit.visible_pos_of_source(range.end)); + // The drawn words are the spans' text without the tag marker, which the preview strips. + let stripped = preview::tagged(spans).map(|(_, stripped)| stripped).unwrap_or_else(|| spans.to_vec()); + let drawn: String = stripped.iter().map(|s| s.text.as_str()).collect(); + let tag = whole.chars().count() - Tag::split(&whole).1.chars().count(); + let byte_at = |at: usize| { + let at = at.saturating_sub(tag).min(drawn.chars().count()); + drawn.char_indices().nth(at).map(|(byte, _)| byte).unwrap_or(drawn.len()) + }; + Some((byte_at(v0), byte_at(v1))) } /// Byte offset in `block_text` of caret-text character `at`. /// -/// The caret's text drops the tag marker and writes an inline image as one character, -/// while `block_text` keeps the marker and the image's markup; `at` counts the caret's -/// characters, so the markup it skipped has to be added back. +/// The caret's text is the visible projection: it drops the tag marker and writes an inline +/// image as one character, while `block_text` keeps the marker and the image's markup; the +/// spans know where each visible character sits in the serialized source. fn byte_of_caret(block: &Block, at: usize) -> usize { let whole = block_text(block); let prefix = whole.chars().count() - Tag::split(&whole).1.chars().count(); - let mut pos = at + prefix; let edit = InlineEdit::new(block, true); - for (image_at, span) in edit.images() { - if *image_at >= at { - break; - } - pos += spans_to_editor(std::slice::from_ref(span)).chars().count().saturating_sub(1); - } + let pos = prefix + edit.source_pos_of_visible(at); byte_of_char(&whole, pos.min(whole.chars().count())) } @@ -2818,27 +2929,29 @@ pub fn format_across(blocks: &mut [Block], across: Across, format: InlineFormat) let whole = block_text(block); let Some((a, b)) = across.covering(index, whole.len()) else { continue }; let (Some(a), Some(b)) = (whole.get(..a), whole.get(..b)) else { continue }; - let covered = (a.chars().count(), b.chars().count()); - // The caret's own text drops the tag marker, which is not words and must not be - // formatted; `covered` is counted in the whole block's text, so the marker's - // characters come off the front of the range. + // `covered` is counted in the serialized source; the caret's text is the visible + // projection, so the range is carried across the spans' own mapping. The tag + // marker's characters come off the front: it is not words and must not be formatted. + let (a, b) = (a.chars().count(), b.chars().count()); + let full = InlineEdit::new(block, false); let prefix = whole.chars().count() - Tag::split(&whole).1.chars().count(); + let range = (full.visible_pos_of_source(a).saturating_sub(prefix), full.visible_pos_of_source(b).saturating_sub(prefix)); let mut edit = InlineEdit::new(block, true); let text = edit.text().to_owned(); - let range = (covered.0.saturating_sub(prefix), covered.1.saturating_sub(prefix)); let Some((formatted, selection)) = edit.format(&text, range, format.clone()) else { continue }; let Some(block) = blocks.get_mut(index) else { continue }; edit.write(block, &formatted); changed = true; - if index == first.0 || index == last.0 { - let now = block_text(block); - let mark = now.chars().count() - Tag::split(&now).1.chars().count(); - let byte_at = |at: usize| byte_of_char(&now, mark + at); + if (index == first.0 || index == last.0) + && let Some(block) = blocks.get(index) + { + // Formatting leaves the visible words where they were; the byte offsets are + // found again through the same visible-to-source map the caret uses. if index == first.0 { - start_byte = Some(byte_at(selection.0.min(selection.1))); + start_byte = Some(byte_of_caret(block, selection.0.min(selection.1))); } if index == last.0 { - end_byte = Some(byte_at(selection.0.max(selection.1))); + end_byte = Some(byte_of_caret(block, selection.0.max(selection.1))); } } } @@ -3097,7 +3210,7 @@ pub struct Wrote { pub fn write_rtl(ui: &mut Ui, c: &mut Caret, size: f32, t: &Tokens, id: egui::Id, page: Option) -> Wrote { let width = ui.available_width().max(32.0); let inline = c.inline.clone().unwrap_or_default(); - let job = inline.layout(&c.text, |text| pagetext::inline_job_with_fonts(ui.ctx(), text, size, false, t, width, page)); + let job = preview::edit_job(ui, inline.spans(), size, t.text, t, page, width); let pieces = job.sections.into_iter().map(|section| (section.byte_range.start.0..section.byte_range.end.0, section.format)).collect::>(); let (drawn, used) = crate::bidi::runs(ui, &c.text, &pieces, size, width, page); // The block's own id, the same one the egui text box uses for a line without @@ -3403,7 +3516,7 @@ fn apply(action: Action, blocks: &mut Vec, caret: &mut Option, cha } renumber(blocks); let land = (start + n).saturating_sub(1).min(blocks.len().saturating_sub(1)); - let text = blocks.get(land).map(block_text).unwrap_or_default(); + let text = text_for_caret(blocks, land); let end = text.chars().count(); *caret = Some(Caret { block: land, text, focus: true, selection: (end, end), place: Some(end), cell: None, span: None, inline: None }); changed.blocks = true; @@ -3608,8 +3721,12 @@ fn char_under(ui: &Ui, block: &Block, resp: &egui::Response, pos: egui::Pos2, t: return at; } let (size, strong) = size_of(block); + let offset = pos - resp.rect.min - egui::vec2(lead_width(block), 0.0); + if let Some(spans) = spans_of(block) { + return char_at_spans(ui, spans, size, strong, t, resp.rect.width(), offset, page); + } let text = caret_text(block); - char_at(ui, &text, size, strong, t, resp.rect.width(), pos - resp.rect.min - egui::vec2(lead_width(block), 0.0), page) + char_at(ui, &text, size, strong, t, resp.rect.width(), offset, page) } /// Where a click on a finished block lands in the text the caret writes in. @@ -3632,11 +3749,8 @@ fn char_under_drawn(ui: &Ui, block: &Block, resp: &egui::Response, pos: egui::Po Some((_, stripped)) => (stripped, 21.0), None => (spans.clone(), 0.0), }; - // The walk below counts the marks span by span. That count is only right when the marks - // it counts are the ones the caret's text really has, so the two are compared first. - if spans_to_editor(&spans) != caret_text(block) { - return None; - } + // The drawn words and the caret's visible text are the same characters now that the + // caret edits what it shows, so a character measured in one is the same in the other. let drawn: String = spans.iter().map(|s| s.text.as_str()).collect(); let lead = mark + lead_width(block); // A row that reads right to left keeps its bullet and its tag mark on the right, so its @@ -3652,10 +3766,11 @@ fn char_under_drawn(ui: &Ui, block: &Block, resp: &egui::Response, pos: egui::Po } else { char_at(ui, &drawn, size, strong, t, column, vec2(x, rel.y), page) }; - Some(over_marks(&spans, at)) + Some(at) } /// A character of the drawn words, as a character of the same line written with its marks. +#[cfg(test)] fn over_marks(spans: &[Span], drawn: usize) -> usize { let source = spans_to_editor(spans); if drawn >= spans.iter().map(|span| span.text.chars().count()).sum() { @@ -3695,11 +3810,11 @@ fn link_in(block: &Block, at: usize, page: Option) -> Opti if matches!(block, Block::Code { .. } | Block::MathBlock(_)) { return None; } - let text = caret_text(block); - if crate::bidi::paints(&text, page) { + let edit = InlineEdit::new(block, true); + if crate::bidi::paints(edit.text(), page) { return None; } - pagetext::link_at(&text, at) + inline_edit::link_span(edit.spans(), at).map(|(_, _, _, href)| href) } /// The link under the pointer at `pos` in a finished block, if the pointer is on one. A @@ -4405,7 +4520,7 @@ ordinary words ); assert!(is_page_stamp(&old, 1)); assert_eq!(text_for_caret(&old, 1), "Monday, 19 October 2026, 05:00"); - assert_eq!(caret_text(&old[1]), "*Monday, 19 October 2026, 05:00*", "while any other line keeps its marks"); + assert_eq!(caret_text(&old[1]), "Monday, 19 October 2026, 05:00", "while any other line keeps its marks"); // A paragraph that is not a date is an ordinary paragraph wherever it sits. let not = blocks( diff --git a/crates/ui-egui/src/pageedit/inline_edit.rs b/crates/ui-egui/src/pageedit/inline_edit.rs index 39198778..15c85141 100644 --- a/crates/ui-egui/src/pageedit/inline_edit.rs +++ b/crates/ui-egui/src/pageedit/inline_edit.rs @@ -1,61 +1,217 @@ -//! Retains literal punctuation and atomic images while the existing Markdown-style editor -//! edits its visible source. Storage quoting belongs to the formats crate, never the widget. +//! Retains formatting while the editor works on the words a reader sees. The spans are the +//! document; `text` is their visible projection (an inline image is one object character, +//! every other span is its own words). Edits arrive as visible text and are folded back into +//! the spans, so marks, links, fonts and literal punctuation survive without ever being +//! shown. +//! +//! `literal` marks which visible characters must stay words: everything that was already in +//! the block. Characters the user types arrive unmarked, so Markdown they type still parses +//! (`**bold**` becomes bold) while stored literal punctuation (`*literal*`) never does — +//! even when a formatting wrap is put around it. Storage quoting belongs to the formats +//! crate, never the widget. -use std::collections::BTreeMap; use std::ops::Range; use notecraft_formats::markdown::{Block, Span, parse_inline}; use notecraft_formats::render::editable_spans; use notecraft_model::Tag; -use super::{FontSelection, INLINE_IMAGE_CHAR, InlineFormat, block_text, format_source_selection, selection_fonts, spans_to_editor}; +use super::{FontSelection, INLINE_IMAGE_CHAR, InlineFormat, block_text, format_span_range, paint_span_range, spans_of, spans_to_editor}; #[derive(Clone, Debug, Default, PartialEq)] pub struct InlineEdit { + spans: Vec, text: String, literal: Vec, - images: Vec<(usize, Span)>, + /// True while `spans`/`text` are the caret's view: the tag marker was taken off the + /// front and goes back on when the block is written. + caret: bool, } -#[derive(Clone)] -enum Atom { - Literal(char), - Image(Span), +/// The words one span shows while editing: an image is one object character, everything +/// else is its own text (code ticks, link targets, maths dollars and style tags are markup, +/// not words). +fn visible_piece(span: &Span) -> String { + if span.image.is_some() { INLINE_IMAGE_CHAR.to_string() } else { span.text.clone() } } -type Projection = (String, Vec<(char, Atom)>); +fn visible_text(spans: &[Span]) -> String { + spans.iter().map(visible_piece).collect() +} + +/// How many visible characters a span covers. +fn visible_len(span: &Span) -> usize { + if span.image.is_some() { 1 } else { span.text.chars().count() } +} + +/// A span that carries no formatting of its own: its words could still be read as Markdown. +fn plain(span: &Span) -> bool { + span.image.is_none() + && !span.math + && !span.code + && !span.bold + && !span.italic + && !span.strike + && !span.underline + && span.script.is_none() + && span.font_size.is_none() + && span.font_family.is_none() + && span.colour.is_none() + && span.highlight.is_none() + && span.link.is_none() +} + +/// Characters that can open or close inline markup; a stored one of these at the edge of +/// an edit may be the other half of syntax the user just typed. +fn is_markup_char(c: char) -> bool { + matches!(c, '*' | '_' | '~' | '$' | '[' | ']' | '<' | '>' | '`' | '!' | '\\') +} + +/// Adjacent spans with the same formatting are one run to the reader and to the writer. +fn merge(spans: Vec) -> Vec { + let mut out: Vec = Vec::new(); + for span in spans { + match out.last_mut() { + Some(last) + if last.image.is_none() + && span.image.is_none() + && Span { text: String::new(), ..last.clone() } == Span { text: String::new(), ..span.clone() } => + { + last.text.push_str(&span.text); + } + _ => out.push(span), + } + } + out +} + +/// The spans covering visible characters `range`, edge spans trimmed to the range. An image +/// is atomic: it is in whole or not at all. +fn take_spans(spans: &[Span], range: Range) -> Vec { + let (start, end) = (range.start, range.end); + if start >= end { + return Vec::new(); + } + let mut out = Vec::new(); + let mut at = 0usize; + for span in spans { + let len = visible_len(span); + let next = at + len; + if next > start && at < end { + if span.image.is_some() { + out.push(span.clone()); + } else { + let a = start.saturating_sub(at).min(span.text.chars().count()); + let b = end.saturating_sub(at).min(span.text.chars().count()); + if a < b { + let chars: Vec = span.text.chars().collect(); + out.push(Span { text: chars[a..b].iter().collect(), ..span.clone() }); + } + } + } + at = next; + if at >= end { + break; + } + } + out +} + +/// Fill the fields a fragment does not set itself from the span the caret sits in, the way +/// typing inside a bold or sized run continues it. Explicit marks in the fragment win. +fn inherit(span: &mut Span, donor: Option<&Span>) { + let Some(donor) = donor.filter(|d| d.image.is_none()) else { return }; + span.bold |= donor.bold; + span.italic |= donor.italic; + span.strike |= donor.strike; + span.underline |= donor.underline; + if span.script.is_none() { + span.script = donor.script; + } + span.code |= donor.code; + span.math |= donor.math; + if span.font_size.is_none() { + span.font_size = donor.font_size; + } + if span.font_family.is_none() { + span.font_family = donor.font_family.clone(); + } + if span.colour.is_none() { + span.colour = donor.colour.clone(); + } + if span.highlight.is_none() { + span.highlight = donor.highlight.clone(); + } + if span.link.is_none() { + span.link = donor.link.clone(); + } +} + +/// Which old character each new character continues, by longest common subsequence, so a +/// stored literal character copied into an edit (a wrap puts marks around it) keeps its +/// protection while the marks around it are free to parse. +fn lcs_align(old: &[char], new: &[char]) -> Vec> { + let (n, m) = (old.len(), new.len()); + let mut out = vec![None; m]; + if n == 0 || m == 0 || n.saturating_mul(m) > 1_000_000 { + return out; + } + let mut dp = vec![vec![0u32; m + 1]; n + 1]; + for i in (0..n).rev() { + for j in (0..m).rev() { + dp[i][j] = if old[i] == new[j] { dp[i + 1][j + 1] + 1 } else { dp[i + 1][j].max(dp[i][j + 1]) }; + } + } + let (mut i, mut j) = (0, 0); + while i < n && j < m { + if old[i] == new[j] && dp[i][j] == dp[i + 1][j + 1] + 1 { + out[j] = Some(i); + i += 1; + j += 1; + } else if dp[i + 1][j] >= dp[i][j + 1] { + i += 1; + } else { + j += 1; + } + } + out +} + +/// The link a visible character position sits in: where it starts and ends in visible +/// characters, its words and its address. For the Link dialog and Ctrl+click. +pub(super) fn link_span(spans: &[Span], at: usize) -> Option<(usize, usize, String, String)> { + let mut pos = 0usize; + let len = spans.iter().map(visible_len).sum::(); + let at = at.min(len.saturating_sub(1)); + for span in spans { + let len = visible_len(span); + let next = pos + len; + if at < next { + let href = span.link.clone().filter(|_| span.image.is_none())?; + return Some((pos, next, span.text.clone(), href)); + } + pos = next; + } + None +} impl InlineEdit { pub(super) fn from_spans(spans: &[Span]) -> Self { - let (text, literal) = editable_spans(spans); - Self { text, literal, images: Vec::new() } + let text = visible_text(spans); + Self { spans: spans.to_vec(), literal: vec![true; text.chars().count()], text, caret: false } } pub(super) fn new(block: &Block, caret: bool) -> Self { let fallback = [Span { text: block_text(block), ..Default::default() }]; - let spans = super::spans_of(block).unwrap_or(&fallback); - let mut result = Self::from_spans(spans); + let mut result = Self::from_spans(spans_of(block).unwrap_or(&fallback)); + result.caret = caret; if caret { - let prefix = result.text.chars().count() - Tag::split(&result.text).1.chars().count(); - result = result.slice(prefix..result.literal.len()); - let mut after = 0; - for span in spans.iter().filter(|span| span.image.is_some()) { - let source = spans_to_editor(std::slice::from_ref(span)); - let found = result.text.get(after..).and_then(|rest| { - rest.match_indices(&source).map(|(relative, _)| after + relative).find(|start| { - let a = result.text[..*start].chars().count(); - !result.literal[a..a + source.chars().count()].iter().any(|literal| *literal) - }) - }); - if let Some(start) = found { - let a = result.text[..start].chars().count(); - let b = a + source.chars().count(); - result.replace_metadata(a..b, 1); - result.text.replace_range(start..start + source.len(), &INLINE_IMAGE_CHAR.to_string()); - result.images.push((a, span.clone())); - after = start + INLINE_IMAGE_CHAR.len_utf8(); - } - } + // The tag marker is drawn as a mark beside the line, not as words. + let whole = spans_to_editor(&result.spans); + let prefix = whole.chars().count() - Tag::split(&whole).1.chars().count(); + result.spans = take_spans(&result.spans, prefix..usize::MAX); + result.text = visible_text(&result.spans); + result.literal = vec![true; result.text.chars().count()]; } result } @@ -64,348 +220,497 @@ impl InlineEdit { &self.text } - /// Where each inline image sits in the caret's text, with the span it stands for. - pub(super) fn images(&self) -> &[(usize, Span)] { - &self.images + /// The spans the visible text stands for. + pub(super) fn spans(&self) -> &[Span] { + &self.spans } - /// The range of a block's drawn words that editable-text characters `range` cover, - /// as bytes of the drawn text. The drawn text is what the preview lays out: the - /// marks and the tag marker are not in it, so a byte of the editable text is not a - /// byte of it. The covered characters are found by marking them in the editable - /// text, parsing it back the way the caret does, and counting the drawn characters - /// up to the marks. - pub(super) fn drawn_range(&mut self, range: Range) -> Option<(usize, usize)> { - let text = self.text.clone(); - let (projected, mapping) = self.project(&text)?; - let chars: Vec = projected.chars().collect(); - let (start, end) = (range.start.min(chars.len()), range.end.min(chars.len())); - if start >= end { - return None; + /// Fold an edited visible text back into spans. + /// + /// The unchanged head and tail keep their spans. The changed middle is reparsed as + /// inline Markdown over the run of unmarked characters around it — the characters the + /// user has been typing — so `**bold**` becomes bold while stored `*literal*` stars, + /// which are marked, stay literal even inside a formatting wrap. When the run replaces + /// most of what was there (a selection typed over), the new characters are all fresh + /// input and parse as Markdown outright. The run then inherits the style of the span + /// it landed in, so typing inside a sized or coloured run continues it. `text` itself + /// may still carry markup the parse consumed (a wrap puts `` around the + /// selection); the stored text is always the canonical visible projection of the spans. + pub(super) fn parse(&mut self, text: &str) -> Vec { + let old = std::mem::take(&mut self.text); + if old == text { + self.text = old; + return self.spans.clone(); } - let mut markers = - ('\u{e000}'..='\u{f8ff}').chain('\u{f0000}'..='\u{ffffd}').chain('\u{100000}'..='\u{10fffd}').filter(|c| !projected.contains(*c)); - let (open, close) = (markers.next()?, markers.next()?); - let mut marked = String::new(); - for at in 0..=chars.len() { - if at == start { - marked.push(open); + let old_chars: Vec = old.chars().collect(); + let new_chars: Vec = text.chars().collect(); + let prefix = old_chars.iter().zip(&new_chars).take_while(|(a, b)| a == b).count(); + let suffix = old_chars[prefix..].iter().rev().zip(new_chars[prefix..].iter().rev()).take_while(|(a, b)| a == b).count(); + let old_end = old_chars.len().saturating_sub(suffix); + let new_end = new_chars.len().saturating_sub(suffix); + // Old characters the run absorbed at its edges: they parse as fresh markup input. + let mut freed = vec![false; old_chars.len()]; + // The hot run: the unmarked characters around the edit, in both texts. Everything + // outside it is stored words and keeps its spans and its marks. When the common + // head and tail cannot be told apart (they overlap), the whole line is the run. + let (run_start, run_end, new_run_end, whole) = if prefix > old_end || prefix > new_end { + (0, old_chars.len(), new_chars.len(), true) + } else { + let (mut run_start, mut run_end) = (prefix, old_end); + while run_start > 0 && !self.literal.get(run_start - 1).copied().unwrap_or(true) { + run_start -= 1; + } + while run_end < old_chars.len() && !self.literal.get(run_end).copied().unwrap_or(true) { + run_end += 1; } - if at == end { - marked.push(close); + let mut new_run_end = new_chars.len().saturating_sub(old_chars.len() - run_end).min(new_chars.len()); + // A stored character that coincides with markup the edit put at the run's edge + // is part of the edit, not an unchanged neighbour: `**bold**` typed where + // `*literal*` stood must see both stars, or `*bold*` parses as italic between + // leftover stars. The absorbed character is freed from literal protection. + while run_start > 0 + && self.literal.get(run_start - 1).copied().unwrap_or(false) + && new_chars.get(run_start) == old_chars.get(run_start - 1) + && is_markup_char(old_chars[run_start - 1]) + { + run_start -= 1; + freed[run_start] = true; } - if let Some(c) = chars.get(at) { - marked.push(*c); + while run_end < old_chars.len() + && new_run_end > run_start + && self.literal.get(run_end).copied().unwrap_or(false) + && new_chars.get(new_run_end - 1) == old_chars.get(run_end) + && is_markup_char(old_chars[run_end]) + { + run_end += 1; + new_run_end += 1; + freed[run_end - 1] = true; + } + // In the new text the same run ends where the marked suffix resumes. + (run_start, run_end, new_run_end.min(new_chars.len()), false) + }; + let old_run = &old_chars[run_start..run_end]; + let new_run = &new_chars[run_start..new_run_end]; + let aligned = lcs_align(old_run, new_run); + // A run that replaced most of the old words is fresh input: nothing in it continues + // a stored character, so nothing keeps literal protection. That is what lets + // `**bold**` typed over a selection become bold instead of `*` + italic + `*`. + let matched: std::collections::HashSet = aligned.iter().flatten().copied().collect(); + let fresh = matched.len() * 2 < old_run.len(); + // Where the run lands: the span holding its first character, for inherited style. + let mut at = 0usize; + let mut donor = None; + if !whole { + for (index, span) in self.spans.iter().enumerate() { + let len = visible_len(span); + if run_start < at + len || (run_start == at + len && index + 1 == self.spans.len()) { + donor = Some(span.clone()); + break; + } + at += len; } } - let spans = Self::restore_spans(parse_inline(&marked), &mapping); - if spans.iter().any(|s| s.math) { - return None; + // The images the run's object characters stand for, in document order. + let image_pool: Vec = self.spans.iter().filter(|s| s.image.is_some()).cloned().collect(); + let mut image_at = 0usize; + // Project the run: characters that continue a marked old character become private + // markers so the parser keeps them words; everything else is free to be Markdown. + let mut markers = + ('\u{e000}'..='\u{f8ff}').chain('\u{f0000}'..='\u{ffffd}').chain('\u{100000}'..='\u{10fffd}').filter(|c| !text.contains(*c)); + // Characters continuing a stored marked character stay literal for good; the rest + // are fresh input the parser may read as Markdown. + let stored: Vec = new_run + .iter() + .enumerate() + .map(|(i, _)| !fresh && aligned[i].map(|j| run_start + j).is_some_and(|g| self.literal.get(g).copied().unwrap_or(false) && !freed[g])) + .collect(); + // A mark with no partner yet is still being typed: `**bold*` must stay words until + // the closing stars arrive, or the half-formed pair italicises "bold" and the + // canonical text loses the stars the next keystroke needs. These stay pending, so + // the completed `**bold**` parses as bold on the next edit. + let mut typed = vec![false; new_run.len()]; + for mark in ['*', '_', '~'] { + if new_run.iter().zip(&stored).filter(|(c, s)| !**s && **c == mark).count() % 2 == 1 { + for (t, c) in typed.iter_mut().zip(new_run) { + if *c == mark { + *t = true; + } + } + } } - let mut drawn = String::new(); - let mut at = 0usize; - let (mut a, mut b) = (None, None); - for span in spans.iter().filter(|s| s.image.is_none()) { + let marked: Vec = stored.iter().zip(&typed).map(|(s, t)| *s || *t).collect(); + let mut projected = String::new(); + let mut restore: Vec<(char, char, bool)> = Vec::new(); + for (i, c) in new_run.iter().enumerate() { + if marked[i] { + let marker = markers.next().unwrap_or(*c); + projected.push(marker); + restore.push((marker, *c, stored[i])); + } else { + projected.push(*c); + } + } + let fragment = parse_inline(&projected); + let mut spans = take_spans(&self.spans, 0..run_start); + let mut literal = self.literal[..run_start.min(self.literal.len())].to_vec(); + for span in fragment { + // Whether the parser gave this run marks of its own, decided before the donor's + // style is inherited: inherited formatting does not finish pending syntax. + let finished = !plain(&span); + if span.image.is_some() { + let mut span = span; + inherit(&mut span, donor.as_ref()); + literal.push(true); + spans.push(span); + continue; + } + let mut pending = span.clone(); + inherit(&mut pending, donor.as_ref()); + let mut buf = String::new(); + let mut flags: Vec = Vec::new(); + let flush = |buf: &mut String, flags: &mut Vec, spans: &mut Vec, literal: &mut Vec| { + if buf.is_empty() { + return; + } + spans.push(Span { text: std::mem::take(buf), ..pending.clone() }); + literal.append(flags); + }; for c in span.text.chars() { - if c == open { - a = Some(at); - } else if c == close { - b = Some(at); + if let Some((_, original, kept)) = restore.iter().find(|(m, _, _)| *m == c) { + if *original == INLINE_IMAGE_CHAR { + flush(&mut buf, &mut flags, &mut spans, &mut literal); + match image_pool.get(image_at) { + Some(image) => { + image_at += 1; + spans.push(image.clone()); + literal.push(true); + } + None => { + buf.push(*original); + flags.push(true); + } + } + } else { + buf.push(*original); + // A stored character stays literal; one protected only because its + // mark was still being typed finishes with the run around it. + flags.push(*kept || finished); + } + } else if c == INLINE_IMAGE_CHAR { + flush(&mut buf, &mut flags, &mut spans, &mut literal); + match image_pool.get(image_at) { + Some(image) => { + image_at += 1; + spans.push(image.clone()); + literal.push(true); + } + None => { + buf.push(c); + flags.push(true); + } + } } else { - drawn.push(c); - at += 1; + buf.push(c); + flags.push(finished); } } + flush(&mut buf, &mut flags, &mut spans, &mut literal); } - let (Some(a), Some(b)) = (a, b) else { return None }; - // The tag marker is drawn as a mark beside the line, not as words. - let prefix = drawn.chars().count() - Tag::split(&drawn).1.chars().count(); - let real = drawn.char_indices().nth(prefix).map(|(byte, _)| &drawn[byte..]).unwrap_or(""); - let byte_at = |char_at: usize| { - let char_at = char_at.saturating_sub(prefix); - real.char_indices().nth(char_at).map(|(byte, _)| byte).unwrap_or(real.len()) - }; - Some((byte_at(a), byte_at(b))) + spans.extend(take_spans(&self.spans, run_end..usize::MAX)); + literal.extend_from_slice(&self.literal[run_end.min(self.literal.len())..]); + self.adopt_with_literal(spans, literal); + self.spans.clone() } - pub(super) fn slice(&self, range: Range) -> Self { - let start = range.start.min(self.literal.len()); - let end = range.end.min(self.literal.len()).max(start); - Self { - text: self.text.chars().skip(start).take(end - start).collect(), - literal: self.literal[start..end].to_vec(), - images: self.images.iter().filter(|(at, _)| *at >= start && *at < end).map(|(at, span)| (at - start, span.clone())).collect(), + /// [`adopt`], keeping the per-character literal flags the edit computed. + fn adopt_with_literal(&mut self, spans: Vec, mut literal: Vec) { + self.spans = merge(spans); + self.text = visible_text(&self.spans); + if literal.len() != self.text.chars().count() { + literal = vec![true; self.text.chars().count()]; } + self.literal = literal; } - pub(super) fn join(&mut self, other: Self) { - let offset = self.literal.len(); - self.text.push_str(&other.text); - self.literal.extend(other.literal); - self.images.extend(other.images.into_iter().map(|(at, span)| (at + offset, span))); - } - - fn replace_metadata(&mut self, range: Range, inserted: usize) { - self.literal.splice(range.clone(), std::iter::repeat_n(false, inserted)); - self.images.retain_mut(|(at, _)| { - if *at >= range.end { - *at = *at - (range.end - range.start) + inserted; - true - } else { - *at < range.start + /// The serialized-source entry point kept for callers that still hand over `block_text`: + /// tags, direction marks and block-kind changes arrive as serialized text. Literal + /// punctuation lines up with the mask the spans' own serialization reports. + pub(super) fn parse_source(&self, text: &str) -> Vec { + let source = spans_to_editor(&self.spans); + let (source_chars, text_chars): (Vec, Vec) = (source.chars().collect(), text.chars().collect()); + let prefix = source_chars.iter().zip(&text_chars).take_while(|(a, b)| a == b).count(); + let suffix = source_chars[prefix..].iter().rev().zip(text_chars[prefix..].iter().rev()).take_while(|(a, b)| a == b).count(); + let (_, mask) = editable_spans(&self.spans); + let mut literal = vec![false; text_chars.len()]; + let n = prefix.min(mask.len()); + literal[..n].copy_from_slice(&mask[..n]); + let tail_start = text_chars.len() - suffix; + let source_tail = source_chars.len() - suffix; + for i in 0..suffix { + if let Some(m) = mask.get(source_tail + i) { + literal[tail_start + i] = *m; } - }); - } - - fn update(&mut self, text: &str) { - if self.text == text { - return; - } - let before: Vec = self.text.chars().collect(); - let after: Vec = text.chars().collect(); - let prefix = before.iter().zip(&after).take_while(|(a, b)| a == b).count(); - let suffix = before[prefix..].iter().rev().zip(after[prefix..].iter().rev()).take_while(|(a, b)| a == b).count(); - self.replace_metadata(prefix..before.len() - suffix, after.len() - prefix - suffix); - self.text = text.to_owned(); - } - - /// Use the widget's actual replacement range, including equal characters at its edges. - /// A text diff alone cannot distinguish replacing '*literal*' from retaining its stars. - pub(super) fn update_at(&mut self, text: &str, before_selection: (usize, usize), after_selection: (usize, usize)) { - let before: Vec = self.text.chars().collect(); - let after: Vec = text.chars().collect(); - let mut a = before_selection.0.min(before_selection.1).min(before.len()); - let mut b = before_selection.0.max(before_selection.1).min(before.len()); - if a == b && after.len() < before.len() { - a = after_selection.0.min(after_selection.1).min(before.len()); - b = (a + before.len() - after.len()).min(before.len()); - } - if let Some(inserted) = after.len().checked_add(b - a).and_then(|len| len.checked_sub(before.len())) - && after.get(..a) == before.get(..a) - && after.get(a + inserted..) == before.get(b..) - { - self.replace_metadata(a..b, inserted); - self.text = text.to_owned(); - return; } - self.update(text); - } - - // A temporary single-character projection lets existing parsing/formatting keep its - // character offsets. Choose markers absent from user text, and restore before output. - fn project(&mut self, text: &str) -> Option { - self.update(text); - let mut mapping = Vec::new(); - let mut available = + let mut markers = ('\u{e000}'..='\u{f8ff}').chain('\u{f0000}'..='\u{ffffd}').chain('\u{100000}'..='\u{10fffd}').filter(|c| !text.contains(*c)); let mut projected = String::new(); - for (at, (c, literal)) in text.chars().zip(&self.literal).enumerate() { - let image = self.images.iter().find(|(index, _)| *index == at).map(|(_, span)| span); - if let Some(image) = image { - let marker = available.next()?; - mapping.push((marker, Atom::Image(image.clone()))); + let mut restore = Vec::new(); + for (i, c) in text_chars.iter().enumerate() { + if literal.get(i).copied().unwrap_or(false) { + let marker = markers.next().unwrap_or(*c); projected.push(marker); - } else if *literal { - if let Some((marker, _)) = mapping.iter().find(|(_, atom)| matches!(atom, Atom::Literal(original) if *original == c)) { - projected.push(*marker); - } else { - let marker = available.next()?; - mapping.push((marker, Atom::Literal(c))); - projected.push(marker); - } + restore.push((marker, *c)); } else { - projected.push(c); + projected.push(*c); } } - Some((projected, mapping)) + let mut spans = parse_inline(&projected); + if !restore.is_empty() { + for span in &mut spans { + span.text = span.text.chars().map(|c| restore.iter().find(|(m, _)| *m == c).map_or(c, |(_, original)| *original)).collect(); + } + } + spans + } + + pub(super) fn slice(&self, range: Range) -> Self { + let spans = take_spans(&self.spans, range.clone()); + let text = visible_text(&spans); + let literal = self.literal.get(range.start..range.end).map(<[bool]>::to_vec).unwrap_or_else(|| vec![true; text.chars().count()]); + Self { spans, text, literal, caret: self.caret } } - fn restored_char(c: char, mapping: &[(char, Atom)]) -> char { - match mapping.iter().find(|(marker, _)| *marker == c).map(|(_, atom)| atom) { - Some(Atom::Literal(original)) => *original, - Some(Atom::Image(_)) => INLINE_IMAGE_CHAR, - None => c, + pub(super) fn join(&mut self, other: Self) { + self.spans.extend(other.spans); + self.spans = merge(std::mem::take(&mut self.spans)); + self.text = visible_text(&self.spans); + self.literal.extend(other.literal); + if self.literal.len() != self.text.chars().count() { + self.literal = vec![true; self.text.chars().count()]; } } - fn restore(text: &str, mapping: &[(char, Atom)]) -> String { - text.chars().map(|c| Self::restored_char(c, mapping)).collect() + /// [`format_span_range`] on the visible selection: the words change marks, the text the + /// caret edits does not. + pub(super) fn format(&mut self, _text: &str, selection: (usize, usize), format: InlineFormat) -> Option<(String, (usize, usize))> { + let mut spans = self.spans.clone(); + if !format_span_range(&mut spans, selection.0.min(selection.1)..selection.0.max(selection.1), format) { + return Some((self.text.clone(), selection)); + } + self.spans = merge(spans); + self.text = visible_text(&self.spans); + Some((self.text.clone(), selection)) } - fn restore_spans(spans: Vec, mapping: &[(char, Atom)]) -> Vec { - let mut result = Vec::new(); - for span in spans { - if span.text.is_empty() { - result.push(span); - continue; - } - let mut text = String::new(); - for c in span.text.chars() { - if let Some((_, Atom::Image(image))) = mapping.iter().find(|(marker, _)| *marker == c) { - if !text.is_empty() { - result.push(Span { text: std::mem::take(&mut text), ..span.clone() }); - } - result.push(image.clone()); - } else { - text.push(Self::restored_char(c, mapping)); - } - } - if !text.is_empty() { - result.push(Span { text, ..span }); - } + /// [`paint_span_range`] on the visible selection. + pub(super) fn paint(&mut self, _text: &str, selection: (usize, usize), style: &Span) -> Option<(String, (usize, usize))> { + let mut spans = self.spans.clone(); + if !paint_span_range(&mut spans, selection.0.min(selection.1)..selection.0.max(selection.1), style) { + return Some((self.text.clone(), selection)); } - result + self.spans = merge(spans); + self.text = visible_text(&self.spans); + Some((self.text.clone(), selection)) } - // Collision-free fallback for text containing every private-use marker. - fn escaped_source(&self) -> String { - let mut source = String::new(); - for (at, (c, literal)) in self.text.chars().zip(&self.literal).enumerate() { - if let Some((_, image)) = self.images.iter().find(|(index, _)| *index == at) { - source.push_str(¬ecraft_formats::render::spans_to_markdown(std::slice::from_ref(image))); - } else { - if *literal { - source.push('\\'); + /// The formatting at the caret or of its selection, read off the spans directly. + pub(super) fn style(&self, _text: &str, selection: (usize, usize)) -> Option { + let (lo, hi) = (selection.0.min(selection.1), selection.0.max(selection.1)); + let len = self.text.chars().count(); + if hi > len { + return None; + } + let at = if lo == hi { lo.saturating_sub(1).min(len.saturating_sub(1)) } else { lo }; + let mut pos = 0usize; + for span in &self.spans { + let len = visible_len(span); + if at < pos + len { + if span.image.is_some() || span.math { + return None; } - source.push(c); + return Some(Span { text: String::new(), link: None, image: None, math: false, ..span.clone() }); } + pos += len; } - source + self.spans.last().and_then(|span| { + (!span.text.is_empty() && span.image.is_none() && !span.math).then(|| Span { + text: String::new(), + link: None, + image: None, + math: false, + ..span.clone() + }) + }) } - fn parse_tagged(&mut self, text: &str, tag: Option) -> Vec { - if let Some((projected, mapping)) = self.project(text) { - let source = tag.map_or(projected.clone(), |tag| Tag::set(&projected, Some(tag))); - Self::restore_spans(parse_inline(&source), &mapping) - } else { - let source = self.escaped_source(); - parse_inline(&tag.map_or(source.clone(), |tag| Tag::set(&source, Some(tag)))) + pub(super) fn fonts(&self, _text: &str, selection: (usize, usize)) -> Option { + let (lo, hi) = (selection.0.min(selection.1), selection.0.max(selection.1)); + let len = self.text.chars().count(); + if hi > len { + return None; } + let spans = if lo == hi { + let at = lo.saturating_sub(1).min(len.saturating_sub(1)); + let mut pos = 0usize; + self.spans + .iter() + .find(|span| { + let l = visible_len(span); + let hit = at < pos + l; + pos += l; + hit + }) + .cloned() + .into_iter() + .collect::>() + } else { + take_spans(&self.spans, lo..hi) + }; + let spans: Vec = spans.into_iter().filter(|s| !s.text.is_empty() && s.image.is_none()).collect(); + (!spans.is_empty()).then(|| FontSelection::from_spans(&spans)) } - /// Select from the complete projected line so surrounding formatting still applies. - /// Markers are absent from the input and are discarded before anything leaves this helper. - pub(super) fn selected(&mut self, text: &str, range: Range) -> Option> { - let (projected, mapping) = self.project(text)?; - let chars: Vec = projected.chars().collect(); - let start = range.start.min(chars.len()); - let end = range.end.min(chars.len()); - if start >= end { - return None; - } - let mut markers = ('\u{e000}'..='\u{f8ff}').chain('\u{f0000}'..='\u{ffffd}').filter(|c| !projected.contains(*c)); - let open = markers.next()?; - let close = markers.next()?; - let mut marked = String::new(); - for at in 0..=chars.len() { - if at == start { - marked.push(open); + /// The visible character position of a serialized-source character position, for the + /// across-block selection that still counts bytes of `block_text`. + pub(super) fn visible_pos_of_source(&self, source_pos: usize) -> usize { + let mut source = 0usize; + let mut visible = 0usize; + for span in &self.spans { + let ser = spans_to_editor(std::slice::from_ref(span)); + let ser_len = ser.chars().count(); + let vis_len = visible_len(span); + if span.image.is_some() { + if source_pos <= source { + return visible; + } + if source_pos >= source + ser_len { + source += ser_len; + visible += vis_len; + continue; + } + return visible + usize::from(source_pos > source); } - if at == end { - marked.push(close); + // The text sits inside the marks; positions inside the marks clamp to the edge. + let open = ser.find(&span.text).map(|byte| ser[..byte].chars().count()).unwrap_or(0); + let text_len = span.text.chars().count(); + if source_pos < source + open { + return visible; } - if let Some(c) = chars.get(at) { - marked.push(*c); + if source_pos <= source + open + text_len { + return visible + (source_pos - source - open).min(text_len); } + source += ser_len; + visible += vis_len; } - let mut selected = Vec::new(); - let mut inside = false; - let mut opened = false; - let mut closed = false; - for span in parse_inline(&marked) { - let mut text = String::new(); - for c in span.text.chars() { - if c == open { - inside = true; - opened = true; - } else if c == close { - inside = false; - closed = true; - } else if inside { - text.push(c); + visible + } + + /// The serialized-source character position of a visible character position. + pub(super) fn source_pos_of_visible(&self, visible_pos: usize) -> usize { + let mut source = 0usize; + let mut visible = 0usize; + for span in &self.spans { + let ser = spans_to_editor(std::slice::from_ref(span)); + let ser_len = ser.chars().count(); + let vis_len = visible_len(span); + if visible_pos <= visible + vis_len || visible + vis_len >= self.text.chars().count() { + if span.image.is_some() { + return source + if visible_pos > visible { ser_len } else { 0 }; } + let open = ser.find(&span.text).map(|byte| ser[..byte].chars().count()).unwrap_or(0); + let text_len = span.text.chars().count(); + let inside = (visible_pos - visible).min(text_len); + return source + open + inside; } - if !text.is_empty() { - selected.push(Span { text, ..span }); - } + source += ser_len; + visible += vis_len; } - let spans = Self::restore_spans(selected, &mapping); - (opened && closed && !spans.is_empty()).then_some(spans) + source } - pub(super) fn parse(&mut self, text: &str) -> Vec { - self.parse_tagged(text, None) + /// The spans covering a visible range, for the clipboard. + pub(super) fn selected(&mut self, _text: &str, range: Range) -> Option> { + let spans = take_spans(&self.spans, range); + (!spans.is_empty()).then_some(spans) } - pub(super) fn write(&mut self, block: &mut Block, text: &str) { - let tag = Tag::split(&block_text(block)).0; - let spans = self.parse_tagged(text, tag); + /// Write the spans back into a block without reparsing: the text already is the + /// canonical visible projection, so the formatting `format`/`paint` applied is kept + /// exactly, and the tag marker goes back on the front for the caret's view. + fn commit(&self, block: &mut Block) { + let mut spans = self.spans.clone(); + if self.caret + && let Some(tag) = Tag::split(&block_text(block)).0 + { + spans.insert(0, Span { text: tag.marker(), ..Default::default() }); + } + let spans = merge(spans); match block { Block::Heading { spans: value, .. } | Block::Paragraph(value) | Block::Quote(value) | Block::Item { spans: value, .. } => *value = spans, - Block::Code { text: value, .. } | Block::MathBlock(value) => *value = text.to_owned(), - Block::Image { alt, .. } => *alt = text.to_owned(), + Block::Code { text: value, .. } | Block::MathBlock(value) => *value = self.text.clone(), + Block::Image { alt, .. } => *alt = self.text.clone(), Block::Table { .. } | Block::Rule => {} } } - pub(super) fn format(&mut self, text: &str, selection: (usize, usize), format: InlineFormat) -> Option<(String, (usize, usize))> { - if text.contains(INLINE_IMAGE_CHAR) { - return None; - } - let (projected, mapping) = self.project(text)?; - let (formatted, selection) = format_source_selection(&projected, selection, format)?; - self.literal = formatted.chars().map(|c| mapping.iter().any(|(marker, _)| *marker == c)).collect(); - self.text = Self::restore(&formatted, &mapping); - Some((self.text.clone(), selection)) - } - - /// [`super::paint_source_selection`] on the line's own text, as [`Self::format`] marks it. - pub(super) fn paint(&mut self, text: &str, selection: (usize, usize), style: &Span) -> Option<(String, (usize, usize))> { - if text.contains(INLINE_IMAGE_CHAR) { - return None; + /// Replace the visible characters `range` with `text` parsed as inline markup, keeping + /// the spans and literal marks on both sides. For dialog edits (links, video) whose + /// replacement may carry markup the caret's text cannot show — and whose visible words + /// may be identical to what was there, which a text diff could never tell apart. + pub(super) fn replace(&mut self, range: Range, text: &str) { + let len = self.text.chars().count(); + let (a, b) = (range.start.min(range.end).min(len), range.start.max(range.end).min(len)); + // The span the replacement lands in lends its style, the way typing inherits it. + let mut at = 0usize; + let mut donor = None; + for (index, span) in self.spans.iter().enumerate() { + let l = visible_len(span); + if a < at + l || (a == at + l && index + 1 == self.spans.len()) { + donor = Some(span.clone()); + break; + } + at += l; } - let (projected, mapping) = self.project(text)?; - let (painted, selection) = super::paint_source_selection(&projected, selection, style)?; - self.literal = painted.chars().map(|c| mapping.iter().any(|(marker, _)| *marker == c)).collect(); - self.text = Self::restore(&painted, &mapping); - Some((self.text.clone(), selection)) - } - - /// [`super::style_at`] on the line's own text. - pub(super) fn style(&self, text: &str, selection: (usize, usize)) -> Option { - if text.contains(INLINE_IMAGE_CHAR) { - return None; + let mut spans = take_spans(&self.spans, 0..a); + let mut literal = self.literal[..a.min(self.literal.len())].to_vec(); + for mut span in parse_inline(text) { + if span.image.is_some() { + literal.push(true); + spans.push(span); + continue; + } + let finished = !plain(&span); + // The replacement's own markup decides the link: plain words must be able to + // take a link off, which inheriting the donor's address would prevent. + let link = span.link.clone(); + inherit(&mut span, donor.as_ref()); + span.link = link; + literal.extend(std::iter::repeat_n(finished, span.text.chars().count())); + spans.push(span); } - let (projected, _) = self.clone().project(text)?; - super::style_at(&projected, selection) + spans.extend(take_spans(&self.spans, b..usize::MAX)); + literal.extend_from_slice(&self.literal[b.min(self.literal.len())..]); + self.adopt_with_literal(spans, literal); } - pub(super) fn fonts(&self, text: &str, selection: (usize, usize)) -> Option { - if text.contains(INLINE_IMAGE_CHAR) { - return None; + pub(super) fn write(&mut self, block: &mut Block, text: &str) { + if text == self.text { + self.commit(block); + return; } - let (projected, _) = self.clone().project(text)?; - selection_fonts(&projected, selection) - } - - pub(super) fn layout(&self, text: &str, layout: impl FnOnce(&str) -> egui::text::LayoutJob) -> egui::text::LayoutJob { - let Some((projected, mapping)) = self.clone().project(text) else { - return layout(text); + // The tag is not part of the visible text; it goes back on before parsing so it + // lands in the words exactly where the block already carries it. + let tag = Tag::split(&block_text(block)).0; + let text = match tag { + Some(tag) => format!("{}{text}", tag.marker()), + None => text.to_owned(), }; - let mut job = layout(&projected); - let restored = Self::restore(&job.text, &mapping); - let offsets: BTreeMap = job - .text - .char_indices() - .map(|(byte, _)| byte) - .chain([job.text.len()]) - .zip(restored.char_indices().map(|(byte, _)| byte).chain([restored.len()])) - .collect(); - for section in &mut job.sections { - section.byte_range.start.0 = offsets.get(§ion.byte_range.start.0).copied().unwrap_or(restored.len()); - section.byte_range.end.0 = offsets.get(§ion.byte_range.end.0).copied().unwrap_or(restored.len()); + let spans = self.parse(&text); + match block { + Block::Heading { spans: value, .. } | Block::Paragraph(value) | Block::Quote(value) | Block::Item { spans: value, .. } => *value = spans, + Block::Code { text: value, .. } | Block::MathBlock(value) => *value = text.to_owned(), + Block::Image { alt, .. } => *alt = text.to_owned(), + Block::Table { .. } | Block::Rule => {} } - job.text = restored; - job } } diff --git a/crates/ui-egui/src/pageedit/regression_tests.rs b/crates/ui-egui/src/pageedit/regression_tests.rs index cedcbd0c..417a873a 100644 --- a/crates/ui-egui/src/pageedit/regression_tests.rs +++ b/crates/ui-egui/src/pageedit/regression_tests.rs @@ -100,8 +100,17 @@ fn frame(ctx: &egui::Context, blocks: &mut Vec, caret: &mut Option output.textures_delta.clear(); fn check(shape: &egui::Shape) { match shape { - egui::Shape::Text(text) if text.galley.job.text.contains("*literal*") => { - assert!(text.galley.job.sections.iter().all(|s| !s.format.italics), "literal stars must stay literal in the widget"); + egui::Shape::Text(text) => { + let job = &text.galley.job; + if let Some(at) = job.text.find("*literal*") { + let end = at + "*literal*".len(); + for section in &job.sections { + let (start, stop) = (usize::from(section.byte_range.start), usize::from(section.byte_range.end)); + if start < end && stop > at { + assert!(!section.format.italics, "literal stars must stay literal in the widget"); + } + } + } } egui::Shape::Vec(shapes) => { for shape in shapes { @@ -132,7 +141,7 @@ fn the_real_widget_keeps_literals_across_edits_and_accepts_new_markdown() { assert_eq!(spans.iter().map(|s| s.text.as_str()).collect::(), format!("{original}bold")); assert!(spans.iter().any(|s| s.bold && s.text == "bold")); apply(Action::Move(0), &mut blocks, &mut caret, &mut changed); - assert_eq!(caret.as_ref().expect("returned caret").text, format!("{original}**bold**")); + assert_eq!(caret.as_ref().expect("returned caret").text, format!("{original}bold")); } #[test] @@ -148,6 +157,37 @@ fn replacing_a_selected_literal_uses_the_new_characters_identity() { assert_eq!(spans.as_slice(), &[Span { text: "bold".into(), bold: true, ..Default::default() }]); } +#[test] +fn formatted_text_enters_the_editor_as_visible_runs() { + let block = Block::Paragraph(vec![ + Span { text: "Testing ".into(), ..Default::default() }, + Span { text: "wierd".into(), font_family: Some("Bahnschrift".into()), ..Default::default() }, + Span { text: " html tags".into(), ..Default::default() }, + ]); + assert_eq!(caret_text(&block), "Testing wierd html tags"); + + let mut edited = block.clone(); + set_caret_text(&mut edited, "Testing weird html tags"); + let Block::Paragraph(spans) = edited else { panic!("paragraph") }; + assert_eq!(spans.iter().map(|span| span.text.as_str()).collect::(), "Testing weird html tags"); + assert!(spans.iter().any(|span| span.text == "weird" && span.font_family.as_deref() == Some("Bahnschrift"))); +} + +#[test] +fn markdown_marks_do_not_enter_the_normal_editor_as_source() { + let block = Block::Paragraph(vec![ + Span { text: "plain ".into(), ..Default::default() }, + Span { text: "bold".into(), bold: true, ..Default::default() }, + Span { text: " italic".into(), italic: true, ..Default::default() }, + Span { text: " struck".into(), strike: true, ..Default::default() }, + ]); + assert_eq!(caret_text(&block), "plain bold italic struck"); + + let mut caret = Some(Caret { text: caret_text(&block), focus: true, ..Default::default() }); + let mut changed = Changed::default(); + apply(Action::Move(0), &mut vec![block], &mut caret, &mut changed); +} + #[test] fn deleting_across_blocks_keeps_literal_identity_from_the_last_block() { let literal = "*literal* $5 or $6"; diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index f26ca682..d1ed08d8 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -202,6 +202,27 @@ pub fn job(ui: &Ui, spans: &[Span], size: f32, color: egui::Color32, tokens: &To job } +/// The editor's own job: the same runs [`job`] draws, but emitting exactly the caret's +/// visible text — an inline image as one object character and maths without its dollars — +/// so the galley the caret measures is the text it edits. +pub fn edit_job(ui: &Ui, spans: &[Span], size: f32, color: egui::Color32, tokens: &Tokens, page: Option, width: f32) -> LayoutJob { + let mut job = LayoutJob { halign: crate::pagetext::halign(&edit_text_of(spans), page), ..LayoutJob::default() }; + job.wrap.max_width = width; + for s in spans { + let format = format_with_family(ui.ctx(), s, size, color, tokens); + if s.image.is_some() { + job.append("\u{fffc}", 0.0, TextFormat::default()); + } else { + job.append(&s.text, 0.0, format); + } + } + job +} + +fn edit_text_of(spans: &[Span]) -> String { + spans.iter().map(|s| if s.image.is_some() { "\u{fffc}".to_string() } else { s.text.clone() }).collect() +} + /// The rectangles to lay behind a selection inside a galley egui laid out: one to a row, /// so a paragraph wrapped over three lines gets three bands and not one tall box. /// diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index a3a89cd3..7d4ec2e9 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -2193,7 +2193,8 @@ fn the_caret_lands_in_the_last_word_of_a_line_that_holds_a_link() { } assert!(h.state().body().is_some_and(|b| b.starts_with("see [the format page]")), "the page stays open: {:?}", h.state().body()); let at = ask(&mut h, "ui.inspect", json!({})).expect("inspect").pointer("/page/caret/at").and_then(Value::as_u64).unwrap_or(0) as usize; - let last_word = body.find("stop").unwrap_or(0); + // The caret counts the words on the page, where the link's marks are not words. + let last_word = "see the format page and stop".find("stop").unwrap_or(0); assert!(at >= last_word, "the caret is in the last word: character {at} of {:?}, which begins at {last_word}", body.trim_end()); } @@ -9526,8 +9527,7 @@ fn home_mark_buttons_show_the_marks_at_the_caret_and_of_the_selection() { let on = |h: &Harness<'_, NoteCraftApp>, label: &str| h.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True); // Puts the caret `right` characters into the line and selects `select` more. The line - // being written in still shows its marks' markup (`alpha **bravo** *omega*`, issue - // #242), and the caret counts through it. + // being written in shows only its words (issue #242), and the caret counts them. let place = |h: &mut Harness<'_, NoteCraftApp>, right: usize, select: usize| { ask(h, "ui.caret", json!({"block": 0})).expect("caret"); pump(h); @@ -9549,9 +9549,9 @@ fn home_mark_buttons_show_the_marks_at_the_caret_and_of_the_selection() { review(&mut h, &format!("mark_state_bold_{format:?}")); place(&mut h, 2, 0); assert!(!on(&h, "Bold"), "{format:?}: the caret in alpha shows no mark"); - place(&mut h, 19, 0); + place(&mut h, 14, 0); assert!(on(&h, "Italic") && !on(&h, "Bold"), "{format:?}: the caret in omega shows Italic"); - place(&mut h, 8, 5); + place(&mut h, 6, 5); assert!(on(&h, "Bold"), "{format:?}: all of bravo selected is bold"); place(&mut h, 0, 13); assert!(!on(&h, "Bold"), "{format:?}: alpha and bravo together are only partly bold"); @@ -9707,7 +9707,7 @@ fn legacy_font_marks_toggle_partial_selection_without_losing_other_styles() { pump(&mut h); ask(&mut h, "ui.key", json!({"key": "End"})).expect("end"); pump(&mut h); - for _ in 0..10 { + for _ in 0..6 { ask(&mut h, "ui.key", json!({"key": "ArrowLeft"})).expect("left"); pump(&mut h); } @@ -9804,7 +9804,7 @@ fn font_size_replaces_only_the_partial_selection_inside_an_existing_size() { pump(&mut h); ask(&mut h, "ui.key", json!({"key": "End"})).expect("end"); pump(&mut h); - for _ in 0..13 { + for _ in 0..6 { ask(&mut h, "ui.key", json!({"key": "ArrowLeft"})).expect("left"); pump(&mut h); } @@ -10160,6 +10160,10 @@ fn legacy_font_marks_apply_to_next_typed_text_without_changing_page_first() { ask(&mut h, "ui.redo", json!({})).expect("redo"); settle(&mut h); assert_eq!(h.state().body().unwrap_or_default(), after); + // Leave the page as it was opened: reopening saves a dirty editor over the + // fixture the next pass writes. + ask(&mut h, "ui.undo", json!({})).expect("undo to clean"); + settle(&mut h); } } }