Skip to main content

leaf_core/
doc.rs

1//! The document model: a `twig::Editor` plus a byte-offset caret and selection.
2//!
3//! Where bough moves a selection through the *tree*, leaf moves a *caret*
4//! through the *characters* — a normal text editor's model — and expresses
5//! every mutation as one of twig's offset-addressed ops:
6//!
7//!   - typing / delete  → `edit_range(start, end, text)`   (P0)
8//!   - re-anchoring      → the returned `Change`            (P1)
9//!   - cursor context    → `node_at` / `ancestors_at`       (P3)
10//!   - the toolbar       → `wrap_range`/`toggle_inline`/`set_block`,
11//!                         `toggle_block_container`/`insert_link`   (P5)
12//!
13//! twig reparses after every edit and leaves everything outside the splice
14//! byte-for-byte untouched, so the document stays a live, navigable AST while
15//! you type into it.
16
17// `PathBuf` names the `path` field and the untitled marker on every build;
18// `Path` is only touched by the filesystem I/O gated behind the `fs` feature.
19// The docs in this file lay their `- key → meaning` lists out in aligned
20// columns, which puts a continuation line further right than clippy's
21// list-indent rule likes. A lazy continuation renders as the same paragraph
22// either way, and the alignment is what makes those tables readable, so the
23// layout wins over the lint.
24#![allow(clippy::doc_overindented_list_items)]
25
26use std::collections::HashMap;
27use std::ops::Range;
28#[cfg(feature = "fs")]
29use std::path::Path;
30use std::path::PathBuf;
31
32#[cfg(feature = "fs")]
33use anyhow::Context;
34use anyhow::{Result, anyhow};
35use twig::{
36    Alignment, BlockContainerKind, BlockKind, Change, Editor, FlatNode, Format, Gesture,
37    InlineKind, Kind, MarkdownExtensions, NodeId, QueryMatch,
38};
39use unicode_segmentation::GraphemeCursor;
40
41use crate::html;
42use crate::source::{self, SourceMap};
43use crate::style::MarkColor;
44use crate::wysiwyg::{self, MediaKind, MediaStop, VisualMap};
45
46/// Which view the body shows.
47#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48pub enum View {
49    /// The raw document with a caret in source bytes.
50    Source,
51    /// Markup resolved to real styles, caret riding the rendered glyphs.
52    Wysiwyg,
53}
54
55/// How much of the source markup the WYSIWYG view exposes — a per-editor
56/// preference, orthogonal to [`View`]. Named for markup rather than for Markdown
57/// because leaf is grammar-agnostic: twig hands it Djot, HTML and XML on the same
58/// terms, and every rung below is about *delimiters*, whatever grammar spells
59/// them. The examples are Markdown only because that is what most documents are.
60///
61/// A single ladder over two underlying axes, because only three of their four
62/// combinations are coherent:
63///
64/// | | authoring off | authoring on |
65/// |---|---|---|
66/// | delimiters hidden | [`None`](Self::None) | [`Shortcuts`](Self::Shortcuts) |
67/// | caret line revealed | *incoherent* | [`Full`](Self::Full) |
68///
69/// The empty quadrant would show delimiters on the caret's line and then escape
70/// the ones you type — a surface that displays a syntax it refuses to accept.
71/// Someone who wants to read raw markup without authoring it has
72/// [`View::Source`], which is the better tool for it.
73///
74/// The two axes are read separately by the code that cares — see
75/// [`reveals_caret_line`](Self::reveals_caret_line) and
76/// [`authors`](Self::authors) — so neither behaviour has to know it's spelled
77/// as a ladder.
78#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
79pub enum MarkupMode {
80    /// Delimiters stay hidden even on the caret's line, and typed syntax stays
81    /// literal — twig escapes anything that would open markup, so formatting
82    /// comes from commands (⌘b, the toolbar) instead of from spelling. The clean
83    /// reading surface for people who don't write markup by hand; the default,
84    /// and what Diaryx ships.
85    #[default]
86    None,
87    /// Delimiters stay hidden, but typing them authors real markup: `*x*`
88    /// becomes italic and the asterisks disappear into the styling
89    /// (Typora/Bear-shaped). For someone who knows the syntax but wants the
90    /// clean surface back once it has been applied.
91    Shortcuts,
92    /// The caret's line shows its raw markup while every other line renders
93    /// resolved (Obsidian live-preview-shaped), and typed syntax authors markup
94    /// — for people fluent in the document's grammar who want to see and edit
95    /// the delimiters they type.
96    Full,
97}
98
99impl MarkupMode {
100    /// Whether the rich view shows raw delimiters on the line holding the caret.
101    /// The rendering axis — read by [`Doc::reveal_line`] and threaded into the
102    /// WYSIWYG builder.
103    pub fn reveals_caret_line(self) -> bool {
104        matches!(self, MarkupMode::Full)
105    }
106
107    /// Whether typed markup characters author real formatting. The editing axis
108    /// — read by [`Doc::insert`], which escapes typed syntax when this is false.
109    pub fn authors(self) -> bool {
110        !matches!(self, MarkupMode::None)
111    }
112}
113
114/// How the WYSIWYG view treats a *soft break* — a bare newline inside a
115/// paragraph. An axis of its own, orthogonal to [`MarkupMode`] (which governs
116/// inline-markup delimiters) and to [`View`]: any reveal preference pairs with
117/// either flow. The renderer consults it when it lays a block's inline content
118/// into visual rows.
119#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
120pub enum LineFlow {
121    /// A soft break folds into a space and the paragraph reflows to the
122    /// viewport width — flowing prose, where the source's line wrapping is
123    /// insignificant. The default, and what Diaryx ships.
124    #[default]
125    Fold,
126    /// A soft break renders as a line break exactly where it was written, so
127    /// the author's source line structure shows on screen unchanged — the mode
128    /// for people who lay out their prose deliberately (one sentence or clause
129    /// per line, semantic line breaks). The break is still a soft break in the
130    /// source; only its rendering changes.
131    Preserve,
132}
133
134/// What the file behind a document looks like right now, against the bytes leaf
135/// last read from it or wrote to it — the question a frontend asks before it
136/// saves (a `Changed` file plus a `dirty` document is an overwrite about to
137/// happen) or when its window regains focus. See [`Doc::disk_state`].
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub enum DiskState {
140    /// The file holds exactly the bytes leaf last read or wrote.
141    Unchanged,
142    /// Someone else wrote the file since. Saving overwrites their work; see
143    /// [`Doc::reload`] for the other direction.
144    Changed,
145    /// The file is gone — deleted or renamed away. A save recreates it.
146    Missing,
147    /// There is a path, but the file couldn't be read (permissions, a directory
148    /// in the way): leaf can't tell, and won't guess.
149    Unreadable,
150    /// No file behind this document yet — see [`Doc::blank`]. Nothing can have
151    /// changed under a document that was never on disk.
152    Untitled,
153}
154
155/// The inline marks in force at a point in the document — what a toolbar
156/// lights up. A `Copy` bitset rather than a `HashSet`, because
157/// [`Doc::active_inline_marks`] is called on every frame that draws a toolbar
158/// and a set that allocates to answer "is Bold on?" is a set that shouldn't.
159#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
160pub struct InlineMarks(u8);
161
162impl InlineMarks {
163    /// Every kind, in the order [`InlineMarks::iter`] yields them.
164    const ALL: [InlineKind; 8] = [
165        InlineKind::Strong,
166        InlineKind::Emph,
167        InlineKind::Verbatim,
168        InlineKind::Mark,
169        InlineKind::Superscript,
170        InlineKind::Subscript,
171        InlineKind::Insert,
172        InlineKind::Delete,
173    ];
174
175    pub const fn empty() -> Self {
176        InlineMarks(0)
177    }
178
179    /// Private: the set is an *answer*, and adding a mark to it doesn't mark
180    /// anything ([`Doc::toggle`] does that). `FromIterator` is the way in.
181    fn insert(&mut self, kind: InlineKind) {
182        self.0 |= Self::bit(kind);
183    }
184
185    /// Flip `kind` in the set — the sticky-marks toggle at a collapsed caret.
186    fn flip(&mut self, kind: InlineKind) {
187        self.0 ^= Self::bit(kind);
188    }
189
190    /// The symmetric difference: which marks differ between the two sets. Used
191    /// to resolve the marks already in force at the caret against the pending
192    /// delta — a bit set in the delta flips the base mark for the next keystroke.
193    fn xor(self, other: InlineMarks) -> InlineMarks {
194        InlineMarks(self.0 ^ other.0)
195    }
196
197    /// Whether `kind` is in force — the toolbar's "is Bold active?".
198    pub fn contains(self, kind: InlineKind) -> bool {
199        self.0 & Self::bit(kind) != 0
200    }
201
202    pub fn is_empty(self) -> bool {
203        self.0 == 0
204    }
205
206    /// The marks in force, for a frontend that renders whatever is on rather
207    /// than asking after a fixed list.
208    pub fn iter(self) -> impl Iterator<Item = InlineKind> {
209        Self::ALL.into_iter().filter(move |&k| self.contains(k))
210    }
211
212    fn bit(kind: InlineKind) -> u8 {
213        1 << match kind {
214            InlineKind::Strong => 0,
215            InlineKind::Emph => 1,
216            InlineKind::Verbatim => 2,
217            InlineKind::Mark => 3,
218            InlineKind::Superscript => 4,
219            InlineKind::Subscript => 5,
220            InlineKind::Insert => 6,
221            InlineKind::Delete => 7,
222        }
223    }
224}
225
226impl FromIterator<InlineKind> for InlineMarks {
227    fn from_iter<I: IntoIterator<Item = InlineKind>>(iter: I) -> Self {
228        let mut m = InlineMarks::empty();
229        for k in iter {
230            m.insert(k);
231        }
232        m
233    }
234}
235
236/// What kind of edit produced an undo group. Same-kind edits in a row coalesce
237/// into one undo step (a run of typed characters undoes together); `Other` never
238/// coalesces, so a paste, format toggle, or block change is always its own step.
239#[derive(Clone, Copy, PartialEq, Eq)]
240enum EditKind {
241    Insert,
242    Delete,
243    /// One step of an IME composition — see [`Doc::edit_composing`]. Its own kind
244    /// rather than `Insert`'s because a composition is not typing: each step
245    /// *replaces* the last (`か` → `かん` → `感`), so the run has to coalesce even
246    /// though no two steps insert the same bytes, and it must not fold into the
247    /// typed characters on either side of it.
248    Compose,
249    Other,
250}
251
252/// Which side of the caret a delete looks for an in-cell `<br>` break to swallow
253/// whole — see [`Doc::cell_break_at`]. `Backward` is Backspace (a break ending at
254/// the caret), `Forward` is Delete (one starting at it).
255#[derive(Clone, Copy)]
256enum BreakEdge {
257    Backward,
258    Forward,
259}
260
261/// A re-spelling of one inline mark run, held ready in case the edit about to
262/// happen breaks it — see [`Doc::mark_edge_fix`] and [`Doc::repair_mark_edges`].
263/// Every offset in it is in the coordinates the document will have *after* the
264/// plain edit, since that is when it may be applied.
265struct MarkEdgeFix {
266    /// The run's kind, and an offset inside what was its content: together they
267    /// answer "did the plain edit actually break this mark?" — the question that
268    /// decides whether any of this is applied at all.
269    kind: InlineKind,
270    probe: usize,
271    /// The byte range to re-spell (the run's delimiters included) and its new
272    /// spelling, with the edge whitespace moved outside the delimiters.
273    start: usize,
274    end: usize,
275    text: String,
276    /// Where the caret belongs afterwards — the same place on screen it would
277    /// have had, which is now on the other side of a delimiter.
278    caret: usize,
279    /// The marks in force for text typed at that caret. The caret can land
280    /// outside a run it was inside, and the marks have to survive the move or
281    /// the toolbar goes dark mid-word.
282    want: InlineMarks,
283}
284
285/// The caret and selection at one moment — the part of a history step twig's
286/// `Change` cannot carry, because the caret is leaf's state and twig only knows
287/// about bytes. leaf serializes it into the opaque per-state blob twig now
288/// stores in its own undo history (see `record_caret`), so undo and redo hand
289/// back the caret that matches the source they restore.
290#[derive(Clone, Copy)]
291struct CaretState {
292    caret: usize,
293    anchor: Option<usize>,
294}
295
296impl CaretState {
297    /// Pack into the fixed 17-byte blob leaf hands twig: the caret as a u64,
298    /// then an anchor-present flag and the anchor. twig copies these bytes and
299    /// never reads them.
300    fn to_blob(self) -> [u8; 17] {
301        let mut b = [0u8; 17];
302        b[..8].copy_from_slice(&(self.caret as u64).to_le_bytes());
303        if let Some(a) = self.anchor {
304            b[8] = 1;
305            b[9..].copy_from_slice(&(a as u64).to_le_bytes());
306        }
307        b
308    }
309
310    /// Recover a state from twig's blob, or `None` when it is empty or the wrong
311    /// length — a state twig restored that never had a caret set on it, which
312    /// leaves the caller to fall back to the edit site.
313    fn from_blob(b: &[u8]) -> Option<Self> {
314        let b: &[u8; 17] = b.try_into().ok()?;
315        let caret = u64::from_le_bytes(b[..8].try_into().unwrap()) as usize;
316        let anchor = (b[8] != 0).then(|| u64::from_le_bytes(b[9..].try_into().unwrap()) as usize);
317        Some(CaretState { caret, anchor })
318    }
319}
320
321/// A footnote reference and the note it names — the answer to
322/// [`Doc::footnote_at`].
323///
324/// The two `Option`s move together: a reference whose definition is missing has
325/// neither a body to show nor a place to jump to, and one that resolved has
326/// both.
327#[derive(Clone, PartialEq, Eq, Debug)]
328pub struct FootnoteRef {
329    /// The reference's label — the `1` of `[^1]`, with neither the `^` that
330    /// spells it a footnote nor the brackets around it.
331    pub label: String,
332    /// The note's body as source bytes (see
333    /// [`wysiwyg::footnote_body_span`](crate::wysiwyg)), or `None` when the
334    /// document defines no `[^label]:` to read one from.
335    pub text: Option<String>,
336    /// Where the note's *body* starts, for a "go to note" that moves the caret
337    /// there. `None` alongside a `None` `text`.
338    ///
339    /// The body rather than the definition, because this is an offset to put a
340    /// caret on and the `[^1]:` marker is decoration the caret can't occupy —
341    /// aiming at the definition's first byte snaps to the nearest real stop,
342    /// which is up in the paragraph above the note. It is also simply where a
343    /// reader following a reference wants to land: at the note's first word,
344    /// ready to read or amend it.
345    pub offset: Option<usize>,
346    /// Where the note's body ends, exclusive — so a frontend can ask which
347    /// *rendered rows* the note occupies and draw those instead of [`text`](Self::text).
348    ///
349    /// The rows are the note with its markup resolved: `see *later*` reaches a
350    /// frontend as an italic run, not as asterisks. `text` is the source bytes
351    /// and stays the honest answer for anything that wants the note as written
352    /// (a search index, a copy); this pair of offsets is for anything that wants
353    /// it as *read*. `None` alongside a `None` `offset`.
354    pub end: Option<usize>,
355}
356
357/// A footnote definition and the reference that sends a reader to it — the
358/// answer to [`Doc::footnote_definition_at`], and the other half of the round
359/// trip [`FootnoteRef`] starts.
360///
361/// A note is a place a reader *arrives*, so the useful thing to know while
362/// standing in one is the way back. Without this the jump to a note is a
363/// one-way door: the definitions sit at the foot of the document, so returning
364/// by hand means scrolling back up and finding the sentence again.
365#[derive(Clone, PartialEq, Eq, Debug)]
366pub struct FootnoteDef {
367    /// The definition's label — the `1` of `[^1]: …`, marker and colon stripped,
368    /// spelled exactly as [`FootnoteRef::label`] spells the same footnote's.
369    pub label: String,
370    /// Where the reference's *label* is, for a "back to reference" that moves
371    /// the caret there. `None` for a note nothing refers to — an orphan, which
372    /// is worth being able to say rather than silently doing nothing.
373    ///
374    /// The label rather than the reference's first byte, for
375    /// [`FootnoteRef::offset`]'s reason: a reference's brackets are decoration
376    /// and its label is the only part of it the caret can rest on.
377    ///
378    /// The *first* reference, when a label is cited more than once: a repeated
379    /// citation has no one true home, and the first is both the one a reader
380    /// most likely came from and the only choice that doesn't depend on how
381    /// they got here.
382    pub offset: Option<usize>,
383}
384
385/// Where a locator lands — the answer to [`Doc::locate`].
386///
387/// A locator (the `v2` of a `chapter.dj#v2`) names a *place* rather than a
388/// document, and a place is a span rather than a point: a reader following one
389/// wants the caret at its first byte, and a reader merely *peeking* at one wants
390/// the block it covers drawn. Both are served by carrying the whole span, and
391/// only one of the two can be recovered from an offset alone.
392#[derive(Clone, PartialEq, Eq, Debug)]
393pub struct Landing {
394    /// The first byte of the block the locator names — where a caret goes.
395    pub start: usize,
396    /// One past its last byte, so a frontend can map the pair through
397    /// [`VisualMap::row_range_for`](crate::wysiwyg::VisualMap::row_range_for) to the rendered rows the block occupies and draw
398    /// those, the way a footnote peek draws a note ([`FootnoteRef::end`]).
399    pub end: usize,
400}
401
402/// A selection cited out of the source: the text itself, up to a requested
403/// number of characters either side, and the byte range it came from. See
404/// [`Doc::selection_quote`].
405///
406/// The prefix and suffix are what make the quote *re-findable*: the same text
407/// can occur twice, and a little of what surrounded it is how a later reader —
408/// or the same document after an edit — tells the occurrences apart. The Web
409/// Annotation model calls this a `TextQuoteSelector`; the shape is older than
410/// the name.
411#[derive(Debug, Clone, PartialEq, Eq)]
412pub struct Quote {
413    /// The selected source, verbatim.
414    pub exact: String,
415    /// What immediately preceded it — possibly empty, at the document's start.
416    pub prefix: String,
417    /// What immediately followed it — possibly empty, at the document's end.
418    pub suffix: String,
419    /// Byte offset in the source where the selection begins.
420    pub start: usize,
421    /// Byte offset where it ends (exclusive).
422    pub end: usize,
423}
424
425/// A host-painted range of the source — an annotation's footprint, a search
426/// hit, a reviewer's mark. Leaf renders it (a background wash behind the
427/// glyphs whose source falls inside it) and hands back the `id` when the
428/// reader activates it; what the range *means* is entirely the host's.
429///
430/// Ranges are source bytes, like the caret and the selection, so a host that
431/// anchors quotes against the source ([`Doc::selection_quote`] is the other
432/// half of that loop) can paint what it found without any coordinate
433/// conversion. A range that drifts off the text it meant is the host's to
434/// re-anchor; leaf draws what it is told.
435#[derive(Debug, Clone, PartialEq, Eq)]
436pub struct Highlight {
437    /// Byte offset in the source where the wash begins.
438    pub start: usize,
439    /// Byte offset where it ends (exclusive).
440    pub end: usize,
441    /// The host's name for it, handed back on activation. Opaque to leaf.
442    pub id: String,
443    /// A rendering hint the frontend maps — a `#RRGGBB` hex string, or
444    /// nothing for the theme's default wash.
445    pub color: Option<String>,
446    /// A margin glyph's name, or nothing for wash-only ink. A highlight with
447    /// a marker gets a small glyph in the margin beside its first line, and
448    /// the glyph — not the wash — is what activates it: the wash is ink, the
449    /// marker is the control, which is what lets a reader put a caret in (or
450    /// copy from) annotated text without a card leaping at them. The name is
451    /// opaque to leaf; an Apple frontend reads it as an SF Symbol, a web one
452    /// as a class.
453    pub marker: Option<String>,
454}
455
456impl Highlight {
457    /// The range covering source `offset` in a list [`Doc::set_highlights`]
458    /// sorted, first by start where several overlap — the one place that
459    /// question is answered, for the frontends that paint by asking it as well
460    /// as for [`Doc::highlight_at`].
461    ///
462    /// The list is sorted by `(start, end)`, so the scan can stop at the first
463    /// range starting past `offset` rather than running to the end. A painter
464    /// asking once per glyph wants [`HighlightCursor`] instead; this is the
465    /// one-shot form, for the host asking what the reader just activated.
466    pub fn covering(highlights: &[Highlight], offset: usize) -> Option<&Highlight> {
467        highlights
468            .iter()
469            .take_while(|h| h.start <= offset)
470            .find(|h| offset < h.end)
471    }
472}
473
474/// [`Highlight::covering`] for a caller walking the document in order — which
475/// is every painter, since a frontend draws rows top to bottom and glyphs left
476/// to right.
477///
478/// The one-shot form is a scan from the front of the list per glyph, and a
479/// document with two hundred search hits pays that two hundred times a row. A
480/// range that ends at or before an offset can never cover that offset *or any
481/// later one*, so the cursor retires those permanently and each glyph costs the
482/// ranges that actually reach it. The answer is identical to
483/// [`Highlight::covering`]'s, offset for offset — this is the same scan with
484/// the part that was being redone dropped, not a cheaper approximation.
485///
486/// Offsets are expected to arrive non-decreasing. One that goes backwards is
487/// still answered correctly: the cursor re-seats to the front, since a painter
488/// that revisits a row is asking a question the retired ranges may own again.
489pub struct HighlightCursor<'a> {
490    highlights: &'a [Highlight],
491    /// The first range not yet retired.
492    at: usize,
493    /// The last offset asked about, to notice a caller going backwards.
494    last: usize,
495}
496
497impl<'a> HighlightCursor<'a> {
498    pub fn new(highlights: &'a [Highlight]) -> Self {
499        HighlightCursor {
500            highlights,
501            at: 0,
502            last: 0,
503        }
504    }
505
506    /// The range covering `offset`, advancing the cursor past every range that
507    /// can no longer cover anything.
508    pub fn at(&mut self, offset: usize) -> Option<&'a Highlight> {
509        if offset < self.last {
510            self.at = 0;
511        }
512        self.last = offset;
513        while self
514            .highlights
515            .get(self.at)
516            .is_some_and(|h| h.end <= offset)
517        {
518            self.at += 1;
519        }
520        Highlight::covering(&self.highlights[self.at..], offset)
521    }
522}
523
524/// The identity of a built [`VisualMap`] — see [`Doc::visual_key`]. Opaque on
525/// purpose: the only useful question is whether two of them are the same map,
526/// and the tuple behind it (revision, wrap, reveal line) is core's business.
527#[derive(Clone, PartialEq, Eq, Debug)]
528pub struct VisualKey(Option<(u64, Option<usize>, Option<Range<usize>>)>);
529
530pub struct Doc {
531    editor: Editor,
532    pub format: Format,
533    pub path: PathBuf,
534    /// Current source, refreshed from the editor after every successful edit.
535    pub source: String,
536    /// The caret, as a byte offset into `source` (always on a char boundary).
537    pub caret: usize,
538    /// The selection's fixed end, if a selection is active; the moving end is
539    /// the caret. `None` means no selection.
540    pub anchor: Option<usize>,
541    pub dirty: bool,
542    pub status: Option<String>,
543    pub view: View,
544    /// Whether the document refuses to change — a *reading* surface over the
545    /// same rendering, selection, and navigation the editor has.
546    ///
547    /// Enforced here rather than by each frontend hiding its input paths,
548    /// because every mutation funnels through a few doors —
549    /// [`splice_exact`](Self::splice_exact), [`undo`](Self::undo),
550    /// [`redo`](Self::redo), and the handful of inserts that go to twig's own
551    /// verbs directly rather than through the splice (a typed literal, a link,
552    /// an image, a rule, a footnote, a cell's line break) — and guarded doors
553    /// are a guarantee where a frontend's suppressed keyboard is a hope. A
554    /// gated door reports exactly like a rolled-back splice, a path every
555    /// caller already handles. `a_read_only_document_refuses_every_door` is
556    /// the list; a new `self.editor.insert_*` call belongs on it.
557    read_only: bool,
558    /// The host-painted ranges, kept sorted by start — see [`Highlight`].
559    /// State like the selection rather than like the text: no edit history,
560    /// no dirty bit, redrawn from whatever the host last set.
561    highlights: Vec<Highlight>,
562    /// How much of the source markup the rich view exposes — a frontend preference (see
563    /// [`MarkupMode`]). Its two axes are read apart: the rendering one by
564    /// [`reveal_line`](Self::reveal_line), the editing one by
565    /// [`insert`](Self::insert).
566    markup_mode: MarkupMode,
567    /// Whether soft breaks fold into the reflowed paragraph or render where
568    /// they were written (see [`LineFlow`]) — an independent frontend
569    /// preference the WYSIWYG builder consults when it lays out a block.
570    line_flow: LineFlow,
571    /// The kind of the last edit, for coalescing: twig owns the undo *history*
572    /// (see `undo`/`redo`), but "what counts as one undo step" is a frontend-UX
573    /// call, so leaf decides when a run continues and tells twig to coalesce.
574    last_edit_kind: Option<EditKind>,
575    /// The inline marks the user has toggled *at a collapsed caret* with no
576    /// selection — "start typing bold here". Held as the XOR delta from the marks
577    /// already in force at [`pending_at`](Self::pending_at): a set bit means
578    /// "flip this kind for the next typed text", so it both turns a mark on where
579    /// none is (type into bold) and off where one already covers the caret (type
580    /// past the bold you're standing in). [`Doc::insert`] realises it onto the
581    /// freshly typed text and then clears it — a mark once realised is carried by
582    /// the caret sitting inside the run, not by this delta.
583    pending_marks: InlineMarks,
584    /// The caret offset [`pending_marks`](Self::pending_marks) applies to. The
585    /// delta is live only while the caret still stands here with no selection;
586    /// any motion or edit ([`move_to`](Self::move_to), a splice, a click) drops
587    /// it, so a toggled-but-never-typed format doesn't leak onto text elsewhere.
588    pending_at: Option<usize>,
589    /// The source as of the last open/save — `dirty` is `source != clean_source`,
590    /// so undoing back to the saved state correctly clears the modified flag.
591    clean_source: String,
592    /// A hash of the bytes leaf last read from `path` or wrote to it; `None`
593    /// while the document has no file behind it. [`Doc::disk_state`] compares
594    /// the file against this to catch an edit made *outside* leaf before a save
595    /// silently overwrites it — `clean_source` only knows what leaf itself did.
596    ///
597    /// A hash, not an mtime: mtime is the cheap answer and the wrong one — two
598    /// writes inside one filesystem timestamp tick are indistinguishable, a
599    /// clock that steps backwards (or a writer that restores an mtime) hides a
600    /// real change, and a `touch` invents one. The whole point of the watermark
601    /// is to not clobber someone's work, so it reads the bytes and compares what
602    /// is actually there. That costs a file read per question, which is why the
603    /// question is asked on a user event (focus, save) and not every frame.
604    disk_hash: Option<u64>,
605    /// The "sticky" display column vertical motion aims for, in the active
606    /// view's grid. Set on the first `move_up`/`move_down` of a run and
607    /// reused by every subsequent one in that run, so passing through a
608    /// shorter line doesn't permanently forget the original column. Any
609    /// horizontal motion or edit clears it.
610    ///
611    /// A column, not a character index: dropping down a line of `你好` onto one
612    /// of ASCII has to land under the glyph the caret was drawn beneath, which
613    /// is the only thing the user can see to aim by. Where the goal falls inside
614    /// a wide character on the target line, the mapping resolves it to that
615    /// character — the caret lands on it rather than between its cells.
616    goal_col: Option<usize>,
617    /// The rendered map for the WYSIWYG view; empty in the source view. Movement
618    /// and clicks read it to stay in visible space.
619    pub vmap: VisualMap,
620    /// The syntax map for the source view; empty in the WYSIWYG view, which
621    /// styles resolved glyphs instead. Built by [`Doc::build_source`] — a
622    /// frontend that never calls it paints raw source unstyled, which is what
623    /// every frontend did before this map existed.
624    pub smap: SourceMap,
625    /// The revision `smap` was built from, or `None` before the first build.
626    /// The map is a pure function of the text alone — no width, no caret, no
627    /// reveal line — so unlike [`vmap_key`](Self::vmap_key) the revision is the
628    /// whole key.
629    smap_key: Option<u64>,
630    /// Everything the map is built from, as one number: bumped whenever the
631    /// document's text changes, and never by a motion, a selection, or a save.
632    /// A frontend can hold work against it — see [`Doc::revision`].
633    revision: u64,
634    /// How many history steps stand behind the caret, and how many ahead of
635    /// it — the answer to a native Edit menu's "may Undo be enabled?", which
636    /// twig's history does not ask itself. Counted at [`refresh`](Self::refresh),
637    /// the funnel every edit comes through, and moved back and forth by
638    /// [`undo`](Self::undo)/[`redo`](Self::redo). An upper bound rather than
639    /// an exact depth: a coalesced run of typing is one of twig's steps but
640    /// several of these, and twig's own cap on history is not mirrored here.
641    /// Neither error can make `can_undo` false while a step remains, which is
642    /// the only property a menu needs; the one place the bound can be wrong the
643    /// other way — the cap has retired every step — is reconciled the moment
644    /// twig reports nothing to undo.
645    undo_steps: usize,
646    redo_steps: usize,
647    /// What `vmap` was built from, or `None` before the first build. The map is
648    /// a pure function of `(revision, wrap, reveal line)`, so when those haven't
649    /// moved, rebuilding it produces the identical map — see
650    /// [`Doc::build_visual`].
651    ///
652    /// The reveal line ([`Doc::reveal_line`]) is the caret's, and is `None` in
653    /// every mode but [`MarkupMode::Full`] — so outside that mode the key is
654    /// text and width alone, and a caret motion still rebuilds nothing.
655    vmap_key: Option<(u64, Option<usize>, Option<Range<usize>>)>,
656    /// Per-block row cache backing the incremental rebuild: when the text
657    /// changes, only the top-level blocks whose bytes moved are re-rendered and
658    /// the rest are reused shifted (see [`wysiwyg::BlockCache`]). Persists across
659    /// builds; a pure accelerator, so it's never read for correctness.
660    block_cache: wysiwyg::BlockCache,
661    /// How many visual rows each block image reserves, keyed by its destination —
662    /// set by the frontend through [`Doc::set_media_rows`] once it has decoded and
663    /// measured the pictures. Core does no image I/O, so this is the only way it
664    /// learns a picture's height; a destination not in the map reserves the bare
665    /// one-row placeholder. Threaded into the builder so [`wysiwyg::build_cached`]
666    /// sizes each placeholder, and folded into `vmap_key` so a height change
667    /// rebuilds the map.
668    media_rows: HashMap<String, usize>,
669
670    // View geometry the renderer stamps each frame, so mouse events can map a
671    // screen cell back to a byte offset.
672    pub scroll: usize,
673    pub body_origin: (u16, u16),
674    /// Width of the body rectangle last painted by the frontend. Zero means
675    /// unknown (used by tests or a frontend that has not drawn yet).
676    pub body_width: u16,
677    pub body_height: u16,
678    /// The caret as of the last frame drawn, or `None` before the first.
679    ///
680    /// Scrolling is the viewport's business, not the caret's: the view follows
681    /// the caret when the caret *moves*, but a wheel that doesn't touch the
682    /// caret has to be free to scroll away from it — otherwise the view is
683    /// pinned to the caret and stops dead at the edge of the document you can
684    /// see. Comparing against this is what tells the two apart, and it catches a
685    /// caret set by any route, including a frontend assigning the field itself.
686    pub drawn_caret: Option<usize>,
687}
688
689/// The Markdown extensions every leaf document is parsed with — four of them,
690/// each departing from twig's defaults for a reason leaf can state.
691///
692/// `html_elements` promotes embedded raw HTML (`<img>`, `<picture>`,
693/// `<source>`, …) into semantic AST nodes, so a picture becomes a real `image`
694/// node the frontends can frame and rasterize instead of opaque `raw_block`
695/// text. `directives` turns on generic `:::name{.class}` fenced-div containers
696/// (`directive` nodes), which a host app uses for its own semantics (diaryx's
697/// `:::vis{.audience}` visibility blocks) — core renders any directive as a
698/// plain tinted container, agnostic of `name`.
699///
700/// `highlight` and `highlight_colors` are the pair that makes Markdown read
701/// `==text==` as a `mark` node, and `==🔴 text==` as one carrying a
702/// `data-color`. leaf already had somewhere to put both: the
703/// [`Mark`](crate::Role::Mark) role and the ⌘⇧M highlight button predate them,
704/// and until twig 3.3 a Markdown document could only ever *receive* a highlight
705/// from a Djot one it was converted from — the button wrote `==…==` and the
706/// reparse read it straight back as text.
707/// They are on together because a colour is inert without the highlight itself,
708/// and a document that writes `==🔴 x==` means the colour by it.
709///
710/// Every flag is inert for non-Markdown formats, so it's safe to pass them
711/// unconditionally. Threading this through every constructor (not just `open`)
712/// keeps `from_source`, `blank`, and `reload` parsing the same document the same
713/// way — twig reparses with these same flags after each edit.
714pub(crate) fn parse_extensions() -> MarkdownExtensions {
715    MarkdownExtensions {
716        html_elements: true,
717        directives: true,
718        highlight: true,
719        highlight_colors: true,
720        ..Default::default()
721    }
722}
723
724/// Build an editor over `bytes` in `format` with leaf's [`parse_extensions`],
725/// mapping twig's error into the `anyhow` context every constructor shares.
726fn new_editor(bytes: &[u8], format: Format) -> Result<Editor> {
727    Editor::new_ext(bytes, format, parse_extensions()).map_err(|e| anyhow!("twig parse: {e}"))
728}
729
730/// Does `format` spell a table as a **pipe table** — the one grid twig's table
731/// editor knows how to emit?
732///
733/// This is the single capability leaf still has to answer for itself, and the
734/// only hand-maintained format list left in this file. Every other gesture is
735/// [`Format::supports`], which is twig's own answer read across the C ABI — but
736/// twig deliberately leaves the table ops out of that query, because they read
737/// no `Syntax` table at all. They rewrite a grid that is already in the source
738/// and refuse on *position*, never on format. Handed a caret inside an HTML
739/// `<table>`, `table_insert_row` therefore re-emits the whole element as
740/// `| a | b |` and reports success — a real splice, a clean reparse, an honest
741/// `dirty` flag, and nothing downstream able to tell it from a good edit.
742///
743/// So the list is narrow on purpose. `Format` is `#[non_exhaustive]`, and the
744/// wildcard answers "no" for a format leaf has never heard of: a new twig
745/// language that *does* spell pipe tables loses its grid controls until this
746/// line is updated, which shows up as a missing button. The other default hands
747/// it to [`Doc::table_op`], which rewrites documents it cannot spell.
748fn spells_pipe_tables(format: Format) -> bool {
749    matches!(format, Format::Markdown | Format::Djot)
750}
751
752/// Which of leaf's authoring controls this document's format can actually
753/// spell — one flag per toolbar button, resolved once so a frontend can build
754/// its chrome instead of discovering each refusal on a click.
755///
756/// Every field but [`table`](Self::table) is `Format::supports_with` on the
757/// gesture the matching [`Doc`] method calls, so this record cannot drift from
758/// what the ops do; `table` is [`spells_pipe_tables`], the one answer twig
759/// doesn't export.
760///
761/// `supports_with` rather than `supports` because two of these are facts about
762/// the *parse options* as much as about the format. `Format::supports` answers
763/// for twig's defaults, and leaf never parses with those — it parses with
764/// [`parse_extensions`], and a document's toolbar has to describe the document
765/// it is over. A Markdown editor holding `highlight` authors `==text==`; one
766/// without it would mint bytes its own reparse hands back as plain text, which
767/// is why twig asks before it writes.
768///
769/// **The formats are ragged, and that is the point.** A single per-document
770/// boolean was enough while the two authorable formats were Markdown and djot
771/// and everything else spelled nothing. HTML is neither: it writes seven of the
772/// eight inline marks as a tag pair, plus `<code>`, `<hr>` and an in-cell
773/// `<br>`, and spells no heading marker, no line prefix, no fence, no task box,
774/// no link — because its versions of those have a different *shape*, not a
775/// different alphabet. So ⌘B works in an HTML document and ⌘1 does not, and no
776/// one flag can say that. Markdown and djot differ from each other too:
777/// `^superscript^` is djot-only, and an in-cell `<br>` is Markdown-only.
778#[derive(Clone, Copy, Debug, Eq, PartialEq)]
779pub struct Capabilities {
780    /// ⌘B — `InlineKind::Strong`.
781    pub bold: bool,
782    /// ⌘I — `InlineKind::Emph`.
783    pub italic: bool,
784    /// Inline code — `InlineKind::Verbatim`.
785    pub code: bool,
786    /// Highlight — `InlineKind::Mark`. Djot spells it, and so does Markdown
787    /// under the `highlight` extension [`parse_extensions`] turns on: the
788    /// button writes `==text==`, which is what the reparse reads back.
789    pub mark: bool,
790    /// ⌘U — `InlineKind::Insert`, which every format that marks at all spells.
791    pub underline: bool,
792    /// Strikethrough — `InlineKind::Delete`. Markdown spells GFM's `~~text~~`
793    /// out of the box, since twig parses it out of the box.
794    pub strike: bool,
795    /// The highlight *palette* — [`Doc::set_mark_color`]. Narrower than
796    /// [`mark`](Self::mark) and deliberately its own flag: Markdown spells a
797    /// colour on a highlight (`==🔴 text==`) and djot spells only the highlight,
798    /// so a toolbar offering the swatches wherever the button lights would offer
799    /// them in a document that cannot write one. Pair with
800    /// [`Doc::caret_in_mark`], which asks the other question — the palette needs
801    /// a highlight to colour as much as a format that spells one.
802    pub mark_color: bool,
803    pub superscript: bool,
804    pub subscript: bool,
805    /// Heading levels and "make this a paragraph" — [`Doc::set_block`].
806    pub heading: bool,
807    pub blockquote: bool,
808    pub bullet_list: bool,
809    pub ordered_list: bool,
810    /// The checkbox controls: giving an item a box, and ticking one.
811    pub task: bool,
812    pub link: bool,
813    /// Covers [`Doc::insert_media`] too — see the note there on why the three
814    /// media kinds stand or fall together.
815    pub image: bool,
816    /// The horizontal-rule button. HTML spells this one (`<hr>`).
817    pub thematic_break: bool,
818    /// The footnote button — [`Doc::insert_footnote`]. Markdown and djot spell
819    /// the pair; HTML has no footnote of its own, so the button goes away rather
820    /// than writing brackets that would render as brackets.
821    pub footnote: bool,
822    /// Setting a fenced block's language — a control only ever offered with the
823    /// caret already in a fence.
824    pub code_language: bool,
825    /// The grid controls: insert/delete/move a row or column, set a column's
826    /// alignment. Pair with [`Doc::caret_in_table`], which asks the other
827    /// question — an HTML `<table>` holds the caret and still can't be edited.
828    pub table: bool,
829    /// Shift+Return inside a cell. Markdown and HTML spell it; djot has no
830    /// idiomatic in-cell break.
831    pub cell_line_break: bool,
832}
833
834impl Capabilities {
835    /// Resolve every flag for `format`, as leaf parses it. Pure and cheap —
836    /// twig computes each from a static table — but a frontend that wants to
837    /// hold them can.
838    ///
839    /// The extensions are not a parameter because they are not a choice a
840    /// caller makes: every leaf document is parsed with [`parse_extensions`],
841    /// so the format is the whole of what varies.
842    pub fn of(format: Format) -> Self {
843        let exts = parse_extensions();
844        let supports = |g| format.supports_with(exts, g);
845        let inline = |k| supports(Gesture::ToggleInline(k));
846        let container = |k| supports(Gesture::ToggleBlockContainer(k));
847        Self {
848            bold: inline(InlineKind::Strong),
849            italic: inline(InlineKind::Emph),
850            code: inline(InlineKind::Verbatim),
851            mark: inline(InlineKind::Mark),
852            underline: inline(InlineKind::Insert),
853            strike: inline(InlineKind::Delete),
854            mark_color: supports(Gesture::SetMarkColor),
855            superscript: inline(InlineKind::Superscript),
856            subscript: inline(InlineKind::Subscript),
857            heading: supports(Gesture::SetBlock),
858            blockquote: container(BlockContainerKind::BlockQuote),
859            bullet_list: container(BlockContainerKind::BulletList),
860            ordered_list: container(BlockContainerKind::OrderedList),
861            // Both halves of the checkbox story, and leaf offers no control that
862            // needs only one: the item gesture mints the box, the checked one
863            // ticks it, and a format spelling a `task_marker` spells both.
864            task: supports(Gesture::ToggleTaskItem) && supports(Gesture::ToggleTaskChecked),
865            link: supports(Gesture::InsertLink),
866            image: supports(Gesture::InsertImage),
867            thematic_break: supports(Gesture::InsertThematicBreak),
868            footnote: supports(Gesture::InsertFootnote),
869            code_language: supports(Gesture::SetCodeLanguage),
870            table: spells_pipe_tables(format),
871            cell_line_break: supports(Gesture::InsertLineBreak),
872        }
873    }
874}
875
876impl Doc {
877    #[cfg(feature = "fs")]
878    pub fn open(path: PathBuf) -> Result<Self> {
879        let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
880        Self::from_disk_bytes(path, bytes)
881    }
882
883    /// An empty document *named* `path`, for a file that isn't there yet — what
884    /// every other terminal editor gives you when you name a file that doesn't
885    /// exist. It is a real named document, not a [`Doc::blank`]: `is_untitled`
886    /// is false, so ⌘S writes straight to `path` with no Save As detour, and
887    /// the header shows the name the user asked for.
888    ///
889    /// The format comes from the extension, exactly as [`Doc::open`] reads it —
890    /// so `leaf notes.dj` starts a djot buffer rather than the Markdown
891    /// [`Doc::blank`] has to assume for want of a name. An extension leaf can't
892    /// parse is still an error: a mistyped flag or a stray argument should say
893    /// so, not open a buffer promising to save somewhere.
894    ///
895    /// The watermark is the hash of *no bytes*, not `None`, and that is the
896    /// whole trick: `None` means untitled, and would leave [`Doc::disk_state`]
897    /// answering [`DiskState::Untitled`] for a document that has a path and
898    /// intends to write to it. Hashing `""` instead makes the answers the true
899    /// ones — [`DiskState::Missing`] while the file still isn't there (a save
900    /// recreates it, which is exactly what this is for), and
901    /// [`DiskState::Changed`] if somebody creates it underneath us between
902    /// launch and save, so the frontend's overwrite prompt guards a new file as
903    /// it guards an opened one.
904    ///
905    /// Nothing is written here. A buffer that is never typed into never touches
906    /// the filesystem, and a `path` whose directory doesn't exist is allowed to
907    /// open — the write is where that fails, and it says so then.
908    #[cfg(feature = "fs")]
909    pub fn create(path: PathBuf) -> Result<Self> {
910        Self::from_disk_bytes(path, Vec::new())
911    }
912
913    /// [`Doc::open`] when the file is there, [`Doc::create`] when it isn't —
914    /// the call a CLI frontend wants for its path argument.
915    ///
916    /// The decision is made from the failed read itself rather than a `exists()`
917    /// check first, so there is no window between the two for the file to appear
918    /// or vanish in. Only `NotFound` opens a new buffer: a permissions error or
919    /// a directory in the way is still an error, because pretending those are
920    /// "no file yet" would offer to save over something leaf couldn't read.
921    #[cfg(feature = "fs")]
922    pub fn open_or_create(path: PathBuf) -> Result<Self> {
923        match std::fs::read(&path) {
924            Ok(bytes) => Self::from_disk_bytes(path, bytes),
925            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::create(path),
926            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
927        }
928    }
929
930    /// The shared body of [`Doc::open`] and [`Doc::create`]: bytes that are (or
931    /// stand in for) the file at `path`, parsed as the format its extension
932    /// names. Keeping the two on one path is what makes a new file's document
933    /// identical in every respect to an opened one but its contents.
934    #[cfg(feature = "fs")]
935    fn from_disk_bytes(path: PathBuf, bytes: Vec<u8>) -> Result<Self> {
936        let format = detect_format(&path)?;
937        let editor = new_editor(&bytes, format)?;
938        let source = String::from_utf8(bytes).map_err(|_| anyhow!("document is not UTF-8"))?;
939        let disk_hash = Some(hash_bytes(source.as_bytes()));
940        // Store the document's *absolute* path. A relative one (`leaf README.md`)
941        // has an empty parent, so a frontend can't resolve a relative image
942        // destination (`![](pic.png)`) against the document's directory and the
943        // picture silently falls back to its text placeholder. `absolute` is
944        // purely lexical — it prefixes the current directory and normalizes, but
945        // reads nothing and resolves no symlinks — so `file_name` and save are
946        // unchanged; it only gives `path.parent()` something to join against.
947        let path = std::path::absolute(&path).unwrap_or(path);
948        Ok(Doc::from_parts(editor, format, path, source, disk_hash))
949    }
950
951    /// Build a document from an in-memory string, the format named explicitly —
952    /// the portable, filesystem-free counterpart to [`Doc::open`] (which reads a
953    /// path and sniffs the format from its extension). A wasm or FFI host, which
954    /// has no path to read, uses this: it hands over bytes it fetched however it
955    /// could, and later persists [`Doc::source`] however it can (a browser
956    /// download, `localStorage`, a backend `PUT`) and calls [`Doc::mark_saved`].
957    ///
958    /// No file backs the result, so it starts untitled ([`Doc::is_untitled`] is
959    /// true) exactly like a [`Doc::blank`] that has been given content.
960    pub fn from_source(source: String, format: Format) -> Result<Self> {
961        let editor = new_editor(source.as_bytes(), format)?;
962        Ok(Doc::from_parts(
963            editor,
964            format,
965            PathBuf::new(),
966            source,
967            None,
968        ))
969    }
970
971    /// An untitled, empty document — the `+` button and a `leaf` launched with
972    /// no file argument. Nothing on disk backs it until a [`Doc::save_as`].
973    ///
974    /// It is Markdown, because a format has to be chosen before a name exists to
975    /// read one from: `detect_format` reads the extension and an untitled
976    /// document has neither. Markdown is what leaf's own files are, what its
977    /// block markers are already written for (`insert_block_prefix`), and the
978    /// extension a Save As will overwhelmingly pick — a wrong guess here would
979    /// mean typing djot into a buffer parsing it as Markdown. Note that Save As
980    /// *doesn't* revisit this: see [`Doc::save_as`].
981    pub fn blank() -> Result<Self> {
982        let format = Format::Markdown;
983        let editor = new_editor(b"", format)?;
984        // An empty `path` is the untitled marker (`path` is a public `PathBuf`
985        // field two frontends already read; making it an `Option` to say this
986        // would break both). `is_untitled` is the question to ask, not the
987        // representation to copy.
988        Ok(Doc::from_parts(
989            editor,
990            format,
991            PathBuf::new(),
992            String::new(),
993            None,
994        ))
995    }
996
997    /// The fields every constructor agrees on, so `open` and `blank` can't drift
998    /// apart in the ones neither of them has an opinion about.
999    fn from_parts(
1000        editor: Editor,
1001        format: Format,
1002        path: PathBuf,
1003        source: String,
1004        disk_hash: Option<u64>,
1005    ) -> Self {
1006        Doc {
1007            editor,
1008            format,
1009            path,
1010            disk_hash,
1011            clean_source: source.clone(),
1012            source,
1013            caret: 0,
1014            anchor: None,
1015            dirty: false,
1016            status: None,
1017            read_only: false,
1018            highlights: Vec::new(),
1019            // leaf opens in the rich-text (WYSIWYG) view by default — the
1020            // markup-resolved surface is leaf's differentiator. Frontends can
1021            // still start in source view explicitly (e.g. a CLI flag), and ⌘e/⌥w
1022            // toggles at runtime.
1023            view: View::Wysiwyg,
1024            // `None` by default — the clean surface Diaryx ships, with typed
1025            // syntax kept literal; a markup-fluent frontend can climb the
1026            // ladder to `Shortcuts` or `Full`.
1027            markup_mode: MarkupMode::default(),
1028            // Fold by default — flowing prose that reflows to the viewport, the
1029            // behaviour every frontend had before this preference existed.
1030            line_flow: LineFlow::default(),
1031            last_edit_kind: None,
1032            pending_marks: InlineMarks::empty(),
1033            pending_at: None,
1034            goal_col: None,
1035            vmap: VisualMap::default(),
1036            smap: SourceMap::default(),
1037            // No map yet — the first `build_source` always builds.
1038            smap_key: None,
1039            revision: 0,
1040            undo_steps: 0,
1041            redo_steps: 0,
1042            // No map yet — the first `build_visual` always builds.
1043            vmap_key: None,
1044            block_cache: wysiwyg::BlockCache::default(),
1045            media_rows: HashMap::new(),
1046            scroll: 0,
1047            body_origin: (0, 0),
1048            body_width: 0,
1049            body_height: 0,
1050            drawn_caret: None,
1051        }
1052    }
1053
1054    /// Whether this document has no file behind it yet — a [`Doc::blank`] that
1055    /// has never been saved. The question a ⌘S handler asks to know it should
1056    /// open a Save As picker instead ([`Doc::save`] won't guess a name), and the
1057    /// header asks to know the name it shows is a placeholder.
1058    pub fn is_untitled(&self) -> bool {
1059        self.path.as_os_str().is_empty()
1060    }
1061
1062    pub fn toggle_view(&mut self) {
1063        self.view = match self.view {
1064            View::Source => View::Wysiwyg,
1065            View::Wysiwyg => View::Source,
1066        };
1067        self.scroll = 0;
1068        self.status = None;
1069        // Entering WYSIWYG, the caret may be sitting in now-hidden frontmatter;
1070        // lift it to the first rendered offset.
1071        self.clamp_caret();
1072    }
1073
1074    /// The current markup-exposure preference (see [`MarkupMode`]).
1075    pub fn markup_mode(&self) -> MarkupMode {
1076        self.markup_mode
1077    }
1078
1079    /// Set the markup-exposure preference. Both of its axes take effect at
1080    /// once: the editing one on the next [`insert`](Self::insert), and the
1081    /// rendering one on the next build — which is why this drops the cached
1082    /// visual map and the per-block render cache, exactly as
1083    /// [`set_line_flow`](Self::set_line_flow) does.
1084    pub fn set_markup_mode(&mut self, mode: MarkupMode) {
1085        if self.markup_mode == mode {
1086            return;
1087        }
1088        self.markup_mode = mode;
1089        // Neither cache is keyed on the mode, and moving between `Full` and the
1090        // hidden modes changes every row the caret's line renders to — so
1091        // invalidate both explicitly.
1092        self.vmap_key = None;
1093        self.block_cache = wysiwyg::BlockCache::default();
1094    }
1095
1096    /// The source byte range of the line the caret sits on, when that line
1097    /// should render its raw delimiters — `None` in every mode and view that
1098    /// hides them, which is what the builder reads as "reveal nothing".
1099    ///
1100    /// A *source* line (newline to newline), not a visual row: a wrapped
1101    /// paragraph and a `LineFlow::Preserve` soft break both split one source
1102    /// line across several rows, and revealing half a delimiter pair because the
1103    /// other half wrapped would be worse than revealing neither. The range
1104    /// excludes the terminating newline and is empty-but-present on a blank
1105    /// line, which reveals nothing but still keys the caches correctly.
1106    ///
1107    /// Only in [`View::Wysiwyg`]: source view already shows every byte, so
1108    /// there is nothing there to reveal.
1109    pub(crate) fn reveal_line(&self) -> Option<Range<usize>> {
1110        if !self.markup_mode.reveals_caret_line() || self.view != View::Wysiwyg {
1111            return None;
1112        }
1113        Some(source_line_range(&self.source, self.caret))
1114    }
1115
1116    /// The current soft-break flow preference (see [`LineFlow`]).
1117    pub fn line_flow(&self) -> LineFlow {
1118        self.line_flow
1119    }
1120
1121    /// Set the soft-break flow preference. The mode changes how every block lays
1122    /// out, so a change drops the cached visual map and the per-block render
1123    /// cache, forcing the next [`build_visual`] to rebuild under the new flow.
1124    ///
1125    /// [`build_visual`]: Self::build_visual
1126    pub fn set_line_flow(&mut self, mode: LineFlow) {
1127        if self.line_flow == mode {
1128            return;
1129        }
1130        self.line_flow = mode;
1131        // Both caches are keyed on `(revision, wrap)`, neither of which moved —
1132        // so invalidate them explicitly, or the next build would reuse rows laid
1133        // out under the old flow.
1134        self.vmap_key = None;
1135        self.block_cache = wysiwyg::BlockCache::default();
1136    }
1137
1138    pub fn view_name(&self) -> &'static str {
1139        match self.view {
1140            View::Source => "source",
1141            View::Wysiwyg => "wysiwyg",
1142        }
1143    }
1144
1145    /// Rebuild the WYSIWYG visual map for the current tree at `width` columns
1146    /// (called by the renderer each frame it's in the WYSIWYG view).
1147    /// Build the WYSIWYG map, wrapped at `width` display columns.
1148    ///
1149    /// Cheap to call every frame, which is what both frontends do: the map is a
1150    /// pure function of the document and the wrap width, so a call that would
1151    /// rebuild the same map returns the one already built. Only an edit (or a
1152    /// resize) pays.
1153    ///
1154    /// That isn't a micro-optimisation. A frontend repaints for reasons that have
1155    /// nothing to do with the text — a blinking caret, a scroll, a focus change —
1156    /// and rebuilding here is O(document): 23 ms on a 1 MB file, of which 5 ms is
1157    /// marshalling twig's AST across the C ABI. Paid twice a second by the GUI's
1158    /// blink timer, that was 14% of a core spent redrawing an unchanged document.
1159    /// (`cargo run --release -p leaf-core --example bench` for the numbers.)
1160    pub fn build_visual(&mut self, width: usize) {
1161        self.build_map(Some(width));
1162    }
1163
1164    /// Build the WYSIWYG map with each block as a single unwrapped row — for a
1165    /// frontend (the GUI) that wraps at its own proportional pixel width rather
1166    /// than a fixed character column.
1167    pub fn build_visual_unwrapped(&mut self) {
1168        self.build_map(None);
1169    }
1170
1171    /// Build the source view's syntax map ([`Doc::smap`]) — the styling for
1172    /// [`View::Source`], the way [`build_visual`](Self::build_visual) is the
1173    /// styling for [`View::Wysiwyg`].
1174    ///
1175    /// A frontend calls this before painting raw source. One that doesn't gets
1176    /// an empty map and paints unstyled text, so this is additive: nothing
1177    /// breaks by not calling it.
1178    ///
1179    /// Built at most once per revision, and the revision is the whole key — the
1180    /// map has no width and no caret in it, so it survives every resize, every
1181    /// motion, and every selection change.
1182    ///
1183    /// The builds it does do cost a whole-arena marshal, which is precisely what
1184    /// the WYSIWYG path works to avoid, so this has no incremental path where
1185    /// that one has two. From `cargo run --release -p leaf-core --example
1186    /// bench`, per keystroke, against the WYSIWYG build the source view is
1187    /// *not* doing:
1188    ///
1189    /// |  size |  nodes | marshal | `source::build` | (`wysiwyg::build`) |
1190    /// |------:|-------:|--------:|----------------:|-------------------:|
1191    /// |  10 KB|    613 |  0.16 ms|         0.07 ms |            0.28 ms |
1192    /// | 100 KB|  6 097 |  0.84 ms|         0.38 ms |            2.43 ms |
1193    /// |   1 MB| 60 601 |  5.67 ms|         3.12 ms |           23.39 ms |
1194    ///
1195    /// Linear, two thirds of it the marshal, and the build itself five to seven
1196    /// times cheaper than the one it stands in for at every size. Comfortable
1197    /// well past any document a person edits in a terminal — a megabyte is where
1198    /// it would want [`Editor::dirty_range`] and the same splice treatment
1199    /// `build_spliced` gives the other map. The door is open; nothing has needed
1200    /// it yet.
1201    pub fn build_source(&mut self) {
1202        if self.smap_key == Some(self.revision) {
1203            return;
1204        }
1205        let nodes = self.nodes();
1206        self.smap = source::build(&nodes, &self.source);
1207        self.smap_key = Some(self.revision);
1208    }
1209
1210    /// Tell the model how many visual rows each block image should reserve, keyed
1211    /// by the image's destination. A terminal frontend calls this once it has
1212    /// decoded and measured its pictures — core does no image I/O, so this is the
1213    /// only way it learns a height — and the next [`Doc::build_visual`] lays each
1214    /// placeholder out that tall (the label row plus blank filler rows the
1215    /// frontend paints the raster over). A destination left out of the map falls
1216    /// back to the bare one-row placeholder, which is also what a frontend that
1217    /// can't draw pictures (or lays them out in its own units, like the GUI) gets
1218    /// by never calling this.
1219    ///
1220    /// Cheap to call every frame with the same map: only a *change* invalidates
1221    /// the built map (and the block-row cache, since a height isn't part of a
1222    /// block's bytes and so wouldn't otherwise re-render it). Steady state is a
1223    /// no-op, so a frontend can just hand over its current measurements each frame.
1224    pub fn set_media_rows(&mut self, rows: HashMap<String, usize>) {
1225        if self.media_rows == rows {
1226            return;
1227        }
1228        self.media_rows = rows;
1229        // A height lives outside the block's source bytes, so the content-keyed
1230        // block cache would hand back the old-height rows on a hit. Drop it (and
1231        // the splice layout it carries) so the next build re-renders every block
1232        // at the new heights, and force that build by clearing the map key.
1233        self.block_cache = wysiwyg::BlockCache::default();
1234        self.vmap_key = None;
1235    }
1236
1237    /// The revision the document's text is at — bumped by every edit, undo,
1238    /// redo, and reload, and by nothing else. A frontend caches against this to
1239    /// tell a repaint that needs new work from one that doesn't.
1240    ///
1241    /// It counts *edits*, not distinct texts: typing `x` and deleting it again
1242    /// lands on the same text two revisions later. Work is only ever rebuilt
1243    /// needlessly, never wrongly reused.
1244    pub fn revision(&self) -> u64 {
1245        self.revision
1246    }
1247
1248    /// The identity of the map presently in [`vmap`](Self::vmap) — what the last
1249    /// [`build_visual`](Self::build_visual) built it from, or the identity of an
1250    /// unbuilt map before the first one.
1251    ///
1252    /// This is *not* [`revision`](Self::revision). The revision says where the
1253    /// text is; this says where the map is, and the two part company the moment
1254    /// an edit lands, until something rebuilds. A frontend that keeps its own
1255    /// copy of the map — leaf-ratatui stashes core's before splicing filler rows
1256    /// under an oversized heading — compares this against the value it held when
1257    /// it took the copy, and learns whether `vmap` is still the map it stashed
1258    /// or one somebody else has since rebuilt. Restoring a copy over a newer
1259    /// map would paint a stale document; restoring nothing hands core's
1260    /// incremental rebuild a map it never built.
1261    pub fn visual_key(&self) -> VisualKey {
1262        VisualKey(self.vmap_key.clone())
1263    }
1264
1265    /// The map, built at most once per `(revision, wrap)`. `clamp_caret` still
1266    /// runs on every call: the caret moves without the document changing, and
1267    /// keeping it on a legal stop is this function's job either way.
1268    fn build_map(&mut self, wrap: Option<usize>) {
1269        // Under `MarkupMode::Full` the map is a function of the caret's *line*
1270        // as well as the text, so the line joins the key: moving within a line
1271        // still reuses the map, and crossing into another one rebuilds it. In
1272        // every other mode `reveal_line` is `None` and the key is what it was,
1273        // so caret motion goes on costing nothing.
1274        let reveal = self.reveal_line();
1275        let key = (self.revision, wrap, reveal.clone());
1276        if self.vmap_key.as_ref() != Some(&key) {
1277            // Enumerate the top-level blocks cheaply — no whole-arena marshal.
1278            // A subtree is pulled only for the block(s) that actually changed, so
1279            // the FFI marshal shrinks from O(document) to O(edited block).
1280            let top = self.top_blocks();
1281
1282            // Fast path: when twig reports a dirty byte range, try to patch the
1283            // previous map in place — a single-block edit moves the prefix,
1284            // shifts the suffix, and re-renders only one block. `build_spliced`
1285            // returns `None` (and we fall back to the always-correct full rebuild)
1286            // whenever the edit reshaped the block structure, hit a table, or
1287            // there's no previous map to patch.
1288            // Preserve soft breaks as written when the flow preference asks for
1289            // it — the builder renders each as its own visual row instead of
1290            // folding it into the reflowed paragraph.
1291            let preserve_soft = self.line_flow == LineFlow::Preserve;
1292            let spliced = match self.editor.dirty_range() {
1293                Some(dirty) => {
1294                    let prev = std::mem::take(&mut self.vmap);
1295                    let source = &self.source;
1296                    let cache = &mut self.block_cache;
1297                    let media_rows = &self.media_rows;
1298                    let editor = &mut self.editor;
1299                    wysiwyg::build_spliced(
1300                        prev,
1301                        source,
1302                        wrap,
1303                        preserve_soft,
1304                        &top,
1305                        dirty,
1306                        media_rows,
1307                        reveal.clone(),
1308                        cache,
1309                        |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1310                    )
1311                }
1312                None => None,
1313            };
1314            self.vmap = spliced.unwrap_or_else(|| {
1315                let source = &self.source;
1316                let cache = &mut self.block_cache;
1317                let media_rows = &self.media_rows;
1318                let editor = &mut self.editor;
1319                wysiwyg::build_cached(
1320                    &top,
1321                    source,
1322                    wrap,
1323                    preserve_soft,
1324                    media_rows,
1325                    reveal,
1326                    cache,
1327                    |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1328                )
1329            });
1330            // Acknowledge the dirty range so the next edit's range starts fresh.
1331            self.editor.clear_dirty();
1332            self.vmap_key = Some(key);
1333        }
1334        self.clamp_caret();
1335    }
1336
1337    fn nodes(&mut self) -> Vec<FlatNode> {
1338        self.editor.nodes().unwrap_or_default()
1339    }
1340
1341    /// The document's top-level blocks for the incremental render. See
1342    /// [`wysiwyg::top_blocks`] for why this isn't simply `child_spans(None)`.
1343    fn top_blocks(&mut self) -> Vec<QueryMatch> {
1344        wysiwyg::top_blocks(&mut self.editor)
1345    }
1346
1347    pub fn format_name(&self) -> &'static str {
1348        // `Format` is `#[non_exhaustive]` as of twig 3.0, so the wildcard is
1349        // required. It also covers `Asciidoc`, which twig parses but cannot
1350        // serialize — leaf never opens a document in it (see `Doc::open`).
1351        match self.format {
1352            Format::Djot => "djot",
1353            Format::Markdown => "markdown",
1354            Format::Xml => "xml",
1355            Format::Html => "html",
1356            _ => "unknown",
1357        }
1358    }
1359
1360    /// Whether this document's format offers *any* door in — `false` only for a
1361    /// wholly parse-only format (XML, AsciiDoc), where every gesture refuses and
1362    /// a frontend may as well open the file read-only.
1363    ///
1364    /// This is a much weaker claim than the name suggests, and driving per-button
1365    /// state from it is exactly the mistake to avoid: HTML answers `true` because
1366    /// it spells the inline marks with a tag pair (`<strong>`, `<em>`, `<code>`)
1367    /// while a heading, a quote, a list, a task box, a link and a code fence all
1368    /// remain unspellable there. Ask [`capabilities`](Self::capabilities) — or
1369    /// [`supports`](Self::supports) — per control.
1370    pub fn authorable(&self) -> bool {
1371        self.format.is_authorable()
1372    }
1373
1374    /// Whether this document can spell `gesture`, which is twig's own answer
1375    /// rather than a copy of it: `Format::supports_with` reads the same
1376    /// `Syntax` table the `Editor` method consults before refusing, chosen by
1377    /// the very [`parse_extensions`] this document's editor reparses with — so
1378    /// what the toolbar offers and what the splice will accept are one table.
1379    ///
1380    /// It is a fact about the *document*, not about the caret. `true` does not
1381    /// promise the gesture succeeds where it is standing — a link over a table
1382    /// border still fails — only that it will not fail with
1383    /// `UnsupportedFormat`. Gray out on `false`; don't read `true` as "this
1384    /// will work here".
1385    pub fn supports(&self, gesture: Gesture) -> bool {
1386        self.format.supports_with(parse_extensions(), gesture)
1387    }
1388
1389    /// Every control's enabled state in one read — what a toolbar builds itself
1390    /// from when a document opens or its format changes. See [`Capabilities`].
1391    pub fn capabilities(&self) -> Capabilities {
1392        Capabilities::of(self.format)
1393    }
1394
1395    /// Refuse a gesture this document's format cannot spell, saying so in the
1396    /// status line. `true` means the caller must return without calling twig.
1397    ///
1398    /// Most of these refusals duplicate one twig would make anyway, and they are
1399    /// made here regardless because a message naming the *document's* format
1400    /// reads better than one naming twig's internals. Two of them are not
1401    /// duplicates and are the reason this is a guard rather than an error
1402    /// translation:
1403    ///
1404    /// - The table family (see [`table_op`](Self::table_op)) consults no
1405    ///   `Syntax` table, so twig does not refuse it at all.
1406    /// - [`toggle`](Self::toggle) at a collapsed caret never reaches twig — it
1407    ///   arms a sticky mark for text not yet typed, which is a promise `insert`
1408    ///   could not keep.
1409    fn refuse_unsupported(&mut self, what: &str, gesture: Gesture) -> bool {
1410        self.refuse_unless(what, self.supports(gesture))
1411    }
1412
1413    /// [`refuse_unsupported`](Self::refuse_unsupported) against a capability leaf
1414    /// answers itself — today only [`spells_pipe_tables`].
1415    fn refuse_unless(&mut self, what: &str, supported: bool) -> bool {
1416        if supported {
1417            return false;
1418        }
1419        self.status = Some(format!("{what}: not supported in {}", self.format_name()));
1420        true
1421    }
1422
1423    /// The name to show for this document. An untitled one has no file to name
1424    /// it, and both frontends put this straight on screen — an empty path
1425    /// renders as an empty header, so it says so instead.
1426    pub fn file_name(&self) -> String {
1427        if self.is_untitled() {
1428            return "untitled".into();
1429        }
1430        self.path
1431            .file_name()
1432            .map(|s| s.to_string_lossy().into_owned())
1433            .unwrap_or_else(|| self.path.display().to_string())
1434    }
1435
1436    /// The selection as an ordered `[start, end)` byte range, or `None` when the
1437    /// caret and anchor coincide (an empty selection is no selection).
1438    pub fn selection(&self) -> Option<(usize, usize)> {
1439        self.anchor
1440            .map(|a| (a.min(self.caret), a.max(self.caret)))
1441            .filter(|(s, e)| s != e)
1442    }
1443
1444    /// The selected text, or `None` when there's no selection — the source
1445    /// slice a copy/cut hands to the system clipboard.
1446    pub fn selected_text(&self) -> Option<&str> {
1447        self.selection().map(|(s, e)| &self.source[s..e])
1448    }
1449
1450    /// The selection as a quote with a little of what surrounds it — the shape
1451    /// a host that cites, annotates, or searches for a passage wants, cut from
1452    /// the **source** rather than from anything rendered, so the quote is
1453    /// findable in the document again by plain string search.
1454    ///
1455    /// `context` is a count of characters (not bytes) on each side, clipped at
1456    /// the document's edges; the slices land on char boundaries by
1457    /// construction. `None` when nothing is selected.
1458    pub fn selection_quote(&self, context: usize) -> Option<Quote> {
1459        let (start, end) = self.selection()?;
1460        let mut before = start;
1461        for _ in 0..context {
1462            match self.source[..before].chars().next_back() {
1463                Some(c) => before -= c.len_utf8(),
1464                None => break,
1465            }
1466        }
1467        let mut after = end;
1468        for _ in 0..context {
1469            match self.source[after..].chars().next() {
1470                Some(c) => after += c.len_utf8(),
1471                None => break,
1472            }
1473        }
1474        Some(Quote {
1475            exact: self.source[start..end].to_string(),
1476            prefix: self.source[before..start].to_string(),
1477            suffix: self.source[end..after].to_string(),
1478            start,
1479            end,
1480        })
1481    }
1482
1483    /// Whether the document refuses to change — see the field.
1484    pub fn read_only(&self) -> bool {
1485        self.read_only
1486    }
1487
1488    /// Turn the read-only gate on or off. A frontend preference like
1489    /// [`set_markup_mode`](Self::set_markup_mode): nothing about the document
1490    /// itself changes, only what may be done to it from here on.
1491    pub fn set_read_only(&mut self, on: bool) {
1492        self.read_only = on;
1493    }
1494
1495    /// The host-painted ranges, sorted by start — see [`Highlight`].
1496    pub fn highlights(&self) -> &[Highlight] {
1497        &self.highlights
1498    }
1499
1500    /// Replace the host-painted ranges wholesale. The whole set each time,
1501    /// rather than add/remove verbs: the host owns the list (it derives it
1502    /// from its own state — annotations, search hits), and a replace can
1503    /// never leave the two disagreeing about what should be on screen.
1504    pub fn set_highlights(&mut self, mut highlights: Vec<Highlight>) {
1505        highlights.retain(|h| h.start < h.end);
1506        highlights.sort_by_key(|h| (h.start, h.end));
1507        self.highlights = highlights;
1508    }
1509
1510    /// The highlight covering source `offset`, if one does — first by start
1511    /// when several overlap, which makes overlapping washes resolvable rather
1512    /// than undefined. What a frontend asks when the reader activates a spot.
1513    ///
1514    /// [`Highlight::covering`] is the whole of it: the frontends paint by
1515    /// asking the same question per glyph, against a slice they were handed
1516    /// rather than against a `Doc`, and one answer for both is what keeps a
1517    /// wash and an activation agreeing about which range a spot is in.
1518    pub fn highlight_at(&self, offset: usize) -> Option<&Highlight> {
1519        Highlight::covering(&self.highlights, offset)
1520    }
1521
1522    /// The AST breadcrumb at the caret (root → deepest), e.g.
1523    /// `doc › para › strong`. Read live from twig via `ancestors_at`.
1524    pub fn breadcrumb(&mut self) -> String {
1525        match self.editor.ancestors_at(self.caret) {
1526            Ok(chain) => chain
1527                .iter()
1528                .map(|m| m.kind.as_str())
1529                .collect::<Vec<_>>()
1530                .join(" › "),
1531            Err(_) => String::new(),
1532        }
1533    }
1534
1535    // ── editing ──────────────────────────────────────────────────────────────
1536
1537    /// Replace the byte range `[start, end)` with `text`, re-anchoring the caret
1538    /// after it. The public form of the internal splice — a pixel frontend that
1539    /// hit-tests to a byte offset (or an IME that hands back an explicit range)
1540    /// edits through this, the same twig `edit_range` the caret ops use.
1541    pub fn edit(&mut self, start: usize, end: usize, text: &str) {
1542        self.splice(start, end, text, EditKind::Other);
1543    }
1544
1545    /// Insert typed `text` at the caret, replacing the selection if there is one.
1546    /// A single typed character coalesces with the run of typing before it; a
1547    /// newline or a multi-character insert is its own undo step.
1548    ///
1549    /// Typed input only — clipboard text goes through [`paste`](Self::paste).
1550    pub fn insert(&mut self, text: &str) {
1551        // The read-only gate, up front: the paths below reach twig by several
1552        // verbs, not all of them through the splice — see the field.
1553        if self.read_only {
1554            return;
1555        }
1556        // Typing against a block picture would dissolve it — see
1557        // `open_paragraph_at_block_media`. Give the text a paragraph first, so
1558        // what the caret was standing beside stays a picture.
1559        self.open_paragraph_at_block_media(text);
1560        // Armed sticky marks (⌘b with no selection) turn the next typed text
1561        // bold/italic/… and then retire — see `insert_with_marks`. Whitespace is
1562        // the exception: it takes no mark of its own and keeps the delta armed
1563        // for the character behind it — see `insert_space_with_marks`.
1564        let pending = self.pending_here();
1565        if !pending.is_empty() && self.selection().is_none() && !text.is_empty() {
1566            if text.trim().is_empty() {
1567                self.insert_space_with_marks(self.caret, text, pending);
1568            } else {
1569                self.insert_with_marks(self.caret, text, pending);
1570            }
1571            return;
1572        }
1573        // `MarkupMode::None`: typed syntax stays literal — twig escapes
1574        // anything that would open markup, so a Diaryx user never mints
1575        // formatting by keyboard (it comes from commands instead). The other two
1576        // rungs of the ladder author markup from what you type, which is the
1577        // whole difference between them and this one. Only in the rendered view
1578        // (source view is for typing raw markup) and only where the format has a
1579        // literal spelling at all: escaping is a backslash before a byte from the
1580        // format's own alphabet, and a format with no such alphabet (HTML escapes
1581        // with entities, XML spells nothing) would have `\&` written into it,
1582        // which is two literal characters and not an escape. Marks (⌘b) still
1583        // format — that path returned above; and leaf's own structural inserts go
1584        // through `insert_raw`, never here, so a list marker or quote gutter is
1585        // written as the markup it is.
1586        if !self.markup_mode.authors()
1587            && self.view == View::Wysiwyg
1588            && !text.is_empty()
1589            && self.supports(Gesture::InsertLiteral)
1590        {
1591            self.insert_literal_typed(text);
1592            return;
1593        }
1594        self.insert_raw(text);
1595    }
1596
1597    /// Insert `text` verbatim at the caret (replacing any selection) — the plain
1598    /// path with no Hidden-mode literal escaping. leaf's own structural inserts
1599    /// (a list marker, a quote gutter, an in-cell `<br>`) call this: they ARE
1600    /// markup by design and must not be escaped.
1601    fn insert_raw(&mut self, text: &str) {
1602        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
1603        self.splice(s, e, text, typed_edit_kind(text));
1604    }
1605
1606    /// Open a paragraph for text about to be inserted at one of a block media's
1607    /// two caret stops, and leave the caret standing in it.
1608    ///
1609    /// A block image is a paragraph whose entire content is the picture, and the
1610    /// caret's only homes on it are in front of it and just past it (see
1611    /// [`VisualMap::block_media_stop`]). Text inserted at either offset joins
1612    /// *that* paragraph — and a paragraph holding anything besides the image is
1613    /// no longer a block image but a line of text with an inline one in it. The
1614    /// frontend that was painting a photo there paints a text run instead; the
1615    /// picture is still in the file, and nothing said a word. Those two offsets
1616    /// are also exactly where a click on the picture lands, so the whole accident
1617    /// is one tap and one keystroke.
1618    ///
1619    /// So the break goes in first and the text lands in the new empty paragraph —
1620    /// what pressing Return before typing would have done, which is a habit no
1621    /// one should have to learn from losing a photo. A no-op everywhere else, and
1622    /// over a selection (which is replaced, not joined into).
1623    ///
1624    /// A picture inside a quote or a list leaves its container, because `\n\n`
1625    /// ends the block. The alternative is worse: the `\n> ` / next-item
1626    /// continuation [`newline`](Self::newline) writes stays in the same
1627    /// *paragraph*, which is the thing being prevented.
1628    ///
1629    /// Only in the rendered view. Source view is for typing raw markup, where
1630    /// putting a character against an image is exactly what it looks like.
1631    fn open_paragraph_at_block_media(&mut self, text: &str) {
1632        if self.view != View::Wysiwyg || text.is_empty() || text == "\n" {
1633            return;
1634        }
1635        if self.selection().is_some() {
1636            return;
1637        }
1638        // The map may be a revision behind (nothing has drawn since the last
1639        // edit), and this asks it about offsets — a stale answer would splice a
1640        // break into the wrong place. Free when it is already current, which it
1641        // is whenever a frontend drew a frame between keystrokes.
1642        self.rebuild_map();
1643        let at = self.caret;
1644        let Some((side, _)) = self.vmap.block_media_stop(at) else {
1645            return;
1646        };
1647        if !self.splice(at, at, "\n\n", EditKind::Other) {
1648            return;
1649        }
1650        // The break is part of the keystroke, not an edit of its own: leave the
1651        // run marked as typing so the character about to arrive folds into it and
1652        // one undo puts the document back the way it was found. (A paste, or a
1653        // multi-character insert, is `EditKind::Other` and stays its own step —
1654        // as it would have been anywhere else in the document.)
1655        self.last_edit_kind = Some(EditKind::Insert);
1656        if side == MediaStop::Before {
1657            // The break went in above the picture and the caret rode to the end
1658            // of it — which is still hard against the picture. Step back onto the
1659            // blank line it opened, so the text lands above rather than in front.
1660            self.caret = at;
1661        }
1662    }
1663
1664    /// A delete key pressed at one of a block picture's two caret stops, handled
1665    /// as the picture being an *atom* rather than a run of bytes. Returns whether
1666    /// the key was consumed.
1667    ///
1668    /// The caret rests in front of a block image and just past it, never inside
1669    /// its markup — which the rendered view doesn't show. So the byte a delete
1670    /// key nominally takes there is one the writer cannot see, and taking it
1671    /// leaves the picture as broken markup rather than as anything anyone asked
1672    /// for: Backspace at the stop past `![](p.png)` removes the closing paren, and
1673    /// a photo becomes the literal text `![](p.png`. That is how a picture goes
1674    /// missing from a document with nobody having touched it — the same
1675    /// dissolution [`open_paragraph_at_block_media`](Self::open_paragraph_at_block_media)
1676    /// prevents from the typing side, and it cost this repository's own test vault
1677    /// a photo before it was found.
1678    ///
1679    /// So the key aimed *at* the picture deletes the picture, whole — Backspace
1680    /// when it is behind the caret, Delete when it is in front — which is what
1681    /// every editor does with an embed, and one undo away. The key aimed *away*
1682    /// from it would otherwise delete the paragraph break and merge a neighbour
1683    /// into the picture's own paragraph, which dissolves it just as surely; it
1684    /// steps the caret over the boundary instead and leaves the
1685    /// next press to delete in the block it has reached — the same "first press
1686    /// steps out of the atom, second press deletes" every delete key here gets,
1687    /// word-deletes included (⌥⌫ in front of a picture is aimed at the prose
1688    /// above, and reaches it on the second press rather than taking the break and
1689    /// the picture with it on the first).
1690    fn delete_around_block_media(&mut self, forward: bool) -> bool {
1691        // The map answers about offsets, so it has to be this revision's — see
1692        // the same call in `open_paragraph_at_block_media`.
1693        self.rebuild_map();
1694        let Some((side, span)) = self.vmap.block_media_stop(self.caret) else {
1695            return false;
1696        };
1697        let aimed_at_it = side
1698            == if forward {
1699                MediaStop::Before
1700            } else {
1701                MediaStop::After
1702            };
1703        if !aimed_at_it {
1704            let over = if forward {
1705                self.vmap.stop_after(self.caret)
1706            } else {
1707                self.vmap.stop_before(self.caret)
1708            };
1709            if let Some(off) = over.filter(|&o| o >= self.caret_floor()) {
1710                self.caret = off;
1711                self.anchor = None;
1712                self.goal_col = None;
1713            }
1714            return true;
1715        }
1716        // Take the break that held the picture apart from its neighbour with it,
1717        // so the delete doesn't leave a blank paragraph standing where the
1718        // picture was. The last arm is a picture that is the whole document.
1719        let (from, to) = if self.source[..span.start].ends_with("\n\n") {
1720            (span.start - 2, span.end)
1721        } else if self.source[span.end..].starts_with("\n\n") {
1722            (span.start, span.end + 2)
1723        } else {
1724            (span.start, span.end)
1725        };
1726        self.splice(from.max(self.caret_floor()), to, "", EditKind::Other);
1727        true
1728    }
1729
1730    /// The Hidden-mode typing path: replace any selection, then insert `text`
1731    /// escaped so it stays literal. When it replaces a selection the two edits
1732    /// fold into one undo step, so an overwrite undoes atomically (and restores
1733    /// the selection) exactly as a plain one does.
1734    fn insert_literal_typed(&mut self, text: &str) {
1735        let kind = typed_edit_kind(text);
1736        match self.selection() {
1737            Some((s, e)) => {
1738                if !self.splice(s, e, "", EditKind::Other) {
1739                    return;
1740                }
1741                // Typing over a whole marked run takes its delimiters with it
1742                // (the empty content couldn't hold them — see
1743                // `repair_mark_edges`) and leaves its marks armed at the caret.
1744                // The text taking the run's place inherits them, exactly as it
1745                // would have by landing inside a run that survived.
1746                let pending = self.pending_here();
1747                if !pending.is_empty() && !text.trim().is_empty() {
1748                    self.insert_with_marks(self.caret, text, pending);
1749                    return;
1750                }
1751                self.insert_literal_at(self.caret, text, kind, true);
1752            }
1753            None => {
1754                self.insert_literal_at(self.caret, text, kind, false);
1755            }
1756        }
1757    }
1758
1759    /// The sticky-mark delta that is live right now: the marks armed by [`toggle`]
1760    /// at a collapsed caret, but only while the caret still stands where they
1761    /// were armed and nothing is selected. Empty otherwise, so a stale delta
1762    /// never styles text it wasn't meant for.
1763    fn pending_here(&self) -> InlineMarks {
1764        if self.anchor.is_none() && self.pending_at == Some(self.caret) {
1765            self.pending_marks
1766        } else {
1767            InlineMarks::empty()
1768        }
1769    }
1770
1771    /// Drop the armed sticky marks — any caret motion, selection, or edit does
1772    /// this, so "start bold here" only ever applies at the exact spot it was
1773    /// asked for.
1774    fn clear_pending(&mut self) {
1775        self.pending_marks = InlineMarks::empty();
1776        self.pending_at = None;
1777    }
1778
1779    /// Insert `text` at `at` carrying the armed sticky `marks`: a mark not yet in
1780    /// force is wrapped around the freshly typed text; a mark the caret already
1781    /// stands inside is *shed* — the text is inserted past the run's end so it
1782    /// lands unmarked ("type normally again"). The caret comes to rest inside any
1783    /// added runs, so continued typing inherits the marks with no re-wrapping,
1784    /// and the delta is cleared: the marks now live in the document, not here.
1785    fn insert_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
1786        let base = self.mark_spans_at(at);
1787        let base_set: InlineMarks = base.iter().map(|(k, _)| *k).collect();
1788        // Nothing to shed, and a run of exactly these marks standing just behind
1789        // the caret: carry on writing *that* run rather than opening a second
1790        // one beside it.
1791        if base_set.is_empty() && self.rejoin_run(at, text, marks) {
1792            return;
1793        }
1794        // Shed the marks we're turning off: step the insertion point past the
1795        // end of each run the caret sits in, so the new text falls outside it.
1796        let mut ins_at = at;
1797        for (kind, span) in &base {
1798            if marks.contains(*kind) {
1799                ins_at = ins_at.max(span.end);
1800            }
1801        }
1802        if !self.splice_exact(ins_at, ins_at, text, EditKind::Other) {
1803            return;
1804        }
1805        // The plain splice inserted exactly `text` at `ins_at`; that byte range
1806        // is the content every added mark wraps.
1807        let (mut cs, mut ce) = (ins_at, ins_at + text.len());
1808        for kind in marks.iter() {
1809            if !base_set.contains(kind) {
1810                let (ncs, nce) = self.wrap_span(cs, ce, kind);
1811                cs = ncs;
1812                ce = nce;
1813            }
1814        }
1815        self.caret = ce.min(self.source.len());
1816        self.anchor = None;
1817        self.last_edit_kind = None;
1818        // Realised: the marks are in the document now, and the caret sits inside
1819        // them, so there is no delta left to carry. Arm nothing, but remember the
1820        // spot so a *further* toggle before typing starts a clean delta here.
1821        self.pending_marks = InlineMarks::empty();
1822        self.pending_at = Some(self.caret);
1823        self.clamp_caret();
1824        self.record_caret();
1825    }
1826
1827    /// Carry on the marked run just behind `at` — moving its closing delimiters
1828    /// out past the new text — instead of opening a second run of the same marks
1829    /// beside it. Returns whether it did.
1830    ///
1831    /// This is the far half of the mark-edge rule (see [`splice`](Self::splice)).
1832    /// A space typed after a bold word steps the caret out of the run, because
1833    /// `**bold **` is not bold; the next character has to step back *in*, or the
1834    /// writer who typed one bold phrase is left with `**bold** **and**` — two
1835    /// runs that read the same to a reader but spell the file in a way nobody
1836    /// wrote. Only whitespace may stand in the gap (a run doesn't reach across
1837    /// words it isn't marking), and the marks behind it must be exactly the ones
1838    /// armed — a run of *some* other kind is a neighbour, not this phrase.
1839    fn rejoin_run(&mut self, at: usize, text: &str, marks: InlineMarks) -> bool {
1840        if text.is_empty() || text.trim() != text {
1841            return false;
1842        }
1843        let gap_at = self.source[..at].trim_end_matches([' ', '\t']).len();
1844        // Walk in through the delimiters stacked at that point, innermost last:
1845        // `***both*** ` closes two runs with one `***`, and rejoining means
1846        // getting behind all of them.
1847        let (mut cut, mut kinds) = (gap_at, InlineMarks::empty());
1848        while let Some((kind, content_end)) = self
1849            .editor
1850            .ancestors_at(prev_boundary(&self.source, cut))
1851            .unwrap_or_default()
1852            .into_iter()
1853            .filter(|m| m.span.end == cut)
1854            .find_map(|m| Some((inline_kind(&m.kind)?, m.content_span.clone()?.end)))
1855        {
1856            if content_end >= cut {
1857                break; // a mark with no closing delimiter to step behind
1858            }
1859            kinds.insert(kind);
1860            cut = content_end;
1861        }
1862        if cut == gap_at || kinds != marks {
1863            return false;
1864        }
1865        // Re-spell the tail: the gap, then the new text, then the delimiters that
1866        // used to close in front of them — read out of the document rather than
1867        // written from a table, so whatever twig spells them with is what moves.
1868        let tail = format!(
1869            "{}{text}{}",
1870            &self.source[gap_at..at],
1871            &self.source[cut..gap_at]
1872        );
1873        if !self.splice_exact(cut, at, &tail, EditKind::Other) {
1874            return false;
1875        }
1876        self.caret = (cut + (at - gap_at) + text.len()).min(self.source.len());
1877        self.anchor = None;
1878        self.last_edit_kind = None;
1879        self.pending_marks = InlineMarks::empty();
1880        self.pending_at = Some(self.caret);
1881        self.clamp_caret();
1882        self.record_caret();
1883        true
1884    }
1885
1886    /// Insert typed whitespace at a caret with sticky marks armed. Whitespace is
1887    /// never itself wrapped: a mark around a space draws nothing a reader can
1888    /// see, and in Markdown and Djot it draws its own delimiters instead
1889    /// (`** **`). So the space goes in unmarked — outside any run the armed
1890    /// marks are shedding — and the marks stay armed for the character after it,
1891    /// which rejoins the run (see [`rejoin_run`](Self::rejoin_run)).
1892    fn insert_space_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
1893        let base = self.mark_spans_at(at);
1894        // What the *next* character carries: the armed delta resolved against the
1895        // marks in force here, which the space must not quietly drop.
1896        let want = base
1897            .iter()
1898            .map(|(k, _)| *k)
1899            .collect::<InlineMarks>()
1900            .xor(marks);
1901        let mut ins_at = at;
1902        for (kind, span) in &base {
1903            if marks.contains(*kind) {
1904                ins_at = ins_at.max(span.end);
1905            }
1906        }
1907        if !self.splice(ins_at, ins_at, text, typed_edit_kind(text)) {
1908            return;
1909        }
1910        self.rearm(want);
1911        self.record_caret();
1912    }
1913
1914    /// Wrap `[s, e)` in `kind` via twig and return the byte span the *content*
1915    /// (not the delimiters) occupies afterwards. Markdown/Djot inline delimiters
1916    /// are symmetric (`**`…`**`, `_`…`_`, `` ` ``…`` ` ``), so the bytes twig
1917    /// added split evenly around the content — half the growth on each side.
1918    fn wrap_span(&mut self, s: usize, e: usize, kind: InlineKind) -> (usize, usize) {
1919        // The read-only gate — this door reaches twig without the splice.
1920        if self.read_only {
1921            return (s, e);
1922        }
1923        match self.editor.toggle_inline(s, e, kind) {
1924            Ok(change) => {
1925                self.last_edit_kind = None;
1926                self.refresh();
1927                self.dirty = self.source != self.clean_source;
1928                let added = (change.new.end - change.new.start).saturating_sub(e - s);
1929                let half = added / 2;
1930                (change.new.start + half, change.new.end - half)
1931            }
1932            // Unsupported here (e.g. mark on Markdown): leave the text unwrapped
1933            // rather than lose the keystroke.
1934            Err(e2) => {
1935                self.status = Some(format!("{kind:?}: {e2}"));
1936                (s, e)
1937            }
1938        }
1939    }
1940
1941    /// The safe offset to splice a block-level break at, given a caret that may
1942    /// sit exactly between an inline mark's content and its own closing
1943    /// delimiter (`content_span.end == off < span.end` for some enclosing mark
1944    /// — the WYSIWYG caret's natural resting place at the end of `**bold**`
1945    /// with nothing following it on the line: the closing `**` renders no
1946    /// glyph of its own, so the caret's "end of line" offset lands right
1947    /// before it). Splicing a paragraph/list/quote break at `off` itself would
1948    /// sever the delimiter from its content, stranding it alone on the new
1949    /// line. Walks out to the *outermost* such mark's `span.end` instead, so
1950    /// nested marks closing at the same point (`**_x_**`) all clear together.
1951    /// A no-op everywhere else — mid-run, or past real trailing content, no
1952    /// mark's `content_span` ends exactly at `off`.
1953    fn skip_trailing_close_delims(&mut self, off: usize) -> usize {
1954        let off = off.min(self.source.len());
1955        self.editor
1956            .ancestors_at(off)
1957            .unwrap_or_default()
1958            .into_iter()
1959            .filter(|m| inline_kind(&m.kind).is_some())
1960            .filter(|m| off < m.span.end && m.content_span.as_ref().is_some_and(|c| c.end == off))
1961            .map(|m| m.span.end)
1962            .max()
1963            .unwrap_or(off)
1964    }
1965
1966    /// The offset a *delete* aimed at the character before `off` should stop at,
1967    /// when `off` is the start of a run's text and the bytes behind it are that
1968    /// run's opening delimiter. The rich view draws no glyph for a `**`, so the
1969    /// byte behind the caret at the start of a bold word is not a character the
1970    /// writer can see, let alone one they aimed Backspace at: taking it leaves
1971    /// `a *bold** c` — the styling gone and a literal asterisk in its place. The
1972    /// delete steps over the whole delimiter to the visible character in front of
1973    /// it instead. Walks out to the *outermost* mark opening there, so
1974    /// `**_x_**` clears every delimiter at once, and is a no-op anywhere else.
1975    fn skip_leading_open_delims(&mut self, off: usize) -> usize {
1976        let off = off.min(self.source.len());
1977        self.editor
1978            .ancestors_at(off)
1979            .unwrap_or_default()
1980            .into_iter()
1981            .filter(|m| inline_kind(&m.kind).is_some())
1982            .filter(|m| {
1983                m.span.start < off && m.content_span.as_ref().is_some_and(|c| c.start == off)
1984            })
1985            .map(|m| m.span.start)
1986            .min()
1987            .unwrap_or(off)
1988    }
1989
1990    /// `off` moved *inside* the run whose closing delimiters end there — the
1991    /// other offset the rich view draws in the same place, since a `**` renders
1992    /// no glyph of its own. `**bold**` has a caret home on each side of its
1993    /// closing delimiter, one column apart on screen and eight bytes and a whole
1994    /// run apart in the file, and a plain ← lands on the outer one whenever a
1995    /// space follows the phrase. The inner one is what the writer is pointing at
1996    /// there: the end of their bold word. Walks in through every mark closing at
1997    /// that point, innermost last, so `***both***` lands inside both. A no-op
1998    /// anywhere else — mid-run, or in prose, no mark's span ends at `off`.
1999    fn step_inside_close_delims(&mut self, off: usize) -> usize {
2000        let mut off = off.min(self.source.len());
2001        loop {
2002            let inner = self
2003                .editor
2004                .ancestors_at(prev_boundary(&self.source, off))
2005                .unwrap_or_default()
2006                .into_iter()
2007                .filter(|m| inline_kind(&m.kind).is_some() && m.span.end == off)
2008                .filter_map(|m| m.content_span.clone().map(|c| c.end))
2009                .filter(|&end| end < off)
2010                .max();
2011            match inner {
2012                Some(end) => off = end,
2013                None => return off,
2014            }
2015        }
2016    }
2017
2018    /// The mirror at the opening edge: `off` moved inside the run whose
2019    /// delimiters *start* there, onto the first character of its text. See
2020    /// [`step_inside_close_delims`](Self::step_inside_close_delims).
2021    fn step_inside_open_delims(&mut self, off: usize) -> usize {
2022        let mut off = off.min(self.source.len());
2023        loop {
2024            let inner = self
2025                .editor
2026                .ancestors_at(off)
2027                .unwrap_or_default()
2028                .into_iter()
2029                .filter(|m| inline_kind(&m.kind).is_some() && m.span.start == off)
2030                .filter_map(|m| m.content_span.clone().map(|c| c.start))
2031                .filter(|&start| start > off)
2032                .min();
2033            match inner {
2034                Some(start) => off = start,
2035                None => return off,
2036            }
2037        }
2038    }
2039
2040    /// The inline mark kinds whose span covers `off`, each with that span — the
2041    /// span-carrying sibling of [`marks_at`](Self::marks_at), which reports node
2042    /// ids instead. Used to shed a mark by stepping past the end of its run.
2043    fn mark_spans_at(&mut self, off: usize) -> Vec<(InlineKind, std::ops::Range<usize>)> {
2044        let off = off.min(self.source.len());
2045        self.editor
2046            .ancestors_at(off)
2047            .unwrap_or_default()
2048            .into_iter()
2049            .filter(|m| off < m.span.end)
2050            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.span.clone())))
2051            .collect()
2052    }
2053
2054    /// Insert clipboard `text` at the caret, replacing the selection if there is
2055    /// one — always its own undo step, whatever its length.
2056    ///
2057    /// Provenance is the whole point, and only the caller has it. `insert` reads
2058    /// a lone character as a keystroke and folds it into the run around it,
2059    /// which is right for typing and wrong for a one-character paste: that paste
2060    /// would vanish mid-run on an undo it was never part of, and the characters
2061    /// the user actually typed would go with it. Length can't tell the two
2062    /// apart — `⌘V` of `x` and typing `x` are the same string — so the door the
2063    /// caller comes through is what says which happened.
2064    pub fn paste(&mut self, text: &str) {
2065        // Pasting against a block picture dissolves it exactly as typing does,
2066        // and for the same reason — see `open_paragraph_at_block_media`.
2067        self.open_paragraph_at_block_media(text);
2068        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2069        self.splice(s, e, text, EditKind::Other);
2070    }
2071
2072    /// Replace `[start, end)` with `text` as one step of an IME composition —
2073    /// the same splice as [`edit`](Self::edit), but marked so the run of steps
2074    /// folds into a single undo.
2075    ///
2076    /// A composition is *one* act of writing. Typing `かんじ` and picking 感じ is a
2077    /// dozen calls here, each replacing the last one's provisional bytes, and an
2078    /// undo step per call means undoing a word means pressing ⌘Z until the reading
2079    /// unspools backwards through kana — the intermediate states were never text
2080    /// the user wrote. Only the frontend knows a call is provisional (the bytes
2081    /// look like any other edit), so the door the caller comes through is what
2082    /// says so, exactly as it is for [`paste`](Self::paste) versus
2083    /// [`insert`](Self::insert).
2084    ///
2085    /// Pair with [`end_composition`](Self::end_composition), or the *next*
2086    /// composition folds into this one.
2087    pub fn edit_composing(&mut self, start: usize, end: usize, text: &str) {
2088        self.splice(start, end, text, EditKind::Compose);
2089    }
2090
2091    /// Close the open composition run, so the next one is its own undo step.
2092    /// Call when the IME commits or withdraws a composition.
2093    ///
2094    /// Only clears a *composition* run: a frontend that reports an end it never
2095    /// began (some IMEs unmark unprompted) would otherwise split the run of
2096    /// typing around it into two undo steps for no reason the user can see.
2097    pub fn end_composition(&mut self) {
2098        if self.last_edit_kind == Some(EditKind::Compose) {
2099            self.last_edit_kind = None;
2100        }
2101    }
2102
2103    // ── the clipboard's rich flavor ──────────────────────────────────────────
2104
2105    /// The selection rendered as HTML, for the clipboard's `text/html` flavor —
2106    /// what lets a paste into Docs/Mail/Slack keep its formatting. `None` when
2107    /// nothing is selected, or when the selection doesn't render (the caller
2108    /// still has [`selected_text`](Self::selected_text), which is what to publish
2109    /// as `text/plain` either way).
2110    ///
2111    /// **The fragment is a source substring, and that is the honest limit here.**
2112    /// It's parsed standalone, so a selection whose meaning depends on its
2113    /// surroundings converts as what it literally says rather than what it looks
2114    /// like on screen: half a list item is a paragraph, a row torn out of a table
2115    /// is the text of a row, the `**` of a bold run selected without its closing
2116    /// `**` is two asterisks. Every one of those still *renders* — there's no
2117    /// error to report — it just renders as the fragment and not as the document.
2118    /// Widening the range to whole blocks would publish text the user didn't
2119    /// select, which is a worse lie than a fragment being a fragment; the plain
2120    /// flavor has the same substring, so the two flavors at least agree.
2121    pub fn selection_html(&mut self) -> Option<String> {
2122        let (start, end) = self.selection()?;
2123        let inline = self.selection_is_inline(start, end);
2124        let html = html::render_fragment(&self.source[start..end], self.format)?;
2125        Some(match inline {
2126            true => html::strip_sole_paragraph(html),
2127            false => html,
2128        })
2129    }
2130
2131    /// Paste the clipboard's `text/html` flavor, converting it to this document's
2132    /// format first. Its own undo step, like any [`paste`](Self::paste).
2133    ///
2134    /// Returns whether it landed. `false` means the HTML didn't convert to
2135    /// anything worth pasting — the caller should fall back to the plain flavor
2136    /// rather than treat it as an error. The `html` module has the full list of
2137    /// what that covers: a table twig won't build, markup it doesn't recognise,
2138    /// an empty result.
2139    pub fn paste_html(&mut self, html: &str) -> bool {
2140        match html::parse_fragment(html, self.format) {
2141            Some(source) => {
2142                self.paste(&source);
2143                true
2144            }
2145            None => false,
2146        }
2147    }
2148
2149    /// Does the selection live *inside* a single top-level block?
2150    ///
2151    /// The question [`selection_html`](Self::selection_html) needs and the
2152    /// fragment can't answer: `**bold**` renders as `<p><strong>bold</strong></p>`
2153    /// whether the user selected one word of a sentence or a whole paragraph, and
2154    /// only the document knows which. Selecting a word and pasting into Docs
2155    /// should extend the line you paste into; selecting the paragraph should make
2156    /// a paragraph. So a selection strictly within one block is inline (its `<p>`
2157    /// is an artifact of standalone parsing), and one that covers a whole block —
2158    /// or spans two — keeps its structure.
2159    ///
2160    /// Reads the block from twig rather than guessing from the bytes:
2161    /// `ancestors_at` is `[doc, block, …inline]`, so index 1 is the top-level
2162    /// block containing an offset, and two ends inside the same one cannot have
2163    /// crossed a block boundary.
2164    fn selection_is_inline(&mut self, start: usize, end: usize) -> bool {
2165        // The last *character*, not `end - 1`: the selection's end is exclusive
2166        // and may sit mid-codepoint's-worth of bytes past the last char.
2167        let Some((off, _)) = self.source[start..end].char_indices().next_back() else {
2168            return false;
2169        };
2170        let (Some(head), Some(tail)) =
2171            (self.top_block_span(start), self.top_block_span(start + off))
2172        else {
2173            return false;
2174        };
2175        head == tail && !(start <= head.start && end >= head.end)
2176    }
2177
2178    /// The byte span of the top-level block containing `offset`, or `None` at an
2179    /// offset that belongs to no block (the blank line between two of them).
2180    fn top_block_span(&mut self, offset: usize) -> Option<std::ops::Range<usize>> {
2181        self.editor
2182            .ancestors_at(offset)
2183            .ok()?
2184            .get(1)
2185            .map(|m| m.span.clone())
2186    }
2187
2188    // ── indentation ──────────────────────────────────────────────────────────
2189
2190    /// One indent level.
2191    ///
2192    /// Two spaces, not the four both frontends type for Tab today, because in a
2193    /// markdown document four columns isn't a width — it's a *meaning*. Four
2194    /// spaces at the head of a line is markdown's indented-code-block marker, so
2195    /// one Tab on a paragraph would reparse it into code and style it as such;
2196    /// two cannot, and the line stays the prose it was. Two is also exactly
2197    /// where a `- ` bullet's content starts, so an indented line lands under its
2198    /// parent item's text instead of beside it — the column a list-aware indent
2199    /// has to hit anyway, which keeps this width from being relitigated later.
2200    const INDENT: &'static str = "  ";
2201
2202    /// Indent the selected lines — or the caret's line, with no selection — by
2203    /// one level (Tab).
2204    pub fn indent(&mut self) {
2205        self.reindent(true);
2206        // Nesting changes an ordered list's numbering (the nested item restarts,
2207        // its old siblings resume) — keep the source markers in step.
2208        self.renumber_here();
2209        // Nesting an empty `-` item under a text line reparses that text as a
2210        // setext heading; swap the dash for a `*` before it can (a no-op unless
2211        // the collapse actually happened).
2212        self.avoid_setext_collapse();
2213    }
2214
2215    /// Take one indent level back off the selected lines, or the caret's line
2216    /// (Shift+Tab). A line with no indentation is left exactly as it is.
2217    ///
2218    /// A line with *less* than a full level gives back what it has rather than
2219    /// refusing: outdent's job is to walk a line left, and real documents — hand
2220    /// written, or reflowed by some other editor — are full of indentation that
2221    /// was never a clean multiple of anything. Refusing there would strand the
2222    /// line at a depth Shift+Tab couldn't undo.
2223    pub fn outdent(&mut self) {
2224        self.reindent(false);
2225        self.renumber_here();
2226    }
2227
2228    /// The body of [`indent`](Self::indent) / [`outdent`](Self::outdent).
2229    ///
2230    /// One splice across the whole line range, never one per line: a Tab is one
2231    /// thing the user did, so it has to be one undo step and one reparse. Per
2232    /// line, twig would reparse the document once per line and leave a stack of
2233    /// steps that Shift+⌘Z walks back one line at a time.
2234    fn reindent(&mut self, add: bool) {
2235        let (sel_start, sel_end) = self.selection().unwrap_or((self.caret, self.caret));
2236        let start = source_line_range(&self.source, sel_start).start;
2237        let end = source_line_range(&self.source, sel_end).end;
2238        let region = self.source[start..end].to_string();
2239        let lines: Vec<&str> = region.split('\n').collect();
2240        // A blank line has no text to move, and padding it would leave nothing
2241        // but trailing whitespace — but Tab on a blank line *is* a request for
2242        // indentation to type into, so the skip only applies where the op has
2243        // other lines to do real work on.
2244        let skip_blank = add && lines.len() > 1;
2245
2246        let mut out = String::with_capacity(region.len() + lines.len() * Self::INDENT.len());
2247        let mut deltas: Vec<isize> = Vec::with_capacity(lines.len());
2248        let mut line_off = start;
2249        for (i, full) in lines.iter().enumerate() {
2250            if i > 0 {
2251                out.push('\n');
2252            }
2253            // A list item moves by having its whole leading prefix *replaced*,
2254            // never by having spaces pushed in front of the line. twig spells
2255            // both prefixes, so the quote markers, the parent's indent and an
2256            // ordered marker's extra column all come out right without leaf
2257            // measuring any of them — and a line that only looks like an item
2258            // (a Djot continuation) reports no marker and is left to the plain
2259            // path, where a Tab is just a Tab.
2260            let marker = self.list_marker_on_line(line_off);
2261            let own = marker
2262                .as_ref()
2263                .map(|m| m.marker_start - m.line_start)
2264                .unwrap_or(0);
2265            let delta = if add {
2266                if skip_blank && full.trim().is_empty() {
2267                    out.push_str(full);
2268                    0
2269                } else if marker.is_some() && self.first_item_of_list(line_off) {
2270                    // The first item of a list has no preceding sibling to nest
2271                    // under, so a Tab here can't spell a sub-list — twig would
2272                    // reparse the shoved-over marker as the same list, only
2273                    // indented, which Shift+Tab then can't cleanly undo. Leave the
2274                    // item where it is, the way every list editor refuses to
2275                    // over-indent a list's first line.
2276                    out.push_str(full);
2277                    0
2278                } else if marker.is_some() {
2279                    // Nesting means standing where a *continuation* of this line
2280                    // would stand: past the parent's marker, inside its content
2281                    // column. That is `continuation_prefix`, less a checkbox.
2282                    let new = self.nesting_prefix_at(line_off);
2283                    let delta = new.len() as isize - own as isize;
2284                    out.push_str(&new);
2285                    out.push_str(&full[own..]);
2286                    delta
2287                } else {
2288                    out.push_str(Self::INDENT);
2289                    out.push_str(full);
2290                    Self::INDENT.len() as isize
2291                }
2292            } else if marker.is_some() {
2293                // Unnesting is the mirror: stand where the parent item's own
2294                // line starts, which drops exactly the level it contributed.
2295                let new = self.outdent_prefix_at(line_off);
2296                let delta = new.len() as isize - own as isize;
2297                out.push_str(&new);
2298                out.push_str(&full[own..]);
2299                delta
2300            } else {
2301                // A plain line gives back the ordinary step.
2302                let strip = outdent_width(full, Self::INDENT.len());
2303                out.push_str(&full[strip..]);
2304                -(strip as isize)
2305            };
2306            deltas.push(delta);
2307            line_off += full.len() + 1;
2308        }
2309        // Nothing to give back. Returning before the splice keeps an outdent at
2310        // column zero from spending an undo step on a document it never changed.
2311        if deltas.iter().all(|d| *d == 0) {
2312            return;
2313        }
2314
2315        // Every line's text keeps its offset *within the line*, so the caret is
2316        // remapped by its column, not by its byte offset — which the prefixes on
2317        // the lines above it have already invalidated.
2318        let remap = |off: usize| -> usize {
2319            let (mut old_ls, mut new_ls) = (start, start);
2320            for (line, delta) in lines.iter().zip(&deltas) {
2321                let old_le = old_ls + line.len();
2322                let new_len = (line.len() as isize + delta) as usize;
2323                if off <= old_le {
2324                    let col = (off - old_ls) as isize;
2325                    return new_ls + ((col + delta).max(0) as usize).min(new_len);
2326                }
2327                old_ls = old_le + 1;
2328                new_ls += new_len + 1;
2329            }
2330            start + out.len()
2331        };
2332        let placed = match self.selection() {
2333            // Keep the rewritten region selected, the way a container toggle
2334            // keeps its own: it leaves a second Tab aimed at the same lines
2335            // rather than at whatever the shifted offsets now happen to cover.
2336            Some(_) => (start + out.len(), Some(start)),
2337            None => (remap(self.caret), None),
2338        };
2339
2340        // A rolled-back splice leaves the old source in place, where every offset
2341        // computed above addresses text that was never written.
2342        if !self.splice(start, end, &out, EditKind::Other) {
2343            return;
2344        }
2345        // `splice` re-anchors to the end of the `Change`, which for a whole-region
2346        // rewrite is the last line's end — nowhere the caret was. Place it, then
2347        // re-record the caret so this is the state redo restores, not the one
2348        // `splice` left behind from the `Change`.
2349        self.caret = placed.0.min(self.source.len());
2350        self.anchor = placed.1;
2351        self.clamp_caret();
2352        self.record_caret();
2353    }
2354
2355    /// The Enter key.
2356    ///
2357    /// In source view it's a literal newline. In WYSIWYG it's **AST-aware**: a
2358    /// bare `\n` is only a markdown soft break (same paragraph), so the block the
2359    /// caret is in decides what actually gets written.
2360    ///
2361    ///   - paragraph            → twig's [`Editor::split_block`], which parts the
2362    ///                            block at the caret and reopens its container
2363    ///   - list item            → likewise: the next item, its indent, quote
2364    ///                            prefix and `[ ]` box all reproduced by twig —
2365    ///                            except an *empty* item, which exits the list
2366    ///   - block quote          → likewise: a new paragraph inside the quote
2367    ///   - heading              → a new *paragraph*, not another heading
2368    ///   - code block           → a literal newline (stay in the block)
2369    ///   - blank line           → a literal newline (one Backspace undoes it)
2370    ///   - [`LineFlow::Preserve`] → a single soft break, which renders as a
2371    ///                            visible line
2372    ///
2373    /// Where `split_block` is used it replaces markup leaf used to spell by hand,
2374    /// and it is better at it: it drops the whitespace the caret was sitting in
2375    /// front of instead of stranding it at the head of the second half, and it
2376    /// knows continuations leaf's marker scan never covered — a checklist item
2377    /// continues as an *unchecked* checklist item rather than a plain bullet.
2378    ///
2379    /// The exceptions above are exceptions because `split_block` is either wrong
2380    /// there or refuses: parting a fence yields two fences with the code split
2381    /// between them, parting a heading yields a second heading where every editor
2382    /// gives a paragraph, and a blank line, an empty item, a setext heading and a
2383    /// table all report an error rather than a split.
2384    pub fn newline(&mut self) {
2385        if self.view == View::Source {
2386            self.insert_raw("\n");
2387            return;
2388        }
2389        // Enter over a selection replaces it with a paragraph break.
2390        if let Some((s, e)) = self.selection() {
2391            self.splice(s, e, "\n\n", EditKind::Other);
2392            return;
2393        }
2394        // A caret resting exactly between an inline mark's content and its own
2395        // closing delimiter (`**bold**` with nothing after it on the line —
2396        // the WYSIWYG caret's natural end-of-line position) must not splice a
2397        // block break there: every path below eventually does via
2398        // `insert_raw`/`self.caret`, and splicing before the hidden closing
2399        // delimiter would strand it alone on the new line.
2400        self.caret = self.skip_trailing_close_delims(self.caret);
2401        // The block the caret is in. `block_offset_for_caret` nudges off a line
2402        // end (where the caret sits at the doc level); on a bare line (e.g. an
2403        // empty list item) fall back to the caret so the enclosing list/quote is
2404        // still visible in the ancestors.
2405        let off = self.block_offset_for_caret().unwrap_or(self.caret);
2406        let kinds: Vec<Kind> = self
2407            .editor
2408            .ancestors_at(off)
2409            .map(|c| c.into_iter().map(|m| m.kind).collect())
2410            .unwrap_or_default();
2411        let has = |k: Kind| kinds.contains(&k);
2412
2413        if has(Kind::CodeBlock) {
2414            self.insert_raw("\n");
2415            return;
2416        }
2417        // An *empty* list item exits the list — the standard double-Enter — which
2418        // `split_block` reports as an error rather than a split (there is no
2419        // content to part), so it stays leaf's. `list_marker_on_line` is itself
2420        // the AST gate — it answers from the tree, so a `- ` that reads as a
2421        // marker byte-for-byte but opens no item (a setext underline, a Djot
2422        // continuation line) never reaches here.
2423        if let Some(marker) = self.list_marker_on_line(self.caret)
2424            && self.item_is_empty(&marker)
2425        {
2426            self.exit_list(&marker);
2427            return;
2428        }
2429        // On an *empty* paragraph line, a lone Enter should add a single blank line,
2430        // not another full paragraph break — so it moves down one line and one
2431        // Backspace undoes it, not two. (`split_block` errors here too.)
2432        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
2433        let line_end = self.source[self.caret..]
2434            .find('\n')
2435            .map_or(self.source.len(), |i| self.caret + i);
2436        if self.source[line_start..line_end].trim().is_empty() {
2437            self.insert_raw("\n");
2438            return;
2439        }
2440        // In `Preserve` flow a soft break is a *visible* line the author means to
2441        // make, so Enter writes a single `\n` and typing continues the same
2442        // paragraph on the next line — the behaviour of an ordinary text editor.
2443        // A second Enter then lands on the blank line above and takes the
2444        // empty-line branch, so double-Enter still promotes to a full paragraph
2445        // break; and Backspace, which deletes a lone `\n` over a soft break,
2446        // undoes a single Enter symmetrically. In `Fold` flow a lone `\n` would
2447        // render as an invisible space, so Enter keeps making the paragraph break
2448        // that actually shows.
2449        //
2450        // Only in running prose. A list or a quote has a continuation of its own
2451        // to write, and a `\n` there is not a soft line but a lost container.
2452        let in_container = has(Kind::ListItem) || has(Kind::TaskListItem) || has(Kind::BlockQuote);
2453        if self.line_flow == LineFlow::Preserve && !in_container {
2454            self.insert_raw("\n");
2455            return;
2456        }
2457        // A heading gets a *paragraph*, never a second heading: Enter at the end
2458        // of a title is how every editor is asked for the body under it, and
2459        // `split_block` would repeat the `#` instead. Whitespace at the split
2460        // point goes with the break rather than opening the new paragraph, which
2461        // is what `split_block` does everywhere else.
2462        if has(Kind::Heading) {
2463            let mut end = self.caret;
2464            while self.source.as_bytes().get(end) == Some(&b' ') {
2465                end += 1;
2466            }
2467            self.splice(self.caret, end, "\n\n", EditKind::Other);
2468            return;
2469        }
2470        self.split_block_here();
2471    }
2472
2473    /// Part the block at the caret with twig's [`Editor::split_block`], leaving
2474    /// the caret in the second half.
2475    ///
2476    /// twig reopens whatever the first half was inside of — the bullet with its
2477    /// indent, the quote's `>`, a checklist item's `[ ]` — which is the whole
2478    /// reason this replaced the markup leaf used to spell from the line's bytes.
2479    /// It renumbers nothing, though: a new item mid-list is written with its
2480    /// neighbour's number, so [`renumber_here`](Self::renumber_here) still runs
2481    /// behind it, folded into the same undo step.
2482    ///
2483    /// Falls back to a plain paragraph break if twig declines, so an unhandled
2484    /// shape still moves the caret down rather than swallowing the keystroke.
2485    fn split_block_here(&mut self) {
2486        // The read-only gate — this door reaches twig without the splice.
2487        if self.read_only {
2488            return;
2489        }
2490        match self.editor.split_block(self.caret) {
2491            Ok(change) => {
2492                self.last_edit_kind = None;
2493                self.refresh();
2494                self.anchor = None;
2495                self.caret = change.new.end;
2496                self.dirty = self.source != self.clean_source;
2497                self.status = None;
2498                self.clamp_caret();
2499                self.record_caret();
2500                // Aimed at the new block's *start*: the caret twig leaves is one
2501                // past the marker it wrote, where there is no list in reach.
2502                self.renumber_at(change.new.start);
2503            }
2504            Err(_) => self.insert_raw("\n\n"),
2505        }
2506    }
2507
2508    /// Whether the item on the marker's line carries no content — the shape
2509    /// double-Enter reads as "I'm done with this list."
2510    fn item_is_empty(&self, line: &ListMarker) -> bool {
2511        let content_start = line.content_start().min(self.source.len());
2512        let line_end = self.source[self.caret..]
2513            .find('\n')
2514            .map(|i| self.caret + i)
2515            .unwrap_or(self.source.len());
2516        self.source[content_start..line_end.max(content_start)]
2517            .trim()
2518            .is_empty()
2519    }
2520
2521    /// Leave the list: replace the empty item's marker with a blank line, so the
2522    /// caret lands in a fresh paragraph below it.
2523    ///
2524    /// Inside a quote the blank line has to stay quoted (a bare one would end the
2525    /// quote), and the caret's new line keeps the `> ` it was already behind —
2526    /// leaving the list without also leaving the quote.
2527    fn exit_list(&mut self, line: &ListMarker) {
2528        let prefix = self.quote_prefix_at(line.marker_start);
2529        let blank = prefix.trim_end();
2530        self.splice(
2531            line.line_start,
2532            self.caret,
2533            &format!("{blank}\n{prefix}"),
2534            EditKind::Other,
2535        );
2536    }
2537
2538    /// What a line continuing the containers at `off` has to open with — the
2539    /// quote markers reproduced, each enclosing item's marker as its width in
2540    /// spaces. Also the column a nested item's marker stands in, which is what
2541    /// makes it Tab's answer.
2542    fn continuation_prefix_at(&mut self, off: usize) -> String {
2543        self.editor
2544            .document()
2545            .and_then(|mut d| d.continuation_prefix(off))
2546            .map(|p| p.text)
2547            .unwrap_or_default()
2548    }
2549
2550    /// The column a *nested list* may open at inside the item at `off` — which
2551    /// is not always where the item's own text continues.
2552    ///
2553    /// twig counts a task item's `[ ] ` box as part of its marker, correctly:
2554    /// it is markup a rich view hides, and the item's own wrapped text does
2555    /// stand past it. But a nested list may only open at the *list* marker's
2556    /// column, and four columns further in is an indented continuation of the
2557    /// paragraph instead — `- [ ] a` + `      - [ ] b` is one item, not two.
2558    /// So the box's own width goes back.
2559    ///
2560    /// The one place leaf still reads a checkbox's spelling. It goes when twig
2561    /// reports the list marker's column apart from the box; `checked` is what
2562    /// says a box is there at all, so only its width is being measured here.
2563    fn nesting_prefix_at(&mut self, off: usize) -> String {
2564        let cont = self.continuation_prefix_at(off);
2565        let Some(item) = self.innermost_list_item(off) else {
2566            return cont;
2567        };
2568        if item.checked.is_none() {
2569            return cont;
2570        }
2571        let box_width = item
2572            .marker_span
2573            .and_then(|m| self.source.get(m))
2574            .and_then(|marker| marker.rfind('[').map(|i| marker.len() - i))
2575            .unwrap_or(0);
2576        // The trailing columns are the ones the item's own marker contributed,
2577        // so trimming from the end leaves any quote prefix standing.
2578        cont[..cont.len().saturating_sub(box_width)].to_string()
2579    }
2580
2581    /// Where the line of the item *containing* the item at `off` begins — the
2582    /// prefix Shift+Tab moves back to, which gives up exactly the level the
2583    /// parent contributed. The quote prefix alone for a top-level item, which
2584    /// has no level left to give.
2585    fn outdent_prefix_at(&mut self, off: usize) -> String {
2586        let items: Vec<usize> = self
2587            .editor
2588            .document()
2589            .and_then(|mut d| d.ancestors_at_caret(off))
2590            .map(|c| {
2591                c.into_iter()
2592                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2593                    .map(|m| m.span.start)
2594                    .collect()
2595            })
2596            .unwrap_or_default();
2597        // The second-innermost item is the parent; its own line's indent is the
2598        // target. `list_marker_on_line` gives that line's prefix directly.
2599        let parent = items.len().checked_sub(2).map(|i| items[i]);
2600        match parent.and_then(|p| self.list_marker_on_line(p)) {
2601            Some(m) => self.source[m.line_start..m.marker_start].to_string(),
2602            None => self.quote_prefix_at(off),
2603        }
2604    }
2605
2606    /// The block-quote prefix in force at `off` — `""` outside a quote, `"> "`
2607    /// inside one, `"> > "` inside two.
2608    ///
2609    /// Assembled from each enclosing quote's own [`FlatNode::marker_span`], so
2610    /// the `>` and the space after it are twig's spelling rather than leaf's.
2611    /// The whole line prefix can't answer this: it also carries the indent of
2612    /// whatever the quote holds, which a blank separator line must *not* repeat.
2613    fn quote_prefix_at(&mut self, off: usize) -> String {
2614        let Ok(chain) = self
2615            .editor
2616            .document()
2617            .and_then(|mut d| d.ancestors_at_caret(off))
2618        else {
2619            return String::new();
2620        };
2621        let quotes: Vec<usize> = chain
2622            .iter()
2623            .filter(|m| m.kind == Kind::BlockQuote)
2624            .map(|m| m.node_id as usize)
2625            .collect();
2626        let Ok(nodes) = self.editor.nodes() else {
2627            return String::new();
2628        };
2629        quotes
2630            .iter()
2631            .filter_map(|id| nodes.get(*id)?.marker_span.clone())
2632            .filter_map(|s| self.source.get(s))
2633            .collect()
2634    }
2635
2636    /// Whether the item at `off` sits inside another one — the test Backspace
2637    /// uses to choose between outdenting and dropping the marker.
2638    ///
2639    /// Counted from the AST rather than from the line's leading whitespace,
2640    /// which is indentation in Markdown and, in Djot, may be nothing at all.
2641    fn item_is_nested(&mut self, off: usize) -> bool {
2642        self.editor
2643            .document()
2644            .and_then(|mut d| d.ancestors_at_caret(off))
2645            .map(|c| {
2646                c.into_iter()
2647                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2648                    .count()
2649                    > 1
2650            })
2651            .unwrap_or(false)
2652    }
2653
2654    /// The innermost list item containing `probe`, under twig's **caret**
2655    /// containment rule — a block's end is inside it.
2656    ///
2657    /// Half-open containment can't answer this. An empty item's span is exactly
2658    /// its marker, so the caret sitting after `- ` is one past the end and the
2659    /// item it is plainly in tests as out of reach; that is the shape
2660    /// double-Enter has to recognise to leave the list.
2661    fn innermost_list_item(&mut self, probe: usize) -> Option<FlatNode> {
2662        let chain = self
2663            .editor
2664            .document()
2665            .and_then(|mut d| d.ancestors_at_caret(probe))
2666            .ok()?;
2667        let id = chain
2668            .iter()
2669            .rev()
2670            .find(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)?
2671            .node_id as usize;
2672        self.editor.nodes().ok()?.get(id).cloned()
2673    }
2674
2675    /// The list marker opening `off`'s line, per twig — `None` when that line
2676    /// opens no list item.
2677    ///
2678    /// [`Document::line_prefix`] is the whole hidden run from the line start:
2679    /// `>   1. ` is a quote's marker, an indent, and an item's marker together,
2680    /// and it is `None` on a *continuation* line, which opens nothing. That last
2681    /// case is the one leaf could never get right by reading bytes. `- a\n  - b`
2682    /// is two items in Markdown and one in Djot, where a marker cannot interrupt
2683    /// a paragraph and `  - b` is literal text — identical bytes, and only the
2684    /// parser knows which document it is looking at.
2685    ///
2686    /// The item's own marker is separated out via its
2687    /// [`FlatNode::marker_span`], so `marker_start` splits the prefix into what
2688    /// the containers around it contribute and what the item does.
2689    fn list_marker_on_line(&mut self, off: usize) -> Option<ListMarker> {
2690        let off = off.min(self.source.len());
2691        let prefix = self.editor.document().ok()?.line_prefix(off).ok()??;
2692        // The prefix belongs to a list only when an item's marker closes it —
2693        // a heading's `# ` or a bare quote's `> ` is a prefix too.
2694        let item = self.innermost_list_item(prefix.end.min(self.source.len()))?;
2695        let marker = item.marker_span.clone()?;
2696        if marker.end != prefix.end {
2697            return None;
2698        }
2699        Some(ListMarker {
2700            line_start: prefix.start,
2701            marker_start: marker.start,
2702            text: self.source.get(prefix)?.to_string(),
2703        })
2704    }
2705
2706    /// Whether the list item on `line_start`'s line is the **first item** of its
2707    /// list — the one Tab must not nest, because nesting needs a preceding
2708    /// sibling to become the new parent and a first item has none. `false` for a
2709    /// line that isn't a list item, and for an item with a sibling above it (the
2710    /// one Tab *can* nest). Gated on the AST, not the marker bytes: `- ` reads
2711    /// the same in a setext underline that opens no list at all.
2712    fn first_item_of_list(&mut self, line_start: usize) -> bool {
2713        let Some(marker) = self.list_marker_on_line(line_start) else {
2714            return false;
2715        };
2716        // Probe just inside the marker, where the item's own node is in reach —
2717        // the marker offset itself can resolve to the enclosing list, not the
2718        // `list_item`, whose span starts at the marker.
2719        let probe = marker.content_start().min(self.source.len());
2720        let Some(item) = self.innermost_list_item(probe) else {
2721            return false;
2722        };
2723        let Ok(nodes) = self.editor.nodes() else {
2724            return false;
2725        };
2726        match item.parent {
2727            // First when the parent list opens with this very item.
2728            Some(pid) => nodes
2729                .get(pid.0 as usize)
2730                .is_some_and(|p| p.first_child == Some(item.id)),
2731            // A parentless item is trivially the first (and only) one.
2732            None => true,
2733        }
2734    }
2735
2736    pub fn backspace(&mut self) {
2737        if let Some((s, e)) = self.selection() {
2738            self.splice(s, e, "", EditKind::Other);
2739            return;
2740        }
2741        // WYSIWYG: Backspace at the very start of a list item's content is a
2742        // structural key, not a character delete — it walks the "un-indent, then
2743        // un-list" ladder every list editor gives that keystroke (outdent a
2744        // nested item, strip a top-level one's marker to a paragraph). In source
2745        // view the `- ` is visible text the user is deleting a byte of, so it
2746        // keeps its literal meaning there, like Enter does.
2747        if self.view != View::Source && self.backspace_list_start() {
2748            return;
2749        }
2750        // WYSIWYG: and the same at the start of a heading's content — the `# `
2751        // there is markup the rich view hides, not text the user typed.
2752        if self.view != View::Source && self.backspace_heading_start() {
2753            return;
2754        }
2755        // WYSIWYG: at a block picture's stops, a byte-at-a-time delete would take
2756        // the markup apart under a caret that cannot see it — see
2757        // `delete_around_block_media`.
2758        if self.view != View::Source && self.delete_around_block_media(false) {
2759            return;
2760        }
2761        // WYSIWYG: Backspace on a *blank line* deletes back to the previous caret
2762        // stop, not a single newline. On a line with no text of its own, the byte
2763        // before the caret is a `\n` that spells part of a block boundary — the gap
2764        // between two blocks, drawn but never a caret home. Removing just it strands
2765        // the caret in that gap and leaves an odd blank line the eye reads as one
2766        // separator but the caret can't land on: the "extra newline" left behind
2767        // after leaving a list (Enter, Enter) or a paragraph and pressing Backspace.
2768        // Deleting to the previous stop instead collapses the whole break at once,
2769        // landing the caret at the end of the block above. Two blank lines in a row
2770        // are one stop apart, so this still removes exactly one — the lone-Enter /
2771        // lone-Backspace symmetry the empty-line case is built on is untouched.
2772        if self.view != View::Source
2773            && self.caret > self.caret_floor()
2774            && self.caret_on_blank_line()
2775            && let Some(stop) = self.vmap.stop_before(self.caret)
2776        {
2777            let stop = stop.max(self.caret_floor());
2778            if stop < self.caret {
2779                self.splice(stop, self.caret, "", EditKind::Delete);
2780                return;
2781            }
2782        }
2783        if self.caret > self.caret_floor() {
2784            // An in-cell `<br>` draws as one newline glyph, so Backspace over it
2785            // takes the whole tag — a single-byte step would leave a broken `<br`
2786            // showing in the cell. Rich view only (source view edits the literal).
2787            if self.view != View::Source
2788                && let Some((start, end)) = self.cell_break_at(BreakEdge::Backward)
2789            {
2790                let start = start.max(self.caret_floor());
2791                if start < end {
2792                    self.splice(start, end, "", EditKind::Delete);
2793                    return;
2794                }
2795            }
2796            // Aim the delete at the character the writer can *see* behind the
2797            // caret, never at a delimiter the rich view drew nothing for. Two
2798            // steps, and either can apply: from the far side of a run's closing
2799            // `**` step back into the run (the caret is drawn at the end of its
2800            // word), and at the start of a run's text step out past its opening
2801            // `**` to the character in front of it, leaving the run standing.
2802            // Without them a plain Backspace unspells the phrase it is editing
2803            // and leaves a literal asterisk on screen.
2804            let end = if self.view == View::Source {
2805                self.caret
2806            } else {
2807                let inside = self.step_inside_close_delims(self.caret);
2808                self.skip_leading_open_delims(inside)
2809                    .max(self.caret_floor())
2810            };
2811            // Never delete back across the floor — that would eat hidden
2812            // frontmatter the WYSIWYG caret can't even see.
2813            let mut prev = prev_boundary(&self.source, end).max(self.caret_floor());
2814            // Take a hidden escape backslash with the char it escapes: the rich
2815            // view draws `\*` as a single `*`, so Backspace over it must delete
2816            // both bytes, never strand the `\` as a lone visible backslash (the
2817            // mirror of the Hidden-mode typing that wrote the escape). Source view
2818            // shows the `\`, so there it is an ordinary character.
2819            if self.view != View::Source
2820                && prev > self.caret_floor()
2821                && self.is_hidden_escape(prev - 1)
2822            {
2823                prev -= 1;
2824            }
2825            if prev < end {
2826                self.splice(prev, end, "", EditKind::Delete);
2827            }
2828        }
2829    }
2830
2831    /// Whether the caret's own source line holds nothing but whitespace — an
2832    /// empty paragraph, or the blank line a block boundary is spelled with. The
2833    /// test for [`backspace`](Self::backspace)'s stop-wise delete: such a line has
2834    /// no text of its own, so the newline before the caret belongs to the gap
2835    /// between blocks rather than to any word the caret is editing.
2836    fn caret_on_blank_line(&self) -> bool {
2837        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
2838        let line_end = self.source[self.caret..]
2839            .find('\n')
2840            .map_or(self.source.len(), |i| self.caret + i);
2841        self.source[line_start..line_end].trim().is_empty()
2842    }
2843
2844    /// The source span of an in-cell hard break (`<br>`) touching the caret on the
2845    /// `edge` side — the byte range to delete whole. A table row is one source
2846    /// line, so its break is spelled `<br>` yet drawn as a single newline glyph
2847    /// (see `wysiwyg.rs`); a delete over it must take every byte, or a one-byte
2848    /// step strands a broken `<br` in the cell. `Backward` matches a break ending
2849    /// at the caret (Backspace), `Forward` one starting at it (Delete). `None`
2850    /// when no such break is adjacent. Only the in-cell break is spelled `<br>`
2851    /// (an ordinary hard break is `  \n`), so the leading `<` alone tells them
2852    /// apart — no ancestor walk needed. Rich view only; source view shows the
2853    /// literal tag and deletes it a byte at a time.
2854    fn cell_break_at(&mut self, edge: BreakEdge) -> Option<(usize, usize)> {
2855        let caret = self.caret;
2856        let nodes = self.nodes();
2857        let src = self.source.as_bytes();
2858        nodes
2859            .iter()
2860            .find(|n| {
2861                n.kind == Kind::HardBreak
2862                    && n.span.start < n.span.end
2863                    && src.get(n.span.start) == Some(&b'<')
2864                    && match edge {
2865                        BreakEdge::Backward => n.span.end == caret,
2866                        BreakEdge::Forward => n.span.start == caret,
2867                    }
2868            })
2869            .map(|n| (n.span.start, n.span.end))
2870    }
2871
2872    /// Whether the source byte at `off` is a backslash twig consumed as an escape
2873    /// (hidden in the rich view), as against a literal backslash (drawn). A
2874    /// backslash escapes exactly an ASCII-punctuation character (the CommonMark /
2875    /// Djot rule twig follows), so `\` + punctuation is the whole test — no AST
2876    /// round-trip needed.
2877    fn is_hidden_escape(&self, off: usize) -> bool {
2878        let b = self.source.as_bytes();
2879        b.get(off) == Some(&b'\\') && b.get(off + 1).is_some_and(u8::is_ascii_punctuation)
2880    }
2881
2882    /// Backspace's list behaviour: when the caret sits exactly at the start of a
2883    /// list item's content (right after its marker), outdent the item if it's
2884    /// nested, else strip the marker so it becomes a paragraph. Returns whether
2885    /// it acted — `false` leaves Backspace its ordinary character delete.
2886    fn backspace_list_start(&mut self) -> bool {
2887        let Some(marker) = self.list_marker_on_line(self.caret) else {
2888            return false;
2889        };
2890        // Only right after the marker. That the line opens a real item is
2891        // already settled: `list_marker_on_line` answers from the tree.
2892        if self.caret != marker.content_start() {
2893            return false;
2894        }
2895        if self.item_is_nested(marker.marker_start) {
2896            // Nested: give back one level, keeping the marker and carrying the
2897            // caret with it.
2898            self.outdent();
2899        } else {
2900            // Top level: drop the marker, leaving a paragraph, then renumber the
2901            // siblings the removed item was counted among. Only the marker goes —
2902            // a quote prefix in front of it still has a quote to hold up.
2903            self.splice(marker.marker_start, self.caret, "", EditKind::Other);
2904            self.renumber_here();
2905        }
2906        true
2907    }
2908
2909    /// Backspace's heading behaviour: with the caret exactly at the start of an
2910    /// ATX heading's content — right after the `#` marker the rich view hides —
2911    /// strip the marker so the line becomes a paragraph. The peer of
2912    /// [`backspace_list_start`](Self::backspace_list_start)'s ladder, and the same
2913    /// reasoning: hidden block markup is structure, so the keystroke over it is
2914    /// structural.
2915    ///
2916    /// Without this the ordinary delete takes the space out of `# Title` and
2917    /// leaves `#Title`, which is no longer a heading at all — the hash the view
2918    /// had been hiding surfaces as literal text the user has to delete a second
2919    /// time, having never typed it. A closing sequence (`# Title #`, hidden at the
2920    /// other end) goes with the marker for the same reason.
2921    ///
2922    /// Returns whether it acted; `false` leaves Backspace its character delete.
2923    fn backspace_heading_start(&mut self) -> bool {
2924        let caret = self.caret;
2925        // The heading whose content opens exactly at the caret. A bare `#` has no
2926        // content span at all — its content starts (and ends) where the line does.
2927        let Some((span, content_end, marker)) = self.nodes().iter().find_map(|n| {
2928            let (start, end) = match &n.content_span {
2929                Some(c) => (c.start, c.end),
2930                None => (n.span.end, n.span.end),
2931            };
2932            (n.kind == Kind::Heading && start == caret)
2933                .then(|| (n.span.clone(), end, n.marker_span.clone()))
2934        }) else {
2935            return false;
2936        };
2937        // twig reports the marker's own extent, so there is nothing to walk back
2938        // over and no `#` in this file. A setext heading has no marker — its
2939        // content opens the line — so it falls through to the ordinary delete,
2940        // as does anything else sitting at a content start.
2941        // `m.end == caret` is what excludes a setext heading, whose marker is the
2942        // underline *after* the content rather than a prefix before it.
2943        let Some(marker) = marker.filter(|m| m.end == caret) else {
2944            return false;
2945        };
2946        let start = marker.start;
2947        // A closing `#` sequence is hidden too, so it can't be left behind. Only
2948        // when the tail really is one: trailing spaces alone are nothing to strip.
2949        let tail = &self.source[content_end..span.end];
2950        if tail.contains('#') && tail.chars().all(|c| c == '#' || c.is_whitespace()) {
2951            let kept = self.source[caret..content_end].to_string();
2952            self.splice(start, span.end, &kept, EditKind::Other);
2953            // The splice leaves the caret past the text it re-wrote; the caret
2954            // belongs where the content now starts, which is where it already was.
2955            self.caret = start;
2956            self.record_caret();
2957        } else {
2958            self.splice(start, caret, "", EditKind::Other);
2959        }
2960        true
2961    }
2962
2963    pub fn delete_forward(&mut self) {
2964        if let Some((s, e)) = self.selection() {
2965            self.splice(s, e, "", EditKind::Other);
2966        } else if self.caret < self.source.len() {
2967            // The mirror of Backspace's: forward-delete in front of a picture
2968            // would eat the `!` off its markup and leave a link where a photo was.
2969            if self.view != View::Source && self.delete_around_block_media(true) {
2970                return;
2971            }
2972            // Delete forward over an in-cell `<br>` takes the whole tag, the mirror
2973            // of Backspace's swallow (see `cell_break_at`) — else a byte-step
2974            // strands a broken `<br` in the cell.
2975            if self.view != View::Source
2976                && let Some((start, end)) = self.cell_break_at(BreakEdge::Forward)
2977            {
2978                self.splice(start, end, "", EditKind::Delete);
2979                return;
2980            }
2981            // The mirror of Backspace's two steps: from in front of a run's
2982            // opening `**` step into it, onto the first letter of its text, and
2983            // at the end of a run's text step out past its closing `**` to the
2984            // character beyond. Either way Delete takes the character it looks
2985            // like it is pointing at, and never a delimiter drawn as nothing.
2986            // The caret then settles back inside the run it was standing in —
2987            // see `settle_inside_close_delims`.
2988            let from = if self.view == View::Source {
2989                self.caret
2990            } else {
2991                let inside = self.step_inside_open_delims(self.caret);
2992                self.skip_trailing_close_delims(inside)
2993            };
2994            let next = next_boundary(&self.source, from);
2995            if from < next {
2996                self.splice(from, next, "", EditKind::Delete);
2997            }
2998        }
2999    }
3000
3001    /// Delete from the caret back to the start of the previous word (⌥⌫ /
3002    /// Ctrl+⌫). Deletes the selection instead when one is active.
3003    pub fn delete_word_back(&mut self) {
3004        if let Some((s, e)) = self.selection() {
3005            self.splice(s, e, "", EditKind::Other);
3006        } else {
3007            // A word back from just past a picture is a word *of its markup*, and
3008            // a word back from in front of one runs through the paragraph break
3009            // into the prose above — dissolving the picture either way. See
3010            // `delete_around_block_media`.
3011            if self.view != View::Source && self.delete_around_block_media(false) {
3012                return;
3013            }
3014            let start = self.word_left_from(self.caret).max(self.caret_floor());
3015            if start < self.caret {
3016                let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3017                self.splice(s, e, "", EditKind::Delete);
3018            }
3019        }
3020    }
3021
3022    /// Delete from the caret forward to the end of the next word (⌥⌦ /
3023    /// Ctrl+Del). Deletes the selection instead when one is active.
3024    pub fn delete_word_forward(&mut self) {
3025        if let Some((s, e)) = self.selection() {
3026            self.splice(s, e, "", EditKind::Other);
3027        } else {
3028            // The mirror: a word forward from in front of a picture is its markup.
3029            if self.view != View::Source && self.delete_around_block_media(true) {
3030                return;
3031            }
3032            let end = self.word_right_from(self.caret);
3033            if end > self.caret {
3034                let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3035                self.splice(s, e, "", EditKind::Delete);
3036            }
3037        }
3038    }
3039
3040    /// Delete from the caret back to the start of its line (⌘⌫). Deletes the
3041    /// selection instead when one is active, as every other delete here does.
3042    ///
3043    /// The line is the view's own — the one Home and End work on, so in WYSIWYG
3044    /// a soft-wrapped row is a line. It is not Home's *target*, though: Home
3045    /// stops at the first character and this takes the indentation with it, the
3046    /// way Cocoa's `deleteToBeginningOfLine:` does. Stopping at the text would
3047    /// leave an indent behind that nothing can then ask to delete, where a caret
3048    /// left at column 0 is one press of Home away from either.
3049    pub fn delete_to_line_start(&mut self) {
3050        if let Some((s, e)) = self.selection() {
3051            self.splice(s, e, "", EditKind::Other);
3052            return;
3053        }
3054        // Never back across the floor: hidden frontmatter isn't on this line, or
3055        // on any line the WYSIWYG caret can see.
3056        let (start, _) = self.line_span();
3057        let start = start.max(self.caret_floor());
3058        if start < self.caret {
3059            let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3060            self.splice(s, e, "", EditKind::Delete);
3061        }
3062    }
3063
3064    /// Kill from the caret to the end of its line (^K). Deletes the selection
3065    /// instead when one is active.
3066    ///
3067    /// At the end of the line it does nothing, rather than pulling the line
3068    /// below up into this one. Joining has no meaning to give it in both views
3069    /// at once: a WYSIWYG line ends at a soft wrap as often as at a newline, and
3070    /// there is nothing there to delete, while the newline a *source* line ends
3071    /// with is only half of the blank line that separates two paragraphs —
3072    /// deleting one leaves a soft break, which is not the join it looks like.
3073    /// The views agreeing is worth more than emacs' second press, and Delete is
3074    /// already the key that joins.
3075    pub fn delete_to_line_end(&mut self) {
3076        if let Some((s, e)) = self.selection() {
3077            self.splice(s, e, "", EditKind::Other);
3078            return;
3079        }
3080        let (_, end) = self.line_span();
3081        if end > self.caret {
3082            let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3083            self.splice(s, e, "", EditKind::Delete);
3084        }
3085    }
3086
3087    /// Grow a WYSIWYG word-delete to swallow any inline node it empties.
3088    ///
3089    /// A glyph-space range covers what the user can see, which for `**bold**` is
3090    /// the word and never the delimiters around it — so deleting the word on its
3091    /// own leaves `a **** c`, markup wrapped around nothing. They asked for the
3092    /// word, and the styling was the word's; the two go together. Only the
3093    /// node's delimiters are taken, and those are hidden here anyway, so nothing
3094    /// visible outside the range is lost.
3095    ///
3096    /// Repeated to a fixed point: emptying `***bold***` empties the emph inside
3097    /// the strong, and only then is the strong empty too.
3098    fn widen_over_emptied_inlines(&mut self, start: usize, end: usize) -> (usize, usize) {
3099        if self.view == View::Source {
3100            return (start, end);
3101        }
3102        let nodes = self.nodes();
3103        let (mut s, mut e) = (start, end);
3104        loop {
3105            let mut grew = false;
3106            for n in nodes.iter().filter(|n| wysiwyg::is_inline(n)) {
3107                let Some(text) = inline_content_span(n, &self.source) else {
3108                    continue;
3109                };
3110                // Some of its text survives, so the node still has a job.
3111                if text.start < s || text.end > e {
3112                    continue;
3113                }
3114                if n.span.start < s || n.span.end > e {
3115                    s = s.min(n.span.start);
3116                    e = e.max(n.span.end);
3117                    grew = true;
3118                }
3119            }
3120            if !grew {
3121                return (s, e);
3122            }
3123        }
3124    }
3125
3126    /// One splice of document text, keeping the **mark-edge rule**: an inline
3127    /// mark's content never begins or ends with whitespace. In Markdown and Djot
3128    /// a delimiter standing against a space is not a delimiter at all — `**bold **`
3129    /// is four literal asterisks around a word, and a rich view drawing the
3130    /// document faithfully has no choice but to show them. That is correct
3131    /// rendering of what the file says, and nobody typing a space after a bold
3132    /// word meant to say it.
3133    ///
3134    /// So the space goes *outside* the run instead — `**bold** ` — which is the
3135    /// same document to a reader and a live one to a parser. The caret follows it
3136    /// out and keeps the marks armed (see [`rearm`](Self::rearm)), so the next
3137    /// character rejoins the run (see [`rejoin_run`](Self::rejoin_run)) and the
3138    /// writer sees one unbroken bold phrase, never a flash of raw syntax.
3139    ///
3140    /// Every ordinary edit — typing, deleting, pasting, an IME step — comes
3141    /// through here, so the rule holds however the whitespace arrives at the
3142    /// edge. The repair is decided *after* the plain edit, by asking whether the
3143    /// mark actually died: a code span's backticks aren't whitespace-sensitive
3144    /// (`` `code ` `` is still code), and nothing is re-spelled when nothing broke.
3145    fn splice(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3146        let fix = self.mark_edge_fix(start, end, text);
3147        if !self.splice_exact(start, end, text, kind) {
3148            return false;
3149        }
3150        if let Some(fix) = fix {
3151            self.repair_mark_edges(fix);
3152        }
3153        if text.is_empty() && end > start {
3154            self.settle_inside_close_delims();
3155        }
3156        true
3157    }
3158
3159    /// After a delete, take a caret left standing past a run's closing delimiters
3160    /// back inside the run.
3161    ///
3162    /// A delete leaves the caret where the deleted bytes began, and when those
3163    /// bytes were the last thing after a marked phrase — the space the mark-edge
3164    /// rule pushed out of `**bold** `, say — that spot is the far side of the
3165    /// closing `**`. The rich view has nothing to draw there: the delimiters are
3166    /// hidden, so the caret shows at the end of the word either way, and the two
3167    /// offsets are one place on screen with two different meanings. Typing at the
3168    /// outer one lands past the run, so the writer who backspaced a space out of
3169    /// their bold phrase watches the next character come out plain, and the
3170    /// toolbar button go dark, with the caret never appearing to move.
3171    ///
3172    /// The end of the run's text is the caret's home there — a delete that took
3173    /// away everything after a phrase leaves the caret at the end of that phrase,
3174    /// which is inside it — so it settles onto that
3175    /// ([`step_inside_close_delims`](Self::step_inside_close_delims) does the
3176    /// walk, through every mark closing at the point): the word stays bold, the
3177    /// button stays lit, and the next character carries on the phrase.
3178    ///
3179    /// Rich view only, and only where a mark really closes at the caret — mid-run
3180    /// or in plain prose no span ends there and the caret stays put. The opening
3181    /// edge is left alone on purpose: a caret in front of a run inherits from the
3182    /// text on its left, which is the plain text outside.
3183    fn settle_inside_close_delims(&mut self) {
3184        if self.view != View::Wysiwyg {
3185            return;
3186        }
3187        let at = self.step_inside_close_delims(self.caret);
3188        if at != self.caret {
3189            self.caret = at;
3190            self.clear_pending();
3191            self.record_caret();
3192        }
3193    }
3194
3195    /// The splice exactly as asked, with no mark-edge repair — for the callers
3196    /// that are *writing* the delimiters themselves ([`insert_with_marks`](Self::insert_with_marks)
3197    /// and [`rejoin_run`](Self::rejoin_run)) and place their own offsets around
3198    /// the bytes they inserted.
3199    ///
3200    /// One `edit_range` through twig, then re-anchor the caret from the returned
3201    /// `Change` and refresh the cached source. A reparse-breaking edit (rare for
3202    /// Markdown/Djot) leaves the document untouched and reports.
3203    ///
3204    /// Returns whether the edit landed — for a caller that has offsets of its
3205    /// own to place afterwards, which a rolled-back splice would leave pointing
3206    /// into text that never came to exist.
3207    fn splice_exact(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3208        // The read-only gate, for every edit at once — see the field.
3209        if self.read_only {
3210            return false;
3211        }
3212        // twig records an undo step for every edit; when this one continues a
3213        // run of the same kind (typing, deleting), tell twig to fold it into the
3214        // step before it so the whole run undoes at once.
3215        let coalesce = kind != EditKind::Other && self.last_edit_kind == Some(kind);
3216        // Hand twig the pre-edit caret before the splice, so the undo step it
3217        // retires carries where the caret was standing.
3218        self.record_caret();
3219        match self.editor.edit_range(start, end, text) {
3220            Ok(change) => {
3221                if coalesce {
3222                    let _ = self.editor.coalesce_last_undo();
3223                }
3224                self.last_edit_kind = Some(kind);
3225                self.refresh();
3226                self.caret = change.new.end;
3227                self.anchor = None;
3228                self.goal_col = None;
3229                self.clear_pending();
3230                self.dirty = self.source != self.clean_source;
3231                self.status = None;
3232                // And the post-edit caret, so a later redo restores it.
3233                self.record_caret();
3234                true
3235            }
3236            // The edit was rolled back, so twig's history did not move and
3237            // neither may ours: pushing here would leave a step with no edit
3238            // under it and shift every later undo onto the wrong caret.
3239            Err(e) => {
3240                self.status = Some(format!("edit: {e}"));
3241                false
3242            }
3243        }
3244    }
3245
3246    /// The re-spelling that would keep the mark-edge rule for the edit
3247    /// `[start, end)` → `text`, or `None` when the edit leaves no whitespace
3248    /// against a delimiter and the plain splice is already right. Computed
3249    /// *before* the edit, while the run's spans and delimiters can still be read
3250    /// off the document; applied afterwards, and only if the mark really died —
3251    /// see [`repair_mark_edges`](Self::repair_mark_edges).
3252    ///
3253    /// Rich view only. Source view is for typing raw markup, where a space put
3254    /// against a `**` is exactly the character it looks like.
3255    fn mark_edge_fix(&mut self, start: usize, end: usize, text: &str) -> Option<MarkEdgeFix> {
3256        if self.view != View::Wysiwyg || start > end || end > self.source.len() {
3257            return None;
3258        }
3259        // Every inline mark standing over the edit, outermost first, with the
3260        // content span that says where its delimiters are.
3261        let chain: Vec<(InlineKind, std::ops::Range<usize>, std::ops::Range<usize>)> = self
3262            .editor
3263            .ancestors_at(start)
3264            .unwrap_or_default()
3265            .into_iter()
3266            .filter_map(|m| {
3267                let kind = inline_kind(&m.kind)?;
3268                let content = m.content_span.clone()?;
3269                Some((kind, m.span.clone(), content))
3270            })
3271            .collect();
3272        // The innermost run whose *content* holds the whole edit: the one whose
3273        // text is being changed, rather than one the edit merely sits under.
3274        let (kind, span, content) = chain
3275            .iter()
3276            .rev()
3277            .find(|(_, _, c)| c.start <= start && end <= c.end)?
3278            .clone();
3279        // What that content becomes. Whitespace at either end of it is what
3280        // would put out the mark.
3281        let body = format!(
3282            "{}{text}{}",
3283            &self.source[content.start..start],
3284            &self.source[end..content.end]
3285        );
3286        let (lead, trail) = if body.trim().is_empty() {
3287            // Nothing but whitespace left: there is no content to mark at all,
3288            // and the delimiters go with it rather than closing on a space.
3289            (body.len(), 0)
3290        } else {
3291            (
3292                body.len() - body.trim_start().len(),
3293                body.len() - body.trim_end().len(),
3294            )
3295        };
3296        // Nothing against a delimiter, and something still between them: the
3297        // plain edit stands. An emptied run is broken just as surely (`**b**`
3298        // with the `b` deleted is the literal `****`) and is re-spelt as the
3299        // nothing it now says.
3300        if lead == 0 && trail == 0 && !body.is_empty() {
3301            return None;
3302        }
3303        // Marks that open or close exactly where this one does — `***both***` is
3304        // two runs sharing an edge — spell their delimiters as one run of bytes,
3305        // so the whitespace has to clear all of them together.
3306        let (mut open_at, mut close_at) = (span.start, span.end);
3307        for _ in 0..chain.len() {
3308            match chain.iter().find(|(_, _, c)| c.start == open_at) {
3309                Some((_, s, _)) => open_at = s.start,
3310                None => break,
3311            }
3312        }
3313        for _ in 0..chain.len() {
3314            match chain.iter().find(|(_, _, c)| c.end == close_at) {
3315                Some((_, s, _)) => close_at = s.end,
3316                None => break,
3317            }
3318        }
3319        let open = &self.source[open_at..content.start];
3320        let close = &self.source[content.end..close_at];
3321        let core = &body[lead..body.len() - trail];
3322        let respelt = if core.is_empty() {
3323            body.clone()
3324        } else {
3325            format!(
3326                "{}{open}{core}{close}{}",
3327                &body[..lead],
3328                &body[body.len() - trail..]
3329            )
3330        };
3331        // The caret sits just past the inserted text within the new content —
3332        // which, when that lands in the whitespace, is now outside the delimiters.
3333        let pos = (start - content.start) + text.len();
3334        let caret = if core.is_empty() || pos <= lead {
3335            open_at + pos
3336        } else if pos >= lead + core.len() {
3337            open_at + lead + open.len() + core.len() + close.len() + (pos - lead - core.len())
3338        } else {
3339            open_at + lead + open.len() + (pos - lead)
3340        };
3341        Some(MarkEdgeFix {
3342            kind,
3343            probe: content.start,
3344            start: open_at,
3345            end: close_at + text.len() - (end - start),
3346            text: respelt,
3347            caret,
3348            // The marks in force here, resolved against any armed sticky delta —
3349            // what the writer is typing in, and so what has to still be true on
3350            // the far side of the delimiter the caret just stepped over.
3351            want: chain
3352                .iter()
3353                .filter(|(_, s, _)| start < s.end)
3354                .map(|(k, _, _)| *k)
3355                .collect::<InlineMarks>()
3356                .xor(self.pending_here()),
3357        })
3358    }
3359
3360    /// Apply a [`MarkEdgeFix`] — but only if the edit it was computed for really
3361    /// did break the mark. Whether whitespace at a delimiter is fatal is the
3362    /// format's business, not leaf's: `**bold **` is no longer strong, while
3363    /// `` `code ` `` is still perfectly good verbatim, and Djot's braced spellings
3364    /// don't care either. Asking the parser afterwards settles it for every kind
3365    /// and format at once, and costs a re-spelling only where one is due.
3366    ///
3367    /// The repair rides along with the edit that caused it — one undo step puts
3368    /// back what the writer typed, not a delimiter shuffle they never saw.
3369    fn repair_mark_edges(&mut self, fix: MarkEdgeFix) {
3370        if fix.end > self.source.len() {
3371            return;
3372        }
3373        if self.marks_at(fix.probe).iter().any(|(k, _)| *k == fix.kind) {
3374            return; // still a mark: these delimiters don't mind the whitespace
3375        }
3376        let resumed = self.last_edit_kind;
3377        if !self.splice_exact(fix.start, fix.end, &fix.text, EditKind::Other) {
3378            return;
3379        }
3380        let _ = self.editor.coalesce_last_undo();
3381        // The keystroke owns the undo step, so the run of typing it belongs to
3382        // keeps coalescing over the repair rather than breaking in two here.
3383        self.last_edit_kind = resumed;
3384        self.caret = fix.caret.min(self.source.len());
3385        self.anchor = None;
3386        self.goal_col = None;
3387        self.rearm(fix.want);
3388        self.clamp_caret();
3389        self.record_caret();
3390    }
3391
3392    /// Arm whatever sticky delta reproduces `want` at the caret — the marks the
3393    /// writer is typing in, carried across an edit that moved the caret out of
3394    /// the run holding them. Arms nothing when the caret already stands in
3395    /// exactly those marks, but still remembers the spot, so a further ⌘b starts
3396    /// a clean delta here (see [`toggle`](Self::toggle)).
3397    fn rearm(&mut self, want: InlineMarks) {
3398        let here: InlineMarks = self
3399            .marks_at(self.caret)
3400            .into_iter()
3401            .map(|(k, _)| k)
3402            .collect();
3403        self.pending_marks = want.xor(here);
3404        self.pending_at = Some(self.caret);
3405    }
3406
3407    /// Insert `text` at `at` as a *literal* run via twig's `insert_literal`,
3408    /// which backslash-escapes any character that would otherwise open markup in
3409    /// this format and position (`*` → `\*`, a line-start `#` → `\#`). The mirror
3410    /// of [`splice`](Self::splice) for the Hidden reveal mode's typing path, with
3411    /// the same caret re-anchor, coalescing, and rollback contract. `at` must be
3412    /// a collapsed point — a selection is deleted by the caller first, since
3413    /// `insert_literal` inserts rather than replaces.
3414    fn insert_literal_at(
3415        &mut self,
3416        at: usize,
3417        text: &str,
3418        kind: EditKind,
3419        force_coalesce: bool,
3420    ) -> bool {
3421        // The read-only gate: this door goes to twig directly, not through
3422        // `splice_exact`, so it guards itself — see the field.
3423        if self.read_only {
3424            return false;
3425        }
3426        // `force_coalesce` folds this into the immediately preceding edit (the
3427        // selection-delete of an overwrite) so the pair is one undo step; else it
3428        // coalesces only when it continues a run of the same-kind typing.
3429        let coalesce =
3430            force_coalesce || (kind != EditKind::Other && self.last_edit_kind == Some(kind));
3431        // The mark-edge rule holds for typed text however it is spelled — see
3432        // `splice`. Only an insert twig passed through unchanged can use it,
3433        // since a fix is measured in the bytes that actually land, and an escape
3434        // adds bytes this couldn't have counted.
3435        let fix = self.mark_edge_fix(at, at, text);
3436        self.record_caret();
3437        match self.editor.insert_literal(at, text) {
3438            Ok(change) => {
3439                if coalesce {
3440                    let _ = self.editor.coalesce_last_undo();
3441                }
3442                self.last_edit_kind = Some(kind);
3443                self.refresh();
3444                self.caret = change.new.end;
3445                self.anchor = None;
3446                self.goal_col = None;
3447                self.clear_pending();
3448                self.dirty = self.source != self.clean_source;
3449                self.status = None;
3450                self.record_caret();
3451                if let Some(fix) = fix.filter(|_| change.new.end - change.new.start == text.len()) {
3452                    self.repair_mark_edges(fix);
3453                }
3454                true
3455            }
3456            Err(e) => {
3457                self.status = Some(format!("edit: {e}"));
3458                false
3459            }
3460        }
3461    }
3462
3463    /// After a structural list edit (a new item, a nest/unnest), renumber the
3464    /// ordered list the caret sits in so its source markers run `1, 2, 3, …`
3465    /// again — a raw splice leaves them stale (`1. 2. 2. 3.`). twig does the
3466    /// renumber as its own edit; fold it into the edit that triggered it so the
3467    /// two undo as one, and only when it actually changed the source (a no-op or
3468    /// a caret outside any ordered list must not coalesce the real edit into the
3469    /// step before it).
3470    fn renumber_here(&mut self) {
3471        self.renumber_at(self.caret);
3472    }
3473
3474    /// [`renumber_here`](Self::renumber_here) aimed somewhere other than the
3475    /// caret — for an edit that leaves the caret one past the item it just wrote,
3476    /// where twig resolves no list to renumber.
3477    fn renumber_at(&mut self, off: usize) {
3478        // The read-only gate — this door reaches twig without the splice.
3479        if self.read_only {
3480            return;
3481        }
3482        let before = self.source.clone();
3483        if self.editor.renumber_ordered_lists(off).is_err() {
3484            return; // not inside an ordered list — nothing to renumber
3485        }
3486        self.refresh();
3487        if self.source != before {
3488            let _ = self.editor.coalesce_last_undo();
3489            self.dirty = self.source != self.clean_source;
3490            self.clamp_caret();
3491            self.record_caret();
3492        }
3493    }
3494
3495    /// Repair the one trap a list edit can spring on itself. An *empty* `-`
3496    /// sub-item written directly beneath a text line reparses that text as a
3497    /// setext heading — `- hello\n  - ` is `<h2>hello</h2>`, because a lone `-`
3498    /// is also a setext-H2 underline (twig is right; pandoc agrees). `*` and `+`
3499    /// bullets can't underline anything, so swap the dash for a `*`: the item
3500    /// stays an empty nested bullet, the parent stays prose, and the source
3501    /// round-trips instead of hiding a heading the user never asked for. Folded
3502    /// into the triggering edit's undo step, the way renumbering is.
3503    ///
3504    /// Gated on the collapse having actually happened (the swapped dash was
3505    /// swallowed into a `heading`), so a real setext heading the author wrote —
3506    /// or a `- x` with content, which can't underline anything — is never
3507    /// touched. This has to live in the *edit*, not the renderer: leaving the
3508    /// hazardous bytes on disk and only painting over them would ship a file
3509    /// every other CommonMark tool reads as a heading.
3510    ///
3511    /// This one keeps its own byte scan, and has to: the hazard is precisely
3512    /// that the dash stopped being a list marker, so [`list_marker_on_line`] —
3513    /// which asks twig which lines open an item — reports nothing here. There is
3514    /// no node to ask about. It is also the last Markdown spelling leaf writes on
3515    /// purpose rather than for want of an answer; once twig spells continuations
3516    /// itself, avoiding the trap becomes twig's, and this goes.
3517    ///
3518    /// [`list_marker_on_line`]: Self::list_marker_on_line
3519    fn avoid_setext_collapse(&mut self) {
3520        let caret = self.caret.min(self.source.len());
3521        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
3522        let bytes = self.source.as_bytes();
3523        let mut dash = line_start;
3524        while matches!(bytes.get(dash), Some(b' ' | b'\t')) {
3525            dash += 1;
3526        }
3527        // A dash bullet is the only marker that doubles as a setext underline.
3528        if bytes.get(dash) != Some(&b'-') {
3529            return;
3530        }
3531        // Only an *empty* item is a bare underline; `- x` carries content and
3532        // can't fold the line above into a heading.
3533        let line_end = self.source[dash..]
3534            .find('\n')
3535            .map_or(self.source.len(), |i| dash + i);
3536        if !self.source[dash + 1..line_end].trim().is_empty() {
3537            return;
3538        }
3539        // The tell: that dash was swallowed into a `heading`. A properly nested
3540        // empty item sits under a `list_item`, with no heading in reach. Probe
3541        // the dash byte itself (well inside the heading), not the caret, whose
3542        // end-of-line offset can fall on the half-open span boundary.
3543        let collapsed = self
3544            .editor
3545            .ancestors_at(dash)
3546            .map(|c| c.into_iter().any(|m| m.kind == Kind::Heading))
3547            .unwrap_or(false);
3548        if !collapsed {
3549            return;
3550        }
3551        let caret = self.caret;
3552        if self.splice(dash, dash + 1, "*", EditKind::Other) {
3553            // Same width, so the caret keeps its column; fold into the edit that
3554            // triggered this so Tab stays one undo step.
3555            let _ = self.editor.coalesce_last_undo();
3556            self.caret = caret.min(self.source.len());
3557            self.clamp_caret();
3558            self.record_caret();
3559        }
3560    }
3561
3562    fn snapshot(&self) -> CaretState {
3563        CaretState {
3564            caret: self.caret,
3565            anchor: self.anchor,
3566        }
3567    }
3568
3569    /// Hand twig the current caret and selection as the blob for the live
3570    /// document state. Called before an edit — so the step twig retires records
3571    /// where the caret was, and undo can restore it — and again once the op has
3572    /// placed the caret, so redo restores where the edit left it.
3573    ///
3574    /// This is the whole of leaf's undo-caret bookkeeping now. twig carries the
3575    /// caret through its own history, so coalescing falls out for free (folding
3576    /// two twig steps into one drops the intermediate blob, keeping the run's
3577    /// first) and the parallel stacks that had to march in lockstep — and could
3578    /// silently drift out of it — are gone.
3579    fn record_caret(&mut self) {
3580        let _ = self.editor.set_caret_blob(&self.snapshot().to_blob());
3581    }
3582
3583    /// Toggle an inline mark over the selection (Bold / Italic / Code / …). Keeps
3584    /// the toggled region selected so a second press cleanly reverses it.
3585    pub fn toggle(&mut self, kind: InlineKind) {
3586        // The read-only gate — this door reaches twig without the splice.
3587        if self.read_only {
3588            return;
3589        }
3590        // Ahead of the no-selection branch below: arming a mark for text not yet
3591        // typed is a promise `insert` cannot keep in a format with no delimiters
3592        // to spell it with. Per *kind*, not per format — Markdown spells five
3593        // of the eight marks (highlight among them, under the `highlight`
3594        // extension leaf parses with), djot all eight, HTML seven.
3595        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleInline(kind)) {
3596            return;
3597        }
3598        let Some((s, e)) = self.selection() else {
3599            // No selection: arm the mark for the next text typed here, the way a
3600            // word processor does. `⌘b`, type, `⌘b` again toggles bold on and off
3601            // in the flow of typing without ever selecting anything — the delta
3602            // is realised onto the freshly typed text by `insert`. A fresh caret
3603            // position starts the delta over from the marks actually in force.
3604            if self.pending_at != Some(self.caret) {
3605                self.pending_marks = InlineMarks::empty();
3606                self.pending_at = Some(self.caret);
3607            }
3608            self.pending_marks.flip(kind);
3609            self.status = None;
3610            return;
3611        };
3612        // Whitespace at the edge of a selection is not part of what was chosen —
3613        // a double-click takes the space after the word with it — and a mark
3614        // cannot close against one anyway: `**word **` is four literal asterisks
3615        // (the mark-edge rule, see `splice`). Mark the words, leave the spaces.
3616        let picked = &self.source[s..e];
3617        let (s, e) = (
3618            s + (picked.len() - picked.trim_start().len()),
3619            e - (picked.len() - picked.trim_end().len()),
3620        );
3621        if s >= e {
3622            self.status = Some(format!("{kind:?}: nothing selected to mark"));
3623            return;
3624        }
3625        // Styling a selection is a one-shot act, not a sticky mode.
3626        self.clear_pending();
3627        self.record_caret();
3628        match self.editor.toggle_inline(s, e, kind) {
3629            Ok(change) => {
3630                self.last_edit_kind = None; // structural edit is its own undo step
3631                self.refresh();
3632                self.anchor = Some(change.new.start);
3633                self.caret = change.new.end;
3634                self.dirty = self.source != self.clean_source;
3635                self.status = None;
3636                self.record_caret();
3637            }
3638            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
3639        }
3640    }
3641
3642    /// Whether the caret stands in a highlight — what a frontend asks to enable
3643    /// or disable its highlight-colour controls, the way
3644    /// [`caret_in_table`](Self::caret_in_table) gates the grid ones.
3645    ///
3646    /// A fact about the *caret*, and the other half of
3647    /// [`Capabilities::mark_color`], which is the fact about the format. A
3648    /// frontend needs both: djot spells a highlight and no colour for it, so a
3649    /// caret standing in `{=word=}` answers `true` here and still has no palette
3650    /// to offer.
3651    ///
3652    /// The rule is [`active_inline_marks`](Self::active_inline_marks)' rule, so
3653    /// the palette appears exactly where the Highlight button is lit — with one
3654    /// deliberate exception: a mark *armed* at a bare caret and not yet typed
3655    /// into lights the button and answers `false` here, because there is no node
3656    /// to colour until the text exists.
3657    pub fn caret_in_mark(&mut self) -> bool {
3658        self.mark_offset().is_some()
3659    }
3660
3661    /// The offset [`set_mark_color`](Self::set_mark_color) speaks for — the one
3662    /// standing in the highlight the gesture means — or `None` when neither end
3663    /// of what is selected is in one.
3664    ///
3665    /// The caret first, and the selection's *start* after it, because of what
3666    /// [`toggle`](Self::toggle) leaves behind: a fresh `==word==` is selected
3667    /// whole, with the caret at its far edge, one past the closing `==` and so
3668    /// (by `marks_at`' half-open rule) not in the mark at all. Highlight a word
3669    /// and colour it — the two presses a coloured highlight is made of — would
3670    /// otherwise refuse on the second, having just written the highlight the
3671    /// author is pointing at.
3672    fn mark_offset(&mut self) -> Option<usize> {
3673        let in_mark = |d: &mut Self, off: usize| {
3674            d.marks_at(off)
3675                .into_iter()
3676                .any(|(k, _)| k == InlineKind::Mark)
3677                .then_some(off)
3678        };
3679        let caret = self.caret.min(self.source.len());
3680        in_mark(self, caret).or_else(|| {
3681            let start = self.selection()?.0;
3682            in_mark(self, start)
3683        })
3684    }
3685
3686    /// The colour of the highlight at the caret — `None` both when the caret is
3687    /// in no highlight and when the highlight it is in names no colour, which
3688    /// are the same answer to "which swatch is lit".
3689    ///
3690    /// The innermost mark, by span, for the same reason
3691    /// [`current_heading_level`](Self::current_heading_level) walks the tree:
3692    /// what the caret is *in* is the deepest node containing it. A `data-color`
3693    /// naming a colour this build has no variant for reads as `None` — the
3694    /// renderer already draws that as a plain highlight rather than guessing,
3695    /// and the toolbar agrees with the renderer.
3696    pub fn mark_color_at_caret(&mut self) -> Option<MarkColor> {
3697        let at = self.mark_offset()?;
3698        self.mark_color_at(at)
3699    }
3700
3701    /// [`mark_color_at_caret`](Self::mark_color_at_caret) at a given offset —
3702    /// the innermost `mark` covering it, and the colour it names.
3703    fn mark_color_at(&mut self, off: usize) -> Option<MarkColor> {
3704        self.nodes()
3705            .into_iter()
3706            .filter(|n| n.kind == Kind::Mark)
3707            .filter(|n| n.span.start <= off && off < n.span.end)
3708            .min_by_key(|n| n.span.end - n.span.start)
3709            .and_then(|n| MarkColor::from_attrs(&n.attrs))
3710    }
3711
3712    /// Colour the highlight at the caret, or clear its colour with `None` — the
3713    /// palette behind a toolbar's Highlight button.
3714    ///
3715    /// Markdown only, and the one gesture whose availability is a fact about the
3716    /// *parse extensions* rather than about the format alone: the colour is
3717    /// spelled `==🔴 text==`, an emoji twig reads back out of the content and
3718    /// records as the mark's `data-color`, and only an editor parsing with
3719    /// `highlight_colors` (which [`parse_extensions`] turns on for every leaf
3720    /// document) reads it back that way. Djot spells the highlight and no colour
3721    /// for it, so this refuses there — see [`Capabilities::mark_color`].
3722    ///
3723    /// **A colour is a property of a highlight that already exists.** There is
3724    /// no "highlight this in red" here, because that is two splices and would be
3725    /// two undo steps under one press; a frontend that wants it calls
3726    /// [`toggle`](Self::toggle) with [`InlineKind::Mark`] first, which is the
3727    /// order the two buttons already sit in. With no highlight at the caret this
3728    /// says so in the status line and writes nothing.
3729    ///
3730    /// The caret keeps its place in the *text*: the splice is entirely in the
3731    /// prefix between the opening `==` and the first word, so an offset past it
3732    /// rides the emoji's width, and one standing on the prefix itself lands
3733    /// where the prefix now ends.
3734    pub fn set_mark_color(&mut self, color: Option<MarkColor>) {
3735        // The read-only gate — this door reaches twig without the splice.
3736        if self.read_only {
3737            return;
3738        }
3739        if self.refuse_unsupported("highlight colour", Gesture::SetMarkColor) {
3740            return;
3741        }
3742        let Some(at) = self.mark_offset() else {
3743            self.status = Some("highlight colour: no highlight at the caret".into());
3744            return;
3745        };
3746        // Clearing a colour a highlight hasn't got is twig's one *successful*
3747        // no-op, and the `Change` it hands back then describes whatever edit came
3748        // before it — a stale span that would drag the caret somewhere it never
3749        // was. Answer it here, where the question is cheap, rather than trusting
3750        // a change that isn't one.
3751        if color.is_none() && self.mark_color_at(at).is_none() {
3752            self.status = None;
3753            return;
3754        }
3755        self.record_caret();
3756        match self.editor.set_mark_color(at, color.map(twig_mark_color)) {
3757            Ok(change) => {
3758                // Re-anchored from the offsets as they were, *before* `refresh`
3759                // sees the new bytes: the caret it clamps is one standing inside
3760                // a prefix that didn't exist a moment ago, and walking it back to
3761                // a char boundary of the emoji loses the place this is restoring.
3762                let caret = reanchor(self.caret, &change);
3763                let anchor = self.anchor.map(|a| reanchor(a, &change));
3764                self.last_edit_kind = None; // structural edit is its own undo step
3765                self.refresh();
3766                self.caret = caret;
3767                self.anchor = anchor;
3768                self.dirty = self.source != self.clean_source;
3769                self.status = None;
3770                self.clamp_caret();
3771                self.record_caret();
3772            }
3773            Err(e) => self.status = Some(format!("highlight colour: {e}")),
3774        }
3775    }
3776
3777    /// One press of a colour swatch: colour the highlight at the caret, or —
3778    /// over a selection that isn't highlighted yet — highlight it and colour it,
3779    /// as **one** undo step.
3780    ///
3781    /// [`set_mark_color`](Self::set_mark_color) is the exact gesture and stays
3782    /// one splice; this is the compound every toolbar actually presses, and it
3783    /// lives here rather than in each frontend because the rule it encodes —
3784    /// what a swatch means when there is no highlight under it yet — is one
3785    /// answer, not one per frontend. The two splices are folded into a single
3786    /// history step, so the press that made a red highlight is taken back by a
3787    /// single undo rather than leaving an uncoloured one behind.
3788    ///
3789    /// `None` clears the colour, and over an unhighlighted selection means
3790    /// simply "highlight this" — the same thing the Highlight button does.
3791    /// A bare caret in no highlight is left alone with a status line, because
3792    /// [`toggle`](Self::toggle) there arms a mark for text not yet typed and a
3793    /// colour cannot be armed with it.
3794    pub fn highlight(&mut self, color: Option<MarkColor>) {
3795        if self.caret_in_mark() || self.selection().is_none() {
3796            self.set_mark_color(color);
3797            return;
3798        }
3799        self.toggle(InlineKind::Mark);
3800        // The format may not spell a highlight at all (`toggle` said so), and
3801        // there is nothing to colour if it doesn't.
3802        if self.status.is_some() {
3803            return;
3804        }
3805        let before = self.revision;
3806        self.set_mark_color(color);
3807        // Only fold when the colour really spliced. `highlight(None)` over a
3808        // fresh highlight is a no-op by design, and coalescing there would eat
3809        // the *previous* edit into the toggle instead.
3810        if self.revision != before {
3811            let _ = self.editor.coalesce_last_undo();
3812        }
3813    }
3814
3815    /// Convert the block at the caret to a heading level or paragraph.
3816    pub fn set_block(&mut self, kind: BlockKind) {
3817        // The read-only gate — this door reaches twig without the splice.
3818        if self.read_only {
3819            return;
3820        }
3821        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::SetBlock) {
3822            return;
3823        }
3824        self.record_caret();
3825        // A blank line has no node to convert, and twig opens a block there
3826        // rather than declining — so the caret's own offset is the right thing
3827        // to hand it when `block_offset_for_caret` finds nothing.
3828        let offset = self.block_offset_for_caret().unwrap_or(self.caret);
3829        match self.editor.set_block(offset, kind) {
3830            Ok(change) => {
3831                self.last_edit_kind = None;
3832                self.refresh();
3833                // Opening a block on a blank line writes a marker the caret
3834                // belongs *after*; converting an existing one moves nothing.
3835                self.caret = self.caret.max(change.new.end);
3836                self.clamp_caret();
3837                self.anchor = None;
3838                self.dirty = self.source != self.clean_source;
3839                self.status = None;
3840                self.record_caret();
3841            }
3842            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
3843        }
3844    }
3845
3846    /// Whether `off` is inside a text block (paragraph, heading, code block…).
3847    fn has_block_at(&mut self, off: usize) -> bool {
3848        self.editor.ancestors_at(off).ok().is_some_and(|chain| {
3849            chain
3850                .iter()
3851                .any(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
3852        })
3853    }
3854
3855    /// The offset to hand twig's `set_block`: the caret when it is already inside
3856    /// a block, otherwise nudged onto the previous character (a caret at a line
3857    /// end sits at the doc level, outside the block). `None` when the caret is on
3858    /// a blank line — a new paragraph with no block node to convert.
3859    fn block_offset_for_caret(&mut self) -> Option<usize> {
3860        let caret = self.caret.min(self.source.len());
3861        if self.has_block_at(caret) {
3862            return Some(caret);
3863        }
3864        // Nudge to the previous character — but never across a newline: that would
3865        // target the previous block, and a blank line genuinely has no block.
3866        if let Some((i, ch)) = self.source[..caret].char_indices().next_back()
3867            && ch != '\n'
3868            && self.has_block_at(i)
3869        {
3870            return Some(i);
3871        }
3872        None
3873    }
3874
3875    /// The heading level of the text block at the caret, or `None` when that
3876    /// block is not a heading.
3877    pub fn current_heading_level(&mut self) -> Option<u32> {
3878        let caret = self.caret;
3879        self.nodes()
3880            .into_iter()
3881            .filter(|n| n.kind == Kind::Heading)
3882            .find(|n| n.span.start <= caret && caret <= n.span.end)
3883            .and_then(|n| n.level)
3884    }
3885
3886    /// The inline marks in force at the caret (or over the selection) — what a
3887    /// toolbar draws lit, and the block-level [`Doc::current_heading_level`]'s
3888    /// inline counterpart. Cheap enough to call every frame: one twig
3889    /// `ancestors_at` query per caret (two with a selection), each walking root
3890    /// → deepest node at one offset. It never snapshots the tree the way
3891    /// `current_heading_level` does, and the returned set is a `Copy` bitset, so
3892    /// the only allocation is twig's own small ancestor `Vec`.
3893    ///
3894    /// **A selection reports a mark only when the mark covers *all* of it.**
3895    /// That's what every real toolbar means by an active button — Bold lit over
3896    /// a half-bold selection would claim a press turns bold *off*, when
3897    /// [`Doc::toggle`] hands the range to twig and gets the whole thing bolded.
3898    /// Whole-coverage is asked as "is the same mark node standing over both the
3899    /// first and the last character?": inline nodes are contiguous, so one node
3900    /// covering both ends covers every byte between them. Two touching runs
3901    /// (`**a****b**`) are two nodes, and correctly light nothing.
3902    ///
3903    /// At a bare caret a mark is active when the caret stands inside the mark's
3904    /// span — `span.start <= caret < span.end`, delimiters included, which is
3905    /// what makes the boundaries behave. In `a **bold** b` the offsets from the
3906    /// opening `*` (2) through the last byte of the closing `**` (9) are all
3907    /// bold, so the WYSIWYG caret both before `b` and after `d` (the delimiters
3908    /// are hidden, and those offsets are 4 and 8) reports bold — matching where
3909    /// typing would actually land inside the marked run. The offset one past the
3910    /// mark (10) is the text after it and reports nothing, at the end of the
3911    /// buffer exactly as in the middle.
3912    pub fn active_inline_marks(&mut self) -> InlineMarks {
3913        let Some((start, end)) = self.selection() else {
3914            // The marks actually in force at the caret, flipped by any armed
3915            // sticky delta — so `⌘b` at a bare caret lights the Bold button
3916            // immediately, before a single character is typed.
3917            let base: InlineMarks = self
3918                .marks_at(self.caret)
3919                .into_iter()
3920                .map(|(k, _)| k)
3921                .collect();
3922            return base.xor(self.pending_here());
3923        };
3924        // The selection's *last character*, not its exclusive end: `end` is the
3925        // offset one past the selection, which for a selection ending exactly at
3926        // a mark's close is already outside it (`[4,10)` of `a **bold** b` is
3927        // entirely bold, but offset 10 is the space after).
3928        let last = prev_boundary(&self.source, end);
3929        let head = self.marks_at(start);
3930        let tail = self.marks_at(last);
3931        head.into_iter()
3932            .filter(|m| tail.contains(m))
3933            .map(|(k, _)| k)
3934            .collect()
3935    }
3936
3937    /// The inline marks whose span covers `off`, each with the id of the node
3938    /// carrying it — the id is what lets a selection tell one mark node from
3939    /// another of the same kind.
3940    fn marks_at(&mut self, off: usize) -> Vec<(InlineKind, u32)> {
3941        let off = off.min(self.source.len());
3942        self.editor
3943            .ancestors_at(off)
3944            .unwrap_or_default()
3945            .into_iter()
3946            // `span.end` is the offset one *past* the mark, so it isn't in it.
3947            // twig already resolves a boundary to whatever starts there — in
3948            // `**bold** x` offset 8 is the following text, not the strong — but
3949            // when nothing follows, the tie has nobody to break for and the
3950            // chain still ends at the mark. That would make the answer at the
3951            // last offset of the document depend on whether the file happens to
3952            // end in a newline; the rule is `span.start <= off < span.end`, and
3953            // it's the same rule at the end of a buffer as in the middle.
3954            .filter(|m| off < m.span.end)
3955            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.node_id)))
3956            .collect()
3957    }
3958
3959    /// Toggle a heading at the caret: if the block is already this heading level,
3960    /// revert it to a paragraph; otherwise convert it to this heading level.
3961    /// This gives the heading commands the same toggle feel as bold/italic/code —
3962    /// re-applying a heading a line already has turns it back into body text.
3963    pub fn toggle_heading(&mut self, level: u32) {
3964        if self.current_heading_level() == Some(level) {
3965            self.set_block(BlockKind::Paragraph);
3966        } else {
3967            self.set_block(BlockKind::Heading(level));
3968        }
3969    }
3970
3971    /// Toggle a block quote around the selection, or around the block at the
3972    /// caret — the toolbar's Quote button.
3973    pub fn toggle_blockquote(&mut self) {
3974        self.toggle_container(BlockContainerKind::BlockQuote);
3975    }
3976
3977    /// Toggle a numbered (`ordered`) or bulleted list over the selection, or
3978    /// over the block at the caret — one op with the kind as a flag, the way
3979    /// `toggle_heading` takes its level, so a frontend needs no twig type to
3980    /// name the two buttons.
3981    ///
3982    /// Pressing the *other* list's button while in a list converts in place
3983    /// rather than nesting, so the pair reads as one three-state control
3984    /// (bulleted / numbered / neither) rather than two independent wrappers.
3985    pub fn toggle_list(&mut self, ordered: bool) {
3986        self.toggle_container(if ordered {
3987            BlockContainerKind::OrderedList
3988        } else {
3989            BlockContainerKind::BulletList
3990        });
3991    }
3992
3993    // ── Task list items ──────────────────────────────────────────────────────
3994    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
3995    // inline content of the item's first paragraph rather than part of its
3996    // marker, so adding or removing one must leave the item's continuation
3997    // indentation alone, and an item inside a quote is found past the quote
3998    // markers. leaf names the gesture and the offset; the spelling is twig's.
3999
4000    /// Whether the list item at the caret carries a checkbox, and which way it
4001    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
4002    /// item or no item at all. What a toolbar reads to light its checkbox button.
4003    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
4004        self.task_checked_at(self.caret)
4005    }
4006
4007    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
4008    /// offset — what a frontend asks before deciding a click landed on a box.
4009    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
4010        self.innermost_list_item(offset.min(self.source.len()))?
4011            .checked
4012    }
4013
4014    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
4015    /// A no-op with a reported reason when the caret is in no task item — minting
4016    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
4017    pub fn toggle_task_checked(&mut self) {
4018        self.toggle_task_at(self.caret);
4019    }
4020
4021    /// Tick or untick the task item covering `offset` — what a *click* on a
4022    /// rendered checkbox is. Separate from the caret form because a click carries
4023    /// its own offset and must not first move the caret there: ticking a box
4024    /// three paragraphs away should not take the cursor with it.
4025    pub fn toggle_task_at(&mut self, offset: usize) {
4026        // The read-only gate — this door reaches twig without the splice.
4027        if self.read_only {
4028            return;
4029        }
4030        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
4031            return;
4032        }
4033        let offset = offset.min(self.source.len());
4034        self.record_caret();
4035        match self.editor.toggle_task_checked(offset) {
4036            Ok(_) => self.after_task_edit(),
4037            Err(e) => self.status = Some(format!("task: {e}")),
4038        }
4039    }
4040
4041    /// Give the list item at the caret a checkbox, or take its checkbox away —
4042    /// the gesture that converts between a plain bullet and a task. A new box
4043    /// arrives unticked.
4044    pub fn toggle_task_item(&mut self) {
4045        // The read-only gate — this door reaches twig without the splice.
4046        if self.read_only {
4047            return;
4048        }
4049        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
4050            return;
4051        }
4052        let caret = self.caret.min(self.source.len());
4053        self.record_caret();
4054        match self.editor.toggle_task_item(caret) {
4055            Ok(_) => self.after_task_edit(),
4056            Err(e) => self.status = Some(format!("task: {e}")),
4057        }
4058    }
4059
4060    /// Settle after a task gesture. The caret rides its old byte offset and is
4061    /// clamped back in: a box is three or four bytes on the item's first line, so
4062    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
4063    /// real stop either way.
4064    fn after_task_edit(&mut self) {
4065        self.last_edit_kind = None;
4066        self.refresh();
4067        self.anchor = None;
4068        self.dirty = self.source != self.clean_source;
4069        self.status = None;
4070        self.clamp_caret();
4071        self.record_caret();
4072    }
4073
4074    // ── Tables ───────────────────────────────────────────────────────────────
4075    // A table is a grid, and twig edits it as one — add/remove/move a row or
4076    // column, set a column's alignment — re-spelling the whole table in a single
4077    // splice. Every gesture is anchored at the caret's cell. leaf just names the
4078    // gesture and re-reads the result; the whole table's numbering, borders, and
4079    // delimiter are twig's to keep straight.
4080
4081    /// Whether the caret is inside a table — what a frontend asks to enable or
4082    /// disable its table controls.
4083    ///
4084    /// An HTML `<table>` still answers `true`: the caret really is in a table,
4085    /// and the reason the grid controls stay dark there is
4086    /// [`Capabilities::table`], which is a fact about the document's format
4087    /// rather than about the caret. A frontend needs both.
4088    pub fn caret_in_table(&mut self) -> bool {
4089        let caret = self.caret.min(self.source.len());
4090        self.editor
4091            .ancestors_at(caret)
4092            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
4093            .unwrap_or(false)
4094    }
4095
4096    /// One grid op, guarded and settled — the shared body of the seven below.
4097    ///
4098    /// The guard is why this exists rather than seven copies of the same three
4099    /// lines, and it is the one guard leaf cannot delegate to twig. The table
4100    /// editor is the gesture family that consults no `Syntax` table (it spells a
4101    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
4102    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
4103    /// grid as a *pipe table* and reports success, swapping the element out for
4104    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
4105    /// downstream could tell that from a successful edit — the splice is real,
4106    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
4107    /// stopping at the door rather than detecting after the fact. See
4108    /// [`spells_pipe_tables`].
4109    fn table_op(
4110        &mut self,
4111        what: &str,
4112        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
4113    ) {
4114        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
4115            return;
4116        }
4117        self.record_caret();
4118        let at = self.caret;
4119        let r = op(&mut self.editor, at);
4120        self.apply_table(r, what);
4121    }
4122
4123    /// Insert an empty row below (`below`) or above the caret's row.
4124    pub fn table_insert_row(&mut self, below: bool) {
4125        self.table_op("table row", |e, at| e.table_insert_row(at, below));
4126    }
4127
4128    /// Delete the caret's row (not the header, not the last body row).
4129    pub fn table_delete_row(&mut self) {
4130        self.table_op("table row", |e, at| e.table_delete_row(at));
4131    }
4132
4133    /// Insert an empty column right (`right`) or left of the caret's column.
4134    pub fn table_insert_column(&mut self, right: bool) {
4135        self.table_op("table column", |e, at| e.table_insert_column(at, right));
4136    }
4137
4138    /// Delete the caret's column (unless it is the only one).
4139    pub fn table_delete_column(&mut self) {
4140        self.table_op("table column", |e, at| e.table_delete_column(at));
4141    }
4142
4143    /// Set the caret's column to `alignment`.
4144    pub fn table_set_alignment(&mut self, alignment: Alignment) {
4145        self.table_op("table alignment", |e, at| {
4146            e.table_set_alignment(at, alignment)
4147        });
4148    }
4149
4150    /// Move the caret's row one place down (`down`) or up, within the body rows.
4151    pub fn table_move_row(&mut self, down: bool) {
4152        self.table_op("table row", |e, at| e.table_move_row(at, down));
4153    }
4154
4155    /// Move the caret's column one place right (`right`) or left.
4156    pub fn table_move_column(&mut self, right: bool) {
4157        self.table_op("table column", |e, at| e.table_move_column(at, right));
4158    }
4159
4160    /// Settle the caret and document flags after a table op (or report its
4161    /// error). twig re-spells the whole table, so the caret rides its old byte
4162    /// offset and is clamped back into the rebuilt bytes — near enough to where
4163    /// it was, since the op preserves the cells' content and order around it.
4164    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
4165        match result {
4166            Ok(()) => {
4167                self.last_edit_kind = None;
4168                self.refresh();
4169                self.anchor = None;
4170                self.clamp_caret();
4171                self.dirty = self.source != self.clean_source;
4172                self.status = None;
4173                self.record_caret();
4174            }
4175            Err(e) => self.status = Some(format!("{what}: {e}")),
4176        }
4177    }
4178
4179    /// One `toggle_block_container` over the block-level target.
4180    ///
4181    /// leaf says *where*; twig decides everything else — which blocks the range
4182    /// covers, whether that means wrapping, unwrapping, nesting or converting,
4183    /// and how this document's format spells the prefix. The rule that a
4184    /// container only comes off when the range covers every block it holds is
4185    /// what the re-anchoring below is built around.
4186    fn toggle_container(&mut self, kind: BlockContainerKind) {
4187        // The read-only gate — this door reaches twig without the splice.
4188        if self.read_only {
4189            return;
4190        }
4191        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
4192            return;
4193        }
4194        let selected = self.selection();
4195        // A blank line holds no block, and twig opens an *empty* container on one
4196        // — since 3.2.0; it used to decline the range with `NotFound`, which is
4197        // why this used to lend it a scratch paragraph to wrap. Worth knowing
4198        // here because the line-for-line caret mapping below cannot describe it:
4199        // opening one under a paragraph writes the blank line the format needs
4200        // above the marker too, so the rewritten region has a line the old one
4201        // didn't, and "the same line, the same distance from its end" lands on
4202        // that new blank instead of in the container.
4203        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
4204        // Without a selection the target is the caret's own block, resolved the
4205        // way `set_block` resolves it — a caret at a line end sits at the doc
4206        // level and has to be nudged back onto the block it looks like it's in.
4207        // An empty range is enough: twig widens to the whole lines it touches.
4208        let (start, end) = match selected {
4209            Some(range) => range,
4210            None => {
4211                let off = self.block_offset_for_caret().unwrap_or(self.caret);
4212                (off, off)
4213            }
4214        };
4215        self.record_caret();
4216        match self.editor.toggle_block_container(start, end, kind) {
4217            Ok(change) => {
4218                // Read the caret's place out of the *pre-edit* source, before
4219                // `refresh` swaps that source out from under it.
4220                let place = (selected.is_none() && !opened_empty)
4221                    .then(|| self.caret_line_tail(&change.old));
4222                self.last_edit_kind = None; // structural edit is its own undo step
4223                self.refresh();
4224                match place {
4225                    // Both land the caret at the far end of what twig wrote, and
4226                    // differ only in what they leave selected.
4227                    //
4228                    // From a selection: select what the container now holds, the
4229                    // way `toggle` keeps its marked region selected — and for a
4230                    // stronger reason than symmetry: a container comes *off* only
4231                    // a range covering every block it holds, so a selection left
4232                    // on its old bytes (now short by a prefix per line) would nest
4233                    // on the second press instead of reversing the first.
4234                    //
4235                    // From a blank line: nothing to select, and the end of the
4236                    // region is exactly past the bare `> ` / `- ` twig wrote —
4237                    // the caret standing inside the container that was asked for.
4238                    None => {
4239                        self.anchor = (!opened_empty).then_some(change.new.start);
4240                        self.caret = change.new.end;
4241                    }
4242                    Some(place) => {
4243                        self.anchor = None;
4244                        self.caret = self.line_tail_offset(&change.new, place);
4245                    }
4246                }
4247                self.dirty = self.source != self.clean_source;
4248                self.status = None;
4249                self.clamp_caret();
4250                self.record_caret();
4251            }
4252            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
4253        }
4254    }
4255
4256    /// The caret's place inside the region a container toggle is rewriting, in
4257    /// the only terms the rewrite preserves: which of the region's lines it sits
4258    /// on, and how many bytes of that line lie ahead of it.
4259    ///
4260    /// A container's markup goes in at column 0 and never touches what follows
4261    /// on the line, so that pair survives the edit exactly where a byte offset
4262    /// does not — a caret left on its old offset slides back by one prefix per
4263    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
4264    /// `> ` it just asked for.
4265    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
4266        let caret = self.caret.clamp(old.start, old.end);
4267        let line = self.source[old.start..caret].matches('\n').count();
4268        let end = self.source[caret..old.end]
4269            .find('\n')
4270            .map_or(old.end, |i| caret + i);
4271        (line, end - caret)
4272    }
4273
4274    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
4275    /// region: the offset `tail` bytes back from the end of the region's `line`.
4276    ///
4277    /// Both walks are clamped rather than trusted, because the one op that does
4278    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
4279    /// the items back apart with blank lines between them — and a caret landing
4280    /// on the nearest line of the right item beats one landing out of the region
4281    /// entirely.
4282    fn line_tail_offset(
4283        &self,
4284        new: &std::ops::Range<usize>,
4285        (line, tail): (usize, usize),
4286    ) -> usize {
4287        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
4288        let mut start = 0;
4289        for _ in 0..line {
4290            match region[start..].find('\n') {
4291                Some(i) => start += i + 1,
4292                None => break,
4293            }
4294        }
4295        let end = region[start..]
4296            .find('\n')
4297            .map_or(region.len(), |i| start + i);
4298        new.start + end.saturating_sub(tail).max(start)
4299    }
4300
4301    /// Link the selection to `destination` — the toolbar's Link button. With no
4302    /// selection it acts at the caret, which re-points a link the caret is
4303    /// already standing in (twig replaces an existing link's destination and
4304    /// keeps its text) and otherwise spells a link that has no text of its own:
4305    /// an autolink (`<https://x.dev>`) where the destination is one, and
4306    /// `[destination](destination)` where it isn't.
4307    ///
4308    /// `destination` reaches twig raw. Escaping it is format knowledge and the
4309    /// two formats genuinely disagree — Markdown ends a destination at the first
4310    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
4311    /// itself — so the side holding the document is the side that gets to spell
4312    /// it. A destination twig can't carry at all (one with a newline) comes back
4313    /// as an error rather than a quietly rewritten URL.
4314    pub fn insert_link(&mut self, destination: &str) {
4315        if self.read_only || self.refuse_unsupported("link", Gesture::InsertLink) {
4316            return;
4317        }
4318        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
4319        self.record_caret();
4320        match self.editor.insert_link(start, end, destination) {
4321            Ok(change) => {
4322                self.last_edit_kind = None;
4323                self.refresh();
4324                match self.link_text_span(change.new.start) {
4325                    // A link with text of its own: select it, so typing replaces
4326                    // a `[dest](dest)`'s stand-in label and a second press
4327                    // re-points what the first one linked.
4328                    Some(text) => {
4329                        self.anchor = (text.start != text.end).then_some(text.start);
4330                        self.caret = text.end;
4331                    }
4332                    // An autolink is finished the moment it's written — its text
4333                    // *is* the URL. Leaving it selected would aim the next press
4334                    // at the one shape twig still wraps instead of re-points.
4335                    None => {
4336                        self.anchor = None;
4337                        self.caret = change.new.end;
4338                    }
4339                }
4340                self.dirty = self.source != self.clean_source;
4341                self.status = None;
4342                self.clamp_caret();
4343                self.record_caret();
4344            }
4345            Err(e) => self.status = Some(format!("link: {e}")),
4346        }
4347    }
4348
4349    /// Insert a block-level image at the caret: `![alt](destination)`. Any
4350    /// selection becomes the alt text (so "select a caption, insert image" labels
4351    /// it); with no selection, `alt` is used — empty for none. The caret lands
4352    /// just past the inserted image.
4353    ///
4354    /// Both halves go through twig (`insert_literal` for the alt text,
4355    /// `insert_image` for the image), so neither is spelled here. That used to be a
4356    /// `format!`, and it was wrong the first time an app inserted a real filename:
4357    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
4358    /// not an image at all — and the fix is per-format, since moving into the
4359    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
4360    pub fn insert_image(&mut self, destination: &str, alt: &str) {
4361        if self.read_only || self.refuse_unsupported("image", Gesture::InsertImage) {
4362            return;
4363        }
4364        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
4365        self.record_caret();
4366        // With no selection and an explicit `alt`, the alt text has to exist in the
4367        // document before it can be the image's — and it is raw caller input, so
4368        // it goes in through `insert_literal`, which escapes it for the format
4369        // rather than letting a `]` in someone's caption close the image early.
4370        let (start, end) = if start == end && !alt.is_empty() {
4371            match self.editor.insert_literal(start, alt) {
4372                Ok(change) => (change.new.start, change.new.end),
4373                Err(e) => {
4374                    self.status = Some(format!("image: {e}"));
4375                    return;
4376                }
4377            }
4378        } else {
4379            (start, end)
4380        };
4381        match self.editor.insert_image(start, end, destination) {
4382            Ok(change) => {
4383                self.last_edit_kind = None;
4384                self.refresh();
4385                // Just past the image, nothing selected — where a caret belongs
4386                // after inserting one.
4387                self.anchor = None;
4388                self.caret = change.new.end;
4389                self.dirty = self.source != self.clean_source;
4390                self.status = None;
4391                self.clamp_caret();
4392                self.record_caret();
4393            }
4394            Err(e) => self.status = Some(format!("image: {e}")),
4395        }
4396    }
4397
4398    /// Insert a block-level image, video, or audio at the caret. The image case
4399    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
4400    /// HTML elements, which is the only spelling Markdown and Djot have for them:
4401    ///
4402    /// ```text
4403    /// <video src="clip.mp4" controls>alt</video>
4404    /// <audio src="take.mp3" controls>alt</audio>
4405    /// ```
4406    ///
4407    /// HTML rather than a `::video{…}` directive deliberately. A directive means
4408    /// something only to an app that knows the vocabulary, so the document would
4409    /// read as literal punctuation everywhere else; `<video>` is what every other
4410    /// renderer already understands, and what leaf's own reader picks back up
4411    /// through `html_elements` promotion (see [`parse_extensions`]).
4412    ///
4413    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
4414    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
4415    /// `html_elements`. Before that only the multi-line form parsed as a block at
4416    /// all, and this wrote three lines to work around it.
4417    ///
4418    /// `controls` is always written: a player with no transport is a still frame
4419    /// the reader can't do anything with. Any selection becomes the element's
4420    /// fallback text, exactly as it becomes an image's alt.
4421    ///
4422    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
4423    /// applies, and bites harder here: a `"` in `destination` closes the
4424    /// attribute. A frontend taking these from a file picker is fine; one taking
4425    /// them from free text should keep them tame.
4426    ///
4427    /// [`MediaInfo`]: crate::MediaInfo
4428    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
4429        if kind == MediaKind::Image {
4430            return self.insert_image(destination, alt);
4431        }
4432        // Gated on the *image* gesture, not on one of its own — there isn't one,
4433        // since the bytes below are spelled here rather than by twig, and an HTML
4434        // document would in fact parse them. The button is one control with three
4435        // kinds behind it, and two of them working in a format where the third
4436        // cannot is a worse surface than three that agree — especially as
4437        // `insert_image` is the kind anyone reaches for first.
4438        if self.refuse_unsupported("media", Gesture::InsertImage) {
4439            return;
4440        }
4441        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
4442        let alt_text = self
4443            .selected_text()
4444            .map(str::to_string)
4445            .unwrap_or_else(|| alt.to_string());
4446        let tag = match kind {
4447            MediaKind::Audio => "audio",
4448            _ => "video",
4449        };
4450        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
4451        self.edit(start, end, &markup);
4452    }
4453
4454    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
4455    /// button. Spelling and placement are both twig's; leaf used to write `---`
4456    /// itself, which was the Markdown spelling in a djot document too.
4457    ///
4458    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
4459    /// mid-paragraph and lands it after the caret's whole block. To get a rule
4460    /// *at* the caret — the paragraph parted in two around it, which is what a
4461    /// rule button is understood to do — the paragraph is first divided with
4462    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
4463    /// the offset `split_block` returns puts the rule after the *second* half
4464    /// instead, which is a rule in the right document and the wrong place.
4465    ///
4466    /// Only a plain paragraph is split. Everywhere else the rule simply lands
4467    /// after the block, which is both twig's own answer and the better one:
4468    /// splitting a fenced code block would leave two fences with a rule between
4469    /// them, and splitting a list item would mint an item nobody asked for on the
4470    /// way to a rule that lands after the list regardless. A table and a setext
4471    /// heading refuse the split outright, so they take the same path by
4472    /// themselves.
4473    pub fn insert_thematic_break(&mut self) {
4474        if self.read_only || self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak)
4475        {
4476            return;
4477        }
4478        self.caret = self.skip_trailing_close_delims(self.caret);
4479        // A selection is replaced by the rule, so collapse it first and let the
4480        // split-and-rule below run from the caret it leaves behind.
4481        if let Some((s, e)) = self.selection() {
4482            self.splice(s, e, "", EditKind::Other);
4483        }
4484        self.anchor = None;
4485        self.record_caret();
4486        let at = self.caret;
4487        if self.caret_in_bare_paragraph() {
4488            // A failure here is not fatal: the rule still lands after the block,
4489            // which is exactly what this call was trying to improve on.
4490            let _ = self.editor.split_block(at);
4491        }
4492        match self.editor.insert_thematic_break(at) {
4493            Ok(change) => {
4494                self.last_edit_kind = None;
4495                self.refresh();
4496                self.anchor = None;
4497                self.caret = change.new.end;
4498                self.dirty = self.source != self.clean_source;
4499                self.status = None;
4500                self.clamp_caret();
4501                self.record_caret();
4502            }
4503            Err(e) => self.status = Some(format!("thematic break: {e}")),
4504        }
4505    }
4506
4507    /// Whether the caret sits in a paragraph and nothing else — no list item, no
4508    /// quote, no fence, no table. The one shape where parting the block around
4509    /// the caret is unambiguously what a rule button means; see
4510    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
4511    /// container is left to take the rule after itself.
4512    fn caret_in_bare_paragraph(&mut self) -> bool {
4513        let caret = self.caret.min(self.source.len());
4514        let Ok(chain) = self.editor.ancestors_at(caret) else {
4515            return false;
4516        };
4517        let mut in_para = false;
4518        for m in chain {
4519            match m.kind {
4520                Kind::Para => in_para = true,
4521                Kind::ListItem
4522                | Kind::TaskListItem
4523                | Kind::BlockQuote
4524                | Kind::CodeBlock
4525                | Kind::Table => return false,
4526                _ => {}
4527            }
4528        }
4529        in_para
4530    }
4531
4532    /// The destination of the link under the caret — what a Link prompt shows so
4533    /// ⌘K on an existing link edits its URL instead of asking for it again.
4534    /// `None` when the caret stands in no link.
4535    ///
4536    /// An autolink carries no separate destination: its text *is* the URL, so
4537    /// that's what comes back for one.
4538    pub fn link_destination_at_caret(&mut self) -> Option<String> {
4539        self.link_destination_at(self.caret)
4540    }
4541
4542    /// The destination of the link at `off`.
4543    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
4544    /// the caret isn't.
4545    ///
4546    /// The offset form exists for the same reason
4547    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
4548    /// the document somewhere else — a footnote's text in a popover, say — has
4549    /// rows and runs but no caret in them, and still needs to know which of those
4550    /// runs a reader can follow.
4551    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
4552        self.nodes()
4553            .into_iter()
4554            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
4555            .filter(|n| n.span.start <= off && off < n.span.end)
4556            .max_by_key(|n| n.span.start)
4557            .and_then(|n| n.destination.or(n.text))
4558    }
4559
4560    /// Where the locator `id` lands in this document — the `#v2` half of a
4561    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
4562    /// answers to it.
4563    ///
4564    /// The other end of a link, and the reason this exists: without it a
4565    /// destination has only file granularity, so following a citation into a
4566    /// chapter drops the reader at the top of it to hunt for the verse. Which is
4567    /// also why it is a *document* query rather than a caret one — the document
4568    /// being asked is usually not the one the reader is in.
4569    ///
4570    /// Three readings, tried in order, because the same `#some-heading` is
4571    /// written three ways across the formats leaf opens:
4572    ///
4573    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
4574    ///    the auto-ids djot mints for its headings. The only exact answer, so it
4575    ///    goes first — a document that says `{#v1}` has settled the question.
4576    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
4577    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
4578    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
4579    ///    authored anywhere land on a djot heading.
4580    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
4581    ///    none and `{#custom}` is literal text in a Markdown heading — so for
4582    ///    the format most vaults are written in, the heading's own words are the
4583    ///    only thing a fragment can name. This is the rule every Markdown
4584    ///    renderer already follows, which is what makes `#a-heading` mean in
4585    ///    diaryx what it means on the web.
4586    ///
4587    /// Ties go to the earliest match, then to the widest: a duplicated id is the
4588    /// document's mistake and the first one is the answer every anchor
4589    /// implementation gives, while preferring the wider span picks the section
4590    /// over the heading that opens it — more for a peek to show, same place to
4591    /// land.
4592    pub fn locate(&mut self, id: &str) -> Option<Landing> {
4593        let id = id.trim();
4594        if id.is_empty() {
4595            return None;
4596        }
4597        let nodes = self.nodes();
4598
4599        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
4600        // is picking, among nodes that start together, the one that ends last.
4601        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
4602            matches
4603                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
4604                .map(|n| Landing {
4605                    start: n.span.start,
4606                    end: n.span.end,
4607                })
4608        };
4609
4610        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
4611            return Some(landing);
4612        }
4613        let want = slug(id);
4614        if want.is_empty() {
4615            return None;
4616        }
4617        if let Some(landing) = pick(
4618            &mut nodes
4619                .iter()
4620                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
4621        ) {
4622            return Some(landing);
4623        }
4624
4625        // A heading by its words. Its span is one line, so the end comes from
4626        // where the *section* it opens gives out — the next heading that is not
4627        // under it, or the end of the document. A Markdown heading has no
4628        // section node to ask (twig only builds those for djot), and a peek that
4629        // showed the heading alone would answer "what does that say" with the
4630        // title of the thing it says.
4631        let heading = nodes
4632            .iter()
4633            .filter(|n| n.kind == Kind::Heading)
4634            .filter(|n| {
4635                n.content_span
4636                    .clone()
4637                    .and_then(|s| self.source.get(s))
4638                    .is_some_and(|text| slug(text) == want)
4639            })
4640            .min_by_key(|n| n.span.start)?;
4641        let level = heading.level.unwrap_or(u32::MAX);
4642        let end = nodes
4643            .iter()
4644            .filter(|n| n.kind == Kind::Heading)
4645            .filter(|n| n.span.start > heading.span.start)
4646            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
4647            .map(|n| n.span.start)
4648            .min()
4649            .unwrap_or(self.source.len());
4650        Some(Landing {
4651            start: heading.span.start,
4652            end,
4653        })
4654    }
4655
4656    /// Write a footnote at the caret — the toolbar's Footnote button, and the
4657    /// one gesture in the footnote story that *authors* rather than follows.
4658    ///
4659    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
4660    /// the `[^1]:` definition at the end of the document. Half a footnote is not
4661    /// a footnote — a bare reference with nothing defining it renders as literal
4662    /// brackets — so a single button that wrote only the reference would leave
4663    /// the author to hand-spell the other half in a document that had just
4664    /// stopped showing them what the first half meant. One edit also means one
4665    /// undo takes both back.
4666    ///
4667    /// The definition's body is left empty and **the caret lands in it**, which
4668    /// is the whole point of pressing the button: nobody wants a reference to a
4669    /// note they have not written yet. Getting back to where they were writing
4670    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
4671    /// the same return leg a reader following a reference already uses, so the
4672    /// author is left standing on the near end of a round trip that works.
4673    ///
4674    /// A selection collapses to its *end* rather than being replaced: a
4675    /// reference annotates the words before it, so "select the claim, add a
4676    /// footnote" should mark that claim, not consume it.
4677    pub fn insert_footnote(&mut self) {
4678        if self.read_only || self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
4679            return;
4680        }
4681        let at = self.selection().map_or(self.caret, |(_, end)| end);
4682        self.anchor = None;
4683        self.caret = at;
4684        self.record_caret();
4685        let label = self.next_footnote_label();
4686        match self.editor.insert_footnote(at, &label) {
4687            Ok(change) => {
4688                self.last_edit_kind = None;
4689                self.refresh();
4690                self.anchor = None;
4691                // `change.new` runs from the reference to the end of the
4692                // document, so its start is the `[^1]` just written and
4693                // `footnote_at` resolves it to the note the same way a reader's
4694                // tap does — and to the note's *body*, which is already a caret
4695                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
4696                // and has none), so this needs no snap on top. The fallback is
4697                // the reference's own offset: a format that spelled the pair some
4698                // way leaf can't read back should still leave the caret on the
4699                // edit rather than at the far end of a document it just grew.
4700                self.caret = self
4701                    .footnote_at(change.new.start)
4702                    .and_then(|note| note.offset)
4703                    .unwrap_or(change.new.start);
4704                self.dirty = self.source != self.clean_source;
4705                self.status = None;
4706                self.clamp_caret();
4707                self.record_caret();
4708            }
4709            Err(e) => self.status = Some(format!("footnote: {e}")),
4710        }
4711    }
4712
4713    /// The label to give a footnote the author has not named: the lowest counting
4714    /// number no footnote in the document is already wearing.
4715    ///
4716    /// twig takes the label rather than minting one, because it holds no opinion
4717    /// about what a document's footnotes should be called — and it is right not
4718    /// to. Numbering them is what every author of a numbered note expects, and
4719    /// re-using a taken number would silently point the new reference at somebody
4720    /// else's note (twig reuses an existing definition rather than appending a
4721    /// second one, which is the right rule for citing a note twice on purpose and
4722    /// exactly the wrong accident to have by default).
4723    ///
4724    /// *References* are counted alongside definitions, not just definitions: a
4725    /// document carrying a dangling `[^2]` has a 2 that means something to
4726    /// whoever wrote it, and minting a definition for it here would answer a
4727    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
4728    /// count entirely — they take no number, so they block none.
4729    fn next_footnote_label(&mut self) -> String {
4730        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
4731            .into_iter()
4732            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
4733            .filter_map(|label| label.parse().ok())
4734            .collect();
4735        taken.extend(
4736            self.nodes()
4737                .into_iter()
4738                .filter(|n| n.kind == Kind::FootnoteReference)
4739                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
4740                .filter_map(|label| label.parse::<u32>().ok()),
4741        );
4742        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
4743    }
4744
4745    /// The footnote reference under the caret, resolved to the note it names.
4746    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
4747    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
4748        self.footnote_at(self.caret)
4749    }
4750
4751    /// The footnote reference at `off`, resolved to the note it names — what a
4752    /// frontend shows when a reader activates a `[^1]`.
4753    ///
4754    /// A reference is not a link node, so
4755    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
4756    /// (and should not) answer for one: a link names a destination to leave for,
4757    /// a reference names a note that is already in this document. Following one
4758    /// is a move within the page, which is why this hands back an `offset`
4759    /// rather than something to open.
4760    ///
4761    /// Offset-based rather than caret-only because the gesture that wants this
4762    /// most is the one that must not move the caret: a pointer hovering a `[1]`
4763    /// asks what note it names without disturbing where the reader was typing.
4764    /// The caret is just the offset a click already placed —
4765    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
4766    ///
4767    /// `None` when `off` stands in no reference. A reference whose note the
4768    /// document never defines is *not* `None` — it answers with the label it
4769    /// looked for and no text, which is what lets a frontend say so instead of
4770    /// silently doing nothing.
4771    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
4772        // Innermost-wins by latest start, the rule its link sibling uses.
4773        let span = self
4774            .nodes()
4775            .into_iter()
4776            .filter(|n| n.kind == Kind::FootnoteReference)
4777            .filter(|n| n.span.start <= off && off < n.span.end)
4778            .max_by_key(|n| n.span.start)?
4779            .span;
4780        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();
4781
4782        // The note itself. Definitions are roots beside `doc` rather than
4783        // children of it, so they're asked for directly — see
4784        // `wysiwyg::footnote_definitions`.
4785        let note = wysiwyg::footnote_definitions(&mut self.editor)
4786            .into_iter()
4787            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
4788        let Some(note) = note else {
4789            return Some(FootnoteRef {
4790                label,
4791                text: None,
4792                offset: None,
4793                end: None,
4794            });
4795        };
4796        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
4797        Some(FootnoteRef {
4798            label,
4799            text: body
4800                .clone()
4801                .and_then(|b| self.source.get(b))
4802                .map(str::to_string),
4803            // The body's start, not the definition's — see `FootnoteRef::offset`.
4804            offset: body.clone().map(|b| b.start),
4805            end: body.map(|b| b.end),
4806        })
4807    }
4808
4809    /// The footnote *definition* the caret stands in, and where the reference
4810    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
4811    /// at the caret's offset.
4812    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
4813        self.footnote_definition_at(self.caret)
4814    }
4815
4816    /// The footnote definition spanning `off`, and where the reference that
4817    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
4818    ///
4819    /// The mirror image, deliberately: the same gesture that takes a reader from
4820    /// `[1]` down to the note takes them from the note back up to `[1]`, so
4821    /// following a footnote is a round trip rather than a fall. It needs no
4822    /// memory of how the reader arrived — the document says where the reference
4823    /// is — which is what makes it work for a reader who scrolled to the notes
4824    /// themselves, and what keeps it right after an edit moves either end.
4825    ///
4826    /// `None` when `off` stands in no definition. A definition nothing cites is
4827    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
4828    /// its label and no offset, so a frontend can say "nothing refers to this"
4829    /// rather than offer a jump that goes nowhere.
4830    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
4831        // Definitions are roots beside `doc`, so `nodes()` — which walks the
4832        // document body — never reports one. They're asked for directly, the way
4833        // `footnote_at` asks for the note it resolves to.
4834        //
4835        // Closed at the end, unlike the half-open test its neighbours use. A
4836        // definition's span stops at its last content byte — the newline ending
4837        // the line is outside it — so `span.end` is the caret stop at the end of
4838        // the note's own row, not the first byte of anything after. Excluding it
4839        // meant the one caret an author is guaranteed to have, the one left
4840        // sitting at the end of the note they just typed, was in no definition at
4841        // all: writing a note and then asking to go back to its reference
4842        // answered nothing. Two definitions in a row still can't both match —
4843        // there is a blank line between them — and `max_by_key` decides anyway.
4844        let note = wysiwyg::footnote_definitions(&mut self.editor)
4845            .into_iter()
4846            .filter(|m| m.span.start <= off && off <= m.span.end)
4847            .max_by_key(|m| m.span.start)?;
4848        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();
4849
4850        // The earliest reference carrying this label. `min` rather than a `find`,
4851        // because `nodes()` reports a flattened walk whose order is twig's
4852        // business, not document order. Bound first: the walk needs `&mut self`
4853        // and reading the labels back out needs `&self.source`.
4854        let nodes = self.nodes();
4855        let offset = nodes
4856            .into_iter()
4857            .filter(|n| n.kind == Kind::FootnoteReference)
4858            .filter(|n| {
4859                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
4860            })
4861            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
4862            .map(|n| n.span.start + 2)
4863            .min();
4864        Some(FootnoteDef { label, offset })
4865    }
4866
4867    /// The destination of the image under the caret — what an image prompt shows
4868    /// so editing an existing image starts from its current URL instead of blank,
4869    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
4870    /// `None` when the caret stands in no image. A caret resting just after a
4871    /// block image (its trailing stop) is still "in" it — the half-open span test
4872    /// excludes that offset, which is the intended precision: past the image is
4873    /// past it.
4874    pub fn image_destination_at_caret(&mut self) -> Option<String> {
4875        let off = self.caret;
4876        self.nodes()
4877            .into_iter()
4878            .filter(|n| n.kind == Kind::Image)
4879            .filter(|n| n.span.start <= off && off < n.span.end)
4880            .max_by_key(|n| n.span.start)
4881            .and_then(|n| n.destination)
4882    }
4883
4884    /// The language of the fenced code block the caret stands in — what a
4885    /// language prompt shows so editing it starts from the current value rather
4886    /// than blank. `None` when the caret is in no code block, or in one whose
4887    /// fence carries no language (or an indented block, which has no fence).
4888    pub fn code_language_at_caret(&mut self) -> Option<String> {
4889        let start = self.code_block_start_at_caret()?;
4890        wysiwyg::code_language(&self.source, start)
4891    }
4892
4893    /// Whether the caret stands in a fenced code block — the one a language
4894    /// prompt could edit. A frontend gates its "set language" affordance on this
4895    /// (an indented block, which can't carry a language, reports `false`).
4896    pub fn caret_in_fenced_code(&mut self) -> bool {
4897        self.code_block_start_at_caret()
4898            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
4899    }
4900
4901    /// Set (or clear, with `""`) the language of the fenced code block the caret
4902    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
4903    /// block, and a reported error for a language the format's fence cannot
4904    /// carry.
4905    ///
4906    /// twig rewrites the info string, so the fence's own width — measured
4907    /// against a body neither side touches — is kept, and a language holding a
4908    /// space, a line end or the fence character is refused rather than written
4909    /// out to reparse as something else. Leaf used to splice over the info span
4910    /// itself and `trim()` the input, which handled the one bad case it had
4911    /// thought of.
4912    pub fn set_code_language(&mut self, lang: &str) {
4913        // The read-only gate — this door reaches twig without the splice.
4914        if self.read_only {
4915            return;
4916        }
4917        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
4918            return;
4919        }
4920        if self.code_block_start_at_caret().is_none() {
4921            return;
4922        }
4923        let lang = lang.trim();
4924        // `None` clears the info string; `Some("")` asks for an empty one. Both
4925        // write a bare fence, and the prompt's empty value means "clear".
4926        let want = (!lang.is_empty()).then_some(lang);
4927        self.record_caret();
4928        match self.editor.set_code_language(self.caret, want) {
4929            Ok(_) => {
4930                self.last_edit_kind = None;
4931                self.refresh();
4932                self.anchor = None;
4933                self.dirty = self.source != self.clean_source;
4934                self.status = None;
4935                self.clamp_caret();
4936                self.record_caret();
4937            }
4938            Err(e) => self.status = Some(format!("code language: {e}")),
4939        }
4940    }
4941
4942    /// The `span.start` of the code block covering the caret — the anchor
4943    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
4944    /// in none.
4945    fn code_block_start_at_caret(&mut self) -> Option<usize> {
4946        let off = self.caret;
4947        self.nodes()
4948            .into_iter()
4949            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
4950            .max_by_key(|n| n.span.start)
4951            .map(|n| n.span.start)
4952    }
4953
4954    /// The source range of the text inside the link covering `off` — what sits
4955    /// between its `[` and `]`. `None` when twig reports no link there.
4956    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
4957        self.nodes()
4958            .into_iter()
4959            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
4960            // the other's `span.start`; the link that starts latest at or before
4961            // `off` is the one `off` is actually in.
4962            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
4963            .max_by_key(|n| n.span.start)
4964            .and_then(|n| n.content_span)
4965    }
4966
4967    // ── undo / redo ───────────────────────────────────────────────────────────
4968    // twig owns the history of *bytes* (it owns the buffer) and now carries the
4969    // caret through it too: `record_caret` stashes each state's caret in twig's
4970    // opaque per-step blob, and undo/redo hand it back with the source they
4971    // restore. So leaf keeps no history of its own — no parallel stacks to march
4972    // in lockstep and silently drift out of it.
4973
4974    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
4975    /// where they were when that step began.
4976    pub fn undo(&mut self) {
4977        if self.read_only {
4978            return;
4979        }
4980        let (undone, redoable) = (self.undo_steps, self.redo_steps);
4981        match self.editor.undo() {
4982            Ok(Some(change)) => {
4983                self.after_history(change);
4984                // `refresh` counted the restore as an edit; it was a step back.
4985                self.undo_steps = undone.saturating_sub(1);
4986                self.redo_steps = redoable + 1;
4987            }
4988            Ok(None) => {
4989                self.undo_steps = 0;
4990                self.status = Some("nothing to undo".into());
4991            }
4992            Err(e) => self.status = Some(format!("undo: {e}")),
4993        }
4994    }
4995
4996    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
4997    /// selection back where that step originally left them.
4998    pub fn redo(&mut self) {
4999        if self.read_only {
5000            return;
5001        }
5002        let (undone, redoable) = (self.undo_steps, self.redo_steps);
5003        match self.editor.redo() {
5004            Ok(Some(change)) => {
5005                self.after_history(change);
5006                // `refresh` counted the restore as an edit; it was a step forward.
5007                self.undo_steps = undone + 1;
5008                self.redo_steps = redoable.saturating_sub(1);
5009            }
5010            Ok(None) => {
5011                self.redo_steps = 0;
5012                self.status = Some("nothing to redo".into());
5013            }
5014            Err(e) => self.status = Some(format!("redo: {e}")),
5015        }
5016    }
5017
5018    /// Refresh the cached source and put the caret back where the step being
5019    /// undone/redone had it, clearing any active run.
5020    ///
5021    /// The caret comes from twig's blob for the restored state (what
5022    /// `record_caret` stored). `change` is only the fallback for a state with no
5023    /// blob — a caret at the end of the restored text, which is where this always
5024    /// landed before the blobs were kept. It is the edit site, not where the user
5025    /// was standing, so it's a floor and not the behaviour: undoing should hand
5026    /// back the document *and* the place you were working, which for an edit made
5027    /// anywhere but under the caret are two different places.
5028    fn after_history(&mut self, change: Change) {
5029        self.refresh();
5030        match self
5031            .editor
5032            .caret_blob()
5033            .ok()
5034            .and_then(|b| CaretState::from_blob(&b))
5035        {
5036            Some(state) => {
5037                self.caret = state.caret.min(self.source.len());
5038                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
5039            }
5040            None => {
5041                self.caret = change.new.end.min(self.source.len());
5042                self.anchor = None;
5043            }
5044        }
5045        self.goal_col = None;
5046        self.last_edit_kind = None;
5047        self.dirty = self.source != self.clean_source;
5048        self.status = None;
5049        self.clamp_caret();
5050    }
5051
5052    // ── the file ──────────────────────────────────────────────────────────────
5053
5054    #[cfg(feature = "fs")]
5055    pub fn save(&mut self) {
5056        if self.is_untitled() {
5057            // No path to write and no name to invent: ⌘S on an untitled document
5058            // is a Save As, and only a frontend has a picker to ask with. Say so
5059            // rather than failing at the filesystem with an empty path.
5060            self.status = Some("untitled — save as…".into());
5061            return;
5062        }
5063        let path = self.path.clone();
5064        if self.write(&path) {
5065            self.mark_saved();
5066        }
5067    }
5068
5069    /// Save As: write the document to `path` and *move* it there — `self.path`
5070    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
5071    /// what Save As means; a copy would leave the user editing a document whose
5072    /// name is no longer where their keystrokes go.
5073    ///
5074    /// The move only happens if the bytes actually landed. A failed write leaves
5075    /// the path, `dirty`, and the disk watermark exactly as they were, with the
5076    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
5077    /// must never come away believing it was saved.
5078    ///
5079    /// An existing `path` is overwritten, and the caller is the one that knows
5080    /// whether to ask first: a Save As picker has already run that prompt, and a
5081    /// second confirmation from down here would be the same question twice.
5082    ///
5083    /// `format` does **not** follow the new extension. The buffer is parsed as
5084    /// the format it was opened with, and re-reading it as another one is a
5085    /// conversion — a different, lossy operation that would throw away the undo
5086    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
5087    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
5088    /// until it's reopened.
5089    #[cfg(feature = "fs")]
5090    pub fn save_as(&mut self, path: PathBuf) {
5091        if !self.write(&path) {
5092            return;
5093        }
5094        self.path = path;
5095        self.mark_saved();
5096    }
5097
5098    /// Put `source` on disk at `path`, reporting whether it got there. The one
5099    /// place leaf writes a document, so a save and a Save As can't disagree
5100    /// about what a failure looks like.
5101    #[cfg(feature = "fs")]
5102    fn write(&mut self, path: &Path) -> bool {
5103        match std::fs::write(path, self.source.as_bytes()) {
5104            Ok(()) => true,
5105            Err(e) => {
5106                self.status = Some(format!("save failed: {e}"));
5107                false
5108            }
5109        }
5110    }
5111
5112    /// Re-base the document's saved watermark to the current bytes: clears
5113    /// `dirty`, records `source` as the new clean state (so undoing back to here
5114    /// clears the flag again), and re-stamps the on-disk hash.
5115    ///
5116    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
5117    /// the hook a **filesystem-free host** calls itself once it has persisted
5118    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
5119    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
5120    /// are already where that host wants them, and this just tells the model they
5121    /// are safe.
5122    pub fn mark_saved(&mut self) {
5123        self.clean_source = self.source.clone();
5124        self.dirty = false;
5125        // The bytes on disk are now ours, so this is the new watermark: without
5126        // re-stamping it, every save would report its own work as an external
5127        // change forever after.
5128        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
5129        self.status = Some(format!("saved {}", self.file_name()));
5130    }
5131
5132    /// What the file looks like now against the bytes leaf last read or wrote.
5133    ///
5134    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
5135    /// so this is a filesystem round-trip, not a per-frame question — ask it
5136    /// when a window regains focus, on a timer, or before a save.
5137    ///
5138    /// This *only* reports the file. Whether the document also has unsaved edits
5139    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
5140    /// [`DiskState::Changed`] means a save overwrites someone's work and a
5141    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
5142    /// it has no way to ask — so it hands a frontend both halves and lets it put
5143    /// the question to the person who can answer it.
5144    #[cfg(feature = "fs")]
5145    pub fn disk_state(&self) -> DiskState {
5146        let Some(want) = self.disk_hash else {
5147            return DiskState::Untitled;
5148        };
5149        match std::fs::read(&self.path) {
5150            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
5151            Ok(_) => DiskState::Changed,
5152            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
5153            Err(_) => DiskState::Unreadable,
5154        }
5155    }
5156
5157    /// Re-read the file and replace the document with what's there — the other
5158    /// answer to a [`DiskState::Changed`].
5159    ///
5160    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
5161    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
5162    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
5163    /// document shouldn't have to argue with a guard.
5164    ///
5165    /// **The undo history survives, and the reload is one step in it.** The
5166    /// whole buffer is spliced with the file's bytes through the same door every
5167    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
5168    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
5169    /// swapped the document out from under a reader gives them back what they
5170    /// were looking at, marked dirty, and ^Z again carries on into whatever they
5171    /// had done before it. This used to build a fresh parse and drop the stack,
5172    /// on the reasoning that twig's history belongs to the buffer and these are
5173    /// different bytes; that is true of *rebasing* a step onto them and not of
5174    /// recording the swap itself as one, which is all this is. A splice twig
5175    /// won't take falls back to the fresh parse, and only that path still costs
5176    /// the history.
5177    ///
5178    /// The caret keeps its byte offset, clamped to the new length; the selection
5179    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
5180    /// file changed, so it can't know where the caret "still" is. Clamping keeps
5181    /// it where the user left it in the common case (a change further down the
5182    /// file, or none in the text they're sitting in), and never puts it
5183    /// somewhere invalid. A selection has two such offsets and no such excuse —
5184    /// silently reinterpreting one over changed bytes would arm the *next*
5185    /// keystroke to delete something the user never selected.
5186    ///
5187    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
5188    /// document alone with a status.
5189    #[cfg(feature = "fs")]
5190    pub fn reload(&mut self) {
5191        if self.is_untitled() {
5192            self.status = Some("no file to reload".into());
5193            return;
5194        }
5195        let bytes = match std::fs::read(&self.path) {
5196            Ok(b) => b,
5197            Err(e) => {
5198                self.status = Some(format!("reload failed: {e}"));
5199                return;
5200            }
5201        };
5202        let Ok(source) = String::from_utf8(bytes) else {
5203            self.status = Some("reload failed: file is not UTF-8".into());
5204            return;
5205        };
5206        // Already these bytes — someone saved a file back unchanged, or leaf's
5207        // own write is being read back. Re-baseline against it and stop: a
5208        // splice of the text onto itself would put an undo step on the stack for
5209        // something nobody did.
5210        if source == self.source {
5211            self.disk_hash = Some(hash_bytes(source.as_bytes()));
5212            self.clean_source = source;
5213            self.dirty = false;
5214            self.status = Some(format!("reloaded {}", self.file_name()));
5215            return;
5216        }
5217        let caret = self.caret;
5218        // The pre-reload caret, so undoing the swap puts it back where the
5219        // reader was standing — the same bracketing `splice_exact` does.
5220        self.record_caret();
5221        if self
5222            .editor
5223            .edit_range(0, self.source.len(), &source)
5224            .is_ok()
5225        {
5226            self.refresh();
5227        } else {
5228            // twig wouldn't take the splice. Start over from the bytes, which is
5229            // what this always did, and is the one path that still costs the
5230            // history — `format` is the format this document *is*, not what the
5231            // (unchanged) name now says, see `save_as`.
5232            match new_editor(source.as_bytes(), self.format) {
5233                Ok(editor) => {
5234                    self.editor = editor;
5235                    self.source = source.clone();
5236                    // Not going through `refresh`, so the revision has to move
5237                    // here or every frontend keeps painting the old file from
5238                    // cache.
5239                    self.revision += 1;
5240                }
5241                Err(e) => {
5242                    self.status = Some(format!("reload failed: {e}"));
5243                    return;
5244                }
5245            }
5246        }
5247        self.disk_hash = Some(hash_bytes(source.as_bytes()));
5248        self.clean_source = self.source.clone();
5249        self.caret = caret.min(self.source.len());
5250        self.anchor = None;
5251        self.goal_col = None;
5252        self.last_edit_kind = None;
5253        self.dirty = false;
5254        self.status = Some(format!("reloaded {}", self.file_name()));
5255        self.clamp_caret();
5256        // And the post-reload caret, so a redo restores it.
5257        self.record_caret();
5258    }
5259
5260    /// Re-read the source from twig after it has changed the document. The one
5261    /// funnel every edit, undo, and redo comes through — so it's where the
5262    /// revision moves, and anything cached against the text dies here.
5263    fn refresh(&mut self) {
5264        if let Ok(s) = self.editor.source_str() {
5265            self.source = s;
5266        }
5267        self.revision += 1;
5268        // An edit is a step onto the history and the end of anything undone;
5269        // `undo`/`redo` come through here too and correct this after.
5270        self.undo_steps += 1;
5271        self.redo_steps = 0;
5272        self.clamp_caret();
5273    }
5274
5275    /// Whether [`undo`](Self::undo) has a step to take back — for a native
5276    /// Edit menu to enable its item by. See the note on `undo_steps` for what
5277    /// "has" means here.
5278    pub fn can_undo(&self) -> bool {
5279        !self.read_only && self.undo_steps > 0
5280    }
5281
5282    /// Whether [`redo`](Self::redo) has an undone step to restore.
5283    pub fn can_redo(&self) -> bool {
5284        !self.read_only && self.redo_steps > 0
5285    }
5286
5287    // ── caret movement ─────────────────────────────────────────────────────────
5288    // `extend` grows the selection (Shift+motion): it pins the anchor on the
5289    // first extended step and moves only the caret; an un-extended motion drops
5290    // the selection.
5291
5292    /// Place the caret at byte `offset` (clamped to a char boundary), extending
5293    /// the selection when `extend` is set. The public form of `move_to`, for a
5294    /// frontend that hit-tests pixels straight to a source offset.
5295    pub fn place_caret(&mut self, offset: usize, extend: bool) {
5296        self.goal_col = None;
5297        let before = self.caret;
5298        // A pixel hit-test can land between the visible caret stops — in the
5299        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
5300        // Snap to the nearest real stop so the caret can't come to rest where it
5301        // would draw in one place and type in another. The `(row, col)` click
5302        // path (`click`) already snaps this way through `offset_of_pos`; the
5303        // source view reaches every byte, so it snaps to nothing.
5304        let target = match self.view {
5305            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
5306            // The source view reaches every byte, so there is no stop to snap
5307            // to — but "every byte" still means every *character* boundary. A
5308            // caret resting inside a multi-byte character draws nowhere real
5309            // and panics the next time anything slices there.
5310            View::Source => self.char_boundary_at_or_before(offset),
5311        };
5312        self.move_to(target, extend);
5313        self.clamp_caret();
5314        self.debug_assert_on_a_stop(before);
5315    }
5316
5317    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
5318    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
5319    /// grab the metadata) while the source view still selects the literal whole.
5320    pub fn select_all(&mut self) {
5321        self.anchor = Some(self.caret_floor());
5322        self.caret = self.source.len();
5323        self.goal_col = None;
5324        self.last_edit_kind = None;
5325        self.status = None;
5326    }
5327
5328    /// Select the word (or whitespace / punctuation run) at `offset` — the
5329    /// double-click gesture. Anchors on the run's start with the caret at its
5330    /// end so a following Shift-motion extends from the far edge.
5331    pub fn select_word_at(&mut self, offset: usize) {
5332        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
5333        self.anchor = Some(s);
5334        self.caret = e;
5335        self.goal_col = None;
5336        self.last_edit_kind = None;
5337        self.status = None;
5338        self.clamp_caret();
5339    }
5340
5341    /// Select the whole enclosing text block (paragraph, heading, list item's
5342    /// text…) at `offset` — the triple-click gesture. Reads the range straight
5343    /// from the AST (twig's `content_span`), so it selects the entire *logical*
5344    /// paragraph even when that paragraph soft-wraps across several visual rows —
5345    /// where a visual-row-based select breaks down, because one source offset at
5346    /// a wrap boundary belongs to two rows at once.
5347    pub fn select_block_at(&mut self, offset: usize) {
5348        let off = offset.min(self.source.len());
5349        let range = self
5350            .editor
5351            .ancestors_at(off)
5352            .ok()
5353            .and_then(|chain| {
5354                // Ancestors run root → deepest; the deepest node that is neither
5355                // an inline span nor a multi-block container is the text block
5356                // the caret sits in (a paragraph, a heading, a code block…).
5357                chain
5358                    .into_iter()
5359                    .rev()
5360                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
5361                    .map(|m| m.content_span.unwrap_or(m.span))
5362            })
5363            .unwrap_or_else(|| source_line_range(&self.source, off));
5364        self.anchor = Some(range.start.min(self.source.len()));
5365        self.caret = range.end.min(self.source.len());
5366        self.goal_col = None;
5367        self.last_edit_kind = None;
5368        self.status = None;
5369        self.clamp_caret();
5370    }
5371
5372    /// Select the exact source range `[start, end)` — anchor at `start`, caret
5373    /// at `end` — without snapping either end to a visible caret stop.
5374    ///
5375    /// The one caret verb that takes a range it was *handed* rather than one it
5376    /// worked out, for a host that already knows the bytes it means: a search
5377    /// hit, an annotation's footprint, a quote re-anchored through
5378    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
5379    /// wrong tool for that, and not by a little — it snaps to the nearest
5380    /// *visible* stop, and where a range butts up against a hidden delimiter
5381    /// the nearest stop is the one before it, so selecting the "needle" of
5382    /// `**needle**` comes back with "needl" and an edit against it strands the
5383    /// "e".
5384    ///
5385    /// What `place_caret` does that is bookkeeping rather than snapping still
5386    /// happens here, because a host handing in a range is not asking to opt out
5387    /// of the invariants:
5388    ///
5389    /// - both ends are clamped into the document and up to
5390    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
5391    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
5392    ///   types into the metadata;
5393    /// - both land on character boundaries, so nothing slices a `é` in half;
5394    /// - the sticky vertical goal column is dropped, and any armed inline mark
5395    ///   disarmed, since a range from outside inherits neither.
5396    ///
5397    /// An empty range is a caret rather than a selection —
5398    /// [`selection`](Self::selection) reports `None` for it, as it does for any
5399    /// anchor that has met the caret.
5400    pub fn select_range(&mut self, start: usize, end: usize) {
5401        let floor = self.caret_floor();
5402        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
5403        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
5404        self.anchor = Some(anchor);
5405        self.caret = caret;
5406        self.goal_col = None;
5407        self.status = None;
5408        self.last_edit_kind = None;
5409        self.clear_pending();
5410    }
5411
5412    /// `offset` itself if it is a character boundary, else the boundary before
5413    /// it. An offset that isn't one draws nowhere real and panics the next time
5414    /// anything slices there.
5415    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
5416        let mut o = offset.min(self.source.len());
5417        while o > 0 && !self.source.is_char_boundary(o) {
5418            o -= 1;
5419        }
5420        o
5421    }
5422
5423    /// The lowest source offset the caret may occupy in the active view. In
5424    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
5425    /// the first rendered offset; the source view reaches everything, so it's 0.
5426    fn caret_floor(&self) -> usize {
5427        match self.view {
5428            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
5429            View::Source => 0,
5430        }
5431    }
5432
5433    /// Land in a table cell with its whole content selected — the anchor at the
5434    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
5435    /// like tabbing into a form field: the text comes up selected, so typing
5436    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
5437    /// end`) collapses to a plain caret home (an empty selection is no selection).
5438    fn select_cell(&mut self, start: usize, end: usize) {
5439        self.select_range(start, end);
5440    }
5441
5442    fn move_to(&mut self, offset: usize, extend: bool) {
5443        if extend {
5444            if self.anchor.is_none() {
5445                self.anchor = Some(self.caret);
5446            }
5447        } else {
5448            self.anchor = None;
5449        }
5450        self.caret = offset.min(self.source.len()).max(self.caret_floor());
5451        self.status = None;
5452        // A caret move ends the current typing/deletion run, so the next edit
5453        // starts a fresh undo group rather than coalescing across the gap.
5454        self.last_edit_kind = None;
5455        // Moving away disarms any sticky mark — "start bold" applies only where
5456        // it was asked for, not wherever the caret next lands.
5457        self.clear_pending();
5458    }
5459
5460    // In the source view, motion walks source bytes / source lines. In the
5461    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
5462    // what steps the caret cleanly over hidden delimiters.
5463
5464    pub fn move_left(&mut self, extend: bool) {
5465        self.goal_col = None;
5466        if !extend && let Some((s, _e)) = self.selection() {
5467            self.move_to(s, false);
5468            return;
5469        }
5470        let target = match self.view {
5471            View::Source => {
5472                if self.caret > 0 {
5473                    prev_boundary(&self.source, self.caret)
5474                } else {
5475                    0
5476                }
5477            }
5478            // Walks caret *stops*, not columns: decoration (a table border, a
5479            // cell's padding) is stepped over in one press, and a hidden
5480            // delimiter never holds the caret up.
5481            View::Wysiwyg => self.vmap.stop_before(self.caret).unwrap_or(self.caret),
5482        };
5483        let before = self.caret;
5484        self.move_to(target, extend);
5485        self.debug_assert_on_a_stop(before);
5486    }
5487
5488    pub fn move_right(&mut self, extend: bool) {
5489        self.goal_col = None;
5490        if !extend && let Some((_s, e)) = self.selection() {
5491            self.move_to(e, false);
5492            return;
5493        }
5494        let target = match self.view {
5495            View::Source => {
5496                if self.caret < self.source.len() {
5497                    next_boundary(&self.source, self.caret)
5498                } else {
5499                    self.caret
5500                }
5501            }
5502            View::Wysiwyg => self.vmap.stop_after(self.caret).unwrap_or(self.caret),
5503        };
5504        let before = self.caret;
5505        self.move_to(target, extend);
5506        self.debug_assert_on_a_stop(before);
5507    }
5508
5509    /// Move to the start of the previous word (⌥← / Ctrl+←).
5510    pub fn move_word_left(&mut self, extend: bool) {
5511        self.goal_col = None;
5512        let before = self.caret;
5513        let target = self.word_left_from(self.caret);
5514        self.move_to(target, extend);
5515        self.debug_assert_on_a_stop(before);
5516    }
5517
5518    /// Move to the end of the next word (⌥→ / Ctrl+→).
5519    pub fn move_word_right(&mut self, extend: bool) {
5520        self.goal_col = None;
5521        let before = self.caret;
5522        let target = self.word_right_from(self.caret);
5523        self.move_to(target, extend);
5524        self.debug_assert_on_a_stop(before);
5525    }
5526
5527    // Word boundaries are found in the space the *view* is in. The source view
5528    // walks the source, because there the source is what's rendered. WYSIWYG
5529    // walks the rendered text instead: `**` is invisible to the user, so it has
5530    // to be invisible to word motion too — a caret parked inside one draws in
5531    // the column after `bold` and types two bytes earlier, and a word-delete
5532    // that stops there shreds the markup into `a ** c`.
5533
5534    /// The word boundary to the left of `off` in the active view's space.
5535    fn word_left_from(&self, off: usize) -> usize {
5536        match self.view {
5537            View::Source => prev_word(&self.source, off),
5538            View::Wysiwyg => self.glyph_word_left(off),
5539        }
5540    }
5541
5542    /// The word boundary to the right of `off` in the active view's space.
5543    fn word_right_from(&self, off: usize) -> usize {
5544        match self.view {
5545            View::Source => next_word(&self.source, off),
5546            View::Wysiwyg => self.glyph_word_right(off),
5547        }
5548    }
5549
5550    /// The character class of the glyph drawn at stop `off`.
5551    ///
5552    /// Read from the source, because a stop points at the source byte its glyph
5553    /// came from — the source *is* where the rendered character is written. What
5554    /// makes the walk glyph space rather than source space is that it only ever
5555    /// visits stops, and the hidden bytes between them have none.
5556    fn class_at(&self, off: usize) -> Class {
5557        self.source
5558            .get(off..)
5559            .and_then(|s| s.chars().next())
5560            .map_or(Class::Space, classify)
5561    }
5562
5563    /// [`next_word`] in glyph space: skip any leading separators, then consume
5564    /// the following word run, with the stop table standing in for the source's
5565    /// characters.
5566    fn glyph_word_right(&self, from: usize) -> usize {
5567        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
5568            return from;
5569        };
5570        let mut in_word = false;
5571        loop {
5572            match self.class_at(off) {
5573                Class::Word => in_word = true,
5574                _ if in_word => return off,
5575                _ => {}
5576            }
5577            match self.vmap.stop_after(off) {
5578                Some(next) => off = next,
5579                None => return off,
5580            }
5581        }
5582    }
5583
5584    /// [`prev_word`] in glyph space: skip separators walking left, then consume
5585    /// the preceding word run.
5586    fn glyph_word_left(&self, from: usize) -> usize {
5587        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
5588            return from;
5589        };
5590        let mut in_word = false;
5591        while let Some(prev) = self.vmap.stop_before(off) {
5592            match self.class_at(prev) {
5593                Class::Word => in_word = true,
5594                _ if in_word => return off,
5595                _ => {}
5596            }
5597            off = prev;
5598        }
5599        off
5600    }
5601
5602    /// After a motion that walks the visual map, the caret must be *on* the map.
5603    /// A stop is the only offset where the caret draws and edits in the same
5604    /// place, and it's the invariant both a caret parked inside an emoji and one
5605    /// parked inside a `**` were quietly breaking.
5606    ///
5607    /// Only when the caret actually moved: a walk with nowhere to go leaves it
5608    /// where it was, which is wherever the floor or a frontend put it rather
5609    /// than somewhere this motion chose.
5610    fn debug_assert_on_a_stop(&self, before: usize) {
5611        debug_assert!(
5612            self.view != View::Wysiwyg
5613                || self.vmap.num_rows() == 0
5614                || self.caret == before
5615                || self.vmap.is_stop(self.caret),
5616            "motion left the caret at {}, which is not a caret stop: it would draw in \
5617             one place and type in another",
5618            self.caret
5619        );
5620    }
5621
5622    // Up and Down run off the ends of the document rather than stopping dead at
5623    // them: Up from the first row lands at the document's start, Down from the
5624    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
5625    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
5626    // reaching the end of the text is what a reader means by it.
5627    //
5628    // The views used to disagree here by accident rather than by decision: the
5629    // source view fell into the edge behaviour through `row_col_to_offset`
5630    // clamping an out-of-range row to the end of the string, while WYSIWYG had
5631    // no row below to walk to and did nothing at all. They share the rule now,
5632    // each in its own space — the source view reaches every byte, WYSIWYG only
5633    // the offsets it draws.
5634
5635    pub fn move_up(&mut self, extend: bool) {
5636        let (row, col) = self.caret_pos();
5637        let goal = self.goal_col.unwrap_or(col);
5638        let target = match self.view {
5639            View::Source => match row.checked_sub(1) {
5640                Some(r) => row_col_to_offset(&self.source, r, goal),
5641                None => self.reachable_start(),
5642            },
5643            // A table's border rules are drawn but hold no caret, so Up steps
5644            // over them to the row that does.
5645            View::Wysiwyg => match self.vmap.navigable_above(row) {
5646                Some(r) => self.row_target(r, goal),
5647                None => self.reachable_start(),
5648            },
5649        };
5650        self.step_vertical(target, goal, extend);
5651    }
5652
5653    pub fn move_down(&mut self, extend: bool) {
5654        let (row, col) = self.caret_pos();
5655        let goal = self.goal_col.unwrap_or(col);
5656        let target = match self.view {
5657            View::Source => match self.source_row_below(row) {
5658                Some(r) => row_col_to_offset(&self.source, r, goal),
5659                None => self.reachable_end(),
5660            },
5661            View::Wysiwyg => match self.vmap.navigable_below(row) {
5662                Some(r) => self.row_target(r, goal),
5663                None => self.reachable_end(),
5664            },
5665        };
5666        self.step_vertical(target, goal, extend);
5667    }
5668
5669    /// Land a vertical motion at `target`, latching the `goal` column it aimed
5670    /// with so the rest of the run keeps aiming there.
5671    ///
5672    /// A motion with nowhere to go changes *nothing*, the goal column included:
5673    /// the latch used to run before the early return at the top of the document,
5674    /// so an Up that did nothing still armed a column, and the next Down aimed
5675    /// at one the caret had never been in.
5676    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
5677        let before = self.caret;
5678        if target == before {
5679            return;
5680        }
5681        self.goal_col = Some(goal);
5682        self.move_to(target, extend);
5683        self.debug_assert_on_a_stop(before);
5684    }
5685
5686    /// The source line below `row`, or `None` when `row` is the last one. Lines
5687    /// are counted by newline, so a trailing one leaves a real, empty last line
5688    /// for the caret to sit on — the document ends below it, not on it.
5689    fn source_row_below(&self, row: usize) -> Option<usize> {
5690        let last = self.source.bytes().filter(|&b| b == b'\n').count();
5691        (row < last).then_some(row + 1)
5692    }
5693
5694    /// Where a vertical motion aiming at the `goal` column lands on visual row
5695    /// `r`: the column clamped to the row, mapped to its offset, then held
5696    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
5697    /// column belongs to the row below, and a gutter's column 0 points at the
5698    /// block rather than at this row.
5699    fn row_target(&self, r: usize, goal: usize) -> usize {
5700        let (start, end) = self.row_bounds(r);
5701        self.vmap
5702            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
5703            .clamp(start, end)
5704    }
5705
5706    /// The first and last offsets the caret can reach in the active view.
5707    ///
5708    /// Not the same span in both: the source view shows every byte, so it can
5709    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
5710    /// sits below the first stop, and a document's trailing newline is drawn
5711    /// nowhere and so sits past the last.
5712    fn reachable_start(&self) -> usize {
5713        match self.view {
5714            View::Source => 0,
5715            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
5716        }
5717    }
5718
5719    fn reachable_end(&self) -> usize {
5720        match self.view {
5721            View::Source => self.source.len(),
5722            View::Wysiwyg => self
5723                .vmap
5724                .stop_at_or_before(self.source.len())
5725                .unwrap_or(self.caret),
5726        }
5727    }
5728
5729    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
5730    /// including the space a soft wrap ate off its end, which is drawn on this
5731    /// row however much the offset past it belongs to the next one.
5732    fn row_span(&self, r: usize) -> (usize, usize) {
5733        let start = self
5734            .vmap
5735            .row_start(r)
5736            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
5737        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
5738        (start.min(end), end)
5739    }
5740
5741    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
5742    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
5743    /// this row's last position is the one before it — the offset before the
5744    /// space the wrap ate, where the caret draws just past the row's last word
5745    /// and types there too.
5746    ///
5747    /// Aiming at the shared offset instead is what stalled End: it is the row's
5748    /// last *column*, so End pressed on the row reached it and then read back as
5749    /// the row below's start, where a second press ran on to that row's end and
5750    /// the next to the one after — End walking down the paragraph a row a press.
5751    fn row_bounds(&self, r: usize) -> (usize, usize) {
5752        let (start, end) = self.row_span(r);
5753        let wraps = self
5754            .vmap
5755            .navigable_below(r)
5756            .and_then(|b| self.vmap.row_start(b))
5757            .is_some_and(|off| off == end);
5758        match wraps {
5759            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
5760            false => (start, end),
5761        }
5762    }
5763
5764    /// The `[start, end]` of the line Home and End aim at: the visual row in
5765    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
5766    ///
5767    /// A soft-wrapped row is a line here, because it is one to the eye and the
5768    /// eye is what these keys are aimed by — a reader pressing End means the end
5769    /// of the line they can see. (`select_block_at` wants the opposite and reads
5770    /// the AST for it: a triple-click grabs the whole paragraph, however many
5771    /// rows it folds into.)
5772    fn line_bounds(&self) -> (usize, usize) {
5773        let (row, _) = self.caret_pos();
5774        match self.view {
5775            View::Source => {
5776                let start = line_start(&self.source, row);
5777                (start, line_end_from(&self.source, start))
5778            }
5779            View::Wysiwyg => self.row_bounds(row),
5780        }
5781    }
5782
5783    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
5784    /// *drawn* — what a kill takes.
5785    ///
5786    /// The two part only at a soft wrap, over the space the wrap ate: the caret
5787    /// can't stand after it (that offset opens the row below, and End stopping
5788    /// there would walk), but it is on this row, and a kill that spared it would
5789    /// leave a double space behind where the row's text had been. Deleting it
5790    /// joins nothing — a wrap is drawn, not written.
5791    fn line_span(&self) -> (usize, usize) {
5792        let (row, _) = self.caret_pos();
5793        match self.view {
5794            View::Source => self.line_bounds(),
5795            View::Wysiwyg => self.row_span(row),
5796        }
5797    }
5798
5799    /// The first offset in `[start, end]` holding something other than
5800    /// whitespace, or `end` when the line holds nothing else — where Home aims.
5801    ///
5802    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
5803    /// so a hidden delimiter is never taken for the line's first character (nor
5804    /// landed on), and the source view steps the source it is showing.
5805    fn first_non_space(&self, start: usize, end: usize) -> usize {
5806        let mut off = start;
5807        while off < end {
5808            if self.class_at(off) != Class::Space {
5809                return off;
5810            }
5811            off = match self.view {
5812                View::Source => next_boundary(&self.source, off),
5813                View::Wysiwyg => match self.vmap.stop_after(off) {
5814                    Some(next) => next,
5815                    None => return end,
5816                },
5817            };
5818        }
5819        end
5820    }
5821
5822    /// Home: to the first character on the line, or to column 0 when the caret
5823    /// is already on it — the two-press toggle every editor spells this way.
5824    /// The indentation is somewhere the caret has to be able to reach and almost
5825    /// never where a reader is headed, so it costs the second press.
5826    pub fn move_home(&mut self, extend: bool) {
5827        self.goal_col = None;
5828        let (start, end) = self.line_bounds();
5829        let text = self.first_non_space(start, end);
5830        let target = if self.caret == text { start } else { text };
5831        let before = self.caret;
5832        self.move_to(target, extend);
5833        self.debug_assert_on_a_stop(before);
5834    }
5835
5836    /// End: to the end of the line.
5837    pub fn move_end(&mut self, extend: bool) {
5838        self.goal_col = None;
5839        let (_, end) = self.line_bounds();
5840        let before = self.caret;
5841        self.move_to(end, extend);
5842        self.debug_assert_on_a_stop(before);
5843    }
5844
5845    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
5846    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
5847    /// when the caret isn't in a table, or is already in the last/first cell — the
5848    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
5849    /// meaning everywhere else.
5850    pub fn cell_hop(&mut self, forward: bool) -> bool {
5851        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
5852            return false;
5853        };
5854        // Flatten to document (row-major) order and step one cell either way.
5855        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
5856        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
5857        let next = if forward {
5858            i.checked_add(1)
5859        } else {
5860            i.checked_sub(1)
5861        };
5862        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
5863            return false; // at the table's edge; leave Tab to the frontend
5864        };
5865        self.select_cell(start, end);
5866        true
5867    }
5868
5869    /// Move the caret to the cell directly above (`down == false`) or below in
5870    /// the same column, landing with the cell's whole content selected (see
5871    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
5872    /// when the caret isn't in a table), so the frontend can fall through — the
5873    /// vertical counterpart of [`Self::cell_hop`].
5874    ///
5875    /// A ragged row that is short a column clamps to its last cell, so Down never
5876    /// falls out of the table over a gap the row above happened to have.
5877    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
5878        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
5879            return false;
5880        };
5881        let target = match down {
5882            true => r + 1,
5883            false if r == 0 => return false,
5884            false => r - 1,
5885        };
5886        let Some(row) = grid.get(target) else {
5887            return false;
5888        };
5889        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
5890            return false;
5891        };
5892        self.select_cell(start, end);
5893        true
5894    }
5895
5896    /// The table containing `off` as a row-major grid of `(start, end)` cell
5897    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
5898    /// isn't in a table. Read straight off the visual map's laid-out grid, so
5899    /// every cell (an empty one included, whose derived home twig gives no
5900    /// `content_span` for) is present and in the order Tab walks them.
5901    // Grid, row, column — three returns that only ever travel together, and a
5902    // named type for the pair of them would be read at one call site.
5903    #[allow(clippy::type_complexity)]
5904    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
5905        for t in &self.vmap.tables {
5906            let mut pos = None;
5907            let grid: Vec<Vec<(usize, usize)>> = t
5908                .grid
5909                .iter()
5910                .enumerate()
5911                .map(|(r, row)| {
5912                    row.cells
5913                        .iter()
5914                        .enumerate()
5915                        .map(|(c, cell)| {
5916                            if pos.is_none() && off >= cell.start && off <= cell.end {
5917                                pos = Some((r, c));
5918                            }
5919                            (cell.start, cell.end)
5920                        })
5921                        .collect()
5922                })
5923                .collect();
5924            if let Some((r, c)) = pos {
5925                return Some((grid, r, c));
5926            }
5927        }
5928        None
5929    }
5930
5931    // ── table key policy ──────────────────────────────────────────────────────
5932    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
5933    // as one policy every frontend shares, rather than each re-deriving it. Each
5934    // reports whether it acted *as a table key*; a `false` hands the key back to
5935    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
5936    // everywhere else.
5937
5938    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
5939    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
5940    /// back and simply stays put at the very first cell. `false` when the caret
5941    /// isn't in a table.
5942    pub fn cell_tab(&mut self, forward: bool) -> bool {
5943        if !self.caret_in_table() {
5944            return false;
5945        }
5946        if self.cell_hop(forward) {
5947            return true;
5948        }
5949        // Off the last cell: grow the table by a row and step into its first
5950        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
5951        if forward {
5952            self.append_row_and_enter(0);
5953        }
5954        true
5955    }
5956
5957    /// Return inside a table: drop to the cell below in the same column,
5958    /// appending a new row when the caret is already in the last one. `false`
5959    /// when the caret isn't in a table, so the frontend inserts a newline.
5960    pub fn cell_return(&mut self) -> bool {
5961        if !self.caret_in_table() {
5962            return false;
5963        }
5964        if self.cell_move_vertical(true) {
5965            return true;
5966        }
5967        // Already on the last row: grow one below and drop into the same column.
5968        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
5969        self.append_row_and_enter(col);
5970        true
5971    }
5972
5973    /// Append a row below the caret's (last) row and land in `col` of it. The
5974    /// caret is in the last row, so twig's "insert below" makes the fresh row the
5975    /// table's new last — but twig re-spells the whole table, moving every byte,
5976    /// so the destination is read back from the rebuilt grid by the table's
5977    /// position (stable across a row insert), not from the pre-edit caret.
5978    fn append_row_and_enter(&mut self, col: usize) {
5979        let table = self.caret_table_index();
5980        self.table_insert_row(true);
5981        self.rebuild_map();
5982        let Some((start, end)) = table
5983            .and_then(|ti| self.vmap.tables.get(ti))
5984            .and_then(|t| t.grid.last())
5985            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
5986            .map(|cell| (cell.start, cell.end))
5987        else {
5988            return;
5989        };
5990        self.select_cell(start, end);
5991    }
5992
5993    /// The index, among the document's tables, of the one the caret sits in —
5994    /// `None` when it's in none. Used to re-find a table after an edit re-spells
5995    /// it (a row insert leaves the table order unchanged).
5996    fn caret_table_index(&self) -> Option<usize> {
5997        let off = self.caret;
5998        self.vmap.tables.iter().position(|t| {
5999            t.grid
6000                .iter()
6001                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
6002        })
6003    }
6004
6005    /// Shift+Return inside a table: insert a hard line break *within* the current
6006    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
6007    /// table, so the frontend inserts an ordinary line break.
6008    ///
6009    /// A table row is a single source line, so the newline-spelled hard break
6010    /// can't live in a cell. twig spells the in-cell break the format's way
6011    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
6012    /// break round-trips as structure the renderer reads back as a line — not the
6013    /// opaque raw HTML the old raw-splice left behind.
6014    ///
6015    /// Djot has no idiomatic in-cell break, so twig refuses it
6016    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
6017    /// would render as the literal text `<br>`. The gesture is still *consumed*
6018    /// there — returning `false` would let the frontend insert a real newline,
6019    /// which splits the one-line row — it just leaves the cell unchanged and says
6020    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
6021    ///
6022    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
6023    /// have to be read together: djot is not the only `false`, and naming it in
6024    /// the message was already a guess that HTML — which spells the break as its
6025    /// own `<br>` — would have made wrong.
6026    pub fn cell_line_break(&mut self) -> bool {
6027        if self.read_only || !self.caret_in_table() {
6028            return false;
6029        }
6030        self.record_caret();
6031        match self.editor.insert_line_break(self.caret) {
6032            Ok(change) => {
6033                self.last_edit_kind = None;
6034                self.refresh();
6035                self.caret = change.new.end;
6036                self.anchor = None;
6037                self.goal_col = None;
6038                self.clamp_caret();
6039                self.dirty = self.source != self.clean_source;
6040                self.status = None;
6041                self.record_caret();
6042            }
6043            Err(twig::Error::UnsupportedFormat) => {
6044                self.status = Some(format!(
6045                    "in-cell line breaks aren't supported in {}",
6046                    self.format_name()
6047                ));
6048            }
6049            Err(_) => {}
6050        }
6051        true
6052    }
6053
6054    /// Rebuild the visual map at the width the last build used. A structural edit
6055    /// bumps the revision and swaps the source in, but leaves the *map* stale;
6056    /// when a single gesture edits and then moves over the result (Tab appending
6057    /// a row, then stepping into it), the move needs the map to already show the
6058    /// edit rather than waiting for the frontend's next frame.
6059    fn rebuild_map(&mut self) {
6060        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
6061        self.build_map(wrap);
6062    }
6063
6064    /// Move the caret to the very start of the document (⌘↑ on macOS,
6065    /// Ctrl+Home on Windows/Linux).
6066    pub fn move_doc_start(&mut self, extend: bool) {
6067        self.goal_col = None;
6068        self.move_to(0, extend);
6069    }
6070
6071    /// Move the caret to the very end of the document (⌘↓ on macOS,
6072    /// Ctrl+End on Windows/Linux).
6073    pub fn move_doc_end(&mut self, extend: bool) {
6074        self.goal_col = None;
6075        let end = self.source.len();
6076        self.move_to(end, extend);
6077    }
6078
6079    /// Point the caret at the body cell `(row, col)` the mouse landed on —
6080    /// `col` being a cell of the terminal grid, which is what a display column
6081    /// is. A click on the far cell of a wide character lands at that
6082    /// character's start; the mapping's own doc-comments carry the rule.
6083    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
6084        self.goal_col = None;
6085        let target = match self.view {
6086            View::Source => row_col_to_offset(&self.source, row, col),
6087            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
6088        };
6089        let before = self.caret;
6090        self.move_to(target, extend);
6091        self.debug_assert_on_a_stop(before);
6092    }
6093
6094    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
6095    /// screen if it has moved since the last frame, and never scroll past the
6096    /// last of `rows`.
6097    ///
6098    /// Only if it has *moved* — that's the whole point. Revealing the caret on
6099    /// every frame ties the viewport to it, and a scroll wheel that fights the
6100    /// caret for the viewport loses: the view snaps back the instant it tries to
6101    /// pass the caret's row, so the document can't be scrolled beyond what's
6102    /// already on screen. A caret move is the frontend's cue to follow; a scroll
6103    /// with the caret sitting still is the reader's cue to leave it alone.
6104    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
6105        if self.drawn_caret != Some(self.caret) {
6106            if caret_row < self.scroll {
6107                self.scroll = caret_row;
6108            } else if height > 0 && caret_row >= self.scroll + height {
6109                self.scroll = caret_row + 1 - height;
6110            }
6111            self.drawn_caret = Some(self.caret);
6112        }
6113        self.scroll = self.scroll.min(rows.saturating_sub(1));
6114    }
6115
6116    /// The caret's screen position `(row, col)` in the active view's grid, with
6117    /// `col` a display column: the cell to draw the caret in, which on a line of
6118    /// `你好` or emoji is not the count of characters before it.
6119    pub fn caret_pos(&self) -> (usize, usize) {
6120        match self.view {
6121            View::Source => offset_to_row_col(&self.source, self.caret),
6122            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
6123        }
6124    }
6125
6126    fn clamp_caret(&mut self) {
6127        if self.caret > self.source.len() {
6128            self.caret = self.source.len();
6129        }
6130        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
6131        // any selection anchor) to the first rendered offset.
6132        let floor = self.caret_floor();
6133        if self.caret < floor {
6134            self.caret = floor;
6135        }
6136        if let Some(a) = self.anchor
6137            && a < floor
6138        {
6139            self.anchor = Some(floor);
6140        }
6141        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
6142            self.caret -= 1;
6143        }
6144    }
6145}
6146
6147// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
6148
6149// Left/right motion and backspace/delete step by *grapheme cluster*, not
6150// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
6151// marks moves and deletes as the single character a user sees. Grapheme
6152// boundaries are a superset of char boundaries, so the caret stays valid for twig.
6153
6154/// How an insert of `text` groups for undo: a single typed character folds into
6155/// the run of typing around it, while a newline or a multi-character insert is a
6156/// step of its own.
6157fn typed_edit_kind(text: &str) -> EditKind {
6158    if text.chars().take(2).count() == 1 && text != "\n" {
6159        EditKind::Insert
6160    } else {
6161        EditKind::Other
6162    }
6163}
6164
6165fn prev_boundary(s: &str, i: usize) -> usize {
6166    let mut cursor = GraphemeCursor::new(i, s.len(), true);
6167    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
6168}
6169
6170fn next_boundary(s: &str, i: usize) -> usize {
6171    let mut cursor = GraphemeCursor::new(i, s.len(), true);
6172    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
6173}
6174
6175// ── word boundaries ──────────────────────────────────────────────────────────
6176// The shared primitive behind word-wise motion, word deletion, and
6177// double-click-to-select-a-word. A "word" is a maximal run of one character
6178// class; whitespace and punctuation are their own classes, so motion skips
6179// cleanly between them the way native text fields do.
6180
6181#[derive(PartialEq, Eq, Clone, Copy)]
6182enum Class {
6183    Word,
6184    Space,
6185    Other,
6186}
6187
6188/// The source range of an inline node's own visible text — the part of it a
6189/// WYSIWYG caret can reach, as against the delimiters that only spell it.
6190/// `None` for a node with no interior to empty (a `str`, a break).
6191///
6192/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
6193/// one delimiter in from the span — the same place the renderer maps it to. A
6194/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
6195/// against the source rather than trusted: a range guessed wrong here is text
6196/// deleted wrong.
6197fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
6198    if let Some(span) = n.content_span.clone() {
6199        return Some(span);
6200    }
6201    match n.kind.as_str() {
6202        "verbatim" | "inline_math" => {
6203            let text = n.text.as_ref()?;
6204            let start = n.span.start + 1;
6205            let range = start..start + text.len();
6206            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
6207        }
6208        _ => None,
6209    }
6210}
6211
6212/// The `id` a node declares, or `None` for one that declares none — the
6213/// attribute djot writes for a `{#v1}` and mints for a heading.
6214///
6215/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
6216/// names nothing, so it reads as absent rather than as the empty string.
6217fn declared_id(n: &FlatNode) -> Option<&str> {
6218    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
6219}
6220
6221/// A heading's words reduced to the form a link fragment spells them in:
6222/// lowercase, runs of anything else collapsed to a single `-`, with none left
6223/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
6224///
6225/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
6226/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
6227/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
6228/// any other language is still a heading someone will link to. Underscores
6229/// survive for the same reason they do on the web: they are word characters
6230/// wherever identifiers are written.
6231fn slug(text: &str) -> String {
6232    let mut out = String::new();
6233    let mut pending = false;
6234    for c in text.chars() {
6235        if c.is_alphanumeric() || c == '_' {
6236            if pending && !out.is_empty() {
6237                out.push('-');
6238            }
6239            pending = false;
6240            out.extend(c.to_lowercase());
6241        } else {
6242            pending = true;
6243        }
6244    }
6245    out
6246}
6247
6248fn is_block_container(kind: &Kind) -> bool {
6249    matches!(
6250        kind,
6251        Kind::Doc
6252            | Kind::Section
6253            | Kind::BlockQuote
6254            | Kind::BulletList
6255            | Kind::OrderedList
6256            | Kind::TaskList
6257            | Kind::ListItem
6258            | Kind::TaskListItem
6259            // Every `container` — a directive in any of its three forms, or a
6260            // promoted HTML element. A *text* directive is really inline, so
6261            // claiming it here is a small overreach, and the deliberate one this
6262            // function's kind-only peer `is_inline_kind` documents: the pair is
6263            // consulted together, and answering "block container" for something
6264            // inline is what keeps an ancestor walk from stopping short of the
6265            // paragraph that actually holds it.
6266            | Kind::Container
6267    )
6268}
6269
6270/// The `[start, end)` byte range of the source line containing `off` (newline
6271/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
6272/// line between paragraphs).
6273fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
6274    let off = off.min(s.len());
6275    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
6276    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
6277    start..end
6278}
6279
6280/// How many leading bytes an outdent takes off `line`: a whole indent level
6281/// where the line has one, and whatever it has where it has less.
6282///
6283/// A leading tab counts as a level on its own. It's indentation some other
6284/// editor wrote, and one tab is one level everywhere it came from — measuring it
6285/// in spaces it doesn't contain would leave it untouchable.
6286fn outdent_width(line: &str, unit: usize) -> usize {
6287    if line.starts_with('\t') {
6288        return 1;
6289    }
6290    line.bytes().take(unit).take_while(|b| *b == b' ').count()
6291}
6292
6293/// A list marker found at the head of a line, together with everything before it
6294/// that a sibling line has to repeat.
6295///
6296/// The three offsets differ only inside a block quote, where `>   - b` opens with
6297/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
6298/// `line_start == marker_start`, and `text` is the plain `"  - "`.
6299#[derive(Clone, Debug)]
6300struct ListMarker {
6301    /// The line's first byte.
6302    line_start: usize,
6303    /// Where the marker proper begins, past any quote prefix. The offset to hand
6304    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
6305    marker_start: usize,
6306    /// `line_start` through the marker's trailing space — quote prefix, indent
6307    /// and bullet together, which is what the next item's line opens with.
6308    text: String,
6309}
6310
6311impl ListMarker {
6312    /// Where the item's content starts — one past the marker's trailing space.
6313    fn content_start(&self) -> usize {
6314        self.line_start + self.text.len()
6315    }
6316}
6317
6318fn classify(c: char) -> Class {
6319    if c == '_' || c.is_alphanumeric() {
6320        Class::Word
6321    } else if c.is_whitespace() {
6322        Class::Space
6323    } else {
6324        Class::Other
6325    }
6326}
6327
6328/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
6329/// skip any leading separators, then consume the following word run.
6330fn next_word(s: &str, i: usize) -> usize {
6331    let mut off = i;
6332    let mut in_word = false;
6333    for c in s[i..].chars() {
6334        if classify(c) == Class::Word {
6335            in_word = true;
6336        } else if in_word {
6337            break;
6338        }
6339        off += c.len_utf8();
6340    }
6341    off
6342}
6343
6344/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
6345/// skip separators walking left, then consume the preceding word run.
6346fn prev_word(s: &str, i: usize) -> usize {
6347    let mut off = i;
6348    let mut in_word = false;
6349    for c in s[..i].chars().rev() {
6350        if classify(c) == Class::Word {
6351            in_word = true;
6352        } else if in_word {
6353            break;
6354        }
6355        off -= c.len_utf8();
6356    }
6357    off
6358}
6359
6360/// The `[start, end)` run of same-class characters surrounding `off` — the
6361/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
6362/// the run ending there is used.
6363fn word_range_at(s: &str, off: usize) -> (usize, usize) {
6364    if s.is_empty() {
6365        return (0, 0);
6366    }
6367    let off = off.min(s.len());
6368    let reference = if off < s.len() {
6369        s[off..].chars().next()
6370    } else {
6371        s[..off].chars().next_back()
6372    };
6373    let Some(rc) = reference else {
6374        return (off, off);
6375    };
6376    let class = classify(rc);
6377
6378    let mut start = off;
6379    for c in s[..start].chars().rev() {
6380        if classify(c) == class {
6381            start -= c.len_utf8();
6382        } else {
6383            break;
6384        }
6385    }
6386    let mut end = off;
6387    for c in s[end..].chars() {
6388        if classify(c) == class {
6389            end += c.len_utf8();
6390        } else {
6391            break;
6392        }
6393    }
6394    (start, end)
6395}
6396
6397/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
6398/// the line's start — terminal cells, not characters, so the column names the
6399/// cell the caret is drawn in even on a line of `你好` or emoji.
6400fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
6401    let off = off.min(s.len());
6402    let mut row = 0;
6403    let mut line_start = 0;
6404    for (i, &b) in s.as_bytes().iter().enumerate() {
6405        if i >= off {
6406            break;
6407        }
6408        if b == b'\n' {
6409            row += 1;
6410            line_start = i + 1;
6411        }
6412    }
6413    (row, wysiwyg::text_width(&s[line_start..off]))
6414}
6415
6416/// The byte offset at display column `col` of `row` (clamped to that line's
6417/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
6418///
6419/// A column landing *inside* a character — the second cell of `你`, or any cell
6420/// but the first of an emoji — resolves to that character's start, which is the
6421/// column the caret would have been drawn at to begin with. So both cells of a
6422/// wide character mean the character, and every offset survives the round trip
6423/// out to a column and back. The walk steps by grapheme cluster for the same
6424/// reason the caret does: a cluster is the character, and the cells belong to it
6425/// rather than to the codepoints spelling it.
6426fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
6427    let start = line_start(s, row);
6428    let end = line_end_from(s, start);
6429    let mut off = start;
6430    let mut at = 0; // the display column `off` sits at
6431    while off < end {
6432        let next = next_boundary(s, off).min(end);
6433        let cells = wysiwyg::text_width(&s[off..next]);
6434        if at + cells > col {
6435            break; // `col` is one of this cluster's own cells
6436        }
6437        at += cells;
6438        off = next;
6439    }
6440    off
6441}
6442
6443fn line_start(s: &str, row: usize) -> usize {
6444    if row == 0 {
6445        return 0;
6446    }
6447    let mut r = 0;
6448    for (i, &b) in s.as_bytes().iter().enumerate() {
6449        if b == b'\n' {
6450            r += 1;
6451            if r == row {
6452                return i + 1;
6453            }
6454        }
6455    }
6456    s.len()
6457}
6458
6459fn line_end_from(s: &str, start: usize) -> usize {
6460    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
6461}
6462
6463/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
6464/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
6465/// twig applies writing the mark out, so the toolbar can light the same button
6466/// that made the node.
6467///
6468/// `None` for every other kind, including the inline nodes that aren't marks at
6469/// all (`str`, `link`, `image`, the math and break kinds): they're things a
6470/// caret stands in, not formatting a button toggles.
6471fn inline_kind(kind: &Kind) -> Option<InlineKind> {
6472    Some(match kind {
6473        Kind::Strong => InlineKind::Strong,
6474        Kind::Emph => InlineKind::Emph,
6475        Kind::Verbatim => InlineKind::Verbatim,
6476        Kind::Mark => InlineKind::Mark,
6477        Kind::Superscript => InlineKind::Superscript,
6478        Kind::Subscript => InlineKind::Subscript,
6479        Kind::Insert => InlineKind::Insert,
6480        Kind::Delete => InlineKind::Delete,
6481        _ => return None,
6482    })
6483}
6484
6485/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
6486/// a highlight's opening `==`.
6487///
6488/// Two enums for one closed vocabulary, and the duplication is the boundary
6489/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
6490/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
6491/// the editor writes. Spelled as a match rather than routed through the two
6492/// crates' name strings so that a colour added on either side is a compile
6493/// error here, where the pairing is decided, rather than a runtime `None` that
6494/// would read as "clear the colour".
6495fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
6496    match color {
6497        MarkColor::Red => twig::MarkColor::Red,
6498        MarkColor::Orange => twig::MarkColor::Orange,
6499        MarkColor::Yellow => twig::MarkColor::Yellow,
6500        MarkColor::Green => twig::MarkColor::Green,
6501        MarkColor::Blue => twig::MarkColor::Blue,
6502        MarkColor::Purple => twig::MarkColor::Purple,
6503        MarkColor::Brown => twig::MarkColor::Brown,
6504    }
6505}
6506
6507/// Where an offset lands after a splice it didn't make — twig's own rule, from
6508/// [`Change`]: shift anything at or past the replaced range's end by the length
6509/// the replacement gained or lost, and leave anything before it alone.
6510///
6511/// An offset *inside* the replaced range has no text of its own to ride any
6512/// more, and lands at the end of what replaced it: for
6513/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
6514/// the prefix is cleared, which then sits where the highlighted text begins.
6515fn reanchor(off: usize, change: &Change) -> usize {
6516    if off < change.old.start {
6517        return off;
6518    }
6519    if off < change.old.end {
6520        return change.new.end;
6521    }
6522    (off + change.new.end).saturating_sub(change.old.end)
6523}
6524
6525/// A watermark for a file's contents (see `Doc::disk_hash`).
6526///
6527/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
6528/// watermark is compared only against one taken by the same process moments
6529/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
6530/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
6531fn hash_bytes(bytes: &[u8]) -> u64 {
6532    use std::hash::{Hash, Hasher};
6533    let mut h = std::collections::hash_map::DefaultHasher::new();
6534    bytes.hash(&mut h);
6535    h.finish()
6536}
6537
6538#[cfg(feature = "fs")]
6539fn detect_format(path: &Path) -> Result<Format> {
6540    let ext = path
6541        .extension()
6542        .and_then(|e| e.to_str())
6543        .unwrap_or("")
6544        .to_ascii_lowercase();
6545    Ok(match ext.as_str() {
6546        "dj" | "djot" => Format::Djot,
6547        "md" | "markdown" => Format::Markdown,
6548        "xml" => Format::Xml,
6549        "html" | "htm" => Format::Html,
6550        other => return Err(anyhow!("unknown document extension: .{other}")),
6551    })
6552}
6553
6554#[cfg(test)]
6555mod tests {
6556    use super::*;
6557
6558    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
6559    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
6560    /// without one is a view no user is ever in.
6561    fn doc_in(view: View, name: &str, body: &str) -> Doc {
6562        // The fixture name doubles as the temp file's, so two tests picking the
6563        // same one raced under the parallel runner and read each other's body —
6564        // a green suite proving the wrong thing. The counter makes that
6565        // unreachable rather than asking every future caller to notice.
6566        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
6567        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6568        let mut p = std::env::temp_dir();
6569        p.push(format!("leaf_test_{name}_{seq}.md"));
6570        std::fs::write(&p, body).unwrap();
6571        let mut d = Doc::open(p).unwrap();
6572        d.view = view;
6573        if view == View::Wysiwyg {
6574            d.build_visual(80);
6575        }
6576        d
6577    }
6578
6579    // Source-view document for the source-behaviour tests. `Doc::open` now
6580    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
6581    // `wysiwyg_doc` builds the rich-text variant on top of this.
6582    fn doc_with(name: &str, body: &str) -> Doc {
6583        doc_in(View::Source, name, body)
6584    }
6585
6586    /// Every visual row's drawn text — what the reader actually sees, which is
6587    /// the only thing the reveal preference is supposed to change.
6588    fn drawn_rows(d: &Doc) -> Vec<String> {
6589        d.vmap
6590            .rows
6591            .iter()
6592            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6593            .collect()
6594    }
6595
6596    /// Put the caret at the first byte of `needle` and rebuild, so the row under
6597    /// it becomes the revealed line.
6598    fn caret_at(d: &mut Doc, needle: &str) {
6599        d.caret = d.source.find(needle).expect("needle in source");
6600        d.build_visual(80);
6601    }
6602
6603    #[test]
6604    fn blockquote_after_a_list_is_not_bulleted() {
6605        // twig nests a following top-level block quote under the `bullet_list`
6606        // (a direct child, not a `list_item`). The map must render it de-nested —
6607        // `│ quote`, never `• │ quote` — with a blank separator, like any block
6608        // that follows a list. Regression for the "combined list + blockquote" bug.
6609        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
6610        d.build_visual(80);
6611        let rows: Vec<String> = d
6612            .vmap
6613            .rows
6614            .iter()
6615            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6616            .collect();
6617        assert!(
6618            rows.iter().any(|r| r == "│ quote"),
6619            "block quote should render on its own gutter, got rows: {rows:?}"
6620        );
6621        assert!(
6622            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
6623            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
6624        );
6625    }
6626
6627    // ── the map is built at most once per (revision, wrap) ───────────────────
6628    //
6629    // A frontend repaints for reasons that have nothing to do with the text — a
6630    // blinking caret, a scroll — and rebuilding the map is O(document). These
6631    // pin *that the cache fires*, which a passing suite can't tell you: a cache
6632    // that never hits is invisible to every other test in this file.
6633    //
6634    // The probe is to wreck the built map and ask for it again. A rebuild
6635    // repairs it; a cache hit hands the wreckage straight back. Nothing else
6636    // can distinguish the two from outside.
6637
6638    #[test]
6639    fn a_rebuild_with_nothing_changed_reuses_the_map() {
6640        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
6641        d.build_visual(80);
6642        assert!(!d.vmap.rows.is_empty());
6643        d.vmap.rows.clear(); // wreck it
6644        d.build_visual(80);
6645        assert!(
6646            d.vmap.rows.is_empty(),
6647            "the map was rebuilt though nothing changed — the cache never fired"
6648        );
6649    }
6650
6651    #[test]
6652    fn an_edit_rebuilds_the_map() {
6653        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
6654        d.build_visual(80);
6655        let before = d.revision();
6656        d.vmap.rows.clear();
6657        d.insert("x");
6658        d.build_visual(80);
6659        assert!(d.revision() > before, "an edit must move the revision");
6660        assert!(
6661            !d.vmap.rows.is_empty(),
6662            "an edited document must not paint from a stale map"
6663        );
6664    }
6665
6666    #[test]
6667    fn a_width_change_rebuilds_the_map() {
6668        // The map is a function of the wrap width too, so a resize is a miss
6669        // even though the text is untouched.
6670        let mut d = doc_in(
6671            View::Wysiwyg,
6672            "cache_width",
6673            "one two three four five six\n",
6674        );
6675        d.build_visual(80);
6676        d.vmap.rows.clear();
6677        d.build_visual(12);
6678        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
6679        // And the unwrapped map is its own key, not the same as any width.
6680        d.vmap.rows.clear();
6681        d.build_visual_unwrapped();
6682        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
6683    }
6684
6685    #[test]
6686    fn a_motion_does_not_rebuild_the_map() {
6687        // The whole point: moving the caret changes nothing the map is built
6688        // from. If a motion bumped the revision, every arrow key would cost a
6689        // full rebuild and the cache would be worthless.
6690        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
6691        d.build_visual(80);
6692        let rev = d.revision();
6693        d.move_right(false);
6694        d.move_right(true);
6695        d.move_down(false);
6696        assert_eq!(d.revision(), rev, "a motion must not move the revision");
6697        d.vmap.rows.clear();
6698        d.build_visual(80);
6699        assert!(
6700            d.vmap.rows.is_empty(),
6701            "a motion should not rebuild the map"
6702        );
6703    }
6704
6705    #[test]
6706    fn saving_does_not_rebuild_the_map() {
6707        // Saving changes `dirty`, not the text.
6708        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
6709        d.insert("x");
6710        d.build_visual(80);
6711        let rev = d.revision();
6712        d.save();
6713        assert_eq!(d.revision(), rev, "a save must not move the revision");
6714        assert!(!d.dirty, "the save should have cleaned the document");
6715    }
6716
6717    #[test]
6718    fn a_reload_rebuilds_the_map() {
6719        // Reload replaces the text without going through `refresh`, so it has to
6720        // move the revision itself — else the editor paints the old file.
6721        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
6722        d.build_visual(80);
6723        let rev = d.revision();
6724        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
6725        d.reload();
6726        assert!(d.revision() > rev, "a reload must move the revision");
6727        d.build_visual(80);
6728        let text: String = d
6729            .vmap
6730            .rows
6731            .iter()
6732            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
6733            .collect();
6734        assert!(
6735            text.contains("wholly new"),
6736            "the reloaded text should be on screen, got {text:?}"
6737        );
6738    }
6739
6740    // ── golden-case harness ──────────────────────────────────────────────────
6741    // The pattern the whole parity suite can reuse: write a fixture with the
6742    // caret marked by `|`, run one action, and compare the rendered result —
6743    // also caret-marked — against the expected string. One readable line per
6744    // behavior, and it exercises the exact `Doc` ops both frontends call.
6745
6746    /// Split a `|`-marked fixture into `(source, caret_offset)`.
6747    fn parse_caret(marked: &str) -> (String, usize) {
6748        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
6749        (marked.replacen('|', "", 1), caret)
6750    }
6751
6752    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
6753    /// selection) so a result reads like the fixtures.
6754    fn render_caret(d: &Doc) -> String {
6755        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
6756        // so the caret always renders inside its own selection.
6757        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
6758        if let Some((s, e)) = d.selection() {
6759            marks.push((s, 0, '['));
6760            marks.push((e, 2, ']'));
6761        }
6762        // Insert right-to-left: descending offset, then descending rank.
6763        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
6764        let mut out = d.source.clone();
6765        for (at, _, ch) in marks {
6766            out.insert(at, ch);
6767        }
6768        out
6769    }
6770
6771    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
6772    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
6773        golden_in(View::Source, name, marked, action)
6774    }
6775
6776    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
6777    /// the same fixture has to read the same way in both.
6778    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
6779        let (src, caret) = parse_caret(marked);
6780        let mut d = doc_in(view, name, &src);
6781        d.caret = caret;
6782        action(&mut d);
6783        render_caret(&d)
6784    }
6785
6786    #[test]
6787    fn word_motion_walks_word_by_word() {
6788        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
6789        assert_eq!(
6790            g("hello wor|ld", |d| d.move_word_left(false)),
6791            "hello |world"
6792        );
6793        assert_eq!(
6794            g("hello| world", |d| d.move_word_left(false)),
6795            "|hello world"
6796        );
6797        assert_eq!(
6798            g("hel|lo world", |d| d.move_word_right(false)),
6799            "hello| world"
6800        );
6801        assert_eq!(
6802            g("hello| world", |d| d.move_word_right(false)),
6803            "hello world|"
6804        );
6805        // Punctuation is its own class, so motion stops at the boundary.
6806        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
6807    }
6808
6809    #[test]
6810    fn word_motion_extends_the_selection_when_asked() {
6811        assert_eq!(
6812            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
6813            "hello [world|]"
6814        );
6815    }
6816
6817    #[test]
6818    fn delete_word_removes_a_whole_word() {
6819        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
6820        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
6821        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
6822        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
6823    }
6824
6825    // ── Home / End ───────────────────────────────────────────────────────────
6826
6827    #[test]
6828    fn home_toggles_between_the_line_s_text_and_its_margin() {
6829        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
6830        // indent to the markup it spells everywhere it means one, so the fixture
6831        // with whitespace left to walk is a code block, which is verbatim.
6832        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
6833        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
6834        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
6835        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
6836        // A line with no indentation has one place to go, so the toggle is a
6837        // no-op rather than a trip to nowhere.
6838        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
6839        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
6840
6841        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
6842        let indent = d.source.find("    indented").unwrap();
6843        d.caret = indent + 6; // inside "indented"
6844        d.move_home(false);
6845        assert_eq!(
6846            d.caret,
6847            indent + 4,
6848            "wysiwyg: Home aims at the code line's text"
6849        );
6850        d.move_home(false);
6851        assert_eq!(
6852            d.caret, indent,
6853            "wysiwyg: the second press takes the indent"
6854        );
6855        d.move_home(false);
6856        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
6857    }
6858
6859    #[test]
6860    fn end_takes_the_line_the_view_is_showing() {
6861        // The line differs by view for the same document, and that is the point:
6862        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
6863        // as a space on one row and the source view as two lines.
6864        let mut d = doc_with("end_src", "one two\nthree\n");
6865        d.caret = 1;
6866        d.move_end(false);
6867        assert_eq!(d.caret, 7, "source: the end of the source line");
6868
6869        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
6870        d.caret = 1;
6871        d.move_end(false);
6872        assert_eq!(
6873            d.caret, 13,
6874            "wysiwyg: the end of the row, soft break and all"
6875        );
6876    }
6877
6878    #[test]
6879    fn home_and_end_extend_the_selection_when_asked() {
6880        for (view, tag) in VIEWS {
6881            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
6882            d.caret = 6;
6883            d.move_end(true);
6884            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
6885            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
6886            d.caret = 6;
6887            d.move_home(true);
6888            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
6889        }
6890    }
6891
6892    // ── kill to the line's start / end ───────────────────────────────────────
6893
6894    #[test]
6895    fn kill_to_the_line_start_and_end_in_both_views() {
6896        for (view, tag) in VIEWS {
6897            // The gap that reads as a paragraph break in each view: the source
6898            // view's lines are the renderer's rows only where the source says so.
6899            let gap = if view == View::Source { "\n" } else { "\n\n" };
6900            let mut d = doc_in(
6901                view,
6902                &format!("kill_end_{tag}"),
6903                &format!("one two{gap}three\n"),
6904            );
6905            d.caret = 3;
6906            d.delete_to_line_end();
6907            assert_eq!(
6908                d.source,
6909                format!("one{gap}three\n"),
6910                "{tag}: ^K to the line's end"
6911            );
6912            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
6913
6914            let mut d = doc_in(
6915                view,
6916                &format!("kill_start_{tag}"),
6917                &format!("one two{gap}three\n"),
6918            );
6919            d.caret = 7; // the end of the first line
6920            d.delete_to_line_start();
6921            assert_eq!(
6922                d.source,
6923                format!("{gap}three\n"),
6924                "{tag}: ⌘⌫ to the line's start"
6925            );
6926            assert_eq!(d.caret, 0, "{tag}");
6927        }
6928    }
6929
6930    #[test]
6931    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
6932        // The decision: at the boundary both kills do nothing, rather than
6933        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
6934        // at a soft wrap as often as at a newline, where there is nothing
6935        // written to delete — and a source newline is only half of the blank
6936        // line between two paragraphs, so taking it leaves a soft break rather
6937        // than the join it looks like. Backspace and Delete are the keys for it.
6938        for (view, tag) in VIEWS {
6939            let gap = if view == View::Source { "\n" } else { "\n\n" };
6940            let src = format!("one{gap}three\n");
6941            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
6942            d.caret = 3; // the end of "one"
6943            d.delete_to_line_end();
6944            assert_eq!(
6945                d.source, src,
6946                "{tag}: ^K at the line's end joined it to the next"
6947            );
6948
6949            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
6950            d.caret = 3 + gap.len(); // the start of "three"
6951            d.delete_to_line_start();
6952            assert_eq!(
6953                d.source, src,
6954                "{tag}: ⌘⌫ at the line's start joined it to the last"
6955            );
6956        }
6957    }
6958
6959    #[test]
6960    fn a_kill_takes_the_selection_when_there_is_one() {
6961        // What every other delete here does with one, so these two as well.
6962        for (view, tag) in VIEWS {
6963            for (name, kill) in [
6964                (
6965                    "end",
6966                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
6967                ),
6968                ("start", |d: &mut Doc| d.delete_to_line_start()),
6969            ] {
6970                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
6971                d.anchor = Some(4);
6972                d.caret = 7; // "two"
6973                kill(&mut d);
6974                assert_eq!(
6975                    d.source, "one  three\n",
6976                    "{tag}: {name} ignored the selection"
6977                );
6978                assert_eq!(d.selection(), None, "{tag}: {name}");
6979            }
6980        }
6981    }
6982
6983    #[test]
6984    fn a_kill_takes_the_markup_it_empties_with_it() {
6985        // The same hazard a word-delete has: a WYSIWYG range covers what the
6986        // user can see, which for `**bold**` is the word and never the
6987        // delimiters, so a kill that stopped at the text would leave `a ****` —
6988        // markup wrapped around nothing.
6989        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
6990        d.caret = d.source.find("bold").unwrap();
6991        d.delete_to_line_end();
6992        assert_eq!(d.source, "a \n");
6993    }
6994
6995    #[test]
6996    fn a_kill_is_undone_in_one_step() {
6997        for (view, tag) in VIEWS {
6998            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
6999            d.caret = 3;
7000            d.delete_to_line_end();
7001            assert_eq!(d.source, "one\n", "{tag}");
7002            d.undo();
7003            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
7004        }
7005    }
7006
7007    #[test]
7008    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
7009        // Regression: triple-click used move_home/move_end over visual rows, so
7010        // it only worked on a paragraph's first row (a wrap-boundary offset maps
7011        // to the earlier row). select_block_at reads the AST, so every offset in
7012        // the paragraph selects the whole thing.
7013        let body = "one two three four five six seven eight\n";
7014        let mut d = doc_with("sel_block", body);
7015        d.view = View::Wysiwyg;
7016        d.build_visual(12); // force the paragraph to wrap into several rows
7017        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
7018        let para = (0, "one two three four five six seven eight".len());
7019        for off in [0usize, 8, 19, 28, 38] {
7020            d.caret = 0;
7021            d.anchor = None;
7022            d.select_block_at(off);
7023            assert_eq!(
7024                d.selection(),
7025                Some(para),
7026                "offset {off} should select the paragraph"
7027            );
7028        }
7029    }
7030
7031    #[test]
7032    fn select_block_uses_content_span_for_a_heading() {
7033        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
7034        d.select_block_at(4); // inside "Title"
7035        // content_span excludes the "# " marker.
7036        assert_eq!(d.selected_text(), Some("Title"));
7037        d.select_block_at(10); // inside "body"
7038        assert_eq!(d.selected_text(), Some("body"));
7039    }
7040
7041    #[test]
7042    fn select_all_spans_the_document() {
7043        let mut d = doc_with("sel_all", "abc\n\ndef\n");
7044        d.select_all();
7045        assert_eq!(d.selection(), Some((0, d.source.len())));
7046    }
7047
7048    #[test]
7049    fn select_word_at_picks_the_surrounding_word() {
7050        let mut d = doc_with("sel_word", "hello world\n");
7051        d.select_word_at(8); // inside "world"
7052        assert_eq!(d.selection(), Some((6, 11)));
7053        // Double-clicking at end-of-word still grabs the word to its left.
7054        d.select_word_at(5); // the space between the words
7055        assert_eq!(d.selection(), Some((5, 6)));
7056    }
7057
7058    #[test]
7059    fn word_helpers_respect_utf8_boundaries() {
7060        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
7061        assert_eq!(
7062            golden("utf8", "|café ok", |d| d.move_word_right(false)),
7063            "café| ok"
7064        );
7065        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
7066    }
7067
7068    #[test]
7069    fn typing_inserts_at_the_caret_and_advances_it() {
7070        let mut d = doc_with("type", "hello\n");
7071        d.insert("Hi ");
7072        assert_eq!(d.source, "Hi hello\n");
7073        assert_eq!(d.caret, 3);
7074        assert!(d.dirty);
7075    }
7076
7077    #[test]
7078    fn backspace_deletes_the_char_before_the_caret() {
7079        let mut d = doc_with("bs", "hello\n");
7080        d.caret = 3; // after "hel"
7081        d.backspace();
7082        assert_eq!(d.source, "helo\n");
7083        assert_eq!(d.caret, 2);
7084    }
7085
7086    #[test]
7087    fn typing_replaces_the_selection() {
7088        let mut d = doc_with("replace", "a word b\n");
7089        d.anchor = Some(2);
7090        d.caret = 6; // "word" selected
7091        d.insert("X");
7092        assert_eq!(d.source, "a X b\n");
7093        assert_eq!(d.caret, 3);
7094        assert_eq!(d.anchor, None);
7095    }
7096
7097    #[test]
7098    fn toggle_bold_wraps_then_unwraps_the_selection() {
7099        let mut d = doc_with("bold", "a word b\n");
7100        d.anchor = Some(2);
7101        d.caret = 6;
7102        d.toggle(InlineKind::Strong);
7103        assert_eq!(d.source, "a **word** b\n");
7104        // The toggled region stays selected, so a second toggle reverses it.
7105        d.toggle(InlineKind::Strong);
7106        assert_eq!(d.source, "a word b\n");
7107        d.toggle(InlineKind::Strong);
7108        assert_eq!(d.source, "a **word** b\n");
7109    }
7110
7111    #[test]
7112    fn toggle_code_wraps_then_unwraps_the_selection() {
7113        let mut d = doc_with("code_rt", "a word b\n");
7114        d.anchor = Some(2);
7115        d.caret = 6;
7116        d.toggle(InlineKind::Verbatim);
7117        assert_eq!(d.source, "a `word` b\n");
7118        d.toggle(InlineKind::Verbatim);
7119        assert_eq!(d.source, "a word b\n");
7120    }
7121
7122    #[test]
7123    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
7124        // ⌘b at a bare caret, then type: the text comes out bold with no
7125        // selection ever made — the word-processor "start bold here" gesture.
7126        let mut d = doc_with("sticky_wrap", "xy\n");
7127        d.caret = 1; // between x and y
7128        d.toggle(InlineKind::Strong);
7129        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
7130        d.insert("A");
7131        assert_eq!(d.source, "x**A**y\n");
7132    }
7133
7134    #[test]
7135    fn sticky_bold_lights_the_toolbar_before_any_typing() {
7136        // The button must light the instant ⌘b is pressed, or the mode is
7137        // invisible until the first character lands.
7138        let mut d = doc_with("sticky_light", "xy\n");
7139        d.caret = 1;
7140        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
7141        d.toggle(InlineKind::Strong);
7142        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7143    }
7144
7145    #[test]
7146    fn sticky_bold_toggled_off_types_normally_again() {
7147        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
7148        // in the flow of typing, the exact sequence the user described.
7149        let mut d = doc_with("sticky_off", "\n");
7150        d.caret = 0;
7151        d.toggle(InlineKind::Strong);
7152        d.insert("a");
7153        d.insert("b"); // continues inside the run, no re-arming
7154        assert_eq!(d.source, "**ab**\n");
7155        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
7156        d.insert("c");
7157        assert_eq!(d.source, "**ab**c\n");
7158    }
7159
7160    #[test]
7161    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
7162        // Once a mark is realised the caret sits inside the run, so plain typing
7163        // extends it rather than starting a second, adjacent bold span.
7164        let mut d = doc_with("sticky_cont", "\n");
7165        d.caret = 0;
7166        d.toggle(InlineKind::Emph);
7167        d.insert("h");
7168        d.insert("i");
7169        assert_eq!(d.source, "*hi*\n");
7170    }
7171
7172    #[test]
7173    fn moving_the_caret_disarms_a_sticky_mark() {
7174        // Arming a mark and then moving away must not style text elsewhere.
7175        let mut d = doc_with("sticky_disarm", "xy\n");
7176        d.caret = 0;
7177        d.toggle(InlineKind::Strong);
7178        d.move_right(false); // caret 0 → 1, disarms
7179        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
7180        d.insert("A");
7181        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
7182    }
7183
7184    #[test]
7185    fn stacked_sticky_marks_apply_together() {
7186        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
7187        let mut d = doc_with("sticky_stack", "\n");
7188        d.caret = 0;
7189        d.toggle(InlineKind::Strong);
7190        d.toggle(InlineKind::Emph);
7191        d.insert("x");
7192        // Land the caret on the styled character and confirm both marks are live.
7193        d.anchor = Some(d.source.find('x').unwrap());
7194        d.caret = d.anchor.unwrap() + 1;
7195        let marks = d.active_inline_marks();
7196        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
7197        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
7198    }
7199
7200    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
7201
7202    #[test]
7203    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
7204        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
7205        // The space inside the run made `**bold **`, which is *not* bold — four
7206        // literal asterisks — so the rich view drew them, correctly and
7207        // uselessly, until the next character happened to close the run again.
7208        let mut d = wysiwyg_doc("edge_typing", "a \n");
7209        d.caret = 2;
7210        d.toggle(InlineKind::Strong);
7211        for c in "bold".chars() {
7212            d.insert(&c.to_string());
7213        }
7214        assert_eq!(d.source, "a **bold**\n");
7215        d.insert(" ");
7216        assert_eq!(
7217            d.source, "a **bold** \n",
7218            "the space belongs outside the run"
7219        );
7220        assert!(
7221            d.active_inline_marks().contains(InlineKind::Strong),
7222            "bold is still what's being typed, so the button stays lit"
7223        );
7224        // What the writer is looking at while all this happens: their words.
7225        d.build_visual(80);
7226        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
7227        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
7228        for c in "hey".chars() {
7229            d.insert(&c.to_string());
7230        }
7231        assert_eq!(
7232            d.source, "a **bold hey**\n",
7233            "one bold phrase, not two runs"
7234        );
7235    }
7236
7237    #[test]
7238    fn typing_past_a_space_can_still_leave_the_bold_behind() {
7239        // The other half: the marks stay armed across the space, so ⌘b turns
7240        // them off again there and the next word is plain — the run isn't
7241        // rejoined by a caret that was told not to.
7242        let mut d = wysiwyg_doc("edge_shed", "\n");
7243        d.caret = 0;
7244        d.toggle(InlineKind::Strong);
7245        for c in "bold ".chars() {
7246            d.insert(&c.to_string());
7247        }
7248        assert_eq!(d.source, "**bold** \n");
7249        d.toggle(InlineKind::Strong);
7250        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
7251        d.insert("x");
7252        assert_eq!(d.source, "**bold** x\n");
7253    }
7254
7255    #[test]
7256    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
7257        // ⌘b and then a space before any word: the space is not marked (nothing
7258        // is), and the word after it is.
7259        let mut d = wysiwyg_doc("edge_space_first", "a\n");
7260        d.caret = 1;
7261        d.toggle(InlineKind::Strong);
7262        d.insert(" ");
7263        assert_eq!(d.source, "a \n");
7264        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7265        d.insert("b");
7266        assert_eq!(d.source, "a **b**\n");
7267    }
7268
7269    #[test]
7270    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
7271        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
7272        d.caret = 8; // the caret's home at the end of the run's text
7273        d.insert(" ");
7274        assert_eq!(
7275            d.source, "x **bold** \n",
7276            "the space lands past the delimiters"
7277        );
7278        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
7279
7280        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
7281        d.caret = 4; // in front of the "b"
7282        d.insert(" ");
7283        assert_eq!(d.source, "x  **bold** y\n");
7284        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
7285    }
7286
7287    #[test]
7288    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
7289        // Backspace over the last letter of a bold phrase.
7290        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
7291        d.caret = 10; // past the "h"
7292        d.backspace();
7293        assert_eq!(d.source, "a **bold** \n");
7294        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
7295        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7296        d.insert("x");
7297        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
7298    }
7299
7300    #[test]
7301    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
7302        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
7303        // mark, which is only text. The marks live on in the caret instead.
7304        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
7305        d.caret = 5;
7306        d.backspace();
7307        assert_eq!(d.source, "a  c\n");
7308        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7309        d.insert("x");
7310        assert_eq!(d.source, "a **x** c\n");
7311    }
7312
7313    #[test]
7314    fn typing_over_a_whole_bold_word_keeps_it_bold() {
7315        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
7316        d.anchor = Some(4);
7317        d.caret = 8; // the word, not its delimiters
7318        d.insert("x");
7319        assert_eq!(d.source, "a **x** c\n");
7320    }
7321
7322    #[test]
7323    fn a_code_span_keeps_the_space_it_is_given() {
7324        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
7325        // is still verbatim, so nothing is re-spelt. The repair asks the parser
7326        // rather than a table of kinds, and this is the answer it gets.
7327        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
7328        d.caret = 7;
7329        d.insert(" ");
7330        assert_eq!(d.source, "a `code ` c\n");
7331    }
7332
7333    #[test]
7334    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
7335        // A run's closing delimiter has a caret home on each side of it, one
7336        // column apart on screen — and a plain ← off the space after a bold word
7337        // lands on the outer one. The character drawn behind the caret there is
7338        // still the last letter of the phrase, so that is what Backspace takes;
7339        // the byte behind it is a `*` nobody can see.
7340        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
7341        d.caret = 9;
7342        d.move_left(false);
7343        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
7344        d.backspace();
7345        assert_eq!(
7346            d.source, "**bol** x\n",
7347            "a letter of the phrase, not its `*`"
7348        );
7349        assert_eq!(d.caret, 5);
7350
7351        // And the mirror in front of the opening delimiter, where Delete's
7352        // character is the first letter of the run.
7353        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
7354        d.caret = 1;
7355        d.delete_forward();
7356        assert_eq!(d.source, "x**old**\n");
7357        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
7358    }
7359
7360    #[test]
7361    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
7362        // The byte beside the caret at either edge of a bold word is a `*` the
7363        // rich view draws nothing for. Taking it is not the character delete the
7364        // key was pressed for — it unspells the run and puts a literal asterisk
7365        // on screen (`a *bold** c`). The visible character is the one that goes.
7366        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
7367        d.caret = 4; // in front of the "b"
7368        d.backspace();
7369        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
7370
7371        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
7372        d.caret = 8; // past the "d"
7373        d.delete_forward();
7374        assert_eq!(d.source, "a **bold**c\n");
7375        assert_eq!(d.caret, 8, "and the caret stays inside the run");
7376        d.insert("x");
7377        assert_eq!(d.source, "a **boldx**c\n");
7378
7379        // A code span's backticks are hidden the same way, so they are covered
7380        // by the same rule and not by a list of kinds.
7381        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
7382        d.caret = 3;
7383        d.backspace();
7384        assert_eq!(d.source, "a`code` c\n");
7385    }
7386
7387    #[test]
7388    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
7389        // The asterisks are on the screen there and the caret can stand between
7390        // them, so a delete takes exactly the byte it is aimed at.
7391        let mut d = doc_with("edge_open_src", "a **bold** c\n");
7392        d.caret = 4;
7393        d.backspace();
7394        assert_eq!(d.source, "a *bold** c\n");
7395
7396        let mut d = doc_with("edge_close_src", "a **bold** c\n");
7397        d.caret = 8;
7398        d.delete_forward();
7399        assert_eq!(d.source, "a **bold* c\n");
7400    }
7401
7402    #[test]
7403    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
7404        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
7405        // The space had stepped outside the run (the mark-edge rule), taking the
7406        // caret with it, so the delete put it back down on the far side of the
7407        // closing `**` — one place on screen, and the wrong side of it. Typing
7408        // came out plain and the toolbar went dark, with nothing to see.
7409        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
7410        d.caret = 0;
7411        d.toggle(InlineKind::Strong);
7412        for c in "bold".chars() {
7413            d.insert(&c.to_string());
7414        }
7415        d.insert(" ");
7416        assert_eq!(d.source, "**bold** \n");
7417        d.backspace();
7418        assert_eq!(
7419            d.source, "**bold**\n",
7420            "the space goes, the delimiters stay"
7421        );
7422        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
7423        assert!(
7424            d.active_inline_marks().contains(InlineKind::Strong),
7425            "so the button is still lit"
7426        );
7427        d.insert("x");
7428        assert_eq!(
7429            d.source, "**boldx**\n",
7430            "and the next character is still bold"
7431        );
7432    }
7433
7434    #[test]
7435    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
7436        // What the stranded caret did next: the byte behind it was the closing
7437        // `*`, so a second press took that instead of a letter — `**bold*`, the
7438        // styling gone and an asterisk on the screen where the word had been.
7439        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
7440        d.caret = 0;
7441        d.toggle(InlineKind::Strong);
7442        for c in "bold ".chars() {
7443            d.insert(&c.to_string());
7444        }
7445        assert_eq!(d.source, "**bold** \n");
7446        d.backspace();
7447        d.backspace();
7448        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
7449        assert_eq!(d.caret, 5);
7450    }
7451
7452    #[test]
7453    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
7454        // `***both***` closes two runs with one stack of asterisks: the caret has
7455        // to walk in through all of them, or it lands between the emph and the
7456        // strong and types half-marked.
7457        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
7458        d.caret = 11;
7459        d.backspace();
7460        assert_eq!(d.source, "***both***\n");
7461        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
7462        d.insert("x");
7463        assert_eq!(d.source, "***bothx***\n");
7464    }
7465
7466    #[test]
7467    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
7468        // The settle only moves a caret a run actually closed over. Ordinary
7469        // deletes — inside a run, or in plain prose — are untouched.
7470        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
7471        d.caret = 8;
7472        d.backspace();
7473        assert_eq!(d.source, "a **bol** c\n");
7474        assert_eq!(d.caret, 7);
7475
7476        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
7477        d.caret = 5;
7478        d.backspace();
7479        assert_eq!(d.source, "plai\n");
7480        assert_eq!(d.caret, 4);
7481    }
7482
7483    #[test]
7484    fn the_source_view_leaves_a_delete_where_it_landed() {
7485        // The delimiters are on the screen there, so the offset past them is a
7486        // place the caret can be seen to be — nothing to settle.
7487        let mut d = doc_with("edge_bksp_src", "**bold** \n");
7488        d.caret = 9;
7489        d.backspace();
7490        assert_eq!(d.source, "**bold**\n");
7491        assert_eq!(d.caret, 8);
7492    }
7493
7494    #[test]
7495    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
7496        // `***both***` closes two runs with one stack of asterisks; a space that
7497        // clears only the inner one lands against the outer's and breaks that
7498        // instead.
7499        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
7500        d.caret = 9;
7501        d.insert(" ");
7502        assert_eq!(d.source, "a ***both*** \n");
7503        assert_eq!(d.caret, 13);
7504        d.insert("x");
7505        assert_eq!(d.source, "a ***both x***\n");
7506    }
7507
7508    #[test]
7509    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
7510        // The delimiter shuffle is not an edit the writer made, so it is not a
7511        // step they have to undo past.
7512        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
7513        d.caret = 8;
7514        d.insert(" ");
7515        assert_eq!(d.source, "a **bold** \n");
7516        d.undo();
7517        assert_eq!(d.source, "a **bold**\n");
7518    }
7519
7520    #[test]
7521    fn the_source_view_types_the_space_where_it_was_asked_to() {
7522        // The rule is a rich-view courtesy. In the source view the delimiters are
7523        // on the screen and the user is editing the bytes they can see.
7524        let mut d = doc_with("edge_src", "a **bold** c\n");
7525        d.caret = 8;
7526        d.insert(" ");
7527        assert_eq!(d.source, "a **bold ** c\n");
7528    }
7529
7530    #[test]
7531    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
7532        // Double-clicking a word takes the space after it; bolding that must not
7533        // spell `**word **`, which is not bold at all.
7534        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
7535        d.anchor = Some(2);
7536        d.caret = 7; // "word "
7537        d.toggle(InlineKind::Strong);
7538        assert_eq!(d.source, "a **word** b\n");
7539        d.toggle(InlineKind::Strong);
7540        assert_eq!(d.source, "a word b\n");
7541        d.toggle(InlineKind::Strong);
7542        assert_eq!(
7543            d.source, "a **word** b\n",
7544            "reapplying the mark must not wrap stale delimiter offsets"
7545        );
7546        // And a selection of nothing but whitespace has no word to mark.
7547        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
7548        d.anchor = Some(6);
7549        d.caret = 7;
7550        d.toggle(InlineKind::Strong);
7551        assert_eq!(d.source, "a word b\n");
7552        assert!(d.status.is_some());
7553    }
7554
7555    #[test]
7556    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
7557        let mut d = doc_with("head_set", "hello\n");
7558        d.caret = 2; // caret inside the paragraph, no selection
7559        d.set_block(BlockKind::Heading(1));
7560        assert_eq!(d.source, "# hello\n");
7561    }
7562
7563    #[test]
7564    fn set_block_heading_works_in_wysiwyg_view() {
7565        // The app defaults to WYSIWYG; the caret is a source offset either way.
7566        let mut d = wysiwyg_doc("head_wys", "hello\n");
7567        d.caret = 2;
7568        d.set_block(BlockKind::Heading(1));
7569        assert_eq!(d.source, "# hello\n");
7570    }
7571
7572    #[test]
7573    fn toggle_heading_applies_switches_and_reverts() {
7574        let mut d = doc_with("head_toggle", "hello\n");
7575        d.caret = 2;
7576        d.toggle_heading(1);
7577        assert_eq!(d.source, "# hello\n"); // paragraph → H1
7578        d.toggle_heading(2);
7579        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
7580        d.toggle_heading(2);
7581        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
7582    }
7583
7584    #[test]
7585    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
7586        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
7587        // the blank line but the caret rendered on the *next* line, because the
7588        // separator was a non-navigable decoration row. In Preserve flow that
7589        // blank line is a real caret home — the caret must resolve onto it, and
7590        // typing there makes the soft break that continues the paragraph.
7591        let src = "line one:\nsecond line\n";
7592        let mut d = wysiwyg_doc("pre_enter_lineend", src);
7593        d.set_line_flow(LineFlow::Preserve);
7594        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
7595        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
7596        d.newline();
7597        d.build_visual_unwrapped();
7598        assert_eq!(d.source, "line one:\n\nsecond line\n");
7599        assert_eq!(
7600            d.caret, 10,
7601            "caret sits on the new blank line, not the next line"
7602        );
7603        // The blank line is row 1, and the caret resolves onto it — not row 2.
7604        assert_eq!(
7605            d.vmap.pos_of_offset(10),
7606            (1, 0),
7607            "caret renders on the blank row"
7608        );
7609        assert!(
7610            !d.vmap.rows[1].decoration,
7611            "the blank line is navigable in Preserve"
7612        );
7613        // Typing there makes a soft break: one paragraph, three lines.
7614        d.insert("new clause,");
7615        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
7616    }
7617
7618    #[test]
7619    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
7620        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
7621        // that keeps it one paragraph — where Fold would open a second paragraph.
7622        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
7623        d.set_line_flow(LineFlow::Preserve);
7624        d.caret = 3;
7625        d.newline();
7626        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
7627
7628        // End-of-paragraph: Enter then typing continues the same paragraph on a
7629        // new line (a soft break), not a fresh paragraph.
7630        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
7631        d.set_line_flow(LineFlow::Preserve);
7632        d.caret = 3;
7633        d.newline();
7634        d.insert("def");
7635        assert_eq!(
7636            d.source, "abc\ndef\n",
7637            "end-of-line Enter + typing is a soft break"
7638        );
7639    }
7640
7641    #[test]
7642    fn preserve_double_enter_still_makes_a_paragraph() {
7643        // Two Enters in a row promote to a real paragraph break: the second lands
7644        // on the blank line the first opened and takes the empty-line branch.
7645        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
7646        d.set_line_flow(LineFlow::Preserve);
7647        d.caret = 3;
7648        d.newline();
7649        d.newline();
7650        d.insert("def");
7651        assert_eq!(
7652            d.source, "abc\n\ndef\n",
7653            "double Enter is a paragraph break"
7654        );
7655    }
7656
7657    #[test]
7658    fn preserve_backspace_joins_across_a_soft_break() {
7659        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
7660        // soft break it deletes the single newline and joins the two lines.
7661        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
7662        d.set_line_flow(LineFlow::Preserve);
7663        d.build_visual(80);
7664        d.caret = 4; // start of "def", just past the soft break
7665        d.backspace();
7666        assert_eq!(
7667            d.source, "abcdef\n",
7668            "Backspace joins across the soft break"
7669        );
7670        assert_eq!(d.caret, 3, "caret lands where the lines meet");
7671    }
7672
7673    #[test]
7674    fn fold_enter_still_starts_a_new_paragraph() {
7675        // The default flow is unchanged: a lone `\n` would render as an invisible
7676        // space, so Enter keeps opening the paragraph break that actually shows.
7677        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
7678        d.caret = 3;
7679        d.newline();
7680        assert_eq!(
7681            d.source, "abc\n\ndef\n",
7682            "Fold mid-line Enter is a paragraph break"
7683        );
7684    }
7685
7686    #[test]
7687    fn wysiwyg_one_enter_starts_a_new_paragraph() {
7688        // Regression: one Enter left the caret between the two newlines, so typing
7689        // made a soft break (one paragraph) and you needed a second Enter.
7690        let mut d = wysiwyg_doc("wys_enter", "abc\n");
7691        d.caret = 3;
7692        d.newline();
7693        d.insert("def");
7694        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
7695    }
7696
7697    #[test]
7698    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
7699        // Regression: Enter at the caret's natural End-of-line resting place
7700        // after a bold run with nothing following it (on screen: right after
7701        // "bold", before the hidden closing "**") spliced the paragraph break
7702        // at that very byte offset — which sits *before* the closing "**" in
7703        // the source, since the delimiter is hidden and emits no glyph of its
7704        // own for `push_row`'s "end of row" fallback to count. That severed the
7705        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
7706        // "**" alone on the new line instead of leaving "**bold**" intact with
7707        // a fresh empty paragraph after it.
7708        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
7709        d.move_end(false); // the WYSIWYG End key, from caret 0
7710        assert_eq!(
7711            d.caret, 6,
7712            "caret rests right after \"bold\", before the hidden \"**\""
7713        );
7714        d.newline();
7715        assert!(
7716            d.source.starts_with("**bold**"),
7717            "the closing ** must stay attached to \"bold\": got {:?}",
7718            d.source
7719        );
7720        assert_eq!(
7721            d.source, "**bold**\n\n\n",
7722            "a fresh empty paragraph follows the still-intact bold run"
7723        );
7724    }
7725
7726    #[test]
7727    fn source_view_enter_is_a_single_newline() {
7728        let mut d = doc_with("src_enter", "abc\n");
7729        d.caret = 3;
7730        d.newline();
7731        assert_eq!(d.source, "abc\n\n");
7732    }
7733
7734    #[test]
7735    fn heading_applies_at_the_end_of_a_paragraph() {
7736        // The caret at a line end sits at the doc level; set_block must still find
7737        // the block on that line.
7738        let mut d = doc_with("head_end", "abc\n");
7739        d.caret = 3; // end of "abc"
7740        d.toggle_heading(1);
7741        assert_eq!(d.source, "# abc\n");
7742    }
7743
7744    #[test]
7745    fn heading_on_an_empty_new_paragraph_creates_one() {
7746        let mut d = wysiwyg_doc("head_empty", "abc\n");
7747        d.caret = 3;
7748        d.newline(); // caret now on a fresh, empty paragraph
7749        d.toggle_heading(1);
7750        d.insert("Title");
7751        assert!(d.source.contains("# Title"), "got {:?}", d.source);
7752    }
7753
7754    #[test]
7755    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
7756        // The reported bug, end to end: click a blank line with another one under
7757        // it, press H1, type. The text landed in the heading and the caret's
7758        // offset was right (the source view drew it there), but the rich view
7759        // drew it two rows lower, on the trailing blank line — the empty `# `
7760        // heading had left every row below it short by the marker's two bytes,
7761        // and the blank line ended up claiming the heading's own end offset.
7762        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
7763        d.build_visual_unwrapped();
7764        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
7765        d.toggle_heading(1);
7766        for c in "title".chars() {
7767            d.insert(&c.to_string());
7768            d.build_visual_unwrapped(); // as a frontend does, one frame per key
7769        }
7770        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
7771        assert_eq!(
7772            d.caret_pos(),
7773            (4, 5),
7774            "the caret draws at the end of the heading"
7775        );
7776    }
7777
7778    #[test]
7779    fn clicking_an_empty_heading_types_after_its_marker() {
7780        // The same anchor from the other side: the empty heading's row is its own
7781        // caret home, so a click on it must land past the hidden `# `. Landing in
7782        // front of the hashes made the first keystroke un-heading the line.
7783        let mut d = wysiwyg_doc("head_click", "# \n");
7784        d.build_visual_unwrapped();
7785        d.caret = d.vmap.offset_of_pos(0, 0);
7786        d.insert("x");
7787        assert_eq!(d.source, "# x\n");
7788    }
7789
7790    #[test]
7791    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
7792        let mut d = wysiwyg_doc("head_enter", "# Title\n");
7793        d.caret = 7; // end of the heading
7794        d.newline();
7795        d.insert("body");
7796        assert_eq!(d.source, "# Title\n\nbody\n");
7797    }
7798
7799    #[test]
7800    fn wysiwyg_enter_continues_a_bullet_list() {
7801        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
7802        d.caret = 6; // end of "item"
7803        d.newline();
7804        d.insert("two");
7805        assert_eq!(d.source, "- item\n- two\n");
7806    }
7807
7808    #[test]
7809    fn wysiwyg_enter_increments_an_ordered_list() {
7810        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
7811        d.caret = 6; // end of "one"
7812        d.newline();
7813        d.insert("two");
7814        assert_eq!(d.source, "1. one\n2. two\n");
7815    }
7816
7817    #[test]
7818    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
7819        // Regression for the "extra newline" left between a list and the paragraph
7820        // below it. Enter, Enter leaves the list on a fresh empty paragraph
7821        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
7822        // Backspace should then take the caret cleanly back to the end of the list
7823        // item, `- item\n\nnext`, not delete a single newline and strand it on the
7824        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
7825        // no caret can land on. The map is rebuilt between keystrokes exactly as a
7826        // frontend does, since Backspace reads the stop table to place the delete.
7827        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
7828        d.caret = 6; // end of "item"
7829        d.newline();
7830        d.build_visual(80);
7831        d.newline(); // leave the list onto a fresh empty paragraph
7832        d.build_visual(80);
7833        assert_eq!(
7834            d.source, "- item\n\n\n\nnext\n",
7835            "double-Enter opens the empty paragraph"
7836        );
7837        d.backspace();
7838        assert_eq!(
7839            d.source, "- item\n\nnext\n",
7840            "one Backspace collapses the whole gap"
7841        );
7842        assert_eq!(
7843            d.caret, 6,
7844            "and lands the caret back at the end of the list item"
7845        );
7846    }
7847
7848    #[test]
7849    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
7850        // The stop-wise delete must not over-reach when there is no block boundary
7851        // to cross: two blank lines in a row are one caret stop apart, so pressing
7852        // Enter on an empty line and then Backspace removes exactly the one newline
7853        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
7854        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
7855        d.caret = 5; // the empty paragraph the first Enter already opened
7856        d.build_visual(80);
7857        d.newline();
7858        d.build_visual(80);
7859        assert_eq!(
7860            d.source, "abc\n\n\n\n",
7861            "Enter on the blank line adds one newline"
7862        );
7863        d.backspace();
7864        assert_eq!(
7865            d.source, "abc\n\n\n",
7866            "Backspace takes back exactly that one newline"
7867        );
7868    }
7869
7870    #[test]
7871    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
7872        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
7873        d.caret = 6; // end of the empty "- " item
7874        d.newline();
7875        d.insert("p");
7876        assert_eq!(d.source, "- a\n\np\n");
7877    }
7878
7879    #[test]
7880    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
7881        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
7882        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
7883        // not take the list-exit path (which would splice the `- ` away as if
7884        // leaving an empty item); the AST guard sends it to a normal break and
7885        // leaves the underline intact.
7886        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
7887        assert!(
7888            d.nodes().iter().any(|n| n.kind == Kind::Heading),
7889            "precondition: twig parses this as a heading, not a list",
7890        );
7891        d.caret = 7; // on the `- ` underline line
7892        d.newline();
7893        assert!(
7894            d.source.contains("- "),
7895            "the setext underline survives, not spliced away as a list item: {:?}",
7896            d.source,
7897        );
7898    }
7899
7900    #[test]
7901    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
7902        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
7903        d.caret = 7; // end of "abc" inside the fence
7904        d.newline();
7905        d.insert("def");
7906        assert_eq!(d.source, "```\nabc\ndef\n```\n");
7907    }
7908
7909    #[test]
7910    fn wysiwyg_enter_continues_a_block_quote() {
7911        // Enter opens a new *paragraph* inside the quote, not a second line of
7912        // the same one. `> quote\n> more` is a soft break, which under
7913        // `LineFlow::Fold` renders as a space — the keystroke would look like it
7914        // did nothing. The quoted blank line is what makes the break visible, and
7915        // it's the same thing Enter does in running prose.
7916        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
7917        d.caret = 7; // end of "quote"
7918        d.newline();
7919        d.insert("more");
7920        assert_eq!(d.source, "> quote\n>\n> more\n");
7921        // Still one quote, now holding two paragraphs — not a quote and a stray
7922        // line that fell out of it.
7923        let quotes = d
7924            .nodes()
7925            .iter()
7926            .filter(|n| n.kind == Kind::BlockQuote)
7927            .count();
7928        assert_eq!(quotes, 1);
7929    }
7930
7931    #[test]
7932    fn set_block_makes_a_heading_at_the_caret() {
7933        let mut d = doc_with("head", "Title\n\nbody\n");
7934        d.caret = 0;
7935        d.set_block(BlockKind::Heading(2));
7936        assert_eq!(d.source, "## Title\n\nbody\n");
7937        d.set_block(BlockKind::Paragraph);
7938        assert_eq!(d.source, "Title\n\nbody\n");
7939    }
7940
7941    // ── block containers (quote / list) ──────────────────────────────────────
7942
7943    #[test]
7944    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
7945        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
7946        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
7947        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
7948        // A caret at a line end sits at the doc level; the block is still found.
7949        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
7950    }
7951
7952    #[test]
7953    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
7954        // Every source line of the paragraph gets its own `> `, so a caret left
7955        // on its old byte offset falls one prefix per line above it too far
7956        // back — inside the markup it just asked for rather than in its word.
7957        assert_eq!(
7958            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
7959            "> aaa\n> b|bb\n> ccc\n"
7960        );
7961    }
7962
7963    #[test]
7964    fn toggle_blockquote_works_in_wysiwyg_view() {
7965        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
7966        assert_eq!(
7967            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
7968            "> hel|lo\n"
7969        );
7970        assert_eq!(
7971            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
7972            "hel|lo\n"
7973        );
7974    }
7975
7976    #[test]
7977    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
7978        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
7979        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
7980        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
7981        // The *other* kind converts in place instead of nesting, which is what
7982        // makes the two buttons one three-state control.
7983        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
7984        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
7985        // Its own kind, over the only item the list holds, takes it off.
7986        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
7987    }
7988
7989    #[test]
7990    fn toggle_list_works_in_wysiwyg_view() {
7991        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
7992        assert_eq!(
7993            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
7994            "1. hel|lo\n"
7995        );
7996        assert_eq!(
7997            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
7998            "- hel|lo\n"
7999        );
8000        assert_eq!(
8001            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
8002            "hel|lo\n"
8003        );
8004    }
8005
8006    #[test]
8007    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
8008        // The selection has to grow with the markup: twig takes a container off
8009        // only a range covering every block it holds, so the second press can
8010        // reverse the first only if the result is what's selected.
8011        let mut d = doc_with("list_sel", "abc\n\ndef\n");
8012        d.select_all();
8013        d.toggle_list(true);
8014        assert_eq!(d.source, "1. abc\n\n2. def\n");
8015        assert_eq!(d.selection(), Some((0, d.source.len())));
8016        d.toggle_list(true);
8017        assert_eq!(d.source, "abc\n\ndef\n");
8018    }
8019
8020    #[test]
8021    fn toggle_blockquote_nests_a_partly_covered_quote() {
8022        // twig's rule: covering only some of a container's blocks nests, because
8023        // taking the quote off would drag its uncovered siblings out with it.
8024        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
8025        d.caret = 2; // in the first quoted paragraph only
8026        d.toggle_blockquote();
8027        assert_eq!(d.source, "> > a\n>\n> b\n");
8028    }
8029
8030    #[test]
8031    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
8032        // A blank line used to be no block for twig to wrap —
8033        // `toggle_block_container` answered `NotFound` — so Quote and the list
8034        // buttons did nothing on the very line the H1 button works on, and leaf
8035        // lent twig a scratch paragraph to wrap and took it back out again.
8036        // twig 3.2.0 opens an empty container there itself, so what is left here
8037        // is where the caret lands: inside the marker that was just written.
8038        let mut d = doc_with("quote_blank", "\nabc\n");
8039        d.caret = 0;
8040        d.toggle_blockquote();
8041        assert_eq!(d.source, "> \nabc\n");
8042        assert_eq!(
8043            d.caret, 2,
8044            "the caret belongs inside the quote it just opened"
8045        );
8046        assert!(d.status.is_none(), "{:?}", d.status);
8047        assert!(d.dirty);
8048
8049        // And the paragraph below is still its own block: an empty container one
8050        // soft break from `abc` would take that paragraph into the quote with it.
8051        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
8052        d.caret = 0;
8053        d.toggle_blockquote();
8054        d.build_visual(80);
8055        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
8056
8057        // The same from the other side: a blank line directly under a paragraph
8058        // earns the blank line an empty block needs, rather than being read as a
8059        // soft break inside that paragraph.
8060        let mut d = doc_with("list_blank_below", "abc\n");
8061        d.caret = 4;
8062        d.toggle_list(false);
8063        assert_eq!(d.source, "abc\n\n- ");
8064        assert_eq!(d.caret, 7);
8065    }
8066
8067    #[test]
8068    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
8069        // The gesture the rendering fix is for. `newline` inside a quote already
8070        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
8071        // spelling — but the two marker lines it adds belonged to no node until
8072        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
8073        // just made drew as plain prose under the quote.
8074        let mut d = wysiwyg_doc("quote_enter", "> a\n");
8075        d.caret = 3; // past `a`, at the end of the quoted line
8076        d.newline();
8077        assert_eq!(d.source, "> a\n>\n> \n");
8078        d.build_visual(80);
8079        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
8080        // And the caret is on the new line, not stranded on the old one.
8081        assert_eq!(d.caret, 8);
8082    }
8083
8084    #[test]
8085    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
8086        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
8087        // now it is twig's single edit. Either way one ⌘z has to put the blank
8088        // line back rather than undoing into a half-built document.
8089        for open in [
8090            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
8091            &|d: &mut Doc| d.toggle_list(false),
8092            &|d: &mut Doc| d.toggle_list(true),
8093        ] {
8094            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
8095            d.caret = 3;
8096            open(&mut d);
8097            assert_ne!(d.source, "a\n\n\n\nb\n");
8098            d.undo();
8099            assert_eq!(d.source, "a\n\n\n\nb\n");
8100        }
8101    }
8102
8103    #[test]
8104    fn a_container_toggle_is_one_undo_step() {
8105        let mut d = doc_with("quote_undo", "hello\n");
8106        d.caret = 3;
8107        d.insert("X"); // a typing run the structural edit must not fold into
8108        d.toggle_blockquote();
8109        assert_eq!(d.source, "> helXlo\n");
8110        d.undo();
8111        assert_eq!(d.source, "helXlo\n");
8112    }
8113
8114    // ── links ────────────────────────────────────────────────────────────────
8115
8116    #[test]
8117    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
8118        let mut d = doc_with("link_sel", "word here\n");
8119        d.anchor = Some(0);
8120        d.caret = 4;
8121        d.insert_link("http://x.dev");
8122        assert_eq!(d.source, "[word](http://x.dev) here\n");
8123        // The text, not the destination — so a second press re-points the link
8124        // the first one made rather than nesting one inside it.
8125        assert_eq!(d.selected_text(), Some("word"));
8126        d.insert_link("http://y.dev");
8127        assert_eq!(d.source, "[word](http://y.dev) here\n");
8128        assert_eq!(d.selected_text(), Some("word"));
8129    }
8130
8131    #[test]
8132    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
8133        let mut d = doc_with("img_caret", "before after\n");
8134        d.caret = 7; // between "before " and "after"
8135        d.insert_image("cat.png", "a cat");
8136        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
8137        // The caret sits just past the inserted image, nothing selected.
8138        assert_eq!(d.selection(), None);
8139        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
8140    }
8141
8142    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
8143    /// destination at the first space, so the `format!` this used to be wrote
8144    /// something that was not an image at all — and the reader saw the markup as
8145    /// text. twig owns the spelling now, and moves it into the angle form.
8146    #[test]
8147    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
8148        let mut d = doc_with("img_space", "x\n");
8149        d.caret = 0;
8150        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
8151        assert_eq!(
8152            d.source,
8153            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
8154        );
8155        // And it reads back as an image pointing at the unescaped path — the angle
8156        // brackets are spelling, not part of the destination.
8157        d.caret = 2;
8158        assert_eq!(
8159            d.image_destination_at_caret(),
8160            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
8161        );
8162    }
8163
8164    /// A `)` in a caption or a filename must not close the image early.
8165    #[test]
8166    fn insert_image_escapes_a_paren_in_either_half() {
8167        let mut d = doc_with("img_paren", "x\n");
8168        d.caret = 0;
8169        d.insert_image("a)b.png", "");
8170        assert_eq!(d.source, "![](a\\)b.png)x\n");
8171        d.caret = 2;
8172        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
8173    }
8174
8175    #[test]
8176    fn insert_image_uses_the_selection_as_alt_text() {
8177        let mut d = doc_with("img_sel", "caption here\n");
8178        d.anchor = Some(0);
8179        d.caret = 7; // "caption"
8180        d.insert_image("p.png", "ignored fallback");
8181        assert_eq!(d.source, "![caption](p.png) here\n");
8182    }
8183
8184    #[test]
8185    fn insert_image_with_no_alt_leaves_empty_brackets() {
8186        let mut d = doc_with("img_noalt", "\n");
8187        d.caret = 0;
8188        d.insert_image("logo.svg", "");
8189        assert_eq!(d.source, "![](logo.svg)\n");
8190    }
8191
8192    #[test]
8193    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
8194        // The round trip is the point: it's no use writing markup the reader
8195        // can't pick up again. This is the pair that only holds from twig 2.5.1
8196        // on — before it, the one-line form went in fine and came back as a
8197        // paragraph of raw tags, publishing no media at all.
8198        let mut d = doc_with("vid_rt", "\n");
8199        d.caret = 0;
8200        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
8201        assert_eq!(
8202            d.source,
8203            "<video src=\"clip.mp4\" controls>a clip</video>\n"
8204        );
8205
8206        d.build_visual(80);
8207        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
8208        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
8209        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
8210        assert_eq!(d.vmap.media[0].alt, "a clip");
8211    }
8212
8213    #[test]
8214    fn insert_media_spells_audio_with_its_own_tag() {
8215        let mut d = doc_with("aud_rt", "\n");
8216        d.caret = 0;
8217        d.insert_media(MediaKind::Audio, "take.mp3", "");
8218        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
8219        d.build_visual(80);
8220        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
8221    }
8222
8223    #[test]
8224    fn insert_media_uses_the_selection_as_fallback_text() {
8225        // The same courtesy `insert_image` does with alt: select a caption,
8226        // insert, and the caption labels the thing rather than being replaced.
8227        let mut d = doc_with("vid_sel", "the talk here\n");
8228        d.anchor = Some(0);
8229        d.caret = 8; // "the talk"
8230        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
8231        assert_eq!(
8232            d.source,
8233            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
8234        );
8235    }
8236
8237    #[test]
8238    fn insert_media_with_an_image_kind_is_just_insert_image() {
8239        let mut d = doc_with("img_via_media", "\n");
8240        d.caret = 0;
8241        d.insert_media(MediaKind::Image, "logo.svg", "x");
8242        assert_eq!(d.source, "![x](logo.svg)\n");
8243    }
8244
8245    // ── thematic breaks ─────────────────────────────────────────────────────
8246
8247    /// The node the source parses as at `caret` — what confirms an inserted
8248    /// `---` actually reads back as a rule, not stray text or a setext heading.
8249    ///
8250    /// The *narrowest* node covering the offset. Every ancestor covers it too,
8251    /// and since twig 2.8 that includes the `doc` root, which now carries a real
8252    /// span (it reported none before, so taking the first match used to land on
8253    /// the block by luck and now always answers `"doc"`).
8254    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
8255        d.nodes()
8256            .into_iter()
8257            .filter(|n| n.span.start <= caret && caret < n.span.end)
8258            .min_by_key(|n| n.span.end - n.span.start)
8259            .map(|n| n.kind)
8260    }
8261
8262    #[test]
8263    fn a_task_box_toggles_at_the_caret_and_reads_back() {
8264        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
8265        d.caret = 8; // inside "todo"
8266        assert_eq!(d.task_checked_at_caret(), Some(false));
8267        d.toggle_task_checked();
8268        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
8269        assert_eq!(d.task_checked_at_caret(), Some(true));
8270        d.toggle_task_checked();
8271        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
8272    }
8273
8274    #[test]
8275    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
8276        // The whole reason `toggle_task_at` exists apart from the caret form:
8277        // ticking a box elsewhere must not move the cursor out of what's being
8278        // typed.
8279        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
8280        d.caret = 8; // inside "first"
8281        let second = d.source.find("second").unwrap();
8282        d.toggle_task_at(second);
8283        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
8284        assert_eq!(d.caret, 8, "the caret stayed in the first item");
8285    }
8286
8287    #[test]
8288    fn a_plain_item_gains_and_loses_a_box() {
8289        let mut d = doc_with("task_mint", "- plain\n");
8290        d.caret = 4;
8291        assert_eq!(d.task_checked_at_caret(), None);
8292        d.toggle_task_item();
8293        assert_eq!(d.source, "- [ ] plain\n");
8294        assert_eq!(
8295            d.task_checked_at_caret(),
8296            Some(false),
8297            "a new box arrives unticked"
8298        );
8299        d.toggle_task_item();
8300        assert_eq!(d.source, "- plain\n");
8301    }
8302
8303    #[test]
8304    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
8305        // `set checked` must not silently convert a bullet into a task — that is
8306        // `toggle_task_item`'s job, and twig refuses it here.
8307        let mut d = doc_with("task_none", "- plain\n");
8308        d.caret = 4;
8309        d.toggle_task_checked();
8310        assert_eq!(d.source, "- plain\n", "nothing written");
8311        assert!(
8312            d.status.is_some(),
8313            "the refusal should reach the status line"
8314        );
8315    }
8316
8317    #[test]
8318    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
8319        let mut d = doc_with("task_quote", "> - [ ] nested\n");
8320        d.caret = d.source.find("nested").unwrap();
8321        assert_eq!(d.task_checked_at_caret(), Some(false));
8322        d.toggle_task_checked();
8323        assert_eq!(d.source, "> - [x] nested\n");
8324    }
8325
8326    #[test]
8327    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
8328        // A rule is a block, so twig's `insert_thematic_break` alone lands it
8329        // after the whole paragraph. `split_block` parts the paragraph first and
8330        // the rule is aimed at the *first* half, which is what a rule button is
8331        // understood to do — and what leaf spelled by hand until twig grew both
8332        // halves of the gesture.
8333        let mut d = doc_with("hr_mid", "before after\n");
8334        d.caret = 7; // between "before " and "after"
8335        d.insert_thematic_break();
8336        assert_eq!(d.source, "before \n\n---\n\nafter\n");
8337        assert_eq!(d.selection(), None);
8338        assert_eq!(
8339            kind_at(&mut d, "before \n\n".len()),
8340            Some(Kind::ThematicBreak)
8341        );
8342    }
8343
8344    #[test]
8345    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
8346        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
8347        // and leaf wrote the first into both until twig started spelling it.
8348        let mut md = doc_with("hr_md", "para\n");
8349        md.caret = 2;
8350        md.insert_thematic_break();
8351        assert_eq!(md.source, "pa\n\n---\n\nra\n");
8352
8353        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
8354        dj.caret = 2;
8355        dj.insert_thematic_break();
8356        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
8357    }
8358
8359    #[test]
8360    fn clicking_below_a_final_thematic_break_can_type_after_it() {
8361        let mut d = wysiwyg_doc("hr_final_click", "---\n");
8362        d.build_visual(80);
8363        d.click(d.vmap.num_rows() + 2, 0, false);
8364        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
8365        d.insert("after");
8366        assert_eq!(d.source, "---\nafter");
8367    }
8368
8369    #[test]
8370    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
8371        // The same bytes are two documents. In Markdown `  - b` is a nested item
8372        // and the next one belongs beside it, at its indent. In Djot a list
8373        // marker can't interrupt a paragraph, so those bytes are literal text in
8374        // item `a` and there is only one item — writing `  - ` under it would add
8375        // no item at all, just more text, and the new sibling has to go to
8376        // column zero. Both spellings come out of the *enclosing item's* line.
8377        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
8378        md.caret = "- a\n  - b".len();
8379        md.newline();
8380        assert_eq!(md.source, "- a\n  - b\n  - \n");
8381        assert_eq!(list_items(&mut md), 3);
8382
8383        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
8384        dj.view = View::Wysiwyg;
8385        dj.build_visual(80);
8386        dj.caret = "- a\n  - b".len();
8387        dj.newline();
8388        assert_eq!(dj.source, "- a\n  - b\n- \n");
8389        assert_eq!(list_items(&mut dj), 2);
8390
8391        // Where Djot's nesting is real — opened by a blank line — the indent is
8392        // reproduced there too, and the two formats agree again.
8393        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
8394        dj.view = View::Wysiwyg;
8395        dj.build_visual(80);
8396        dj.caret = "- a\n\n  - b".len();
8397        dj.newline();
8398        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
8399        assert_eq!(list_items(&mut dj), 3);
8400    }
8401
8402    #[test]
8403    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
8404        // Tab replaces the line's whole prefix with the one twig spells, so the
8405        // quote markers, the parent's indent and an ordered marker's extra
8406        // column are all its answer rather than leaf's arithmetic.
8407        for (name, body, caret, want) in [
8408            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
8409            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
8410            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
8411            // A checkbox is markup the item's own text wraps past, but a nested
8412            // list may only open at the *list* marker's column — four in from
8413            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
8414            // parses as one item, not two.
8415            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
8416            (
8417                "quoted task",
8418                "> - [ ] a\n> - [ ] b\n",
8419                18,
8420                "> - [ ] a\n>   - [ ] b\n",
8421            ),
8422        ] {
8423            let mut doc = wysiwyg_doc(name, body);
8424            doc.caret = caret;
8425            doc.indent();
8426            assert_eq!(doc.source, want, "{name}");
8427            // The nesting is real, not just indented text.
8428            assert_eq!(list_items(&mut doc), 2, "{name}");
8429        }
8430    }
8431
8432    #[test]
8433    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
8434        // The same bytes, the two formats disagreeing, and a gesture that used
8435        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
8436        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
8437        // so those bytes are literal text inside item `a` — there is nothing to
8438        // outdent, and treating them as a marker turned one item into two, a
8439        // structural edit from a keystroke that should delete one character.
8440        //
8441        // twig's `line_prefix` is what tells them apart: it reports the marker
8442        // on the Markdown line and nothing on the Djot one, which is a
8443        // continuation. No byte scan can reach that answer.
8444        let src = "- a\n  - b\n";
8445        let at = "- a\n  - ".len();
8446
8447        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
8448        md.view = View::Wysiwyg;
8449        md.build_visual(80);
8450        md.caret = at;
8451        md.backspace();
8452        assert_eq!(md.source, "- a\n- b\n");
8453        assert_eq!(list_items(&mut md), 2);
8454
8455        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
8456        dj.view = View::Wysiwyg;
8457        dj.build_visual(80);
8458        dj.caret = at;
8459        dj.backspace();
8460        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
8461        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
8462    }
8463
8464    #[test]
8465    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
8466        // Leaf used to spell the next item from the marker bytes it scanned, and
8467        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
8468        // and dropped out of the checklist. twig reproduces the whole
8469        // continuation, and a fresh item is always unticked however the one above
8470        // it stands.
8471        for (name, body, want) in [
8472            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
8473            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
8474        ] {
8475            let mut doc = wysiwyg_doc(name, body);
8476            doc.caret = body.trim_end_matches('\n').len();
8477            doc.newline();
8478            assert_eq!(doc.source, want, "{name}");
8479            // Both items are checklist items — the new one is a box, not the
8480            // plain bullet the old marker scan left behind — and it is unticked
8481            // whichever way the one above it faces.
8482            let boxes: Vec<Option<bool>> = doc
8483                .nodes()
8484                .iter()
8485                .filter(|n| n.kind == Kind::TaskListItem)
8486                .map(|n| n.checked)
8487                .collect();
8488            assert_eq!(boxes.len(), 2, "{name}");
8489            assert_eq!(boxes[1], Some(false), "{name}");
8490        }
8491    }
8492
8493    #[test]
8494    fn a_split_takes_the_space_the_caret_was_in_front_of() {
8495        // Splicing a break at the caret strands the space the words were parted
8496        // at on the head of the second block, where it reads as an indent nobody
8497        // typed. twig's split consumes it.
8498        for (name, body, caret, want) in [
8499            ("para", "one two\n", 3, "one\n\ntwo\n"),
8500            ("item", "- one two\n", 5, "- one\n- two\n"),
8501            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
8502            // A heading takes leaf's own path, which has to match.
8503            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
8504        ] {
8505            let mut doc = wysiwyg_doc(name, body);
8506            doc.caret = caret;
8507            doc.newline();
8508            assert_eq!(doc.source, want, "{name}");
8509        }
8510    }
8511
8512    #[test]
8513    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
8514        // The one place leaf keeps its own break: `split_block` repeats the `#`,
8515        // and Enter after a title is how the body under it is asked for.
8516        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
8517        doc.caret = "# Title".len();
8518        doc.newline();
8519        doc.insert("body");
8520        assert_eq!(doc.source, "# Title\n\nbody\n");
8521        assert_eq!(
8522            doc.nodes()
8523                .iter()
8524                .filter(|n| n.kind == Kind::Heading)
8525                .count(),
8526            1
8527        );
8528    }
8529
8530    #[test]
8531    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
8532        // A quoted item's marker doesn't open its line, so a scan that starts at
8533        // column zero finds a `>` where it wanted a bullet, calls the line "not a
8534        // list" and hands Enter to the plain-quote branch — which writes `> ` and
8535        // drops the list. The next item has to carry the whole prefix.
8536        for (name, body, want) in [
8537            ("flat", "> - a\n", "> - a\n> - \n"),
8538            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
8539            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
8540            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
8541            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
8542        ] {
8543            let mut doc = wysiwyg_doc(name, body);
8544            doc.caret = body.trim_end_matches('\n').len();
8545            doc.newline();
8546            assert_eq!(doc.source, want, "{name}");
8547            // The marker isn't just spelled right, it parses as an item.
8548            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
8549        }
8550    }
8551
8552    #[test]
8553    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
8554        // Double-Enter exits the list. Unquoted that means a blank line, but a
8555        // *bare* blank line would end the quote too and drop the caret out of it,
8556        // so the separator keeps its `>` and the caret's line keeps its `> `.
8557        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
8558        doc.caret = "> - a\n> - ".len();
8559        doc.newline();
8560        assert_eq!(doc.source, "> - a\n>\n> \n");
8561        assert_eq!(list_items(&mut doc), 1);
8562        // What "still in the quote" means for the next keystroke: the caret sits
8563        // behind the prefix, and what's typed there lands inside the quote as a
8564        // paragraph of its own — not as more of item `a`.
8565        doc.insert("x");
8566        assert_eq!(doc.source, "> - a\n>\n> x\n");
8567        assert!(
8568            doc.editor
8569                .ancestors_at(doc.caret - 1)
8570                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
8571        );
8572    }
8573
8574    #[test]
8575    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
8576        // The marker is hidden block markup, so Backspace over it is structural —
8577        // but only the marker is the list's. Splicing from the line start would
8578        // take the `>` with it and silently unquote the line.
8579        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
8580        doc.caret = "> - ".len();
8581        doc.backspace();
8582        assert_eq!(doc.source, "> a\n");
8583        assert_eq!(list_items(&mut doc), 0);
8584
8585        // A nested one outdents instead, moving the bullet within the quote
8586        // rather than moving the quote.
8587        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
8588        doc.caret = "> - a\n>   - ".len();
8589        doc.backspace();
8590        assert_eq!(doc.source, "> - a\n> - b\n");
8591        assert_eq!(list_items(&mut doc), 2);
8592    }
8593
8594    #[test]
8595    fn only_a_bare_paragraph_is_parted_around_the_caret() {
8596        // The split is deliberately narrow. Parting a fenced block would leave
8597        // two fences with a rule between them, and parting a list item would
8598        // mint an item nobody asked for on the way to a rule that lands after
8599        // the list either way — so both keep the whole block intact and take the
8600        // rule after it. A caret in a quote is likewise left alone.
8601        for (name, body, caret, want) in [
8602            (
8603                "code",
8604                "```\nfn x() {}\n```\n",
8605                8,
8606                "```\nfn x() {}\n```\n\n---\n",
8607            ),
8608            ("list", "- one two\n", 6, "- one two\n\n---\n"),
8609            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n"),
8610        ] {
8611            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
8612            d.caret = caret;
8613            d.insert_thematic_break();
8614            assert_eq!(d.source, want, "{name}: the block should stay whole");
8615        }
8616    }
8617
8618    #[test]
8619    fn insert_thematic_break_replaces_the_selection() {
8620        // Now that the rule lands *at* the caret again, replacing the selection
8621        // is coherent once more: the text goes, and the rule takes its place.
8622        // The space the deletion left leading the second half is consumed by the
8623        // split rather than opening the new paragraph with it.
8624        let mut d = doc_with("hr_sel", "one two three\n");
8625        d.anchor = Some(4);
8626        d.caret = 7; // "two"
8627        d.insert_thematic_break();
8628        assert_eq!(d.source, "one \n\n---\n\nthree\n");
8629        assert_eq!(d.selection(), None);
8630    }
8631
8632    #[test]
8633    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
8634        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
8635        // because writing `---` into one is code, not a rule — twig now walks out
8636        // to the block that owns the caret's line, so there is nothing to refuse.
8637        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
8638        code.caret = 5; // inside the fenced code
8639        code.insert_thematic_break();
8640        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n");
8641        assert_eq!(code.status, None, "no refusal to report any more");
8642
8643        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
8644        table.caret = 3; // in the header row
8645        table.insert_thematic_break();
8646        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n");
8647    }
8648
8649    #[test]
8650    fn insert_thematic_break_in_a_list_item_ends_the_list() {
8651        // The un-indented rule cannot continue the list, so it closes the list
8652        // and lands at the top level rather than nested inside it.
8653        let mut d = doc_with("hr_list", "- one\n- two\n");
8654        d.caret = "- one\n- tw".len(); // mid "two"
8655        d.insert_thematic_break();
8656        d.build_visual(80);
8657        let rule_at = d.source.find("---").unwrap();
8658        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
8659        assert!(
8660            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
8661                && n.span.start <= rule_at
8662                && rule_at < n.span.end),
8663            "the rule must not be nested inside the list"
8664        );
8665    }
8666
8667    #[test]
8668    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
8669        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
8670        // which is the document the gesture was actually asked for.
8671        let mut d = doc_with("hr_quote", "> hello\n");
8672        d.caret = 4; // inside the quoted text
8673        d.insert_thematic_break();
8674        assert_eq!(d.source, "> hello\n>\n> ---\n");
8675        d.build_visual(80);
8676        let rule_at = d.source.find("---").unwrap();
8677        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
8678        assert!(
8679            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
8680                && n.span.start <= rule_at
8681                && rule_at < n.span.end),
8682            "the rule belongs to the quote it was asked for"
8683        );
8684    }
8685
8686    // ── typing against a block picture ────────────────────────────────────────
8687
8688    /// A rendered-view document with the caret parked on one of the picture's two
8689    /// stops, and the map already built — the state a frontend is in between
8690    /// drawing a frame and the next keystroke.
8691    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
8692        let mut d = doc_in(View::Wysiwyg, name, src);
8693        d.build_visual_unwrapped();
8694        let start = src.find("![").unwrap();
8695        d.caret = match side {
8696            MediaStop::Before => start,
8697            MediaStop::After => start + "![](p.png)".len(),
8698        };
8699        d
8700    }
8701
8702    /// The block media the map publishes, after rebuilding it — "is this still a
8703    /// picture, or has it become a line of text with an image in it?"
8704    fn media_count(d: &mut Doc) -> usize {
8705        d.build_visual_unwrapped();
8706        d.vmap.media.len()
8707    }
8708
8709    #[test]
8710    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
8711        // The accident this prevents: tap the blank page under a photo (which
8712        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
8713        // paragraph with an *inline* image — the photo stops being drawn.
8714        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
8715        d.insert("xy");
8716        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
8717        assert_eq!(media_count(&mut d), 1, "still a picture");
8718    }
8719
8720    #[test]
8721    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
8722        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
8723        d.insert("xy");
8724        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
8725        assert_eq!(media_count(&mut d), 1);
8726    }
8727
8728    #[test]
8729    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
8730        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
8731        d.insert("x");
8732        assert_eq!(d.source, "x\n\n![](p.png)\n");
8733        assert_eq!(media_count(&mut d), 1);
8734    }
8735
8736    #[test]
8737    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
8738        // The opened paragraph is part of the keystroke, not an edit the writer
8739        // made — so it undoes with the character, not a step later.
8740        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
8741        d.insert("x");
8742        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
8743        d.undo();
8744        assert_eq!(d.source, "hi\n\n![](p.png)\n");
8745    }
8746
8747    #[test]
8748    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
8749        // ⌘V dissolves the picture exactly as a keystroke does.
8750        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
8751        d.paste("pasted");
8752        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
8753        assert_eq!(media_count(&mut d), 1);
8754    }
8755
8756    #[test]
8757    fn typing_beside_an_inline_image_is_ordinary_editing() {
8758        // An inline image has no placeholder row and no stops of its own. Opening
8759        // a paragraph mid-sentence would be the bug, not the fix.
8760        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
8761        d.build_visual_unwrapped();
8762        d.caret = "see ![](p.png)".len();
8763        d.insert("!");
8764        assert_eq!(d.source, "see ![](p.png)! here\n");
8765    }
8766
8767    #[test]
8768    fn source_view_types_raw_markup_against_an_image_untouched() {
8769        // Source view is for writing the markup itself; a break inserted behind
8770        // the writer's back there would be the editor arguing with them.
8771        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
8772        d.caret = "![](p.png)".len();
8773        d.insert("x");
8774        assert_eq!(d.source, "![](p.png)x\n");
8775    }
8776
8777    #[test]
8778    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
8779        // A selection is replaced, not joined into, so there is nothing to
8780        // protect: the range takes the picture with it.
8781        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
8782        d.anchor = Some(d.caret);
8783        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
8784        d.insert("x");
8785        assert_eq!(d.source, "hi\n\nx\n");
8786    }
8787
8788    #[test]
8789    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
8790        // What this actually cost: a real vault's photo, to one stray Backspace.
8791        // The caret past `![](p.png)` was deleting the closing paren — invisible
8792        // in the rendered view — and the photo became the text `![](p.png`.
8793        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
8794        d.backspace();
8795        assert_eq!(d.source, "hi\n");
8796        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
8797        d.undo();
8798        assert_eq!(
8799            d.source, "hi\n\n![](p.png)\n",
8800            "and comes back in one piece"
8801        );
8802    }
8803
8804    #[test]
8805    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
8806        // Deleting the break here would join the picture to the paragraph above,
8807        // where it is an *inline* image and stops being drawn. Step over the
8808        // boundary; the next press deletes in the paragraph the caret reached.
8809        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
8810        d.backspace();
8811        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
8812        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
8813        d.backspace();
8814        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
8815        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
8816    }
8817
8818    #[test]
8819    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
8820        // The mirror. A byte-step here eats the `!` and leaves a link.
8821        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
8822        d.delete_forward();
8823        assert_eq!(d.source, "hi\n\nbye\n");
8824        assert_eq!(media_count(&mut d), 0);
8825    }
8826
8827    #[test]
8828    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
8829        let mut d = doc_at_picture(
8830            "pic_del_after",
8831            "hi\n\n![](p.png)\n\nbye\n",
8832            MediaStop::After,
8833        );
8834        d.delete_forward();
8835        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
8836        assert_eq!(
8837            d.caret,
8838            d.source.find("bye").unwrap(),
8839            "the caret stepped down to `bye`"
8840        );
8841    }
8842
8843    #[test]
8844    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
8845        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
8846        d.backspace();
8847        assert_eq!(d.source, "\n");
8848        assert_eq!(media_count(&mut d), 0);
8849    }
8850
8851    #[test]
8852    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
8853        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
8854        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
8855        d.delete_word_back();
8856        assert_eq!(d.source, "hi there\n");
8857
8858        // And in front of one it runs *through* the paragraph break into the
8859        // prose above, which merges the picture inline — so it steps out first,
8860        // and the second press deletes the word it was aimed at.
8861        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
8862        d.delete_word_back();
8863        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
8864        d.delete_word_back();
8865        assert_eq!(
8866            d.source, "hi \n\n![](p.png)\n",
8867            "the word above went, the picture stayed"
8868        );
8869        assert_eq!(media_count(&mut d), 1);
8870    }
8871
8872    #[test]
8873    fn source_view_deletes_raw_markup_against_an_image_untouched() {
8874        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
8875        d.caret = "![](p.png)".len();
8876        d.backspace();
8877        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
8878    }
8879
8880    #[test]
8881    fn image_destination_at_caret_reads_the_image_under_the_caret() {
8882        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
8883        d.caret = 3; // inside the image markup
8884        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
8885        // Past the image, the caret is in no image.
8886        d.caret = "![a cat](cat.png)".len();
8887        assert_eq!(d.image_destination_at_caret(), None);
8888    }
8889
8890    #[test]
8891    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
8892        // The image is one placeholder row by default, and `set_media_rows` grows
8893        // it to the height the frontend measured: the label row plus blank
8894        // `decoration` fillers that hold the vertical space a raster is drawn into.
8895        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
8896        assert_eq!(d.vmap.media.len(), 1);
8897        let img_row = d.vmap.media[0].rows_span.start;
8898        assert_eq!(
8899            d.vmap.media[0].rows_span,
8900            img_row..img_row + 1,
8901            "default is one row"
8902        );
8903
8904        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
8905        d.build_visual(80);
8906        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
8907        let span = d.vmap.media[0].rows_span.clone();
8908        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
8909        // The label row carries the mark and its glyphs; the three below are blank
8910        // decoration — drawn, but no caret and no text.
8911        assert!(
8912            d.vmap.rows[span.start].media.is_some(),
8913            "mark rides the first row"
8914        );
8915        for r in (span.start + 1)..span.end {
8916            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
8917            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
8918            assert!(
8919                d.vmap.rows[r].media.is_none(),
8920                "only the first row is marked"
8921            );
8922        }
8923    }
8924
8925    #[test]
8926    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
8927        // The extra rows are pure spacers: the caret's only homes stay the stop in
8928        // front of the image and the one just past it, so walking the document top
8929        // to bottom visits the same offsets whether the image is 1 row or 5.
8930        let body = "ab\n\n![x](p.png)\n\ncd\n";
8931        let stops_at = |rows: usize| -> Vec<usize> {
8932            let mut d = wysiwyg_doc("img_stops", body);
8933            if rows > 1 {
8934                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
8935                d.build_visual(80);
8936            }
8937            d.caret = 0;
8938            let mut seen = vec![d.caret];
8939            loop {
8940                d.move_right(false);
8941                if *seen.last().unwrap() == d.caret {
8942                    break;
8943                }
8944                seen.push(d.caret);
8945            }
8946            seen
8947        };
8948        assert_eq!(
8949            stops_at(1),
8950            stops_at(5),
8951            "reserving rows must not add stops"
8952        );
8953    }
8954
8955    #[test]
8956    fn insert_link_repoints_the_link_at_a_bare_caret() {
8957        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
8958        d.caret = 3; // in the link's text, nothing selected
8959        d.insert_link("http://y.dev");
8960        assert_eq!(d.source, "[word](http://y.dev)\n");
8961        assert_eq!(d.selected_text(), Some("word"));
8962    }
8963
8964    #[test]
8965    fn insert_link_on_an_empty_range_autolinks_a_url() {
8966        // A link with no text of its own is an autolink, and twig spells it —
8967        // `<…>` is the canonical form and needs no text typed into it, so the
8968        // caret lands after it rather than selecting a finished link.
8969        let mut d = doc_with("link_empty", "\n");
8970        d.caret = 0;
8971        d.insert_link("http://x.dev");
8972        assert_eq!(d.source, "<http://x.dev>\n");
8973        assert_eq!(d.selection(), None);
8974        assert_eq!(d.caret, 14);
8975    }
8976
8977    #[test]
8978    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
8979        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
8980        // in Markdown, so a destination that can't autolink doubles as the text
8981        // instead — which is then selected, ready to be typed over.
8982        let mut d = doc_with("link_rel", "\n");
8983        d.caret = 0;
8984        d.insert_link("./notes.md");
8985        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
8986        assert_eq!(d.selection(), Some((1, 11)));
8987        d.insert("Notes");
8988        assert_eq!(d.source, "[Notes](./notes.md)\n");
8989    }
8990
8991    #[test]
8992    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
8993        // The autolink's text is its URL, so re-pointing replaces the whole
8994        // node — the caret must not splice a second link inside the first.
8995        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
8996        d.caret = 10;
8997        d.insert_link("https://y.dev");
8998        assert_eq!(d.source, "see <https://y.dev> ok\n");
8999    }
9000
9001    #[test]
9002    fn code_language_reads_and_edits_through_the_fence() {
9003        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
9004        d.caret = 10; // inside the code body
9005        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
9006        assert!(d.caret_in_fenced_code());
9007
9008        d.set_code_language("python");
9009        assert!(
9010            d.source.starts_with("```python\n"),
9011            "source: {:?}",
9012            d.source
9013        );
9014        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
9015
9016        // Clearing it leaves a bare fence and no label.
9017        d.set_code_language("");
9018        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
9019        assert_eq!(d.code_language_at_caret(), None);
9020
9021        // A caret outside any code block edits nothing.
9022        let mut p = doc_with("code_lang_none", "just prose\n");
9023        assert!(!p.caret_in_fenced_code());
9024        p.set_code_language("rust");
9025        assert_eq!(p.source, "just prose\n");
9026    }
9027
9028    #[test]
9029    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
9030        // Markdown's info string ends at whitespace, so `two words` would write
9031        // a fence that reads back with a different language than the one asked
9032        // for. twig refuses it; leaf reports that and leaves the source alone.
9033        // The old splice trimmed the ends and wrote whatever was left.
9034        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
9035        d.caret = 10;
9036        d.set_code_language("two words");
9037        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
9038        assert!(d.status.is_some(), "the refusal should be reported");
9039        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
9040    }
9041
9042    #[test]
9043    fn link_destination_at_caret_reads_both_spellings() {
9044        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
9045        d.caret = 5;
9046        assert_eq!(
9047            d.link_destination_at_caret().as_deref(),
9048            Some("https://x.dev")
9049        );
9050        d.caret = 0;
9051        assert_eq!(d.link_destination_at_caret(), None);
9052
9053        // An autolink has no `destination`; its text is the URL.
9054        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
9055        a.caret = 10;
9056        assert_eq!(
9057            a.link_destination_at_caret().as_deref(),
9058            Some("https://x.dev")
9059        );
9060        a.caret = 21;
9061        assert_eq!(a.link_destination_at_caret(), None);
9062    }
9063
9064    #[test]
9065    fn locate_finds_the_block_a_declared_id_names() {
9066        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
9067        // verse. The locator has to land on the *verse*, which is the whole
9068        // reason a link carries one.
9069        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
9070                   {#v2}\nYea, I make a record in the language of my father.\n";
9071        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9072        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
9073        assert_eq!(
9074            d.source[v2.start..v2.end].trim_end(),
9075            "Yea, I make a record in the language of my father."
9076        );
9077        // The attribute line is not part of it: `start` is a place to put a
9078        // caret, and `{#v2}` is markup the caret has no business landing in.
9079        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
9080        assert_eq!(d.locate("v99"), None);
9081    }
9082
9083    #[test]
9084    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
9085        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
9086        // Markdown heading is literal text. So `#the-second-part` can only be
9087        // the heading's own words, which is the rule every Markdown renderer
9088        // already follows and therefore the one a link was authored against.
9089        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
9090        let mut d = doc_with("locate_md", src);
9091        let hit = d.locate("the-second-part").expect("the heading's slug");
9092        assert!(d.source[hit.start..].starts_with("## The Second Part"));
9093        // Bounded by the next heading that isn't under it, so a peek shows the
9094        // section rather than only its title.
9095        assert_eq!(
9096            &d.source[hit.start..hit.end],
9097            "## The Second Part\n\nbody\n\n"
9098        );
9099
9100        // A subsection does not end its parent: `# Title` runs to `## Third`'s
9101        // sibling only because there is no other `#`, so it covers the lot.
9102        let title = d.locate("title").expect("the top heading");
9103        assert_eq!(title.end, d.source.len());
9104    }
9105
9106    #[test]
9107    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
9108        // djot mints `Some-Heading-Here`; a link to it is written
9109        // `#some-heading-here` by nearly everything that writes links. Both
9110        // spellings are one question.
9111        let src = "## Some Heading Here\n\nbody\n";
9112        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9113        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
9114        let slugged = d.locate("some-heading-here").expect("the link's spelling");
9115        assert_eq!(exact, slugged);
9116        // The section, not the heading line — there is more to show than a title.
9117        assert_eq!(&d.source[exact.start..exact.end], src);
9118    }
9119
9120    #[test]
9121    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
9122        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
9123        assert_eq!(d.locate(""), None);
9124        assert_eq!(d.locate("   "), None);
9125        // All punctuation: it names nothing, and must not be read as "match the
9126        // first heading whose slug is also empty".
9127        assert_eq!(d.locate("!!!"), None);
9128    }
9129
9130    #[test]
9131    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
9132        // The document's mistake, and the answer every other anchor
9133        // implementation gives — the alternative is for a link to mean whichever
9134        // of the two a walk happened to reach first.
9135        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
9136        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9137        let hit = d.locate("dup").expect("the first `{#dup}`");
9138        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
9139    }
9140
9141    #[test]
9142    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
9143        // The button's whole job: a reference where the caret was, a definition
9144        // to give it meaning, and the caret waiting in the empty note so the
9145        // next keystroke is the note's first word.
9146        let mut d = doc_with("fn_insert", "A claim and more.\n");
9147        d.caret = 7; // just past "A claim"
9148        d.insert_footnote();
9149        assert!(
9150            d.source.starts_with("A claim[^1] and more."),
9151            "{:?}",
9152            d.source
9153        );
9154        assert!(
9155            d.source.contains("[^1]:"),
9156            "the definition too: {:?}",
9157            d.source
9158        );
9159        assert_eq!(d.status, None);
9160
9161        let reference = d.source.find("[^1]").unwrap();
9162        let note = d
9163            .footnote_at(reference + 2)
9164            .expect("the reference just written");
9165        assert_eq!(note.label, "1");
9166        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
9167        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
9168        // …and typing there is typing into the note, not near it.
9169        d.insert("the note");
9170        assert_eq!(
9171            d.footnote_at(reference + 2).and_then(|f| f.text),
9172            Some("the note".to_string())
9173        );
9174    }
9175
9176    #[test]
9177    fn insert_footnote_numbers_past_the_notes_already_written() {
9178        // A second press must not hand back a label somebody else is using: twig
9179        // reuses a defined label rather than appending a rival definition, so a
9180        // repeat of `1` would quietly point the new reference at the old note.
9181        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
9182        d.caret = 7; // past `[^1]`, before " two."
9183        d.insert_footnote();
9184        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
9185        assert_eq!(d.source.matches("[^2]:").count(), 1);
9186    }
9187
9188    #[test]
9189    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
9190        // `[^2]` with no definition is still a 2 that means something to whoever
9191        // wrote it — stepping over it would mint a note for their reference. A
9192        // word label takes no number, so it blocks none.
9193        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
9194        d.caret = d.source.find(" c").unwrap();
9195        d.insert_footnote();
9196        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
9197        assert!(
9198            d.source.starts_with("a[^2] b[^why][^1] c"),
9199            "{:?}",
9200            d.source
9201        );
9202    }
9203
9204    #[test]
9205    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
9206        // A reference annotates the words before it. Consuming the selection —
9207        // which is what an insert normally does — would delete the very claim
9208        // the author selected in order to footnote.
9209        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
9210        d.anchor = Some(2);
9211        d.caret = 7; // "claim" selected
9212        d.insert_footnote();
9213        assert!(
9214            d.source.starts_with("A claim[^1] and more."),
9215            "{:?}",
9216            d.source
9217        );
9218    }
9219
9220    #[test]
9221    fn a_note_just_written_still_knows_where_its_reference_is() {
9222        // The authoring loop in one test: press the button, type the note, ask to
9223        // go back. The caret ends at the note's last byte — which is the *end* of
9224        // the definition's span, the one offset the query used to exclude — so
9225        // this is where the round trip either works or doesn't.
9226        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
9227        d.caret = 7;
9228        d.insert_footnote();
9229        d.insert("the note");
9230        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
9231        let back = d
9232            .footnote_definition_at_caret()
9233            .expect("still in the note we just typed");
9234        assert_eq!(back.label, "1");
9235        // …and following it lands on the reference's label, where a reader's
9236        // return leg lands.
9237        assert_eq!(back.offset, Some(9));
9238        assert_eq!(&d.source[9..10], "1");
9239    }
9240
9241    #[test]
9242    fn insert_footnote_takes_one_undo_for_both_halves() {
9243        // twig writes the pair as a single edit; the point of that is here.
9244        let before = "A claim and more.\n";
9245        let mut d = doc_with("fn_insert_undo", before);
9246        d.caret = 7;
9247        d.insert_footnote();
9248        assert_ne!(d.source, before);
9249        d.undo();
9250        assert_eq!(d.source, before, "one undo takes back both halves");
9251    }
9252
9253    #[test]
9254    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
9255        // HTML is authorable — it spells the inline marks — and has no footnote.
9256        // The refusal says so rather than writing brackets that would render as
9257        // brackets.
9258        let src = "<p>A claim.</p>\n";
9259        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
9260        assert!(!Capabilities::of(Format::Html).footnote);
9261        d.caret = 5;
9262        d.insert_footnote();
9263        assert_eq!(d.source, src, "nothing written");
9264        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
9265    }
9266
9267    #[test]
9268    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
9269        // The empty body is the one place this could go wrong: the definition
9270        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
9271        // byte early would draw up in the paragraph above the note it belongs to.
9272        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
9273        d.place_caret(7, false);
9274        d.insert_footnote();
9275        d.build_visual(80); // the frame a frontend draws after the edit
9276        assert_eq!(
9277            d.vmap.snap_to_stop(d.caret),
9278            d.caret,
9279            "the caret sits on a stop"
9280        );
9281        let (row, _) = d.caret_pos();
9282        assert!(
9283            drawn_rows(&d)[row].contains("[1]"),
9284            "the caret is on the note's row, not above it: {:?}",
9285            drawn_rows(&d)
9286        );
9287    }
9288
9289    #[test]
9290    fn footnote_at_caret_resolves_a_reference_to_its_note() {
9291        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
9292        // blank line, as one has to.
9293        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
9294        d.caret = 9;
9295        let f = d
9296            .footnote_at_caret()
9297            .expect("the caret stands in a reference");
9298        assert_eq!(f.label, "1");
9299        assert_eq!(f.text.as_deref(), Some("the note"));
9300        // The offset points at the note's first word, not at the definition's
9301        // `[` — the marker is decoration with no caret stop on it.
9302        assert_eq!(f.offset, Some(29));
9303        assert_eq!(&d.source[29..37], "the note");
9304        // …and `end` closes the range, so a frontend can ask which rendered rows
9305        // the note occupies rather than re-deriving them from the text.
9306        assert_eq!(f.end, Some(37));
9307        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
9308    }
9309
9310    /// Two definitions in a row: each is its own note, and neither reaches into
9311    /// the other.
9312    ///
9313    /// A djot definition's span used to run past the blank line into the first
9314    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
9315    /// offsets named the *next* note's rows too, showing a reader two footnotes
9316    /// when they had asked about one. twig 3.1 ends the span after the block's
9317    /// own last line; the test outlives the workaround leaf carried for it.
9318    #[test]
9319    fn footnote_at_stops_a_note_at_the_definition_after_it() {
9320        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
9321        for format in [Format::Markdown, Format::Djot] {
9322            let mut d = Doc::from_source(src.to_string(), format).unwrap();
9323            d.caret = 7;
9324            let f = d.footnote_at_caret().expect("a reference");
9325            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
9326            assert_eq!(
9327                &src[f.offset.unwrap()..f.end.unwrap()],
9328                "first note.",
9329                "in {format:?}"
9330            );
9331        }
9332    }
9333
9334    /// The other side of that boundary: a blank line *inside* a definition is
9335    /// interior to it, and the note keeps its second paragraph.
9336    ///
9337    /// This is what the old body scan cost. It stopped at the first line not
9338    /// indented under the note — a blank line is not — so a two-paragraph note
9339    /// came back as its first paragraph, and "go to note" framed half of it.
9340    /// Reading the span twig gives is both simpler and right.
9341    #[test]
9342    fn footnote_at_keeps_a_notes_second_paragraph() {
9343        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
9344        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9345        d.caret = 7;
9346        let f = d.footnote_at_caret().expect("a reference");
9347        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
9348        // And it stops there — `After.` is the next block, not more note.
9349        assert_eq!(
9350            &src[f.offset.unwrap()..f.end.unwrap()],
9351            f.text.as_deref().unwrap()
9352        );
9353        assert!(!f.text.as_deref().unwrap().contains("After"));
9354    }
9355
9356    #[test]
9357    fn footnote_at_bounds_a_note_whose_body_is_empty() {
9358        // `[^1]:` with nothing after it. The range is empty rather than
9359        // inverted, and still points inside the definition — which is what keeps
9360        // a frontend's row lookup from walking off into the block above.
9361        let src = "A claim[^1].\n\n[^1]:\n";
9362        let mut d = doc_with("fn_empty_body", src);
9363        d.caret = 9;
9364        let f = d.footnote_at_caret().expect("a reference");
9365        assert_eq!(f.text.as_deref(), Some(""));
9366        assert_eq!(f.offset, f.end, "an empty note is an empty range");
9367        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
9368    }
9369
9370    #[test]
9371    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
9372        let mut d = doc_with(
9373            "fn_at_caret_none",
9374            "A claim[^1] and more.\n\n[^1]: the note\n",
9375        );
9376        d.caret = 2; // in the prose
9377        assert_eq!(d.footnote_at_caret(), None);
9378    }
9379
9380    #[test]
9381    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
9382        // The two are deliberately separate: a reference names a note in this
9383        // document, a link names somewhere to leave for, and answering one with
9384        // the other is what made a reference click do nothing at all.
9385        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
9386        d.caret = 3; // the `1` of `[^1]`
9387        assert!(d.footnote_at_caret().is_some());
9388        assert_eq!(
9389            d.link_destination_at_caret(),
9390            None,
9391            "a reference is not a link"
9392        );
9393
9394        d.caret = 10; // inside the link's label
9395        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
9396        assert_eq!(
9397            d.link_destination_at_caret().as_deref(),
9398            Some("https://x.dev")
9399        );
9400    }
9401
9402    #[test]
9403    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
9404        // A `[^99]` the document never defines is a real state — a note deleted
9405        // out from under its reference — and the label is what lets a frontend
9406        // say so. `None` here would be indistinguishable from "not on a
9407        // reference", which is the wrong thing to tell a reader.
9408        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
9409        d.caret = 9;
9410        let f = d
9411            .footnote_at_caret()
9412            .expect("the reference is still a reference");
9413        assert_eq!(f.label, "99");
9414        assert_eq!(f.text, None);
9415        assert_eq!(f.offset, None);
9416    }
9417
9418    #[test]
9419    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
9420        // Labels are not always numbers, and a note's body runs past its first
9421        // line — the indented continuation belongs to the note, so it comes back
9422        // with it (source bytes, verbatim, as documented).
9423        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
9424        let mut d = doc_with("fn_word_label", src);
9425        d.caret = 6;
9426        let f = d
9427            .footnote_at_caret()
9428            .expect("the caret stands in a reference");
9429        assert_eq!(f.label, "note");
9430        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
9431    }
9432
9433    #[test]
9434    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
9435        // The point of the offset form: a pointer hovering a reference asks what
9436        // note it names, and must not drag the caret along to ask.
9437        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
9438        d.caret = 0;
9439        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
9440        assert_eq!(f.label, "1");
9441        assert_eq!(f.text.as_deref(), Some("the note"));
9442        assert_eq!(d.caret, 0, "asking must not move the caret");
9443        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
9444    }
9445
9446    #[test]
9447    fn footnote_definition_at_caret_points_back_at_the_reference() {
9448        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
9449        // the caret can rest on — is at 9.
9450        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
9451        d.caret = 30; // inside the note's body
9452        let f = d
9453            .footnote_definition_at_caret()
9454            .expect("the caret stands in a definition");
9455        assert_eq!(f.label, "1");
9456        assert_eq!(f.offset, Some(9));
9457        assert_eq!(&d.source[7..11], "[^1]");
9458    }
9459
9460    #[test]
9461    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
9462        // The two legs have to meet: wherever `footnote_at` sends the caret, the
9463        // definition query must answer for — otherwise arriving at a note leaves
9464        // the reader somewhere the way back isn't offered.
9465        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
9466        let mut d = doc_with("fn_def_marker", src);
9467        let landed = d.footnote_at(9).unwrap().offset.unwrap();
9468        assert_eq!(
9469            d.footnote_definition_at(landed).and_then(|f| f.offset),
9470            Some(9),
9471            "the note a reference sends you to offers the way back"
9472        );
9473    }
9474
9475    #[test]
9476    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
9477        // The two queries answer for disjoint places, which is what lets one
9478        // gesture mean "down to the note" in one and "back up" in the other
9479        // without either having to remember which way the reader is going.
9480        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
9481        d.caret = 2; // prose
9482        assert_eq!(d.footnote_definition_at_caret(), None);
9483        d.caret = 9; // the reference
9484        assert_eq!(d.footnote_definition_at_caret(), None);
9485        assert!(
9486            d.footnote_at_caret().is_some(),
9487            "which is the reference's own query"
9488        );
9489    }
9490
9491    #[test]
9492    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
9493        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
9494        // note", which is false and leaves a frontend unable to explain why the
9495        // way back is missing.
9496        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
9497        let mut d = doc_with("fn_def_orphan", src);
9498        d.caret = src.find("orphan").unwrap();
9499        let f = d
9500            .footnote_definition_at_caret()
9501            .expect("an orphan is still a definition");
9502        assert_eq!(f.label, "2");
9503        assert_eq!(f.offset, None);
9504    }
9505
9506    #[test]
9507    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
9508        // One label, cited twice. The first is where the reader most likely came
9509        // from, and the only answer that doesn't depend on how they got here.
9510        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
9511        let mut d = doc_with("fn_def_repeat", src);
9512        d.caret = src.find("the note").unwrap();
9513        let f = d.footnote_definition_at_caret().expect("a definition");
9514        assert_eq!(
9515            f.offset,
9516            Some(5),
9517            "the first `[^a]`'s label, not the second's"
9518        );
9519        assert_eq!(&src[3..7], "[^a]");
9520    }
9521
9522    #[test]
9523    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
9524        // Down and back up, each leg found from the document rather than from a
9525        // memory of the other — so it still works for a reader who scrolled to
9526        // the notes instead of jumping there.
9527        //
9528        // `place_caret` rather than assigning `caret`, because that is what a
9529        // frontend calls: it snaps to a real caret stop, and a jump that lands
9530        // on a byte the caret can't rest on would arrive somewhere the return
9531        // leg no longer answers for. `build_map` first, since snapping is a
9532        // no-op until the map exists — which is exactly how this went unnoticed
9533        // when the offsets pointed at the `[^` markers.
9534        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
9535        d.build_map(None);
9536        d.place_caret(9, false);
9537        let down = d
9538            .footnote_at_caret()
9539            .expect("a reference")
9540            .offset
9541            .expect("a note");
9542        d.place_caret(down, false);
9543        let up = d
9544            .footnote_definition_at_caret()
9545            .expect("a definition")
9546            .offset
9547            .expect("a reference");
9548        d.place_caret(up, false);
9549        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
9550        assert_eq!(
9551            d.footnote_at_caret().expect("back on the reference").label,
9552            "1"
9553        );
9554    }
9555
9556    #[test]
9557    fn insert_link_hands_the_destination_to_twig_raw() {
9558        // Escaping is twig's, and format-specific: Markdown ends a destination
9559        // at the first space and needs the `<…>` form, where djot would read
9560        // those angle brackets as part of the URL.
9561        let mut d = doc_with("link_space", "word\n");
9562        d.anchor = Some(0);
9563        d.caret = 4;
9564        d.insert_link("a b");
9565        assert_eq!(d.source, "[word](<a b>)\n");
9566    }
9567
9568    #[test]
9569    fn insert_link_reports_a_destination_no_format_can_carry() {
9570        let mut d = doc_with("link_bad", "word\n");
9571        d.anchor = Some(0);
9572        d.caret = 4;
9573        d.insert_link("a\nb");
9574        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
9575        assert!(
9576            d.status.is_some(),
9577            "InvalidArgument should reach the status line"
9578        );
9579        assert!(!d.dirty);
9580    }
9581
9582    #[test]
9583    fn insert_link_works_in_wysiwyg_view() {
9584        let mut d = wysiwyg_doc("link_wys", "word here\n");
9585        d.anchor = Some(0);
9586        d.caret = 4;
9587        d.insert_link("http://x.dev");
9588        assert_eq!(d.source, "[word](http://x.dev) here\n");
9589        assert_eq!(d.selected_text(), Some("word"));
9590        // The map the caret has to keep riding is rebuilt each frame; motion
9591        // over the fresh one must still land on a real stop (the debug_assert).
9592        d.build_visual(80);
9593        d.move_right(false);
9594        d.move_left(false);
9595    }
9596
9597    #[test]
9598    fn click_maps_a_row_col_to_a_byte_offset() {
9599        let mut d = doc_with("click", "ab\ncd\n");
9600        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
9601        assert_eq!(d.caret, 4);
9602    }
9603
9604    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
9605    // stop just as the `(row, col)` click path does, so the caret can never come
9606    // to rest in the blank gap between two paragraphs — where it would draw in one
9607    // place and type in another.
9608    #[test]
9609    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
9610        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
9611        // caret stop (stops are 0,1,3,4).
9612        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
9613        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
9614        d.place_caret(2, false);
9615        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
9616        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
9617    }
9618
9619    #[test]
9620    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
9621        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
9622        d.place_caret(0, false); // anchor at the start of "A"
9623        d.place_caret(2, true); // drag into the gap
9624        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
9625        let (s, e) = d.selection().expect("a selection");
9626        assert!(
9627            d.vmap.is_stop(s) && d.vmap.is_stop(e),
9628            "selection {s}..{e} off a stop"
9629        );
9630    }
9631
9632    #[test]
9633    fn place_caret_on_a_real_stop_is_left_untouched() {
9634        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
9635        d.place_caret(3, false); // the start of "B" — a genuine stop
9636        assert_eq!(d.caret, 3);
9637    }
9638
9639    // An *empty paragraph* (two blank lines, an intentional blank line the user
9640    // opened) is a real caret stop, unlike the gap — a click into it must stay.
9641    #[test]
9642    fn place_caret_rests_in_an_empty_paragraph() {
9643        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
9644        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
9645        assert!(d.vmap.is_stop(empty));
9646        d.place_caret(empty, false);
9647        assert_eq!(d.caret, empty);
9648    }
9649
9650    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
9651        doc_in(View::Wysiwyg, name, body)
9652    }
9653
9654    /// How many list items the source actually parses into — the check that a
9655    /// marker Leaf wrote is a marker the format agrees is one.
9656    fn list_items(doc: &mut Doc) -> usize {
9657        doc.editor
9658            .nodes()
9659            .unwrap()
9660            .iter()
9661            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
9662            .count()
9663    }
9664
9665    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
9666    /// incremental (`build_spliced` / `build_cached`) path must always match.
9667    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
9668        reference_map_revealing(source, None)
9669    }
9670
9671    /// [`reference_map`] with a reveal line — the ground truth for the
9672    /// `MarkupMode::Full` builds, where the map is a function of the caret's
9673    /// line as well as the text.
9674    fn reference_map_revealing(
9675        source: &str,
9676        reveal: Option<Range<usize>>,
9677    ) -> crate::wysiwyg::VisualMap {
9678        // The same parse `Doc` uses. With twig's plain defaults instead, the two
9679        // sides disagree on what the *document* is before the renderer is even
9680        // reached — a bare `:word` is a text directive to one and prose to the
9681        // other — and the mismatch reads as a splice bug that isn't one.
9682        let mut ed =
9683            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
9684        let nodes = ed.nodes().unwrap();
9685        crate::wysiwyg::build(
9686            &nodes,
9687            source,
9688            None,
9689            false,
9690            &std::collections::HashMap::new(),
9691            reveal,
9692        )
9693    }
9694
9695    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
9696        if a.rows.len() != b.rows.len() {
9697            return true;
9698        }
9699        for (ra, rb) in a.rows.iter().zip(&b.rows) {
9700            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
9701                return true;
9702            }
9703            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
9704                if ga.ch != gb.ch || ga.src != gb.src {
9705                    return true;
9706                }
9707            }
9708        }
9709        false
9710    }
9711
9712    #[test]
9713    fn incremental_build_matches_a_fresh_build_across_edits() {
9714        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
9715        // fast path, gated on twig's `dirty_range`) or falls back to
9716        // `build_cached`. After each edit the map must be byte-identical to a
9717        // from-scratch build — this is the correctness net under the splice.
9718        let docs = [
9719            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
9720            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
9721            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
9722            // A footnote definition is a root beside `doc`, merged back into the
9723            // top-level list by `wysiwyg::top_blocks`. The random edits below
9724            // make and unmake definitions as they go (a deleted `:` turns one
9725            // back into a paragraph, and vice versa), which is exactly the
9726            // structural churn the splice path has to notice and bail out of.
9727            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
9728        ];
9729        // A deterministic mix: mostly single characters (which stay inside one
9730        // block → splice), plus edits that reshape structure (a paragraph break,
9731        // a heading marker, a code fence → fallback), so both paths are exercised.
9732        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
9733        for src in docs {
9734            let mut d = wysiwyg_doc("diff", src);
9735            d.build_visual_unwrapped();
9736            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
9737
9738            for step in 0..60usize {
9739                let len = d.source.len();
9740                let raw = (step * 13 + 5) % (len + 1);
9741                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
9742                let pre = d.source.clone();
9743                let action;
9744                if step % 3 == 0 && pos < len {
9745                    let end = (pos + 1..=len)
9746                        .find(|&i| d.source.is_char_boundary(i))
9747                        .unwrap();
9748                    action = format!("delete [{pos},{end})");
9749                    d.edit(pos, end, "");
9750                } else {
9751                    let ins = inserts[step % inserts.len()];
9752                    action = format!("insert {ins:?} @ {pos}");
9753                    d.edit(pos, pos, ins);
9754                }
9755                d.build_visual_unwrapped();
9756                if maps_differ(&d.vmap, &reference_map(&d.source)) {
9757                    panic!(
9758                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
9759                        d.source
9760                    );
9761                }
9762            }
9763        }
9764    }
9765
9766    /// A frontend is handed [`Doc::vmap`] and may present it differently:
9767    /// leaf-ratatui splices blank filler rows under an oversized heading so the
9768    /// raster it paints there has somewhere to stand, and leaves them in the map
9769    /// because the caret and the mouse both read it between frames. The splice
9770    /// path addresses that map by *row index*, against the block layout the last
9771    /// build recorded — so handed a map with rows in it that no block owns, it
9772    /// laid the re-rendered block over one of the fillers and carried the rows
9773    /// the block really occupied into the suffix. One stranded copy of the
9774    /// edited line, and everything below it a row further down, per keystroke.
9775    ///
9776    /// A map that isn't the one the layout describes is a map this path can't
9777    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
9778    #[test]
9779    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
9780        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
9781        d.build_visual_unwrapped();
9782
9783        // Stand in for the heading filler rows: two blank rows past the heading
9784        // that no block accounts for. Cloning a real row keeps every field
9785        // plausible — it is the row *count* the splice can't survive.
9786        let filler = d.vmap.rows[0].clone();
9787        d.vmap.rows.insert(1, filler.clone());
9788        d.vmap.rows.insert(1, filler);
9789
9790        // An edit inside the last block: the single-block case the splice path
9791        // is for, and the one the frontend hits on every keystroke.
9792        let at = d.source.len() - 1;
9793        d.edit(at, at, "!");
9794        d.build_visual_unwrapped();
9795
9796        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
9797    }
9798
9799    #[test]
9800    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
9801        // The same correctness net as `incremental_build_matches_a_fresh_build_
9802        // across_edits`, under `MarkupMode::Full` — where the map depends on
9803        // the caret's *line* as well as the text, so the two caches have a new
9804        // way to be wrong. Both are exercised: the block cache can hand back
9805        // rows built for a line that is no longer the revealed one, and the
9806        // splice path can reuse a suffix that still has yesterday's line raw.
9807        //
9808        // Caret motion is interleaved with the edits deliberately, because a
9809        // caret that only ever moved with the edit would never cross a line
9810        // without also dirtying it — the case where a stale reveal survives.
9811        let docs = [
9812            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
9813            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
9814        ];
9815        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
9816        for src in docs {
9817            let mut d = wysiwyg_doc("reveal_diff", src);
9818            d.set_markup_mode(MarkupMode::Full);
9819
9820            for step in 0..60usize {
9821                let len = d.source.len();
9822                let raw = (step * 13 + 5) % (len + 1);
9823                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
9824                let pre = d.source.clone();
9825                let action;
9826                if step % 3 == 0 && pos < len {
9827                    let end = (pos + 1..=len)
9828                        .find(|&i| d.source.is_char_boundary(i))
9829                        .unwrap();
9830                    action = format!("delete [{pos},{end})");
9831                    d.edit(pos, end, "");
9832                } else {
9833                    let ins = inserts[step % inserts.len()];
9834                    action = format!("insert {ins:?} @ {pos}");
9835                    d.edit(pos, pos, ins);
9836                }
9837                // Walk the caret somewhere else in the document, independently
9838                // of where the edit landed.
9839                let want = (step * 29 + 11) % (d.source.len() + 1);
9840                d.caret = (want..=d.source.len())
9841                    .find(|&i| d.source.is_char_boundary(i))
9842                    .unwrap();
9843                d.build_visual_unwrapped();
9844
9845                let want = reference_map_revealing(&d.source, d.reveal_line());
9846                if maps_differ(&d.vmap, &want) {
9847                    panic!(
9848                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
9849                        d.caret, d.source
9850                    );
9851                }
9852            }
9853        }
9854    }
9855
9856    #[test]
9857    fn caret_motion_across_lines_rebuilds_only_under_full() {
9858        // The cache-key change has to earn its keep in both directions: `Full`
9859        // must rebuild when the caret changes line (or the reveal would never
9860        // move), and the hidden modes must *not* (or every arrow key would pay
9861        // for a feature they don't use). The existing `cache_motion` test pins
9862        // the second for the default mode; this pins the pair against a mode
9863        // change alone.
9864        let body = "*one* here\n\n*two* there\n";
9865
9866        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
9867        full.set_markup_mode(MarkupMode::Full);
9868        caret_at(&mut full, "one");
9869        let before = full.revision();
9870        caret_at(&mut full, "two");
9871        assert_eq!(full.revision(), before, "motion is not an edit");
9872        assert!(
9873            drawn_rows(&full).iter().any(|r| r == "*two* there"),
9874            "the map followed the caret: {:?}",
9875            drawn_rows(&full)
9876        );
9877
9878        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
9879        caret_at(&mut hidden, "one");
9880        let key = hidden.vmap_key.clone();
9881        caret_at(&mut hidden, "two");
9882        assert_eq!(
9883            hidden.vmap_key, key,
9884            "a hidden mode rebuilds nothing on motion"
9885        );
9886    }
9887
9888    #[test]
9889    fn wysiwyg_down_crosses_a_paragraph_boundary() {
9890        // Regression: the blank separator row used to share the previous
9891        // paragraph's end offset, so Down got pinned at the boundary (while Up
9892        // still crossed). Both directions must step through it symmetrically.
9893        //
9894        // It's now stepped *over* rather than onto: the blank line between two
9895        // paragraphs is the boundary being drawn, not a line of the document, so
9896        // one press of Down crosses it. The goal column survives the crossing —
9897        // col 3 at the end of "abc" is col 3 at the end of "def".
9898        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
9899        d.caret = 3; // end of "abc" (row 0)
9900        d.move_down(false);
9901        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
9902        assert_eq!(d.caret, 8); // end of "def", col 3 kept
9903        d.move_up(false);
9904        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
9905        assert_eq!(d.caret, 3);
9906    }
9907
9908    #[test]
9909    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
9910        // The second Up and the second Down here run off the ends of the
9911        // document, which is no longer a place a press is swallowed: they carry
9912        // the caret to the start and the end of the text. The claim in the
9913        // middle — that a Down retraces the Up that crossed the paragraph gap —
9914        // is the one this test is for, and it is asserted where it is made.
9915        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
9916        d.caret = 5; // start of "def"
9917        let start = d.caret_pos();
9918        d.move_up(false);
9919        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
9920        d.move_up(false);
9921        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
9922        d.move_down(false);
9923        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
9924        d.move_down(false);
9925        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
9926    }
9927
9928    #[test]
9929    fn wysiwyg_new_paragraph_shows_before_typing() {
9930        // Regression: two Enters at the end of a paragraph produced trailing
9931        // newlines with no AST node, so the caret appeared stuck on the old line
9932        // until a character was typed. It must ride down onto the new line now.
9933        let mut d = doc_with("wys_newpara", "abc\n");
9934        d.view = View::Wysiwyg;
9935        d.caret = 3;
9936        d.insert("\n");
9937        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
9938        assert_eq!(d.source, "abc\n\n\n");
9939        d.build_visual(80);
9940        let (row, _) = d.caret_pos();
9941        assert!(
9942            row >= 2,
9943            "caret should have moved down to the new line, got row {row}"
9944        );
9945        assert!(
9946            d.vmap.num_rows() >= 3,
9947            "the blank lines should render as rows"
9948        );
9949    }
9950
9951    #[test]
9952    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
9953        // The reported bug: Enter at the end of a paragraph that has another
9954        // paragraph below put the caret at the *start of the next paragraph* —
9955        // the empty paragraph it opened had no row, so the caret snapped onto
9956        // "World". It must now sit on its own empty line, with a blank spacer
9957        // above it (the paragraph gap).
9958        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
9959        d.caret = 5; // end of "Hello"
9960        d.newline();
9961        d.build_visual(80);
9962        let (row, col) = d.caret_pos();
9963        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
9964        assert_eq!(
9965            d.vmap.row_width(row),
9966            0,
9967            "caret's row must be empty, not 'World'"
9968        );
9969        assert!(
9970            row >= 2,
9971            "a blank spacer row should sit above the caret, got row {row}"
9972        );
9973        // The row above the caret is a real (empty) gap, and "Hello" stays put.
9974        assert_eq!(
9975            d.vmap.row_width(row - 1),
9976            0,
9977            "the row above the caret is a gap"
9978        );
9979        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
9980        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
9981    }
9982
9983    #[test]
9984    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
9985        // At the document end a single Enter must also show the paragraph gap —
9986        // a blank spacer row above the caret — so the layout already matches how
9987        // it will look once the new paragraph has text.
9988        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
9989        d.caret = 5; // end of "Hello", no trailing newline
9990        d.newline(); // source becomes "Hello\n\n"
9991        d.build_visual(80);
9992        let (row, col) = d.caret_pos();
9993        assert_eq!(col, 0);
9994        assert!(
9995            row >= 2,
9996            "caret should sit below a blank spacer, got row {row}"
9997        );
9998        assert_eq!(
9999            d.vmap.row_width(row - 1),
10000            0,
10001            "the row above the caret is a gap"
10002        );
10003    }
10004
10005    #[test]
10006    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
10007        // The spacer is view-only: typing the new paragraph must not reflow the
10008        // caret onto a different row — the transient view already matched the
10009        // settled one.
10010        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
10011        d.caret = 5;
10012        d.newline();
10013        d.build_visual(80);
10014        let before = d.caret_pos();
10015        d.insert("New");
10016        d.build_visual(80);
10017        let after = d.caret_pos();
10018        assert_eq!(
10019            after.0, before.0,
10020            "typing must not move the caret to another row ({before:?} -> {after:?})"
10021        );
10022    }
10023
10024    #[test]
10025    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
10026        let fm = "---\ntitle: hi\n---\n";
10027        let body = format!("{fm}# leaf\n\nbody\n");
10028        let mut d = wysiwyg_doc("wys_fm", &body);
10029        // Opening lifts the caret out of the now-hidden frontmatter.
10030        assert_eq!(
10031            d.caret,
10032            fm.len(),
10033            "caret should start at the first real block"
10034        );
10035        // Left at the content start can't step back into frontmatter.
10036        d.move_left(false);
10037        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
10038        // Doc-start lands on the content floor, not offset 0.
10039        d.move_doc_start(false);
10040        assert_eq!(d.caret, fm.len());
10041        // Select-all + copy never include the frontmatter bytes.
10042        d.select_all();
10043        let sel = d.selected_text().unwrap().to_string();
10044        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
10045        assert!(
10046            sel.starts_with("# leaf"),
10047            "selection should begin at content: {sel:?}"
10048        );
10049    }
10050
10051    #[test]
10052    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
10053        // A fresh note is frontmatter and nothing else. With no rendered block
10054        // to floor the caret it opened at offset 0 — before the opening `---` —
10055        // so the first keystroke wrote itself in front of the metadata and the
10056        // file came out as `This---\ntitle: …`.
10057        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
10058        let mut d = wysiwyg_doc("wys_fm_only", fm);
10059        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
10060        // Nothing is rendered, so the caret draws at the origin of an empty view
10061        // — the same place an empty document puts it.
10062        assert_eq!(d.caret_pos(), (0, 0));
10063        d.insert("This");
10064        assert_eq!(d.source, format!("{fm}This"));
10065    }
10066
10067    /// `select_range` is the verb for a range a host already knows the bytes of,
10068    /// so it must not snap — and must still hold every invariant `place_caret`
10069    /// holds, the frontmatter floor above all.
10070    #[test]
10071    fn select_range_takes_the_range_as_given_but_still_floors_it() {
10072        let fm = "---\ntitle: foo\n---\n\n";
10073        let body = format!("{fm}body foo here\n");
10074        let mut d = wysiwyg_doc("wys_select_range", &body);
10075
10076        // The `foo` in the body: taken exactly, not snapped to a caret stop.
10077        let at = body.rfind("foo").unwrap();
10078        d.select_range(at, at + 3);
10079        assert_eq!(d.selection(), Some((at, at + 3)));
10080        assert_eq!(d.selected_text(), Some("foo"));
10081
10082        // The `foo` in the hidden frontmatter: below the floor, so both ends
10083        // come up to it rather than parking the caret in the metadata, where a
10084        // later keystroke would rewrite `title:`.
10085        let hidden = body.find("foo").unwrap();
10086        assert!(hidden < d.vmap.content_start);
10087        d.select_range(hidden, hidden + 3);
10088        assert!(
10089            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
10090            "a range under the floor must not leave the caret in the frontmatter"
10091        );
10092
10093        // Past the end, and mid-character, are both brought back to something
10094        // sliceable rather than panicking the next reader of the range.
10095        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
10096        let mut d = multi;
10097        d.select_range(2, 9_999);
10098        assert_eq!(d.caret, d.source.len());
10099        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
10100        assert!(d.source.is_char_boundary(d.caret));
10101    }
10102
10103    /// The bug `select_range` exists for: a match butting up against a hidden
10104    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
10105    /// the one before the `**`.
10106    #[test]
10107    fn select_range_does_not_snap_off_a_hidden_delimiter() {
10108        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
10109        let at = d.source.find("needle").unwrap();
10110        d.select_range(at, at + 6);
10111        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
10112    }
10113
10114    #[test]
10115    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
10116        // Backspace deletes `prev_boundary..caret` directly; at the first real
10117        // block that boundary is inside the hidden frontmatter, so it must be a
10118        // no-op rather than eating the closing `---`.
10119        let fm = "---\ntitle: hi\n---\n";
10120        let body = format!("{fm}leaf\n");
10121        let mut d = wysiwyg_doc("wys_fm_bs", &body);
10122        assert_eq!(d.caret, fm.len());
10123        d.backspace();
10124        assert_eq!(d.source, body, "backspace must not touch frontmatter");
10125        d.delete_word_back();
10126        assert_eq!(
10127            d.source, body,
10128            "word-delete must not touch frontmatter either"
10129        );
10130    }
10131
10132    #[test]
10133    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
10134        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
10135        // fenced div, really, since core parses these on for every document
10136        // now (`parse_extensions`). The container is a `directive` node, an
10137        // `is_block_container` kind like `block_quote`, so the caret works
10138        // inside its child paragraph exactly as it would inside a quote: typing
10139        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
10140        // untouched.
10141        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
10142        let mut d = wysiwyg_doc("wys_vis", body);
10143        d.caret = body.find("hello").unwrap() + "hello".len();
10144        d.insert("!");
10145        assert_eq!(
10146            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
10147            "typing inside the block edits its content in place"
10148        );
10149        assert!(
10150            d.source.contains(":::vis{.public .family}"),
10151            "opening fence survives"
10152        );
10153        assert!(d.source.contains(":::\nafter"), "closing fence survives");
10154    }
10155
10156    #[test]
10157    fn source_view_still_reaches_frontmatter() {
10158        // The metadata is only *hidden*, never lost: the source view edits and
10159        // selects it in full, and it's always preserved on save.
10160        let fm = "---\ntitle: hi\n---\n";
10161        let body = format!("{fm}# leaf\n");
10162        let mut d = doc_with("src_fm", &body);
10163        d.select_all();
10164        let sel = d.selected_text().unwrap();
10165        assert!(
10166            sel.contains("title"),
10167            "source view should select everything"
10168        );
10169        d.move_doc_start(false);
10170        assert_eq!(d.caret, 0, "source view can reach offset 0");
10171    }
10172
10173    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
10174
10175    #[test]
10176    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
10177        // The border and padding between two cells all share one source offset,
10178        // so a column-stepping caret would sit on `│` and then stall there
10179        // forever. Right must step: end of "Name" -> start of "Qty".
10180        let mut d = wysiwyg_doc("tbl_right", TABLE);
10181        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
10182        d.move_right(false);
10183        assert_eq!(
10184            d.caret,
10185            TABLE.find("Qty").unwrap(),
10186            "should land in the next cell"
10187        );
10188        let (r, c) = d.caret_pos();
10189        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
10190    }
10191
10192    #[test]
10193    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
10194        let mut d = wysiwyg_doc("tbl_left", TABLE);
10195        d.caret = TABLE.find("Qty").unwrap();
10196        d.move_left(false);
10197        assert_eq!(
10198            d.caret,
10199            TABLE.find("Name").unwrap() + 4,
10200            "end of the previous cell"
10201        );
10202    }
10203
10204    #[test]
10205    fn wysiwyg_down_steps_over_a_table_rule() {
10206        // Between the header and the first body row sits a `├───┼───┤` rule.
10207        // It's drawn but holds no caret, so one Down must reach "Pear".
10208        let mut d = wysiwyg_doc("tbl_down", TABLE);
10209        d.caret = TABLE.find("Name").unwrap();
10210        d.move_down(false);
10211        assert_eq!(
10212            d.caret,
10213            TABLE.find("Pear").unwrap(),
10214            "one Down reaches the body row"
10215        );
10216        d.move_down(false);
10217        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
10218    }
10219
10220    #[test]
10221    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
10222        let mut d = wysiwyg_doc("tbl_tab", TABLE);
10223        d.caret = TABLE.find("Name").unwrap();
10224        // A hop lands with the destination cell's whole content selected, the
10225        // caret at its end — so typing replaces the cell like a form field.
10226        assert!(d.cell_hop(true));
10227        assert_eq!(
10228            d.selected_text(),
10229            Some("Qty"),
10230            "the target cell comes up selected"
10231        );
10232        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
10233        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
10234        assert_eq!(d.selected_text(), Some("Pear"));
10235        assert!(d.cell_hop(false));
10236        assert_eq!(d.selected_text(), Some("Qty"));
10237    }
10238
10239    #[test]
10240    fn tab_outside_a_table_is_not_a_cell_hop() {
10241        // `cell_hop` reports false so the frontend can indent as usual.
10242        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
10243        d.caret = 4;
10244        assert!(!d.cell_hop(true));
10245        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
10246    }
10247
10248    #[test]
10249    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
10250        let mut d = wysiwyg_doc("tbl_edge", TABLE);
10251        d.caret = TABLE.rfind("12").unwrap(); // the final cell
10252        assert!(!d.cell_hop(true), "no cell after the last one");
10253        d.caret = TABLE.find("Name").unwrap();
10254        assert!(!d.cell_hop(false), "no cell before the first one");
10255    }
10256
10257    #[test]
10258    fn wysiwyg_vertical_cell_motion_holds_the_column() {
10259        // Down/Up step to the cell above/below in the *same column*, not back to
10260        // the top-left the way a naive row/col motion over the picture would.
10261        let mut d = wysiwyg_doc("tbl_vert", TABLE);
10262        d.caret = TABLE.find("Qty").unwrap();
10263        // Each vertical hop selects the destination cell, holding the column.
10264        assert!(d.cell_move_vertical(true));
10265        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
10266        assert!(d.cell_move_vertical(true));
10267        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
10268        assert!(!d.cell_move_vertical(true), "no row below the last");
10269        assert!(d.cell_move_vertical(false));
10270        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
10271        assert!(d.cell_move_vertical(false));
10272        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
10273        assert!(!d.cell_move_vertical(false), "no row above the header");
10274    }
10275
10276    #[test]
10277    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
10278        let mut d = wysiwyg_doc("tbl_grow", TABLE);
10279        d.caret = TABLE.rfind("12").unwrap();
10280        let rows_before = d.source.matches('\n').count();
10281        assert!(d.cell_tab(true), "acts as a table key");
10282        assert_eq!(
10283            d.source.matches('\n').count(),
10284            rows_before + 1,
10285            "a fresh row was appended"
10286        );
10287        assert!(d.caret_in_table(), "the caret entered the new row");
10288        // The caret sits in the new row's first cell — past the old last cell.
10289        assert!(d.caret > TABLE.rfind("12").unwrap());
10290    }
10291
10292    #[test]
10293    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
10294        let mut d = wysiwyg_doc("tbl_ret", TABLE);
10295        d.caret = TABLE.find("Name").unwrap();
10296        assert!(d.cell_return(), "acts as a table key");
10297        assert_eq!(
10298            d.selected_text(),
10299            Some("Pear"),
10300            "Return drops one cell, selecting it"
10301        );
10302        // From the last row, Return appends a row and enters it.
10303        d.caret = TABLE.rfind("Fig").unwrap();
10304        let rows_before = d.source.matches('\n').count();
10305        assert!(d.cell_return());
10306        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
10307        assert!(d.caret_in_table());
10308    }
10309
10310    #[test]
10311    fn return_and_tab_outside_a_table_decline() {
10312        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
10313        d.caret = 4;
10314        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
10315        assert!(!d.cell_tab(true), "no table: the frontend indents");
10316        assert!(
10317            !d.cell_line_break(),
10318            "no table: the frontend breaks the line"
10319        );
10320    }
10321
10322    #[test]
10323    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
10324        let mut d = wysiwyg_doc("tbl_break", TABLE);
10325        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
10326        assert!(d.cell_line_break(), "acts as a table key");
10327        assert!(
10328            d.source.contains("Pear<br>"),
10329            "spelled as an inline <br>: {}",
10330            d.source
10331        );
10332        assert!(d.caret_in_table(), "still in the cell, past the break");
10333        // The break renders as a real line: the "Pear" cell now draws two lines,
10334        // so the table's picture is one row taller than a single-line table.
10335        d.build_visual(80);
10336        let table = &d.vmap.tables[0];
10337        let cell = &table.grid[1].cells[0]; // first body row, first column
10338        assert!(
10339            cell.glyphs.iter().any(|g| g.ch == '\n'),
10340            "the cell carries the break as a newline glyph for the frontend to split"
10341        );
10342    }
10343
10344    #[test]
10345    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
10346        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
10347        // back as structure — the whole point of routing through insert_line_break
10348        // instead of splicing raw `<br>` bytes.
10349        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
10350        d.caret = TABLE.find("Pear").unwrap() + 4;
10351        assert!(d.cell_line_break());
10352        let kinds: Vec<Kind> = d
10353            .editor
10354            .nodes()
10355            .unwrap()
10356            .iter()
10357            .map(|n| n.kind.clone())
10358            .collect();
10359        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
10360        assert!(
10361            !kinds.contains(&Kind::RawInline),
10362            "still raw HTML: {kinds:?}"
10363        );
10364    }
10365
10366    #[test]
10367    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
10368        // The `<br>` draws as one newline glyph, so Backspace over it must take
10369        // all four bytes — a one-byte delete would strand a visible `<br` in the
10370        // cell (the reported bug).
10371        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
10372        d.caret = TABLE.find("Pear").unwrap() + 4;
10373        assert!(d.cell_line_break());
10374        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
10375        d.backspace(); // caret sits just past the break
10376        assert!(
10377            !d.source.contains("<br"),
10378            "no half-deleted <br left: {}",
10379            d.source
10380        );
10381        assert!(
10382            d.source.contains("| Pear |"),
10383            "the cell is back to one line: {}",
10384            d.source
10385        );
10386    }
10387
10388    #[test]
10389    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
10390        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
10391        d.caret = TABLE.find("Pear").unwrap() + 4;
10392        assert!(d.cell_line_break());
10393        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
10394        d.delete_forward();
10395        assert!(
10396            !d.source.contains("<br"),
10397            "no half-deleted <br: {}",
10398            d.source
10399        );
10400        assert!(
10401            d.source.contains("| Pear |"),
10402            "cell back to one line: {}",
10403            d.source
10404        );
10405    }
10406
10407    #[test]
10408    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
10409        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
10410        // still consumed (a real newline would split the one-line row), but the
10411        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
10412        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
10413        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10414        d.caret = src.find("Pear").unwrap() + 4;
10415        assert!(d.caret_in_table(), "caret should be inside the djot table");
10416        assert!(
10417            d.cell_line_break(),
10418            "the key is consumed, not passed to the frontend"
10419        );
10420        assert_eq!(d.source, src, "the djot cell is left untouched");
10421        assert!(
10422            !d.source.contains("<br>"),
10423            "no non-idiomatic <br> spliced into djot"
10424        );
10425        assert!(
10426            d.status.is_some(),
10427            "the refusal is surfaced on the status line"
10428        );
10429    }
10430
10431    #[test]
10432    fn typing_in_a_cell_edits_that_cell() {
10433        // Editing comes free once offsets map correctly: the caret is a source
10434        // offset, so a normal splice lands inside the pipe table.
10435        let mut d = wysiwyg_doc("tbl_type", TABLE);
10436        d.caret = TABLE.find("Pear").unwrap() + 4;
10437        d.insert("s");
10438        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
10439    }
10440
10441    #[test]
10442    fn motion_and_delete_treat_an_emoji_as_one_character() {
10443        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
10444        // bytes, several codepoints. Right-arrow must clear it in one step, and
10445        // backspace must remove the whole cluster, not a stray joiner.
10446        let family = "👨‍👩‍👧";
10447        let mut d = doc_with("emoji", &format!("a{family}b\n"));
10448        d.caret = 1; // just after 'a', before the emoji
10449        d.move_right(false);
10450        assert_eq!(
10451            d.caret,
10452            1 + family.len(),
10453            "one step clears the whole cluster"
10454        );
10455        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
10456
10457        d.backspace(); // delete the emoji as a unit
10458        assert_eq!(d.source, "ab\n");
10459        assert_eq!(d.caret, 1);
10460    }
10461
10462    #[test]
10463    fn motion_handles_a_combining_accent_as_one_character() {
10464        // "e" + U+0301 (combining acute) renders as one é.
10465        let mut d = doc_with("combining", "e\u{0301}x\n");
10466        d.caret = 0;
10467        d.move_right(false);
10468        assert_eq!(
10469            d.caret,
10470            "e\u{0301}".len(),
10471            "steps past base + combining mark"
10472        );
10473    }
10474
10475    #[test]
10476    fn undo_then_redo_round_trips_an_edit() {
10477        let mut d = doc_with("undo", "hello\n");
10478        d.caret = 5;
10479        d.insert("!");
10480        assert_eq!(d.source, "hello!\n");
10481        d.undo();
10482        assert_eq!(d.source, "hello\n");
10483        assert_eq!(d.caret, 5, "undo restores the caret");
10484        d.redo();
10485        assert_eq!(d.source, "hello!\n");
10486    }
10487
10488    #[test]
10489    fn a_run_of_typing_undoes_as_one_step() {
10490        let mut d = doc_with("coalesce", "\n");
10491        d.caret = 0;
10492        d.insert("a");
10493        d.insert("b");
10494        d.insert("c");
10495        assert_eq!(d.source, "abc\n");
10496        d.undo(); // the whole typed run, not just "c"
10497        assert_eq!(d.source, "\n");
10498        d.undo(); // nothing left — the run was one step
10499        assert_eq!(d.source, "\n");
10500        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
10501    }
10502
10503    // ── IME composition ──────────────────────────────────────────────────────
10504
10505    #[test]
10506    fn a_composition_run_undoes_as_one_step() {
10507        let mut d = doc_with("compose", "\n");
10508        d.caret = 0;
10509        // What an IME does: each step replaces the last one's provisional bytes.
10510        d.edit_composing(0, 0, "k");
10511        d.edit_composing(0, 1, "か");
10512        d.edit_composing(0, 3, "かん");
10513        d.edit_composing(0, 6, "感"); // the commit
10514        d.end_composition();
10515        assert_eq!(d.source, "感\n");
10516        d.undo(); // the whole composition, not its last keystroke
10517        assert_eq!(d.source, "\n");
10518        assert_eq!(d.status.as_deref(), None, "the run was a single step");
10519    }
10520
10521    #[test]
10522    fn two_compositions_are_two_undo_steps() {
10523        let mut d = doc_with("compose_two", "\n");
10524        d.caret = 0;
10525        d.edit_composing(0, 0, "か");
10526        d.edit_composing(0, 3, "蚊");
10527        d.end_composition();
10528        d.edit_composing(3, 3, "き");
10529        d.edit_composing(3, 6, "木");
10530        d.end_composition();
10531        assert_eq!(d.source, "蚊木\n");
10532        d.undo();
10533        assert_eq!(d.source, "蚊\n", "only the second composition");
10534        d.undo();
10535        assert_eq!(d.source, "\n");
10536    }
10537
10538    #[test]
10539    fn a_composition_does_not_fold_into_the_typing_around_it() {
10540        let mut d = doc_with("compose_typing", "\n");
10541        d.caret = 0;
10542        d.insert("a");
10543        d.insert("b");
10544        d.edit_composing(2, 2, "か");
10545        d.edit_composing(2, 5, "蚊");
10546        d.end_composition();
10547        d.insert("c");
10548        assert_eq!(d.source, "ab蚊c\n");
10549        d.undo();
10550        assert_eq!(d.source, "ab蚊\n");
10551        d.undo();
10552        assert_eq!(d.source, "ab\n");
10553        d.undo();
10554        assert_eq!(d.source, "\n");
10555    }
10556
10557    #[test]
10558    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
10559        let mut d = doc_with("compose_spurious", "\n");
10560        d.caret = 0;
10561        d.insert("a");
10562        d.end_composition(); // an IME unmarking unprompted
10563        d.insert("b");
10564        assert_eq!(d.source, "ab\n");
10565        d.undo();
10566        assert_eq!(d.source, "\n", "still one typed run");
10567    }
10568
10569    // ── the clipboard's rich flavor ──────────────────────────────────────────
10570
10571    #[test]
10572    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
10573        let mut d = doc_with("sel_inline", "a **bold** c\n");
10574        d.anchor = Some(2);
10575        d.caret = 10; // `**bold**`, inside the paragraph
10576        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
10577    }
10578
10579    #[test]
10580    fn a_whole_block_selection_keeps_its_paragraph() {
10581        let mut d = doc_with("sel_block", "a **bold** c\n");
10582        d.anchor = Some(0);
10583        d.caret = 12; // the entire paragraph
10584        assert_eq!(
10585            d.selection_html().as_deref(),
10586            Some("<p>a <strong>bold</strong> c</p>")
10587        );
10588    }
10589
10590    #[test]
10591    fn a_multi_block_selection_keeps_its_structure() {
10592        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
10593        d.select_all();
10594        let html = d.selection_html().expect("renders");
10595        assert!(html.contains("<p>para</p>"), "{html:?}");
10596        assert!(html.contains("<li>one</li>"), "{html:?}");
10597    }
10598
10599    #[test]
10600    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
10601        // The fragment `Head` is a paragraph standalone; the *document* says it
10602        // sits inside one block, so the wrapper is an artifact either way.
10603        let mut d = doc_with("sel_heading", "# Head line\n");
10604        d.anchor = Some(2);
10605        d.caret = 6;
10606        assert_eq!(d.selection_html().as_deref(), Some("Head"));
10607    }
10608
10609    #[test]
10610    fn no_selection_publishes_no_html() {
10611        let mut d = doc_with("sel_none", "a b\n");
10612        d.caret = 1;
10613        assert_eq!(d.selection_html(), None);
10614    }
10615
10616    #[test]
10617    fn pasting_html_converts_it_and_is_one_undo_step() {
10618        let mut d = doc_with("paste_html", "x\n");
10619        d.caret = 1;
10620        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
10621        assert_eq!(d.source, "xa **b** c\n");
10622        d.undo();
10623        assert_eq!(d.source, "x\n", "the whole paste, in one step");
10624    }
10625
10626    #[test]
10627    fn pasting_html_replaces_the_selection() {
10628        let mut d = doc_with("paste_html_sel", "keep drop\n");
10629        d.anchor = Some(5);
10630        d.caret = 9;
10631        assert!(d.paste_html("<em>new</em>"));
10632        assert_eq!(d.source, "keep *new*\n");
10633    }
10634
10635    #[test]
10636    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
10637        let mut d = doc_with("paste_html_bad", "x\n");
10638        d.caret = 1;
10639        // twig builds no table from HTML; raw `<table>` in prose is worse than
10640        // the plain flavor the caller still holds.
10641        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
10642        assert_eq!(d.source, "x\n", "declined edits nothing");
10643    }
10644
10645    #[test]
10646    fn copy_then_paste_round_trips_through_the_html_flavor() {
10647        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
10648        d.select_all();
10649        let html = d.selection_html().expect("renders");
10650        let mut into = doc_with("clip_round_dst", "\n");
10651        into.caret = 0;
10652        assert!(into.paste_html(&html));
10653        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
10654    }
10655
10656    #[test]
10657    fn moving_the_caret_starts_a_new_undo_group() {
10658        let mut d = doc_with("break", "\n");
10659        d.caret = 0;
10660        d.insert("a");
10661        d.insert("b"); // "ab\n", caret at 2
10662        d.move_left(false); // breaks the run
10663        d.insert("X"); // "aXb\n"
10664        assert_eq!(d.source, "aXb\n");
10665        d.undo();
10666        assert_eq!(
10667            d.source, "ab\n",
10668            "first undo removes only the post-move insert"
10669        );
10670        d.undo();
10671        assert_eq!(d.source, "\n", "second undo removes the earlier run");
10672    }
10673
10674    #[test]
10675    fn undo_reverses_a_format_toggle() {
10676        let mut d = doc_with("fmt_undo", "a word b\n");
10677        d.anchor = Some(2);
10678        d.caret = 6;
10679        d.toggle(InlineKind::Strong);
10680        assert_eq!(d.source, "a **word** b\n");
10681        d.undo();
10682        assert_eq!(d.source, "a word b\n");
10683    }
10684
10685    #[test]
10686    fn undo_back_to_the_saved_state_clears_dirty() {
10687        let mut d = doc_with("dirty_undo", "hello\n");
10688        assert!(!d.dirty);
10689        d.caret = 5;
10690        d.insert("!");
10691        assert!(d.dirty);
10692        d.undo();
10693        assert!(
10694            !d.dirty,
10695            "undoing to the saved source is not a modification"
10696        );
10697    }
10698
10699    #[test]
10700    fn a_new_edit_invalidates_redo() {
10701        let mut d = doc_with("redo_inv", "\n");
10702        d.caret = 0;
10703        d.insert("a");
10704        d.undo();
10705        d.insert("b"); // diverges — the redo of "a" is now gone
10706        d.redo();
10707        assert_eq!(d.source, "b\n");
10708    }
10709
10710    #[test]
10711    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
10712        let mut d = doc_with("can_undo", "hello\n");
10713        assert!(
10714            !d.can_undo() && !d.can_redo(),
10715            "a fresh document has no history"
10716        );
10717        d.caret = 5;
10718        d.insert("!");
10719        assert!(
10720            d.can_undo() && !d.can_redo(),
10721            "an edit is a step to take back"
10722        );
10723        d.undo();
10724        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
10725        d.redo();
10726        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
10727        d.undo();
10728        d.insert("?");
10729        assert!(
10730            d.can_undo() && !d.can_redo(),
10731            "a fresh edit ends the redo chain"
10732        );
10733        // A coalesced run over-counts steps — the bound is what a menu needs,
10734        // and it reconciles the moment twig reports the history empty.
10735        d.insert("a");
10736        d.insert("b");
10737        while d.can_undo() {
10738            d.undo();
10739        }
10740        assert_eq!(d.source, "hello\n");
10741        assert!(!d.can_undo());
10742        // A reading surface has nothing to undo, whatever the history holds.
10743        d.redo();
10744        d.set_read_only(true);
10745        assert!(!d.can_undo() && !d.can_redo());
10746    }
10747
10748    #[test]
10749    fn undo_on_empty_history_is_a_no_op() {
10750        let mut d = doc_with("undo_empty", "hi\n");
10751        d.undo();
10752        assert_eq!(d.source, "hi\n");
10753        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
10754    }
10755
10756    #[test]
10757    fn a_one_character_paste_is_its_own_undo_step() {
10758        for view in [View::Source, View::Wysiwyg] {
10759            let mut d = doc_in(view, "paste_step", "ab\n");
10760            d.caret = 0;
10761            d.insert("x");
10762            d.insert("y"); // a run of typing
10763            d.paste("z"); // one character, but pasted — not part of that run
10764            assert_eq!(d.source, "xyzab\n");
10765            d.undo();
10766            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
10767            assert_eq!(d.caret, 2, "and hands back the caret it found");
10768            d.undo();
10769            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
10770        }
10771    }
10772
10773    #[test]
10774    fn the_same_character_typed_still_joins_the_run() {
10775        // The other half of the pair: `z` is a keystroke here and a paste above,
10776        // and the two undo differently. Nothing about the *string* says which —
10777        // which is why provenance has to come from the door the caller uses.
10778        for view in [View::Source, View::Wysiwyg] {
10779            let mut d = doc_in(view, "typed_run", "ab\n");
10780            d.caret = 0;
10781            d.insert("x");
10782            d.insert("y");
10783            d.insert("z");
10784            d.undo();
10785            assert_eq!(d.source, "ab\n", "one run, one step");
10786        }
10787    }
10788
10789    #[test]
10790    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
10791        for view in [View::Source, View::Wysiwyg] {
10792            let mut d = doc_in(view, "undo_caret", "hello world\n");
10793            d.caret = 11; // standing at the end of "world", away from the edit
10794            d.edit(0, 5, "goodbye");
10795            assert_eq!(d.source, "goodbye world\n");
10796            d.undo();
10797            assert_eq!(d.source, "hello world\n");
10798            // The undone edit ends at offset 5; the user was at 11.
10799            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
10800        }
10801    }
10802
10803    #[test]
10804    fn undo_restores_the_selection_the_edit_replaced() {
10805        for view in [View::Source, View::Wysiwyg] {
10806            let mut d = doc_in(view, "undo_sel", "a word b\n");
10807            d.anchor = Some(2);
10808            d.caret = 6; // "word" selected
10809            d.insert("X");
10810            assert_eq!(d.source, "a X b\n");
10811            d.undo();
10812            assert_eq!(d.source, "a word b\n");
10813            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
10814        }
10815    }
10816
10817    #[test]
10818    fn redo_restores_the_caret_the_edit_left_behind() {
10819        for view in [View::Source, View::Wysiwyg] {
10820            let mut d = doc_in(view, "redo_caret", "hello world\n");
10821            d.caret = 11;
10822            d.edit(0, 5, "goodbye");
10823            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
10824            d.undo();
10825            d.redo();
10826            assert_eq!(d.source, "goodbye world\n");
10827            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
10828        }
10829    }
10830
10831    #[test]
10832    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
10833        for view in [View::Source, View::Wysiwyg] {
10834            let mut d = doc_in(view, "run_caret", "hi\n");
10835            d.caret = 2;
10836            d.insert("a");
10837            d.insert("b");
10838            d.insert("c");
10839            assert_eq!(d.source, "hiabc\n");
10840            d.undo();
10841            assert_eq!(d.source, "hi\n");
10842            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
10843            d.redo();
10844            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
10845        }
10846    }
10847
10848    #[test]
10849    fn undo_restores_the_caret_across_a_format_toggle() {
10850        // A toggle reaches twig without going through `splice`, so it has to
10851        // record its own step — miss it and every stack depth below it is off by
10852        // one, and undo starts handing back another edit's caret.
10853        for view in [View::Source, View::Wysiwyg] {
10854            let mut d = doc_in(view, "fmt_caret", "a word b\n");
10855            d.caret = 8;
10856            d.anchor = Some(2);
10857            d.caret = 6;
10858            d.toggle(InlineKind::Strong);
10859            assert_eq!(d.source, "a **word** b\n");
10860            d.undo();
10861            assert_eq!(d.source, "a word b\n");
10862            assert_eq!(
10863                d.selection(),
10864                Some((2, 6)),
10865                "the toggled selection comes back"
10866            );
10867        }
10868    }
10869
10870    #[test]
10871    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
10872        // The drift that would never announce itself: twig drops its redo stack
10873        // on any fresh edit, so a leaf redo entry that outlives it would restore
10874        // a caret from the timeline that edit abandoned.
10875        for view in [View::Source, View::Wysiwyg] {
10876            let mut d = doc_in(view, "redo_trunc", "hello world\n");
10877            d.caret = 11;
10878            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
10879            d.undo();
10880            assert_eq!(d.caret, 11);
10881            d.caret = 0;
10882            d.insert("X"); // diverges: A's redo is gone from twig
10883            assert_eq!(d.source, "Xhello world\n");
10884
10885            d.redo();
10886            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
10887            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
10888            d.undo();
10889            assert_eq!(d.source, "hello world\n");
10890            assert_eq!(
10891                d.caret, 0,
10892                "the surviving step's caret, not the dropped one"
10893            );
10894        }
10895    }
10896
10897    #[test]
10898    fn indent_and_outdent_move_the_caret_line_with_its_text() {
10899        for view in [View::Source, View::Wysiwyg] {
10900            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
10901            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
10902            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
10903            // Indentation the caret is standing *in* collapses to the line start
10904            // rather than dragging the caret into the text.
10905            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
10906            // A line with none to give back is left exactly as it was.
10907            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
10908            // Less than a full level gives back what it has.
10909            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
10910            // A tab is one level however many spaces it isn't.
10911            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
10912        }
10913    }
10914
10915    #[test]
10916    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
10917        // Why the level is two spaces and not the four both frontends type
10918        // today. Four is markdown's indented-code-block marker, so a Tab on a
10919        // paragraph would silently restyle it as code — a width that changes
10920        // what the document *means* isn't an indent. Pinned because the number
10921        // is the kind of thing a later list-aware pass would reach for.
10922        let mut d = doc_with("indent_kind", "hello\n");
10923        d.caret = 2;
10924        d.indent();
10925        assert_eq!(d.source, "  hello\n");
10926        assert!(
10927            d.nodes().iter().any(|n| n.kind == Kind::Para),
10928            "still prose after a Tab"
10929        );
10930        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
10931
10932        // The four-space level this replaces, for contrast: same text, and twig
10933        // reparses the paragraph into a code block.
10934        let mut wide = doc_with("indent_kind_4", "    hello\n");
10935        wide.build_visual(80);
10936        assert!(
10937            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
10938            "four spaces is a code block, not an indented paragraph"
10939        );
10940    }
10941
10942    #[test]
10943    fn indent_nests_a_list_item_under_its_parent() {
10944        // Tab indents a list item by its own marker width, landing its marker at
10945        // the parent's content column so twig reparses it as a nested list.
10946        for view in [View::Source, View::Wysiwyg] {
10947            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
10948            d.caret = 6; // on the second item
10949            d.indent();
10950            assert_eq!(d.source, "- a\n  - b\n");
10951            let lists = d
10952                .nodes()
10953                .iter()
10954                .filter(|n| n.kind == Kind::BulletList)
10955                .count();
10956            assert_eq!(lists, 2, "the indented item is a nested list");
10957        }
10958    }
10959
10960    #[test]
10961    fn indent_nests_an_ordered_item_at_its_marker_width() {
10962        // An ordered marker `1. ` is three columns wide, so a two-space step
10963        // (which nests a bullet) leaves it flat. Regression: Tab must use the
10964        // marker width, three, so the item actually nests — and the source
10965        // renumbers so the sub-list restarts at 1 and the outer list resumes.
10966        for view in [View::Source, View::Wysiwyg] {
10967            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
10968            d.caret = d.source.find('b').unwrap();
10969            d.indent();
10970            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
10971            let lists = d
10972                .nodes()
10973                .iter()
10974                .filter(|n| n.kind == Kind::OrderedList)
10975                .count();
10976            assert_eq!(lists, 2, "the indented item is a nested ordered list");
10977        }
10978    }
10979
10980    #[test]
10981    fn indent_leaves_a_lists_first_item_put() {
10982        // The first item of a list has no sibling above it to nest under, so Tab
10983        // is a no-op there — the marker stays at column zero rather than being
10984        // shoved into indentation twig can't read as a sub-list.
10985        for view in [View::Source, View::Wysiwyg] {
10986            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
10987            d.caret = 1; // on the FIRST item
10988            d.indent();
10989            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
10990            // The sibling below still nests, proving the guard is per-item.
10991            d.caret = d.source.find('b').unwrap();
10992            d.indent();
10993            assert_eq!(d.source, "- a\n  - b\n");
10994        }
10995    }
10996
10997    #[test]
10998    fn hidden_mode_keeps_typed_markup_literal() {
10999        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
11000        // twig escapes what would open markup, so the source is `\*hi\*` and the
11001        // AST is a plain string. Formatting is the commands' job in this mode.
11002        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
11003        d.insert("*hi*");
11004        assert_eq!(d.source, "\\*hi\\*");
11005        assert!(
11006            d.nodes()
11007                .iter()
11008                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
11009        );
11010    }
11011
11012    #[test]
11013    fn hidden_mode_escapes_a_line_start_block_marker() {
11014        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
11015        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
11016        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
11017        d.insert("# hi");
11018        assert_eq!(d.source, "\\# hi");
11019        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
11020    }
11021
11022    #[test]
11023    fn authoring_modes_keep_typed_markup_live() {
11024        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
11025        // (no escape), the same as source view — escaping is `None`'s alone, and
11026        // it's the axis, not the reveal, that decides.
11027        for (view, mode) in [
11028            (View::Wysiwyg, MarkupMode::Shortcuts),
11029            (View::Wysiwyg, MarkupMode::Full),
11030            (View::Source, MarkupMode::None),
11031        ] {
11032            let mut d = doc_in(view, "live_markup", "");
11033            d.set_markup_mode(mode);
11034            d.insert("*hi*");
11035            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
11036        }
11037    }
11038
11039    #[test]
11040    fn hidden_mode_overwrite_undoes_in_one_step() {
11041        // Typing over a selection escapes the replacement *and* stays a single
11042        // undo — the selection-delete and the literal insert fold together, so
11043        // one undo brings the whole selection back, like a plain overwrite.
11044        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
11045        d.anchor = Some(2);
11046        d.caret = 6; // "word"
11047        d.insert("*");
11048        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
11049        d.undo();
11050        assert_eq!(d.source, "a word b\n");
11051        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
11052    }
11053
11054    #[test]
11055    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
11056        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
11057        // the whole visual character, never stranding the hidden `\`.
11058        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
11059        d.insert("*");
11060        assert_eq!(d.source, "\\*");
11061        d.backspace();
11062        assert_eq!(d.source, "", "the escape backslash went with the *");
11063        // A *literal* backslash (source view, no escape) is an ordinary char.
11064        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
11065        s.caret = 3; // after `b`
11066        s.backspace();
11067        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
11068    }
11069
11070    #[test]
11071    fn hidden_mode_leaves_structural_markup_alone() {
11072        // Enter continues a bullet list by writing a real `- ` marker (an
11073        // `insert_raw`, not the typing path), so Hidden mode's escaping never
11074        // touches it — the list keeps working.
11075        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
11076        d.caret = 6;
11077        d.newline();
11078        d.insert("two");
11079        assert_eq!(d.source, "- item\n- two\n");
11080    }
11081
11082    #[test]
11083    fn markup_mode_defaults_to_none_and_round_trips() {
11084        // Diaryx's default is the clean `None` surface; a markup-fluent
11085        // frontend can climb the ladder, and the choice sticks.
11086        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
11087        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
11088        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
11089            d.set_markup_mode(mode);
11090            assert_eq!(d.markup_mode(), mode);
11091        }
11092    }
11093
11094    #[test]
11095    fn full_mode_reveals_only_the_caret_line() {
11096        // The mode's whole claim: the caret's line shows its raw delimiters and
11097        // every other line stays resolved. Two paragraphs with identical markup
11098        // so the only difference between the rows is where the caret is.
11099        let mut d = doc_in(
11100            View::Wysiwyg,
11101            "reveal_caret_line",
11102            "*one* here\n\n*two* there\n",
11103        );
11104        d.set_markup_mode(MarkupMode::Full);
11105
11106        caret_at(&mut d, "one");
11107        let rows = drawn_rows(&d);
11108        assert!(
11109            rows.iter().any(|r| r == "*one* here"),
11110            "caret's line raw: {rows:?}"
11111        );
11112        assert!(
11113            rows.iter().any(|r| r == "two there"),
11114            "other line resolved: {rows:?}"
11115        );
11116
11117        // Move to the other paragraph: the reveal follows, and the line just
11118        // left goes back to being resolved.
11119        caret_at(&mut d, "two");
11120        let rows = drawn_rows(&d);
11121        assert!(
11122            rows.iter().any(|r| r == "*two* there"),
11123            "caret's line raw: {rows:?}"
11124        );
11125        assert!(
11126            rows.iter().any(|r| r == "one here"),
11127            "left line resolved: {rows:?}"
11128        );
11129    }
11130
11131    #[test]
11132    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
11133        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
11134        // the same treatment as an emphasis's `*`: hidden while the caret is
11135        // elsewhere, shown in full where the caret lands. That falls out of
11136        // `delims` reading the bytes between the mark's span and its content
11137        // span, which is exactly `==🔴 ` and `==`, rather than from a table
11138        // of spellings — so the no-space form `==🟢green==` reveals right too.
11139        let mut d = doc_in(
11140            View::Wysiwyg,
11141            "reveal_coloured_mark",
11142            "a ==🔴 red== one\n\nb ==plain== two\n",
11143        );
11144        d.set_markup_mode(MarkupMode::Full);
11145
11146        caret_at(&mut d, "red");
11147        let rows = drawn_rows(&d);
11148        assert!(
11149            rows.iter().any(|r| r == "a ==🔴 red== one"),
11150            "the caret's line shows the colour it was written with: {rows:?}"
11151        );
11152        assert!(
11153            rows.iter().any(|r| r == "b plain two"),
11154            "and every other line stays resolved: {rows:?}"
11155        );
11156
11157        // Away from it, the emoji goes back to being markup — the reader sees
11158        // the words and the wash.
11159        caret_at(&mut d, "two");
11160        let rows = drawn_rows(&d);
11161        assert!(
11162            rows.iter().any(|r| r == "a red one"),
11163            "resolved again: {rows:?}"
11164        );
11165    }
11166
11167    #[test]
11168    fn hidden_modes_never_reveal_wherever_the_caret_is() {
11169        // The two rungs below `Full` share a rendering: delimiters stay hidden
11170        // even under the caret. `Shortcuts` differing from `None` only in what
11171        // typing does is exactly the point of splitting the axes.
11172        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
11173            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
11174            d.set_markup_mode(mode);
11175            caret_at(&mut d, "one");
11176            let rows = drawn_rows(&d);
11177            assert!(
11178                rows.iter().any(|r| r == "one here"),
11179                "{mode:?} hides: {rows:?}"
11180            );
11181            assert!(
11182                !rows.iter().any(|r| r.contains('*')),
11183                "{mode:?} shows no `*`: {rows:?}"
11184            );
11185        }
11186    }
11187
11188    #[test]
11189    fn revealed_delimiters_are_the_authors_own_spelling() {
11190        // Delimiters are re-read from the source rather than synthesized per
11191        // kind, so a line comes back spelled the way it was written: `_em_` does
11192        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
11193        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
11194        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
11195        d.set_markup_mode(MarkupMode::Full);
11196        caret_at(&mut d, "em");
11197        let rows = drawn_rows(&d);
11198        assert!(
11199            rows.iter().any(|r| r == body.trim_end()),
11200            "the revealed line is its own source: {rows:?}"
11201        );
11202    }
11203
11204    #[test]
11205    fn revealed_heading_shows_its_hashes() {
11206        // The `# ` marker is a block-level prefix, not an inline delimiter, so
11207        // it takes its own path — but it reveals on the same rule.
11208        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
11209        d.set_markup_mode(MarkupMode::Full);
11210
11211        caret_at(&mut d, "Title");
11212        assert!(
11213            drawn_rows(&d).iter().any(|r| r == "# Title"),
11214            "{:?}",
11215            drawn_rows(&d)
11216        );
11217
11218        caret_at(&mut d, "body");
11219        let rows = drawn_rows(&d);
11220        assert!(
11221            rows.iter().any(|r| r == "Title"),
11222            "hashes hidden again: {rows:?}"
11223        );
11224    }
11225
11226    #[test]
11227    fn revealed_delimiters_are_caret_stops() {
11228        // A delimiter that is drawn but can't be reached is worse than one
11229        // that's hidden: the mode exists so the markup can be *edited*. Every
11230        // revealed byte must be somewhere the caret can stand.
11231        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
11232        d.set_markup_mode(MarkupMode::Full);
11233        caret_at(&mut d, "em");
11234        let opener = d.source.find('*').unwrap();
11235        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
11236        assert!(
11237            d.vmap.is_stop(opener + 3),
11238            "the closing `*` is a caret stop"
11239        );
11240    }
11241
11242    #[test]
11243    fn setext_heading_reveals_nothing_across_its_newline() {
11244        // A setext heading's underline is on another line, so it is not the
11245        // caret line's to reveal — and emitting it would inject a `\n` glyph
11246        // that splits the row where the author wrote no break.
11247        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
11248        d.set_markup_mode(MarkupMode::Full);
11249        caret_at(&mut d, "Title");
11250        let rows = drawn_rows(&d);
11251        assert!(
11252            rows.iter().any(|r| r == "Title"),
11253            "title renders alone: {rows:?}"
11254        );
11255        assert!(
11256            !rows.iter().any(|r| r.contains('=')),
11257            "no underline leaks in: {rows:?}"
11258        );
11259    }
11260
11261    #[test]
11262    fn markup_mode_axes_split_the_ladder() {
11263        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
11264        // that authors markup but still hides it, and it's the only rung where
11265        // the two axes disagree.
11266        assert!(!MarkupMode::None.authors());
11267        assert!(!MarkupMode::None.reveals_caret_line());
11268        assert!(MarkupMode::Shortcuts.authors());
11269        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
11270        assert!(MarkupMode::Full.authors());
11271        assert!(MarkupMode::Full.reveals_caret_line());
11272    }
11273
11274    #[test]
11275    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
11276        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
11277        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
11278        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
11279        // nested bullet and `hello` stays prose: the file round-trips instead of
11280        // hiding a heading the user never asked for.
11281        for view in [View::Source, View::Wysiwyg] {
11282            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
11283            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
11284            d.indent();
11285            assert_eq!(d.source, "- hello\n  * \n");
11286            assert!(
11287                d.nodes().iter().all(|n| n.kind != Kind::Heading),
11288                "no heading"
11289            );
11290            // And it's genuinely a nested list, not a flat one.
11291            assert_eq!(
11292                d.nodes()
11293                    .iter()
11294                    .filter(|n| n.kind == Kind::BulletList)
11295                    .count(),
11296                2
11297            );
11298        }
11299    }
11300
11301    #[test]
11302    fn indenting_a_dash_item_with_content_keeps_its_dash() {
11303        // With content, `- x` can't be a setext underline, so there's nothing to
11304        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
11305        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
11306        d.caret = d.source.find('x').unwrap();
11307        d.indent();
11308        assert_eq!(d.source, "- hello\n  - x\n");
11309    }
11310
11311    #[test]
11312    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
11313        // The dash→`*` repair coalesces into the Tab, so a single undo restores
11314        // the whole pre-Tab state rather than stranding a half-collapsed doc.
11315        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
11316        d.caret = d.source.find("- \n").unwrap() + 2;
11317        d.indent();
11318        assert_eq!(d.source, "- hello\n  * \n");
11319        d.undo();
11320        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
11321    }
11322
11323    #[test]
11324    fn indent_leaves_a_nested_lists_first_item_put_too() {
11325        // The guard is about siblings, not depth: the first item of an *inner*
11326        // list (already nested under `a`) still has nothing before it at its own
11327        // level, so Tab can't take it deeper.
11328        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
11329        d.caret = d.source.find('b').unwrap();
11330        d.indent();
11331        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
11332        // But `c` (a sibling of `b`) nests under `b`.
11333        d.caret = d.source.find('c').unwrap();
11334        d.indent();
11335        assert_eq!(d.source, "- a\n  - b\n    - c\n");
11336    }
11337
11338    #[test]
11339    fn backspace_at_a_nested_item_start_outdents_it() {
11340        // Backspace with the caret right after a nested item's marker gives back
11341        // one level of nesting, the mirror of Tab — and renumbers the flattened
11342        // ordered list back to a clean run.
11343        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
11344        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
11345        d.backspace();
11346        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
11347    }
11348
11349    #[test]
11350    fn backspace_at_a_top_level_item_start_strips_the_marker() {
11351        // At the outermost level there's no nesting left to give back, so the same
11352        // keystroke drops the bullet and leaves a plain paragraph.
11353        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
11354        d.caret = d.source.find('b').unwrap(); // right after `- `
11355        d.backspace();
11356        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
11357    }
11358
11359    #[test]
11360    fn backspace_mid_item_still_deletes_a_character() {
11361        // The list behaviour is armed only at the item's content start; anywhere
11362        // else Backspace is the ordinary character delete.
11363        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
11364        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
11365        d.backspace();
11366        assert_eq!(d.source, "- b\n");
11367    }
11368
11369    #[test]
11370    fn backspace_at_a_heading_start_strips_the_marker() {
11371        // The `# ` is markup the rich view hides, so Backspace over it takes the
11372        // whole marker and leaves a paragraph. Deleting a byte of it instead left
11373        // `#Title` — no longer a heading, with the hash now literal text the user
11374        // never typed and has to delete again.
11375        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
11376        d.caret = d.source.find('T').unwrap(); // right after `## `
11377        d.backspace();
11378        assert_eq!(d.source, "Title\n");
11379        assert_eq!(
11380            d.caret, 0,
11381            "the caret stays with the text it was in front of"
11382        );
11383    }
11384
11385    #[test]
11386    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
11387        // Only the heading's own marker goes — the quote (or list) it sits in is
11388        // untouched, exactly as un-heading it should be.
11389        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
11390        d.caret = d.source.find('T').unwrap();
11391        d.backspace();
11392        assert_eq!(d.source, "> Title\n");
11393    }
11394
11395    #[test]
11396    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
11397        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
11398        // behind would surface the same stray hash the marker delete just avoided.
11399        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
11400        d.caret = d.source.find('T').unwrap();
11401        d.backspace();
11402        assert_eq!(d.source, "Title\n");
11403        // And it's one edit: a single undo puts the whole heading back.
11404        d.undo();
11405        assert_eq!(d.source, "# Title #\n");
11406    }
11407
11408    #[test]
11409    fn backspace_mid_heading_still_deletes_a_character() {
11410        // The heading behaviour is armed only at the content's start; anywhere
11411        // else Backspace is the ordinary character delete.
11412        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
11413        d.caret = d.source.find('b').unwrap();
11414        d.backspace();
11415        assert_eq!(d.source, "# b\n");
11416    }
11417
11418    #[test]
11419    fn source_view_backspace_still_edits_the_heading_marker_literally() {
11420        // In source view the `# ` is text on the screen the user is deleting a
11421        // byte of, so it keeps its literal meaning — the same split the list
11422        // ladder and Enter draw between the two views.
11423        let mut d = doc_with("bsp_head_src", "# Title\n");
11424        d.caret = d.source.find('T').unwrap();
11425        d.backspace();
11426        assert_eq!(d.source, "#Title\n");
11427    }
11428
11429    #[test]
11430    fn outdent_unnests_an_ordered_item_in_one_press() {
11431        // Shift+Tab gives back exactly the marker width the indent added, so a
11432        // nested ordered item unnests in a single press, and the flattened list
11433        // renumbers back to a clean 1, 2, 3.
11434        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
11435        d.caret = d.source.find('b').unwrap();
11436        d.outdent();
11437        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
11438        let lists = d
11439            .nodes()
11440            .iter()
11441            .filter(|n| n.kind == Kind::OrderedList)
11442            .count();
11443        assert_eq!(lists, 1, "back to one flat list");
11444    }
11445
11446    #[test]
11447    fn table_insert_row_adds_a_row_below_the_caret() {
11448        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
11449        d.caret = d.source.find('1').unwrap(); // in the body row
11450        d.table_insert_row(true);
11451        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
11452    }
11453
11454    #[test]
11455    fn table_insert_and_delete_column_at_the_caret() {
11456        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
11457        d.caret = d.source.find('a').unwrap(); // column 0
11458        d.table_insert_column(true); // add a column to the right of `a`
11459        assert_eq!(
11460            d.source,
11461            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
11462        );
11463        d.caret = d.source.find('b').unwrap(); // now the third column
11464        d.table_delete_column();
11465        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
11466    }
11467
11468    // ── ragged formats ───────────────────────────────────────────────────────
11469    // No format spells every gesture. HTML writes the inline marks as a tag pair
11470    // and no heading, list, quote or link; Markdown spells five of the eight
11471    // marks — the highlight only because leaf parses with `highlight`, which is
11472    // why the question is asked with the extensions; djot spells all eight and
11473    // no in-cell break. leaf asks twig per
11474    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
11475    // op discover the fact on its own — one of them didn't.
11476
11477    /// An HTML document in the rich view, ready for a gesture.
11478    fn html_doc(body: &str) -> Doc {
11479        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
11480        d.view = View::Wysiwyg;
11481        d.build_visual(80);
11482        d
11483    }
11484
11485    #[test]
11486    fn a_table_gesture_leaves_an_html_table_alone() {
11487        // The regression this guard exists for. twig's table editor consults no
11488        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
11489        // HTML `<table>` as a *pipe table* and reported success: the whole
11490        // element replaced by `| a | b |`, silently, on one press of a toolbar
11491        // button. Every grid op went the same way.
11492        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
11493        // A table of named operations, which is what it looks like.
11494        #[allow(clippy::type_complexity)]
11495        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
11496            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
11497            ("delete row", &|d: &mut Doc| d.table_delete_row()),
11498            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
11499            ("delete column", &|d: &mut Doc| d.table_delete_column()),
11500            ("align", &|d: &mut Doc| {
11501                d.table_set_alignment(Alignment::Right)
11502            }),
11503            ("move row", &|d: &mut Doc| d.table_move_row(true)),
11504            ("move column", &|d: &mut Doc| d.table_move_column(true)),
11505        ];
11506        for (name, op) in ops {
11507            let mut d = html_doc(src);
11508            d.caret = d.source.find('a').unwrap();
11509            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
11510            op(&mut d);
11511            assert_eq!(d.source, src, "{name} rewrote an HTML table");
11512            assert!(
11513                !d.dirty,
11514                "{name} marked the document dirty without editing it"
11515            );
11516            assert!(d.status.is_some(), "{name} refused without saying why");
11517        }
11518    }
11519
11520    #[test]
11521    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
11522        // A heading is a wrapping tag pair carrying its level in both ends, a
11523        // quote wraps a range rather than prefixing each line, a link's
11524        // destination lives in an attribute — different *shapes*, not a
11525        // different alphabet, so twig spells none of them and neither does leaf.
11526        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
11527        // A table of named operations, which is what it looks like.
11528        #[allow(clippy::type_complexity)]
11529        let ops: [(&str, &dyn Fn(&mut Doc)); 9] = [
11530            ("heading", &|d: &mut Doc| d.toggle_heading(2)),
11531            ("paragraph", &|d: &mut Doc| {
11532                d.set_block(BlockKind::Paragraph)
11533            }),
11534            ("quote", &|d: &mut Doc| d.toggle_blockquote()),
11535            ("list", &|d: &mut Doc| d.toggle_list(false)),
11536            ("task item", &|d: &mut Doc| d.toggle_task_item()),
11537            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
11538            ("link", &|d: &mut Doc| d.insert_link("https://example.dev")),
11539            ("image", &|d: &mut Doc| d.insert_image("pic.png", "alt")),
11540            ("video", &|d: &mut Doc| {
11541                d.insert_media(MediaKind::Video, "clip.mp4", "")
11542            }),
11543        ];
11544        for (name, op) in ops {
11545            let mut d = html_doc(src);
11546            let at = d.source.find("Hello").unwrap();
11547            d.caret = at;
11548            d.anchor = Some(at + 5); // a selection, for the ops that want one
11549            op(&mut d);
11550            assert_eq!(d.source, src, "{name} edited an HTML document");
11551            assert!(
11552                !d.dirty,
11553                "{name} marked the document dirty without editing it"
11554            );
11555            let status = d.status.as_deref().unwrap_or("");
11556            assert!(
11557                status.contains("html"),
11558                "{name}: the refusal should name the format, got {status:?}"
11559            );
11560        }
11561    }
11562
11563    #[test]
11564    fn html_spells_the_inline_marks_and_the_rule() {
11565        // The other half, and why one per-document flag stopped being enough:
11566        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
11567        // already emits and the parser reads straight back as the same mark —
11568        // and the rule button writes an `<hr>`. Refusing these on the old
11569        // "HTML is parse-only" reading would now be leaf's own limitation.
11570        let mut d = html_doc("<p>Hello world</p>\n");
11571        let at = d.source.find("world").unwrap();
11572        d.caret = at;
11573        d.anchor = Some(at + 5);
11574        d.toggle(InlineKind::Strong);
11575        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
11576        assert!(d.dirty);
11577        assert_eq!(d.status, None, "a supported gesture reports nothing");
11578
11579        // And off again — the toggle reverses, which is the property that makes
11580        // authoring in HTML worth offering rather than a one-way trip.
11581        d.toggle(InlineKind::Strong);
11582        assert_eq!(d.source, "<p>Hello world</p>\n");
11583
11584        let mut d = html_doc("<p>Hello world</p>\n");
11585        d.caret = d.source.find("world").unwrap();
11586        d.insert_thematic_break();
11587        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
11588    }
11589
11590    #[test]
11591    fn a_mark_the_format_cannot_spell_arms_nothing() {
11592        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
11593        // sticky mark for the next text typed. Guarding only the twig call
11594        // leaves that path live, promising a mark the gesture will not write and
11595        // then swallowing the error inside `insert`.
11596        //
11597        // Markdown carries this, on the superscript now rather than on the
11598        // highlight: `^x^` is text there in any configuration, whereas twig
11599        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
11600        // which every leaf document does.
11601        let mut d = doc_with("mark", "Hello world\n");
11602        d.view = View::Wysiwyg;
11603        d.build_visual(80);
11604        d.caret = d.source.find("world").unwrap();
11605        d.toggle(InlineKind::Superscript);
11606        assert!(d.pending_marks.is_empty(), "no mark should be armed");
11607        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
11608        d.insert("X");
11609        assert_eq!(d.source, "Hello Xworld\n");
11610    }
11611
11612    #[test]
11613    fn markdown_authors_a_highlight_and_a_strikethrough() {
11614        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
11615        // write. `==x==` is authorable because leaf's own `parse_extensions`
11616        // turns `highlight` on — twig will only mint bytes this editor's reparse
11617        // reads back — and `~~x~~` because GFM strikethrough is parsed by
11618        // default, so the refusal there was never right for any leaf document.
11619        for (kind, marked) in [
11620            (InlineKind::Mark, "a ==word== b\n"),
11621            (InlineKind::Delete, "a ~~word~~ b\n"),
11622        ] {
11623            let mut d = doc_with("author_mark", "a word b\n");
11624            d.anchor = Some(2);
11625            d.caret = 6;
11626            d.toggle(kind);
11627            assert_eq!(d.source, marked, "{kind:?}");
11628            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
11629            assert!(d.dirty, "{kind:?}");
11630            // The region stays selected, so the second press reverses it — the
11631            // property that separates authoring from a one-way trip.
11632            d.toggle(kind);
11633            assert_eq!(d.source, "a word b\n", "{kind:?}");
11634        }
11635    }
11636
11637    #[test]
11638    fn an_authored_highlight_reads_back_as_a_mark() {
11639        // The round trip the extension gate exists to protect: what the toggle
11640        // writes, the reparse must read back as a `mark` rather than as two
11641        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
11642        // rebuilt map rather than from the source text.
11643        let mut d = doc_with("mark_roundtrip", "a word b\n");
11644        d.view = View::Wysiwyg;
11645        d.build_visual(80);
11646        d.anchor = Some(2);
11647        d.caret = 6;
11648        d.toggle(InlineKind::Mark);
11649        assert_eq!(d.source, "a ==word== b\n");
11650        d.build_visual(80);
11651        let w = d
11652            .vmap
11653            .rows
11654            .iter()
11655            .flat_map(|r| r.glyphs.iter())
11656            .find(|g| g.ch == 'w')
11657            .expect("the highlighted word");
11658        assert_eq!(w.style.role, crate::Role::Mark(None));
11659    }
11660
11661    #[test]
11662    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
11663        // The three states of one gesture, in the order a palette is pressed:
11664        // an uncoloured highlight takes the prefix, a coloured one has it
11665        // replaced, and `None` takes it away with the space that was part of the
11666        // spelling.
11667        let mut d = doc_with("mark_colour", "a ==word== b\n");
11668        d.caret = d.source.find("word").unwrap();
11669        d.set_mark_color(Some(MarkColor::Red));
11670        assert_eq!(d.source, "a ==🔴 word== b\n");
11671        assert_eq!(d.status, None);
11672        assert!(d.dirty);
11673
11674        d.set_mark_color(Some(MarkColor::Blue));
11675        assert_eq!(d.source, "a ==🔵 word== b\n");
11676
11677        d.set_mark_color(None);
11678        assert_eq!(d.source, "a ==word== b\n");
11679    }
11680
11681    #[test]
11682    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
11683        // The prefix is written *before* the word, so an offset in the word has
11684        // to ride its width — a caret that stayed put would be a caret that
11685        // walked backwards through the text it was standing in.
11686        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
11687        let word = d.source.find("word").unwrap();
11688        d.caret = word + 2; // between `wo` and `rd`
11689        d.set_mark_color(Some(MarkColor::Red));
11690        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
11691
11692        // And back the other way when the prefix goes.
11693        d.set_mark_color(None);
11694        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
11695    }
11696
11697    #[test]
11698    fn the_colour_at_the_caret_is_what_the_palette_lights() {
11699        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
11700        d.caret = d.source.find("red").unwrap();
11701        assert!(d.caret_in_mark());
11702        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
11703
11704        d.caret = d.source.find("plain").unwrap();
11705        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
11706        assert_eq!(d.mark_color_at_caret(), None);
11707
11708        d.caret = d.source.find(" and ").unwrap() + 2;
11709        assert!(!d.caret_in_mark());
11710        assert_eq!(d.mark_color_at_caret(), None);
11711    }
11712
11713    #[test]
11714    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
11715        // The gesture colours a highlight that exists; it does not make one.
11716        // Two presses is the price of a coloured highlight from bare text, and
11717        // the reason is undo — one press that spliced twice would take two
11718        // presses to take back.
11719        let mut d = doc_with("mark_colour_none", "a word b\n");
11720        d.caret = d.source.find("word").unwrap();
11721        d.set_mark_color(Some(MarkColor::Red));
11722        assert_eq!(d.source, "a word b\n");
11723        assert!(d.status.is_some(), "it should say why");
11724        assert!(!d.dirty);
11725
11726        // Clearing where there is nothing to clear is the same refusal, not a
11727        // quiet success — the caret is in no highlight either way.
11728        d.status = None;
11729        d.set_mark_color(None);
11730        assert_eq!(d.source, "a word b\n");
11731        assert!(d.status.is_some());
11732    }
11733
11734    #[test]
11735    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
11736        // twig answers this one *successfully* with a `Change` describing some
11737        // earlier edit, so a caller that trusted the change would jump the caret
11738        // to wherever that was. Core answers it before asking.
11739        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
11740        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
11741        d.caret = d.source.find("word").unwrap();
11742        let (source, caret) = (d.source.clone(), d.caret);
11743        d.set_mark_color(None);
11744        assert_eq!(d.source, source);
11745        assert_eq!(
11746            d.caret, caret,
11747            "the caret must not ride a change that isn't one"
11748        );
11749        assert_eq!(d.status, None, "and it is not an error either");
11750    }
11751
11752    #[test]
11753    fn djot_spells_the_highlight_and_not_its_colour() {
11754        // The reason the palette is its own capability rather than the Highlight
11755        // button's: `{=word=}` is a highlight djot writes happily, and there is
11756        // no djot spelling for a colour on it.
11757        assert!(Capabilities::of(Format::Djot).mark);
11758        assert!(!Capabilities::of(Format::Djot).mark_color);
11759        assert!(Capabilities::of(Format::Markdown).mark_color);
11760
11761        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
11762        d.caret = d.source.find("word").unwrap();
11763        assert!(
11764            d.caret_in_mark(),
11765            "the caret is in a highlight all the same"
11766        );
11767        d.set_mark_color(Some(MarkColor::Red));
11768        assert_eq!(d.source, "a {=word=} b\n");
11769        assert!(
11770            d.status.as_deref().unwrap_or("").contains("djot"),
11771            "and the refusal names the document's format: {:?}",
11772            d.status
11773        );
11774    }
11775
11776    #[test]
11777    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
11778        // The round trip that matters for a palette: the bytes twig writes are
11779        // bytes its own reparse reads back as a colour, so the swatch that was
11780        // pressed is the swatch that lights afterwards.
11781        let mut d = doc_with("mark_colour_undo", "a word b\n");
11782        d.anchor = Some(2);
11783        d.caret = 6;
11784        d.toggle(InlineKind::Mark);
11785        d.caret = d.source.find("word").unwrap();
11786        d.set_mark_color(Some(MarkColor::Green));
11787        assert_eq!(d.source, "a ==🟢 word== b\n");
11788        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
11789
11790        // One splice, one step: the colour comes off and the highlight stays.
11791        d.undo();
11792        assert_eq!(d.source, "a ==word== b\n");
11793        d.undo();
11794        assert_eq!(d.source, "a word b\n");
11795    }
11796
11797    #[test]
11798    fn every_colour_leaf_names_is_one_twig_writes() {
11799        // The two enums are one vocabulary, and this is what says so: each of
11800        // leaf's colours writes an emoji twig's reparse reads back as *that*
11801        // colour, so `twig_mark_color`'s table cannot quietly pair red with
11802        // orange.
11803        for color in MarkColor::ALL {
11804            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
11805            d.caret = d.source.find("word").unwrap();
11806            d.set_mark_color(Some(color));
11807            assert_eq!(d.status, None, "{color:?}");
11808            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
11809        }
11810    }
11811
11812    #[test]
11813    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
11814        // The two presses a coloured highlight is made of, in the state the
11815        // first one leaves: `toggle` selects the whole `==word==` and puts the
11816        // caret one past the closing `==`, which is *not* in the mark. Asking at
11817        // the caret alone would refuse to colour the highlight just written —
11818        // the selection's start is what answers.
11819        let mut d = doc_with("mark_colour_fresh", "a word b\n");
11820        d.anchor = Some(2);
11821        d.caret = 6;
11822        d.toggle(InlineKind::Mark);
11823        assert_eq!(d.source, "a ==word== b\n");
11824        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
11825
11826        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
11827        d.set_mark_color(Some(MarkColor::Yellow));
11828        assert_eq!(d.source, "a ==🟡 word== b\n");
11829        assert_eq!(d.status, None);
11830    }
11831
11832    #[test]
11833    fn one_press_highlights_a_selection_and_colours_it() {
11834        // What a toolbar swatch means over a plain selection, and the undo it
11835        // has to have: one press, one step. Two steps would leave an uncoloured
11836        // highlight behind on the way back, which is a state the author never
11837        // asked for and never saw.
11838        let mut d = doc_with("highlight_one", "a word b\n");
11839        d.anchor = Some(2);
11840        d.caret = 6;
11841        d.highlight(Some(MarkColor::Purple));
11842        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
11843        assert_eq!(d.status, None);
11844
11845        d.undo();
11846        assert_eq!(d.source, "a word b\n", "one press, one undo");
11847    }
11848
11849    #[test]
11850    fn one_press_on_an_existing_highlight_only_recolours_it() {
11851        // The other half: inside a highlight there is nothing to make, so the
11852        // compound is the plain gesture and the text is untouched.
11853        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
11854        d.caret = d.source.find("word").unwrap();
11855        d.highlight(Some(MarkColor::Blue));
11856        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
11857        d.undo();
11858        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
11859    }
11860
11861    #[test]
11862    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
11863        // `None` means "no colour", and over bare text that is the Highlight
11864        // button's own job. The fold must not happen here — there is no second
11865        // splice, and folding would take the *previous* edit into this one.
11866        let mut d = doc_with("highlight_none", "a word b and more\n");
11867        d.caret = d.source.find("more").unwrap() + 4; // after "more"
11868        d.insert("!"); // an earlier edit for a wrong fold to swallow
11869        d.anchor = Some(2);
11870        d.caret = 6;
11871        d.highlight(None);
11872        assert_eq!(d.source, "a ==word== b and more!\n");
11873
11874        d.undo();
11875        assert_eq!(
11876            d.source, "a word b and more!\n",
11877            "only the highlight came off"
11878        );
11879        d.undo();
11880        assert_eq!(
11881            d.source, "a word b and more\n",
11882            "and the edit before it survived"
11883        );
11884    }
11885
11886    #[test]
11887    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
11888        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
11889        // a colour cannot be armed with it — so the compound declines rather
11890        // than leaving half a promise.
11891        let mut d = doc_with("highlight_bare", "a word b\n");
11892        d.caret = 4;
11893        d.highlight(Some(MarkColor::Red));
11894        assert_eq!(d.source, "a word b\n");
11895        assert!(d.pending_marks.is_empty(), "and nothing armed");
11896        assert!(d.status.is_some());
11897    }
11898
11899    #[test]
11900    fn a_read_only_document_takes_no_colour() {
11901        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
11902        d.caret = d.source.find("word").unwrap();
11903        d.set_read_only(true);
11904        d.set_mark_color(Some(MarkColor::Red));
11905        assert_eq!(d.source, "a ==word== b\n");
11906    }
11907
11908    #[test]
11909    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
11910        // The other door into `toggle`: no selection, so nothing reaches twig
11911        // until `insert` realises the armed mark. It is armed now — the guard
11912        // above asks `Doc::supports`, which asks with the extensions — and what
11913        // it writes is the same `==…==`.
11914        let mut d = doc_with("sticky_mark", "xy\n");
11915        d.caret = 1;
11916        d.toggle(InlineKind::Mark);
11917        assert!(d.pending_marks.contains(InlineKind::Mark));
11918        d.insert("Z");
11919        assert_eq!(d.source, "x==Z==y\n");
11920    }
11921
11922    #[test]
11923    fn html_documents_still_take_typed_text() {
11924        // The guard covers *markup* gestures and must not touch plain editing:
11925        // twig's splicer is language-neutral, and typing into an HTML document
11926        // is the thing that does work today.
11927        let mut d = html_doc("<p>Hello world</p>\n");
11928        d.caret = d.source.find("world").unwrap();
11929        d.insert("big ");
11930        assert_eq!(d.source, "<p>Hello big world</p>\n");
11931        assert!(d.dirty);
11932        d.backspace();
11933        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
11934        d.undo();
11935        d.undo();
11936        assert_eq!(d.source, "<p>Hello world</p>\n");
11937    }
11938
11939    #[test]
11940    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
11941        // `authorable` only separates "there is a door in" from "there is not",
11942        // and HTML is on the near side of that line — which is exactly why a
11943        // toolbar must not be built from it.
11944        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
11945        assert!(html.authorable());
11946        assert!(
11947            !Doc::from_source("<r>x</r>".into(), Format::Xml)
11948                .unwrap()
11949                .authorable()
11950        );
11951
11952        let caps = html.capabilities();
11953        assert!(caps.bold && caps.italic && caps.code && caps.mark);
11954        assert!(caps.thematic_break && caps.cell_line_break);
11955        assert!(!caps.heading && !caps.blockquote && !caps.bullet_list);
11956        assert!(!caps.task && !caps.link && !caps.image && !caps.code_language);
11957        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
11958        // twig's table editor would happily re-emit as `| a | b |`.
11959        assert!(!caps.table);
11960
11961        // The two lightweight formats spell everything leaf offers — and still
11962        // differ from each other, which is the other half of why one boolean
11963        // can't serve.
11964        for fmt in [Format::Markdown, Format::Djot] {
11965            let caps = Capabilities::of(fmt);
11966            assert!(
11967                caps.heading && caps.blockquote && caps.ordered_list,
11968                "{fmt:?}"
11969            );
11970            assert!(
11971                caps.task && caps.link && caps.image && caps.table,
11972                "{fmt:?}"
11973            );
11974        }
11975        // Both spell the highlight and the strikethrough: djot natively, and
11976        // Markdown because `Capabilities` asks with `parse_extensions` rather
11977        // than with twig's defaults — `==x==` is text under those, and a mark
11978        // under the `highlight` leaf always parses with.
11979        for fmt in [Format::Markdown, Format::Djot] {
11980            let caps = Capabilities::of(fmt);
11981            assert!(caps.mark && caps.strike, "{fmt:?}");
11982        }
11983        // What still separates them, now that the highlight doesn't: djot has
11984        // no in-cell break, and Markdown spells neither of the scripts.
11985        assert!(Capabilities::of(Format::Djot).superscript);
11986        assert!(!Capabilities::of(Format::Markdown).superscript);
11987        assert!(Capabilities::of(Format::Markdown).cell_line_break);
11988        assert!(!Capabilities::of(Format::Djot).cell_line_break);
11989
11990        // A parse-only format answers no to every one of them, so the coarse
11991        // predicate and the record agree there.
11992        let caps = Capabilities::of(Format::Xml);
11993        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
11994    }
11995
11996    #[test]
11997    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
11998        // The guard exists to name the *document's* format rather than twig's
11999        // internals, so the message has to survive being one leaf writes itself.
12000        // Checked against the gesture twig also refuses, since that is the pair
12001        // most at risk of drifting apart.
12002        let mut d = html_doc("<p>Hello</p>\n");
12003        d.caret = d.source.find("Hello").unwrap();
12004        d.set_code_language("zig");
12005        assert_eq!(
12006            d.status.as_deref(),
12007            Some("code language: not supported in html")
12008        );
12009        assert!(!d.dirty);
12010    }
12011
12012    #[test]
12013    fn table_set_alignment_respells_the_delimiter() {
12014        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
12015        d.caret = d.source.find('b').unwrap();
12016        d.table_set_alignment(Alignment::Right);
12017        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
12018    }
12019
12020    #[test]
12021    fn each_empty_table_cell_has_its_own_editable_home() {
12022        // Regression: an empty cell has no twig content_span, so both cells of a
12023        // `|  |  |` row collapsed onto the row's start (before the first `│`).
12024        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
12025        // tell the cells apart. Each empty cell must now have a distinct home
12026        // inside it.
12027        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
12028        let (c0, c1) = {
12029            let cells = &d.vmap.tables[0].grid[1].cells;
12030            (cells[0].start, cells[1].start)
12031        };
12032        assert!(
12033            c0 < c1,
12034            "the two empty cells have distinct homes: {c0} < {c1}"
12035        );
12036        d.caret = c0;
12037        d.insert("x");
12038        assert_eq!(
12039            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
12040            "typed inside the cell"
12041        );
12042    }
12043
12044    #[test]
12045    fn arrows_step_into_each_empty_table_cell() {
12046        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
12047        let (c0, c1) = {
12048            let cells = &d.vmap.tables[0].grid[1].cells;
12049            (cells[0].start, cells[1].start)
12050        };
12051        d.caret = d.source.find('b').unwrap(); // in the header's second cell
12052        let mut seen = std::collections::HashSet::new();
12053        for _ in 0..6 {
12054            d.move_right(false);
12055            seen.insert(d.caret);
12056        }
12057        assert!(
12058            seen.contains(&c0),
12059            "right arrow reaches the first empty cell"
12060        );
12061        assert!(
12062            seen.contains(&c1),
12063            "right arrow reaches the second empty cell"
12064        );
12065    }
12066
12067    #[test]
12068    fn table_op_off_a_table_is_a_no_op_with_a_status() {
12069        let mut d = doc_with("tbl_none", "just text\n");
12070        d.caret = 3;
12071        d.table_insert_row(true);
12072        assert_eq!(d.source, "just text\n", "nothing changed");
12073        assert!(d.status.is_some(), "a status explains why");
12074        assert!(!d.caret_in_table());
12075    }
12076
12077    #[test]
12078    fn enter_in_an_ordered_list_renumbers_the_following_items() {
12079        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
12080        // the renumber pass keeps them sequential, matching what the view draws.
12081        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
12082        d.caret = d.source.find('a').unwrap() + 1; // end of item a
12083        d.newline();
12084        d.insert("x");
12085        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
12086    }
12087
12088    #[test]
12089    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
12090        for view in [View::Source, View::Wysiwyg] {
12091            let mut d = doc_in(view, "outdent_noop", "hello\n");
12092            d.caret = 2;
12093            d.outdent();
12094            assert_eq!(d.source, "hello\n");
12095            assert!(!d.dirty, "a no-op is not a modification");
12096            d.undo();
12097            assert_eq!(
12098                d.status.as_deref(),
12099                Some("nothing to undo"),
12100                "spends no undo step"
12101            );
12102            assert_eq!(d.source, "hello\n");
12103        }
12104    }
12105
12106    #[test]
12107    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
12108        for view in [View::Source, View::Wysiwyg] {
12109            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
12110            d.anchor = Some(0);
12111            d.caret = 7; // through "two"
12112            d.indent();
12113            assert_eq!(
12114                d.source, "  one\n\n  two\n",
12115                "the blank line keeps no trailing pad"
12116            );
12117            // Selected, so a second Tab lands on the same lines rather than on
12118            // whatever the shifted offsets now cover.
12119            assert_eq!(d.selection(), Some((0, 12)));
12120            d.indent();
12121            assert_eq!(d.source, "    one\n\n    two\n");
12122        }
12123    }
12124
12125    #[test]
12126    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
12127        for view in [View::Source, View::Wysiwyg] {
12128            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
12129            d.anchor = Some(0);
12130            d.caret = 15;
12131            d.outdent();
12132            assert_eq!(d.source, "two\none\nnone\n");
12133        }
12134    }
12135
12136    #[test]
12137    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
12138        for view in [View::Source, View::Wysiwyg] {
12139            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
12140            d.anchor = Some(0);
12141            d.caret = 7;
12142            d.indent();
12143            assert_eq!(d.source, "  one\n\n  two\n");
12144            d.undo();
12145            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
12146            assert_eq!(
12147                d.selection(),
12148                Some((0, 7)),
12149                "with the selection it was aimed at"
12150            );
12151            d.redo();
12152            assert_eq!(d.source, "  one\n\n  two\n");
12153            assert_eq!(
12154                d.selection(),
12155                Some((0, 12)),
12156                "redo replays the caret the indent placed, not the one splice left"
12157            );
12158        }
12159    }
12160
12161    #[test]
12162    fn vertical_motion_keeps_the_column() {
12163        let mut d = doc_with("move", "abcd\nef\n");
12164        d.caret = 3; // "abc|d" on row 0, col 3
12165        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
12166        assert_eq!(d.caret, 7); // just after "ef"
12167    }
12168
12169    // ── goal column ──────────────────────────────────────────────────────────
12170
12171    #[test]
12172    fn vertical_motion_goal_column_survives_a_short_line() {
12173        // Regression: re-deriving the column from the clamped position on
12174        // every step permanently forgets it once a short line clamps it.
12175        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
12176        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
12177        assert_eq!(
12178            g("abcd|ef\nxy\nghijkl\n", |d| {
12179                d.move_down(false); // clamps to end of "xy"
12180                d.move_down(false); // restores col 4 on the long line
12181            }),
12182            "abcdef\nxy\nghij|kl\n"
12183        );
12184    }
12185
12186    #[test]
12187    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
12188        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
12189        assert_eq!(d.goal_col, None);
12190        d.caret = 4; // row 0, col 4
12191        d.move_down(false); // clamps into "xy"; goal stays the original col
12192        assert_eq!(d.goal_col, Some(4));
12193        assert_eq!(d.caret_pos(), (1, 2));
12194
12195        // A horizontal motion drops the goal column...
12196        d.move_left(false);
12197        assert_eq!(d.goal_col, None);
12198
12199        // ...so the next vertical motion picks up the *new* column (1), not
12200        // the stale one (4).
12201        d.move_down(false);
12202        assert_eq!(d.goal_col, Some(1));
12203        assert_eq!(d.caret_pos(), (2, 1));
12204    }
12205
12206    #[test]
12207    fn editing_clears_the_goal_column() {
12208        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
12209        d.caret = 4;
12210        d.move_down(false);
12211        assert_eq!(d.goal_col, Some(4));
12212        d.insert("Z");
12213        assert_eq!(d.goal_col, None);
12214    }
12215
12216    #[test]
12217    fn vertical_motion_on_an_empty_document_is_a_no_op() {
12218        let mut d = doc_with("empty_vert", "");
12219        d.move_down(false);
12220        assert_eq!(d.caret, 0);
12221        d.move_up(false);
12222        assert_eq!(d.caret, 0);
12223    }
12224
12225    // ── the document's edges ─────────────────────────────────────────────────
12226
12227    #[test]
12228    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
12229        // The reproduction, and the disagreement: Down on the last line ran to
12230        // the end of the document in the source view — by accident, an
12231        // out-of-range row clamping to the end of the string — and did nothing
12232        // whatever in the view leaf opens in. One rule now, in both.
12233        for (view, tag) in VIEWS {
12234            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
12235            d.caret = 1;
12236            d.move_down(false);
12237            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
12238            d.move_up(false);
12239            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
12240        }
12241    }
12242
12243    #[test]
12244    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
12245        // Down off the bottom is a motion like any other, so it latches a goal
12246        // column — and Up comes back to the column the caret left, not to the
12247        // one the document's end happened to be in.
12248        for (view, tag) in VIEWS {
12249            let gap = if view == View::Source { "\n" } else { "\n\n" };
12250            let src = format!("abcdef{gap}ghijkl");
12251            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
12252            d.caret = 2; // row 0, col 2
12253            d.move_down(false);
12254            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
12255            d.move_down(false);
12256            assert_eq!(
12257                d.caret,
12258                src.len(),
12259                "{tag}: Down off the bottom reaches the end"
12260            );
12261            d.move_up(false);
12262            assert_eq!(
12263                d.caret_pos().1,
12264                2,
12265                "{tag}: Up returns to the column Down left"
12266            );
12267        }
12268    }
12269
12270    #[test]
12271    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
12272        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
12273        // Up that did nothing still armed a goal column, and the next Down aimed
12274        // at a column the caret had never been in.
12275        for (view, tag) in VIEWS {
12276            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
12277            d.caret = 0;
12278            d.move_up(false);
12279            assert_eq!(d.caret, 0, "{tag}: already at the start");
12280            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
12281
12282            d.caret = d.source.len();
12283            d.move_down(false);
12284            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
12285            assert_eq!(
12286                d.goal_col, None,
12287                "{tag}: a no-op Down latched a goal column"
12288            );
12289        }
12290    }
12291
12292    // ── soft wrap ────────────────────────────────────────────────────────────
12293    // Every other test here builds the map at 80 columns, where no fixture is
12294    // long enough to fold. A wrap is where one offset belongs to two rows at
12295    // once, and it broke everything that asks the caret what row it is on.
12296
12297    /// The wrapped fixture these cases share, folded at 12 columns into
12298    /// `one two ` / `three four ` / `five six ` / `seven eight`.
12299    fn wrapped_doc(name: &str) -> Doc {
12300        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
12301        d.build_visual(12);
12302        d
12303    }
12304
12305    #[test]
12306    fn home_and_end_work_from_a_wrapped_row() {
12307        // The reproduction: offset 19 is the `f` of "five", the first character
12308        // of the third row — and also the offset the second row ends at. It
12309        // resolved to the *second* row, so End aimed at a place the caret was
12310        // already in and did nothing, while Home walked backwards onto a row the
12311        // caret had left.
12312        let mut d = wrapped_doc("wrap_home_end");
12313        d.caret = 19;
12314        assert_eq!(
12315            d.caret_pos(),
12316            (2, 0),
12317            "the wrap boundary opens the third row"
12318        );
12319        d.move_end(false);
12320        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
12321        d.move_home(false);
12322        assert_eq!(d.caret, 19, "Home left the row the caret was on");
12323    }
12324
12325    #[test]
12326    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
12327        // The row's end is the last offset that is only ever its own: the offset
12328        // past it opens the row below, and aiming there would send a second
12329        // press on to *that* row's end, and a third to the next — End walking
12330        // down the paragraph rather than sitting where it landed.
12331        let mut d = wrapped_doc("wrap_end_twice");
12332        d.caret = 12; // inside "three", on the second row
12333        d.move_end(false);
12334        assert_eq!(
12335            d.caret, 18,
12336            "the end of `three four`, before the space the wrap ate"
12337        );
12338        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
12339        d.move_end(false);
12340        assert_eq!(d.caret, 18, "a second End moved the caret");
12341        d.move_home(false);
12342        assert_eq!(d.caret, 8, "Home takes the row's own start");
12343    }
12344
12345    #[test]
12346    fn vertical_motion_crosses_a_soft_wrap() {
12347        // Down aimed at the row below's column 0, an offset that resolved *up*
12348        // to the row above's end — so it landed on the offset it already had and
12349        // the caret could never leave a paragraph's first row.
12350        let mut d = wrapped_doc("wrap_down");
12351        d.caret = 0;
12352        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
12353            d.move_down(false);
12354            assert_eq!(d.caret, want, "Down stalled");
12355            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
12356        }
12357        d.move_down(false);
12358        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
12359
12360        // ...and back up, one row per press. The goal column is the end of the
12361        // last row, past every other row's width, so each press clamps to the
12362        // row's own last offset rather than to the one that opens the next.
12363        let mut d = wrapped_doc("wrap_up");
12364        d.caret = 39;
12365        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
12366            d.move_up(false);
12367            assert_eq!(d.caret, want, "Up stalled");
12368            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
12369        }
12370    }
12371
12372    #[test]
12373    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
12374        // The kills take the same line Home and End do, so in WYSIWYG they take
12375        // the visual row — and a soft wrap has no newline in it to delete, so
12376        // nothing is joined by reaching the end of one.
12377        let mut d = wrapped_doc("wrap_kill");
12378        d.caret = 19; // the `f` of "five", opening the third row
12379        d.delete_to_line_end();
12380        // The space the wrap ate goes with the row it was drawn on: sparing it
12381        // would leave "four  seven", two spaces where the row had been.
12382        assert_eq!(d.source, "one two three four seven eight");
12383
12384        // Backwards from the row's last caret position — which is *before* that
12385        // space, so this one survives, being on the far side of the caret.
12386        let mut d = wrapped_doc("wrap_kill_back");
12387        d.caret = 27;
12388        d.delete_to_line_start();
12389        assert_eq!(d.source, "one two three four  seven eight");
12390    }
12391
12392    // ── document start / end ────────────────────────────────────────────────
12393
12394    #[test]
12395    fn move_doc_start_and_end_jump_to_the_edges() {
12396        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
12397        assert_eq!(
12398            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
12399            "|hello\nworld\n"
12400        );
12401        assert_eq!(
12402            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
12403            "hello\nworld\n|"
12404        );
12405        // Already at the edge: a no-op.
12406        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
12407        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
12408    }
12409
12410    #[test]
12411    fn move_doc_start_and_end_extend_the_selection() {
12412        assert_eq!(
12413            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
12414                .move_doc_end(true)),
12415            "hello wor[ld\n|]"
12416        );
12417        assert_eq!(
12418            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
12419                .move_doc_start(true)),
12420            "[|hello wor]ld\n"
12421        );
12422    }
12423
12424    #[test]
12425    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
12426        let mut d = doc_with("empty_edges", "");
12427        d.move_doc_end(false);
12428        assert_eq!(d.caret, 0);
12429        d.move_doc_start(false);
12430        assert_eq!(d.caret, 0);
12431    }
12432
12433    // ── arrow collapses an active selection ─────────────────────────────────
12434
12435    #[test]
12436    fn arrow_collapses_selection_to_its_near_edge() {
12437        let mut d = doc_with("collapse", "hello world\n");
12438
12439        // Forward selection (anchor before caret): Right -> end, Left -> start.
12440        d.anchor = Some(2);
12441        d.caret = 7;
12442        d.move_right(false);
12443        assert_eq!((d.caret, d.anchor), (7, None));
12444
12445        d.anchor = Some(2);
12446        d.caret = 7;
12447        d.move_left(false);
12448        assert_eq!((d.caret, d.anchor), (2, None));
12449
12450        // Backward selection (anchor after caret): edges are the same
12451        // regardless of which end the caret started on.
12452        d.anchor = Some(7);
12453        d.caret = 2;
12454        d.move_right(false);
12455        assert_eq!((d.caret, d.anchor), (7, None));
12456
12457        d.anchor = Some(7);
12458        d.caret = 2;
12459        d.move_left(false);
12460        assert_eq!((d.caret, d.anchor), (2, None));
12461    }
12462
12463    #[test]
12464    fn arrow_with_extend_keeps_growing_the_selection() {
12465        let mut d = doc_with("collapse_extend", "hello world\n");
12466        d.anchor = Some(2);
12467        d.caret = 7;
12468        d.move_right(true); // extend: no collapse, caret steps one further
12469        assert_eq!((d.caret, d.anchor), (8, Some(2)));
12470    }
12471
12472    #[test]
12473    fn arrow_without_a_selection_moves_one_character_as_before() {
12474        let mut d = doc_with("no_collapse", "hello\n");
12475        d.caret = 2;
12476        d.move_right(false);
12477        assert_eq!(d.caret, 3);
12478        d.move_left(false);
12479        assert_eq!(d.caret, 2);
12480    }
12481
12482    /// Press Right until it stops, collecting the offsets walked through. Every
12483    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
12484    /// two stops sharing one source offset can't be moved between, so the caret
12485    /// stalls on the first of them and the walk never reaches the rest.
12486    fn walk_right(d: &mut Doc) -> Vec<usize> {
12487        let mut seen = vec![d.caret];
12488        for _ in 0..2000 {
12489            let before = d.caret;
12490            d.move_right(false);
12491            if d.caret == before {
12492                break;
12493            }
12494            seen.push(d.caret);
12495        }
12496        seen
12497    }
12498
12499    #[test]
12500    fn the_caret_crosses_a_soft_break() {
12501        // A newline inside a paragraph is a `soft_break`, which twig gives no
12502        // span of its own — the space it renders as used to borrow the offset of
12503        // the character before it, and a caret can't move without changing
12504        // offset. Right must walk clean off the end of the first line.
12505        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
12506        d.caret = 0;
12507        let seen = walk_right(&mut d);
12508        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
12509    }
12510
12511    #[test]
12512    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
12513        // The paragraph holds one soft break. Folded (the default) it lays out as
12514        // a single reflowed row; Preserve re-lays it as a row per source line.
12515        // The setter must invalidate the cached map for the change to show, and
12516        // again on the way back — so a round trip returns to the folded layout.
12517        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
12518        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
12519        d.build_visual(80);
12520        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
12521
12522        d.set_line_flow(LineFlow::Preserve);
12523        d.build_visual(80);
12524        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
12525
12526        d.set_line_flow(LineFlow::Fold);
12527        d.build_visual(80);
12528        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
12529    }
12530
12531    #[test]
12532    fn the_caret_still_crosses_a_preserved_soft_break() {
12533        // Preserve renders the soft break as a row boundary rather than a space,
12534        // but the caret must still reach every offset — the break's own offset is
12535        // the first row's end stop, so Right walks clean off the end of line one
12536        // onto line two, exactly as it does when the break is folded.
12537        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
12538        d.set_line_flow(LineFlow::Preserve);
12539        d.build_visual(80);
12540        d.caret = 0;
12541        let seen = walk_right(&mut d);
12542        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
12543    }
12544
12545    #[test]
12546    fn the_caret_walks_a_code_block() {
12547        // Every glyph of a code block used to map to the block's start, so the
12548        // whole block was a single offset and the caret couldn't move inside it.
12549        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
12550        let mut d = wysiwyg_doc("code_walk", src);
12551        d.caret = 0;
12552        let seen = walk_right(&mut d);
12553        // The fences are markup: hidden, and no caret stop. The code between
12554        // them is reached a character at a time.
12555        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
12556        for off in code.clone() {
12557            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
12558        }
12559        assert!(seen.contains(&code.end), "no stop after the last line");
12560    }
12561
12562    #[test]
12563    fn the_caret_walks_an_indented_code_block() {
12564        // An indented block's text has the four-space indent stripped, so it
12565        // isn't a verbatim slice and its lines have to be re-found. The caret
12566        // lands on the code, never in the indent.
12567        let src = "    indented\n    code\n";
12568        let mut d = wysiwyg_doc("indent_code_walk", src);
12569        d.caret = 0;
12570        let seen = walk_right(&mut d);
12571        assert!(seen.contains(&src.find("indented").unwrap()));
12572        assert!(seen.contains(&src.find("code").unwrap()));
12573        assert!(
12574            !seen.contains(&0) || seen[0] == 0,
12575            "the caret starts where it was put"
12576        );
12577        // Nothing in the stripped indent is a stop.
12578        for off in [1, 2, 3] {
12579            assert!(!seen.contains(&off), "landed in the indent at {off}");
12580        }
12581    }
12582
12583    #[test]
12584    fn the_caret_leaves_a_tight_heading() {
12585        // "# H" with text directly under it: the heading row's end and the
12586        // separator row's end are the same offset. Right used to find the
12587        // separator's copy, set the caret to where it already was, and stop.
12588        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
12589        d.caret = 2; // the "H"
12590        let seen = walk_right(&mut d);
12591        assert!(
12592            seen.len() > 2,
12593            "Right stalled at the heading's end: {seen:?}"
12594        );
12595        assert!(
12596            seen.contains(&8),
12597            "never reached the end of \"text\": {seen:?}"
12598        );
12599    }
12600
12601    #[test]
12602    fn the_caret_skips_the_gap_between_two_paragraphs() {
12603        // The blank line between two paragraphs is the boundary itself. The
12604        // caret used to be able to sit on it, and typing there landed in the
12605        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
12606        // soft break, so the text visibly snapped back up.
12607        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
12608        d.caret = 1; // the end of "A"
12609        d.move_right(false);
12610        assert_eq!(d.caret, 3, "Right stopped in the gap");
12611        d.insert("x");
12612        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
12613    }
12614
12615    #[test]
12616    fn down_from_a_paragraph_lands_on_the_next_one() {
12617        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
12618        d.caret = 0;
12619        d.move_down(false);
12620        assert_eq!(d.caret, 3, "Down stopped in the gap");
12621    }
12622
12623    #[test]
12624    fn clicking_the_gap_lands_on_real_text() {
12625        // A click can still *reach* the gap — it's drawn, so it's clickable.
12626        // It has to resolve to somewhere the caret can be.
12627        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
12628        d.click(1, 0, false); // the gap row
12629        assert!(
12630            d.caret == 1 || d.caret == 3,
12631            "click left the caret in the gap at {}",
12632            d.caret
12633        );
12634        d.insert("x");
12635        // Either edge of the boundary is a fair place to land; inside it isn't.
12636        assert!(
12637            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
12638            "click in the gap typed into the boundary: {:?}",
12639            d.source
12640        );
12641    }
12642
12643    #[test]
12644    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
12645        // Enter inserts a paragraph break, which leaves a blank line spare on
12646        // either side of a new one. That middle line is a real empty paragraph:
12647        // the caret lands there, and typing makes a paragraph rather than
12648        // extending a neighbour.
12649        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
12650        d.caret = 1;
12651        d.newline();
12652        assert_eq!(d.source, "A\n\n\n\nB\n");
12653        d.build_visual(80);
12654        let (row, _) = d.caret_pos();
12655        assert!(
12656            d.vmap.row_is_navigable(row),
12657            "the caret landed on a gap row"
12658        );
12659        d.insert("x");
12660        assert_eq!(
12661            d.source, "A\n\nx\n\nB\n",
12662            "the new paragraph merged into a neighbour"
12663        );
12664    }
12665
12666    #[test]
12667    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
12668        let mut d = wysiwyg_doc("gap_eof", "A\n");
12669        d.caret = 1;
12670        d.newline();
12671        d.build_visual(80);
12672        let (row, _) = d.caret_pos();
12673        assert!(
12674            d.vmap.row_is_navigable(row),
12675            "the caret landed on a gap row"
12676        );
12677        d.insert("x");
12678        assert!(
12679            d.source.starts_with("A\n\n") && d.source.contains('x'),
12680            "typing at the end merged into A: {:?}",
12681            d.source
12682        );
12683    }
12684
12685    #[test]
12686    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
12687        // A paragraph broken over two source lines is one paragraph. Selecting
12688        // it must not stop at the newline inside it — that newline is markup the
12689        // rich-text view exists to hide.
12690        let src = "one two\nthree four\n\nnext\n";
12691        let mut d = wysiwyg_doc("triple_para", src);
12692        d.select_block_at(2);
12693        assert_eq!(
12694            d.selected_text(),
12695            Some("one two\nthree four"),
12696            "stopped at the soft break"
12697        );
12698    }
12699
12700    #[test]
12701    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
12702        // The reader scrolls down past the caret's row. Nothing moved the
12703        // caret, so the view must stay where it was put — the old code revealed
12704        // the caret every frame, which dragged the view straight back and made
12705        // the document unscrollable past the caret.
12706        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
12707        d.caret = 0;
12708        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
12709        d.scroll = 4; // the wheel
12710        d.follow_caret(0, 3, 9);
12711        assert_eq!(
12712            d.scroll, 4,
12713            "the wheel was overruled by a caret that never moved"
12714        );
12715    }
12716
12717    #[test]
12718    fn moving_the_caret_brings_the_view_back_to_it() {
12719        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
12720        d.caret = 0;
12721        d.follow_caret(0, 3, 9);
12722        d.scroll = 6; // scrolled away
12723        d.move_right(false); // ...and now the caret moves
12724        let (row, _) = d.caret_pos();
12725        d.follow_caret(row, 3, 9);
12726        assert!(
12727            d.scroll <= row && row < d.scroll + 3,
12728            "caret row {row} off screen at scroll {}",
12729            d.scroll
12730        );
12731    }
12732
12733    #[test]
12734    fn scrolling_stops_at_the_last_row() {
12735        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
12736        d.caret = 0;
12737        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
12738        d.scroll = 999; // the wheel, spun hard
12739        d.follow_caret(0, 3, 3);
12740        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
12741    }
12742
12743    #[test]
12744    fn every_cell_of_a_wide_table_is_reachable() {
12745        // A table whose cells are far wider than the surface: the columns are
12746        // cut to fit and the text wraps inside them, so no cell hangs off the
12747        // right edge where the caret can never go.
12748        let src = "| Ingredient | Notes |\n|---|---|\n\
12749                   | flour milled coarse | sift it twice before folding it in |\n";
12750        let mut d = wysiwyg_doc("wide_table_walk", src);
12751        d.build_visual(30);
12752        d.caret = 0;
12753        let seen = walk_right(&mut d);
12754        for word in ["Ingredient", "Notes", "coarse", "folding"] {
12755            let at = src.find(word).unwrap();
12756            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
12757        }
12758    }
12759
12760    // ── view parity ──────────────────────────────────────────────────────────
12761    // `doc_with` pins the source view, so everything above tests a view users
12762    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
12763    // deletion golden cases through *both*, plus the WYSIWYG cases the two
12764    // can't share: where the source carries markup the rendered text is a
12765    // different string, and the views agreeing would itself be the bug.
12766
12767    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
12768
12769    /// Run `action` in both views on one `|`-marked fixture and assert they
12770    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
12771    /// source verbatim, so the two views are looking at the same text and any
12772    /// disagreement is one of them having lost the plot.
12773    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
12774        let (src, caret) = parse_caret(marked);
12775        let run = |view: View, tag: &str| {
12776            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
12777            d.caret = caret;
12778            action(&mut d);
12779            render_caret(&d)
12780        };
12781        let source = run(VIEWS[0].0, VIEWS[0].1);
12782        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
12783        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
12784        source
12785    }
12786
12787    #[test]
12788    fn word_motion_agrees_across_the_views_on_plain_prose() {
12789        let g = both_views;
12790        assert_eq!(
12791            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
12792            "hello |world"
12793        );
12794        assert_eq!(
12795            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
12796            "|hello world"
12797        );
12798        assert_eq!(
12799            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
12800            "hello| world"
12801        );
12802        assert_eq!(
12803            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
12804            "hello world|"
12805        );
12806        assert_eq!(
12807            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
12808            "foo|.bar"
12809        );
12810        assert_eq!(
12811            g("par_ext", "hello |world", |d| d.move_word_right(true)),
12812            "hello [world|]"
12813        );
12814    }
12815
12816    #[test]
12817    fn word_deletion_agrees_across_the_views_on_plain_prose() {
12818        let g = both_views;
12819        assert_eq!(
12820            g("par_db", "hello world|", |d| d.delete_word_back()),
12821            "hello |"
12822        );
12823        assert_eq!(
12824            g("par_df", "hello |world", |d| d.delete_word_forward()),
12825            "hello |"
12826        );
12827        assert_eq!(
12828            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
12829            "|bar baz"
12830        );
12831        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
12832    }
12833
12834    #[test]
12835    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
12836        let g = both_views;
12837        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
12838        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
12839        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
12840        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
12841    }
12842
12843    #[test]
12844    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
12845        // The reproduction: the stop table was built one stop per `char`, so
12846        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
12847        // source view, which steps by grapheme, can't reach and backspace can't
12848        // survive. The two views must land on the same offset.
12849        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
12850        for (view, tag) in VIEWS {
12851            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
12852            d.caret = 1;
12853            d.move_right(false);
12854            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
12855
12856            // ...and the edit that used to sever a joiner off the front of it.
12857            d.backspace();
12858            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
12859            assert_eq!(d.caret, 1);
12860        }
12861    }
12862
12863    #[test]
12864    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
12865        for (view, tag) in VIEWS {
12866            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
12867            d.caret = 0;
12868            d.move_right(false);
12869            assert_eq!(
12870                d.caret,
12871                "e\u{0301}".len(),
12872                "{tag} stopped on the combining mark"
12873            );
12874        }
12875    }
12876
12877    #[test]
12878    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
12879        // The general form: whatever route the caret takes through a document
12880        // full of clusters, it never lands between the codepoints of one — so no
12881        // motion-then-backspace sequence can leave a dangling joiner behind.
12882        use unicode_segmentation::UnicodeSegmentation;
12883
12884        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
12885        let mut d = wysiwyg_doc("cluster_walk", src);
12886        d.caret = 0;
12887        let boundaries: Vec<usize> = src
12888            .grapheme_indices(true)
12889            .map(|(i, _)| i)
12890            .chain(std::iter::once(src.len()))
12891            .collect();
12892        for off in walk_right(&mut d) {
12893            assert!(
12894                boundaries.contains(&off),
12895                "Right stopped at {off}, inside a grapheme cluster"
12896            );
12897        }
12898    }
12899
12900    #[test]
12901    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
12902        // The reproduction: ⌥→ from inside the opening `**` computed its
12903        // boundary over the raw source and landed on byte 8 — inside the
12904        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
12905        // "bold". The caret drew past the bold word and sat inside it.
12906        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
12907        d.caret = 2;
12908        d.move_word_right(false);
12909        assert!(
12910            d.vmap.is_stop(d.caret),
12911            "landed at {}, not a caret stop",
12912            d.caret
12913        );
12914        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
12915        // The rendered row is "a bold c": column 6 is the space just past "bold",
12916        // and now the caret is really there rather than only drawn there.
12917        assert_eq!(d.caret_pos(), (0, 6));
12918
12919        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
12920        d.move_word_left(false);
12921        assert_eq!(d.caret, 4);
12922        assert_eq!(d.caret_pos(), (0, 2));
12923    }
12924
12925    #[test]
12926    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
12927        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
12928        // inside the closing `**`, and left "a ** c\n" — delimiters with no
12929        // opener. Glyph space covers the word alone, which would leave
12930        // "a **** c": markup wrapped around nothing. The word and the styling
12931        // that was only ever the word's go together.
12932        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
12933        d.caret = 10;
12934        d.delete_word_back();
12935        assert_eq!(d.source, "a  c\n");
12936        assert_eq!(d.caret, 2);
12937
12938        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
12939        d.caret = 4; // the "b"
12940        d.delete_word_forward();
12941        assert_eq!(d.source, "a  c\n");
12942    }
12943
12944    #[test]
12945    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
12946        let src = "a ***bold*** c\n";
12947        let mut d = wysiwyg_doc("wys_word_del_nest", src);
12948        d.caret = src.find(" c").unwrap();
12949        d.delete_word_back();
12950        assert_eq!(
12951            d.source, "a  c\n",
12952            "the emph inside the strong empties it too"
12953        );
12954
12955        let src = "a `code` c\n";
12956        let mut d = wysiwyg_doc("wys_word_del_code", src);
12957        d.caret = src.find(" c").unwrap();
12958        d.delete_word_back();
12959        assert_eq!(d.source, "a  c\n");
12960    }
12961
12962    #[test]
12963    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
12964        // Only an *emptied* node goes. Take one word of two and the `**` still
12965        // has a job to do — over the word that's left, with the space the delete
12966        // pushed against the opening delimiter moved out in front of it, or the
12967        // run would be no run at all (`** words**` is literal asterisks — see
12968        // the mark-edge rule on `splice`).
12969        let src = "a **two words** c\n";
12970        let mut d = wysiwyg_doc("wys_word_del_partial", src);
12971        d.caret = src.find(" words").unwrap();
12972        d.delete_word_back();
12973        assert_eq!(d.source, "a  **words** c\n");
12974    }
12975
12976    #[test]
12977    fn source_view_word_motion_still_walks_the_markup() {
12978        // The other half of the decision: in the source view the `**` are
12979        // characters like any other — they're on the screen, so word motion has
12980        // to stop at them and a word-delete has to leave them behind. Only
12981        // WYSIWYG hides them, so only WYSIWYG steps over them.
12982        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
12983        assert_eq!(
12984            g("src_word_motion", "a |**bold** c\n", |d| d
12985                .move_word_right(false)),
12986            "a **bold|** c\n"
12987        );
12988        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
12989        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
12990        assert_eq!(
12991            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
12992            "a **| c\n"
12993        );
12994    }
12995
12996    #[test]
12997    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
12998        // The single invariant both bugs violated: the caret draws and edits at
12999        // the same place only when it's on a stop. `debug_assert_on_a_stop`
13000        // makes the same claim in-place; this pins it from the outside, over a
13001        // document with every kind of thing the map has to be careful about.
13002        // At two widths: the wide one every other test builds at, where no
13003        // fixture folds, and one narrow enough that they all do. A soft wrap is
13004        // where an offset stops being on exactly one row, and testing only the
13005        // width that never wraps is how the caret came to be pinned at the first
13006        // one Down reached.
13007        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
13008                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
13009        // A table of named operations, which is what it looks like.
13010        #[allow(clippy::type_complexity)]
13011        let motions: [(&str, fn(&mut Doc)); 8] = [
13012            ("right", |d| d.move_right(false)),
13013            ("left", |d| d.move_left(false)),
13014            ("word_right", |d| d.move_word_right(false)),
13015            ("word_left", |d| d.move_word_left(false)),
13016            ("down", |d| d.move_down(false)),
13017            ("up", |d| d.move_up(false)),
13018            ("home", |d| d.move_home(false)),
13019            ("end", |d| d.move_end(false)),
13020        ];
13021        for width in [80, 12] {
13022            let mut d = wysiwyg_doc("stop_invariant", src);
13023            d.build_visual(width);
13024            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
13025            assert!(stops.len() > 20, "fixture should have plenty of stops");
13026            for start in stops {
13027                for (name, motion) in &motions {
13028                    d.caret = start;
13029                    d.anchor = None;
13030                    motion(&mut d);
13031                    assert!(
13032                        d.vmap.is_stop(d.caret),
13033                        "{name} from {start} at width {width} landed at {} — not a caret stop",
13034                        d.caret
13035                    );
13036                }
13037            }
13038        }
13039    }
13040
13041    #[test]
13042    fn no_wysiwyg_motion_is_a_dead_end() {
13043        // Down held to the bottom of a document reaches the bottom, and Up held
13044        // to the top reaches the top — from anywhere, at a width that wraps. The
13045        // invariant above says a motion lands somewhere legal; this one says it
13046        // gets somewhere at all, which is what a caret pinned at a wrap boundary
13047        // was quietly failing to do while every assertion around it held.
13048        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
13049                   - item one two three four five\n\nlast\n";
13050        for width in [80, 12] {
13051            let mut d = wysiwyg_doc("no_dead_end", src);
13052            d.build_visual(width);
13053            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
13054            let (first, last) = (stops[0], stops[stops.len() - 1]);
13055            for &start in &stops {
13056                for (name, motion, want) in [
13057                    (
13058                        "down",
13059                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
13060                        last,
13061                    ),
13062                    ("up", |d: &mut Doc| d.move_up(false), first),
13063                ] {
13064                    d.caret = start;
13065                    d.anchor = None;
13066                    d.goal_col = None;
13067                    // Every row, plus the presses the edges take, plus slack.
13068                    for _ in 0..d.vmap.num_rows() + 4 {
13069                        motion(&mut d);
13070                    }
13071                    assert_eq!(
13072                        d.caret, want,
13073                        "{name} held from {start} at width {width} never arrived"
13074                    );
13075                }
13076            }
13077        }
13078    }
13079    // ── display columns ──────────────────────────────────────────────────────
13080    // A `col` is a terminal cell, not a character. The two are the same number
13081    // for the ASCII the fixtures above are written in, which is how they came
13082    // apart in the first place: `你` is one character drawn in two cells, so a
13083    // column counted in characters names a cell the text isn't in — one earlier
13084    // for every wide character to its left.
13085
13086    #[test]
13087    fn a_wide_character_is_two_columns_wide() {
13088        // The reproduction: `你` is one char and two cells, so the caret just
13089        // past it drew at column 1 — inside the character it had already left.
13090        for (view, tag) in VIEWS {
13091            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
13092            d.caret = "你".len();
13093            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
13094            d.caret = "你好".len();
13095            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
13096        }
13097    }
13098
13099    #[test]
13100    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
13101        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
13102        // two-cell — measuring six cells one at a time, but the character they
13103        // spell is drawn in two. Width belongs to the cluster, not the glyph,
13104        // and the frontends measure it the same way.
13105        let family = "👨‍👩‍👧";
13106        for (view, tag) in VIEWS {
13107            let src = format!("a{family}b\n");
13108            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
13109            d.caret = 1 + family.len();
13110            assert_eq!(
13111                d.caret_pos(),
13112                (0, 3),
13113                "{tag}: 'a' is one cell, the family two"
13114            );
13115        }
13116    }
13117
13118    #[test]
13119    fn both_cells_of_a_wide_character_mean_the_character() {
13120        // Clicking the far half of `好` is still clicking `好`: half a character
13121        // is not a place the caret can be, so it comes to rest at the
13122        // character's start — the column it would have been drawn at anyway.
13123        for (view, tag) in VIEWS {
13124            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
13125            for col in [2, 3] {
13126                d.caret = 0;
13127                d.click(0, col, false);
13128                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
13129                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
13130            }
13131            // Past the last cell is the line's end, as it is for ASCII.
13132            d.click(0, 9, false);
13133            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
13134        }
13135    }
13136
13137    #[test]
13138    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
13139        // The mapping is only a mapping if it inverts: the cell the caret is
13140        // drawn in has to be the cell that brings it back to the same offset.
13141        // Over a fixture where a character may be one cell or two, and one
13142        // codepoint or five.
13143        use unicode_segmentation::UnicodeSegmentation;
13144
13145        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
13146
13147        let mut d = doc_in(View::Source, "roundtrip_source", src);
13148        // Every offset the source view's caret can occupy: it steps by grapheme
13149        // cluster, so those are its boundaries.
13150        for (off, _) in src
13151            .grapheme_indices(true)
13152            .chain(std::iter::once((src.len(), "")))
13153        {
13154            d.caret = off;
13155            let (row, col) = d.caret_pos();
13156            d.click(row, col, false);
13157            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
13158        }
13159
13160        // And in WYSIWYG, where the offsets the caret can occupy are the map's
13161        // stops rather than every boundary.
13162        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
13163        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
13164        assert!(stops.len() > 20, "fixture should have plenty of stops");
13165        for off in stops {
13166            d.caret = off;
13167            let (row, col) = d.caret_pos();
13168            d.click(row, col, false);
13169            assert_eq!(
13170                d.caret, off,
13171                "wysiwyg: {off} → ({row}, {col}) → {}",
13172                d.caret
13173            );
13174        }
13175    }
13176
13177    #[test]
13178    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
13179        // Down from under `世` lands under the glyph in that cell, not two
13180        // characters further along the line. The goal is a column, so a line of
13181        // wide characters and a line of ASCII line up the way they're drawn.
13182        //
13183        // The gap differs by view: a bare newline inside a paragraph is a soft
13184        // break, which WYSIWYG draws as a space on a single row. The views share
13185        // a grid only where the source's lines are the renderer's rows too.
13186        for (view, tag) in VIEWS {
13187            let gap = if view == View::Source { "\n" } else { "\n\n" };
13188            let src = format!("你好世{gap}abcdef\n");
13189            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
13190            d.caret = "你好".len();
13191            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
13192            d.move_down(false);
13193            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
13194            assert!(
13195                d.source[d.caret..].starts_with('e'),
13196                "{tag}: landed on the wrong glyph"
13197            );
13198        }
13199    }
13200
13201    #[test]
13202    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
13203        // Down from column 3 onto `你好`, whose characters start at columns 0
13204        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
13205        // between the cells of one character, so the caret rests on it — and on
13206        // its start, which is the only offset there that is a caret stop.
13207        for (view, tag) in VIEWS {
13208            let gap = if view == View::Source { "\n" } else { "\n\n" };
13209            let src = format!("abcdef{gap}你好\n");
13210            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
13211            let line = src.find('你').unwrap();
13212            d.caret = 3;
13213            d.move_down(false);
13214            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
13215            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
13216        }
13217    }
13218
13219    #[test]
13220    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
13221        // The column the cell's text is laid out in is measured in cells, so the
13222        // caret walking that text has to be too — the two agreeing is the whole
13223        // point of the grid staying square.
13224        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
13225        let at = d.source.find("你").unwrap();
13226        d.caret = at;
13227        let (row, col) = d.caret_pos();
13228        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
13229        // cells further along.
13230        assert_eq!(col, 2, "the cell's first character");
13231        d.move_right(false);
13232        assert_eq!(
13233            d.caret_pos(),
13234            (row, 4),
13235            "`好` is drawn past `你`'s two cells"
13236        );
13237        assert_eq!(d.caret, at + "你".len());
13238    }
13239
13240    // ── active inline marks ───────────────────────────────────────────────────
13241
13242    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
13243    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
13244        let (src, caret) = parse_caret(marked);
13245        let mut d = doc_in(view, name, &src);
13246        d.caret = caret;
13247        d.active_inline_marks().iter().collect()
13248    }
13249
13250    /// The marks over the selection `[start, end)`.
13251    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
13252        let mut d = doc_in(view, name, src);
13253        d.anchor = Some(start);
13254        d.caret = end;
13255        d.active_inline_marks().iter().collect()
13256    }
13257
13258    #[test]
13259    fn a_caret_in_a_mark_reports_it() {
13260        for (view, tag) in VIEWS {
13261            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
13262            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
13263            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
13264            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
13265            // Plain text under no mark lights nothing — the toolbar's resting state.
13266            assert_eq!(m("a| **bold** b"), [], "{tag}");
13267            assert!(m("plain t|ext").is_empty(), "{tag}");
13268        }
13269    }
13270
13271    #[test]
13272    fn nested_marks_all_report() {
13273        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
13274        // the ancestor chain is a chain, and every mark on it is in force.
13275        for (view, tag) in VIEWS {
13276            assert_eq!(
13277                marks(
13278                    view,
13279                    &format!("marks_nested_{tag}"),
13280                    "**bold and *bo|th*** end"
13281                ),
13282                [InlineKind::Strong, InlineKind::Emph],
13283                "{tag}"
13284            );
13285        }
13286    }
13287
13288    #[test]
13289    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
13290        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
13291        // the first byte of its text and the byte after its last — both inside
13292        // the mark's span, both places typing lands inside the bold. The offset
13293        // past the closing delimiter is the next text, and reports nothing.
13294        let src = "a **bold** b";
13295        let inner_start = src.find("bold").unwrap(); // 4
13296        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
13297        for (view, tag) in VIEWS {
13298            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
13299            for off in [2, 3, inner_start, inner_end, 9] {
13300                d.caret = off;
13301                assert!(
13302                    d.active_inline_marks().contains(InlineKind::Strong),
13303                    "{tag}: offset {off} is inside the strong span"
13304                );
13305            }
13306            for off in [0, 1, 10, 11, 12] {
13307                d.caret = off;
13308                assert!(
13309                    !d.active_inline_marks().contains(InlineKind::Strong),
13310                    "{tag}: offset {off} is outside the strong run"
13311                );
13312            }
13313        }
13314    }
13315
13316    #[test]
13317    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
13318        // Regression: twig resolves an offset that is one node's end and the
13319        // next one's start to the node that *starts* there, so `**bold**|\n`
13320        // isn't bold. With nothing following there's no tie to break and the
13321        // chain still ended at the mark, which made a trailing `\n` — not the
13322        // text — decide whether the caret after a bold word reported bold. It's
13323        // the offset past the mark either way, and typing there is plain either
13324        // way. A blank document typed into is exactly this shape.
13325        for (view, tag) in VIEWS {
13326            let m = |name: String, marked| marks(view, &name, marked);
13327            assert_eq!(
13328                m(format!("marks_eob_{tag}"), "**bold**|"),
13329                [],
13330                "{tag}: no trailing newline"
13331            );
13332            assert_eq!(
13333                m(format!("marks_eol_{tag}"), "**bold**|\n"),
13334                [],
13335                "{tag}: with one"
13336            );
13337            // And the last offset that *is* in the mark still is.
13338            assert_eq!(
13339                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
13340                [InlineKind::Strong],
13341                "{tag}"
13342            );
13343        }
13344    }
13345
13346    #[test]
13347    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
13348        let src = "a **bold** b";
13349        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
13350        for (view, tag) in VIEWS {
13351            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
13352            // The whole bold word, and a slice of it.
13353            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
13354            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
13355            // Ending exactly at the closing delimiter's start is still all-bold:
13356            // an exclusive end sits *past* the last selected character, so the
13357            // question is asked of the character, not the boundary.
13358            assert_eq!(
13359                m(b, d_ + 2),
13360                [InlineKind::Strong],
13361                "{tag}: through the close"
13362            );
13363            // Half in, half out: Bold lit here would claim a press turns it off.
13364            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
13365            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
13366        }
13367    }
13368
13369    #[test]
13370    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
13371        // Both ends are bold, but the space between them isn't — two runs are two
13372        // nodes, which is exactly what the node id catches and a kind-only
13373        // comparison would not.
13374        let src = "**one** **two**";
13375        for (view, tag) in VIEWS {
13376            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
13377            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
13378        }
13379    }
13380
13381    #[test]
13382    fn marks_read_the_document_as_it_is_edited() {
13383        // The point of asking twig every frame instead of caching: the answer has
13384        // to follow the toggle that changed it.
13385        let mut d = wysiwyg_doc("marks_live", "one two\n");
13386        d.anchor = Some(0);
13387        d.caret = 3;
13388        assert!(d.active_inline_marks().is_empty(), "plain to start");
13389        d.toggle(InlineKind::Strong);
13390        assert_eq!(d.source, "**one** two\n");
13391        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
13392        assert!(d.active_inline_marks().contains(InlineKind::Strong));
13393        d.toggle(InlineKind::Strong);
13394        assert!(d.active_inline_marks().is_empty(), "and off again");
13395    }
13396
13397    #[test]
13398    fn a_link_is_not_an_inline_mark() {
13399        // `link`/`str` are inline nodes, but nothing on the inline toolbar
13400        // toggles them — a set with a "link mark" in it would have no button.
13401        for (view, tag) in VIEWS {
13402            assert_eq!(
13403                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
13404                [],
13405                "{tag}"
13406            );
13407        }
13408    }
13409
13410    // ── blank documents ───────────────────────────────────────────────────────
13411
13412    #[test]
13413    fn a_blank_document_is_untitled_empty_and_markdown() {
13414        let mut d = Doc::blank().unwrap();
13415        assert!(d.is_untitled());
13416        assert_eq!(d.path, PathBuf::new());
13417        assert_eq!(
13418            d.file_name(),
13419            "untitled",
13420            "the header has to show something"
13421        );
13422        assert_eq!(d.format_name(), "markdown");
13423        assert_eq!(d.source, "");
13424        assert!(!d.dirty, "nothing typed yet is nothing to lose");
13425        assert_eq!(d.disk_state(), DiskState::Untitled);
13426        // And it's a document you can be in: the default view renders it.
13427        d.build_visual(80);
13428        assert_eq!(d.caret, 0);
13429    }
13430
13431    #[test]
13432    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
13433        let mut d = Doc::blank().unwrap();
13434        d.insert("hello");
13435        assert!(d.dirty);
13436        d.save();
13437        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
13438        assert!(d.dirty, "it must not come away believing it saved");
13439        assert!(d.is_untitled(), "and it still has no file");
13440    }
13441
13442    #[test]
13443    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
13444        let p = temp_path("blank_save_as");
13445        let mut d = Doc::blank().unwrap();
13446        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
13447        // be kept literal (`\#`); this test is about save-as, not escaping (which
13448        // has its own test), so it types nothing that escaping would touch.
13449        d.insert("hi");
13450        d.save_as(p.clone());
13451        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
13452        assert!(!d.is_untitled());
13453        assert!(!d.dirty);
13454        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
13455        assert_eq!(
13456            d.disk_state(),
13457            DiskState::Unchanged,
13458            "the watermark is stamped"
13459        );
13460        // And ⌘S is a plain save from here on.
13461        d.insert("!");
13462        d.save();
13463        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
13464        let _ = std::fs::remove_file(&p);
13465    }
13466
13467    // ── a file that isn't there yet ───────────────────────────────────────────
13468
13469    /// A unique path in the temp dir with the given extension, guaranteed not to
13470    /// exist — what `leaf notes.md` is handed when the file has never been made.
13471    fn missing_path(name: &str, ext: &str) -> PathBuf {
13472        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13473        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13474        let mut p = std::env::temp_dir();
13475        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
13476        let _ = std::fs::remove_file(&p);
13477        p
13478    }
13479
13480    #[test]
13481    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
13482        let p = missing_path("named", "md");
13483        let mut d = Doc::open_or_create(p.clone()).unwrap();
13484
13485        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
13486        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
13487        assert!(
13488            !d.is_untitled(),
13489            "it has the name the user asked for — ^S must not detour to Save As"
13490        );
13491        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
13492        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
13493        assert!(!p.exists(), "and opening it wrote nothing");
13494        // And it's a document you can be in.
13495        d.build_visual(80);
13496        assert_eq!(d.caret, 0);
13497    }
13498
13499    #[test]
13500    fn a_new_file_is_created_by_its_first_save() {
13501        let p = missing_path("first_save", "md");
13502        let mut d = Doc::open_or_create(p.clone()).unwrap();
13503        d.insert("hello\n");
13504        assert!(d.dirty);
13505        d.save();
13506
13507        assert_eq!(
13508            std::fs::read_to_string(&p).unwrap(),
13509            "hello\n",
13510            "a plain ^S wrote it — no Save As, no name to invent"
13511        );
13512        assert!(!d.dirty);
13513        assert_eq!(d.disk_state(), DiskState::Unchanged);
13514        let _ = std::fs::remove_file(&p);
13515    }
13516
13517    #[test]
13518    fn a_new_file_takes_its_format_from_the_extension() {
13519        // The one thing `blank` can't do: with no name it has to assume Markdown,
13520        // and typing djot into a Markdown parse is the wrong buffer.
13521        let dj = missing_path("format", "dj");
13522        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
13523        let md = missing_path("format", "md");
13524        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
13525    }
13526
13527    #[test]
13528    fn a_new_file_reports_itself_missing_until_it_is_saved() {
13529        // Not `Untitled` — that's the answer for a document with no path, and it
13530        // would tell a frontend there is nothing a save could collide with. Here
13531        // there is a path, and the file simply isn't at it yet.
13532        let p = missing_path("disk_state", "md");
13533        let mut d = Doc::open_or_create(p.clone()).unwrap();
13534        assert_eq!(d.disk_state(), DiskState::Missing);
13535
13536        // Somebody else creates it while the buffer is open: that's an overwrite
13537        // the frontend has to be able to prompt about, exactly as for an opened
13538        // file. Their bytes, not ours, so `Changed`.
13539        std::fs::write(&p, "theirs\n").unwrap();
13540        assert_eq!(d.disk_state(), DiskState::Changed);
13541
13542        // Saving makes the file ours and re-stamps the watermark.
13543        d.insert("ours\n");
13544        d.save();
13545        assert_eq!(d.disk_state(), DiskState::Unchanged);
13546        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
13547        let _ = std::fs::remove_file(&p);
13548    }
13549
13550    #[test]
13551    fn open_or_create_still_opens_a_file_that_is_there() {
13552        let d = doc_with("open_or_create_existing", "body\n");
13553        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
13554        assert_eq!(reopened.source, "body\n");
13555        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
13556    }
13557
13558    #[test]
13559    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
13560        // A mistyped flag or a stray argument must not become a buffer promising
13561        // to save somewhere — the same refusal `open` gives a real file.
13562        let mut p = std::env::temp_dir();
13563        p.push("leaf_test_new_bad_ext.wat");
13564        assert!(Doc::open_or_create(p).is_err());
13565        let mut none = std::env::temp_dir();
13566        none.push("leaf_test_new_no_ext");
13567        assert!(Doc::open_or_create(none).is_err());
13568    }
13569
13570    #[test]
13571    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
13572        // Opening reads nothing, so there is nothing to fail on yet; the write is
13573        // where it fails, and it says so rather than claiming a save.
13574        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
13575        let mut d = Doc::open_or_create(p).unwrap();
13576        d.insert("x");
13577        d.save();
13578        assert!(
13579            d.status.as_deref().unwrap().starts_with("save failed:"),
13580            "got {:?}",
13581            d.status
13582        );
13583        assert!(d.dirty, "it must not come away believing it saved");
13584    }
13585
13586    // ── save as ───────────────────────────────────────────────────────────────
13587
13588    /// A unique path in the temp dir that no fixture wrote — a Save As target.
13589    fn temp_path(name: &str) -> PathBuf {
13590        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13591        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13592        let mut p = std::env::temp_dir();
13593        p.push(format!("leaf_test_target_{name}_{seq}.md"));
13594        let _ = std::fs::remove_file(&p);
13595        p
13596    }
13597
13598    #[test]
13599    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
13600        let mut d = doc_with("save_as_move", "original\n");
13601        let old = d.path.clone();
13602        let new = temp_path("save_as_move");
13603        d.insert("edited: ");
13604        d.save_as(new.clone());
13605
13606        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
13607        assert_eq!(
13608            std::fs::read_to_string(&old).unwrap(),
13609            "original\n",
13610            "Save As doesn't touch the file it came from"
13611        );
13612        assert_eq!(d.path, new, "the document moved");
13613        assert!(!d.dirty);
13614        assert_eq!(
13615            d.status.as_deref(),
13616            Some(&*format!("saved {}", d.file_name()))
13617        );
13618
13619        // Every later save follows it, which is the whole difference from a copy.
13620        d.caret = 0;
13621        d.insert("re-");
13622        d.save();
13623        assert_eq!(
13624            std::fs::read_to_string(&new).unwrap(),
13625            "re-edited: original\n"
13626        );
13627        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
13628        let _ = std::fs::remove_file(&new);
13629    }
13630
13631    #[test]
13632    fn save_as_overwrites_an_existing_target() {
13633        // The picker already asked; asking again down here is the same question
13634        // twice, and the second one has no way to be answered.
13635        let new = temp_path("save_as_over");
13636        std::fs::write(&new, "theirs\n").unwrap();
13637        let mut d = doc_with("save_as_over", "ours\n");
13638        d.save_as(new.clone());
13639        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
13640        let _ = std::fs::remove_file(&new);
13641    }
13642
13643    #[test]
13644    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
13645        let mut d = doc_with("save_as_fail", "body\n");
13646        let old = d.path.clone();
13647        d.insert("x");
13648        // A directory that doesn't exist: the write can't land.
13649        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
13650        d.save_as(bad);
13651
13652        assert_eq!(
13653            d.path, old,
13654            "the document must not move to a file that isn't there"
13655        );
13656        assert!(d.dirty, "and must not believe it saved");
13657        assert!(
13658            d.status.as_deref().unwrap().starts_with("save failed:"),
13659            "the same failure a plain save reports, got {:?}",
13660            d.status
13661        );
13662        // The original is still the document's file, and still saveable.
13663        d.save();
13664        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
13665        assert!(!d.dirty);
13666    }
13667
13668    #[test]
13669    fn save_as_renames_without_reparsing_the_format() {
13670        // `.dj` on the name doesn't make the buffer djot: it was parsed as
13671        // Markdown and still is, and saying otherwise would be a conversion the
13672        // user never asked for (and an undo history thrown away to do it).
13673        let mut d = doc_with("save_as_format", "**b**\n");
13674        let mut new = temp_path("save_as_format");
13675        new.set_extension("dj");
13676        d.save_as(new.clone());
13677        assert_eq!(d.format_name(), "markdown");
13678        let _ = std::fs::remove_file(&new);
13679    }
13680
13681    // ── external change / reload ──────────────────────────────────────────────
13682
13683    #[test]
13684    fn an_untouched_file_reports_unchanged() {
13685        let mut d = doc_with("disk_clean", "body\n");
13686        assert_eq!(d.disk_state(), DiskState::Unchanged);
13687        // Editing the buffer is not editing the file.
13688        d.insert("x");
13689        assert_eq!(d.disk_state(), DiskState::Unchanged);
13690        assert!(d.dirty);
13691        // Saving re-stamps the watermark rather than reporting our own bytes back.
13692        d.save();
13693        assert_eq!(d.disk_state(), DiskState::Unchanged);
13694    }
13695
13696    #[test]
13697    fn a_file_written_underneath_reports_changed() {
13698        let mut d = doc_with("disk_changed", "body\n");
13699        std::fs::write(&d.path, "someone else\n").unwrap();
13700        assert_eq!(d.disk_state(), DiskState::Changed);
13701        // Dirty *and* changed is the clobber: both halves are readable, and
13702        // leaf-core takes neither side.
13703        d.insert("x");
13704        assert!(d.dirty && d.disk_state() == DiskState::Changed);
13705        // Saving anyway is allowed — the frontend asked, or chose not to.
13706        d.save();
13707        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
13708        assert_eq!(d.disk_state(), DiskState::Unchanged);
13709    }
13710
13711    #[test]
13712    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
13713        // The hash is what makes this honest: the file was written (a fresh
13714        // mtime), and nothing about the document is stale.
13715        let d = doc_with("disk_same_bytes", "body\n");
13716        std::fs::write(&d.path, "body\n").unwrap();
13717        assert_eq!(d.disk_state(), DiskState::Unchanged);
13718    }
13719
13720    #[test]
13721    fn a_deleted_file_reports_missing() {
13722        let mut d = doc_with("disk_missing", "body\n");
13723        std::fs::remove_file(&d.path).unwrap();
13724        assert_eq!(d.disk_state(), DiskState::Missing);
13725        // A save recreates it, and the document is whole again.
13726        d.save();
13727        assert_eq!(d.disk_state(), DiskState::Unchanged);
13728        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
13729    }
13730
13731    #[test]
13732    fn reload_replaces_the_document_with_the_file() {
13733        for (view, tag) in VIEWS {
13734            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
13735            d.insert("edited ");
13736            assert!(d.dirty);
13737            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
13738            d.reload();
13739
13740            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
13741            assert!(!d.dirty, "{tag}: the file is what we have");
13742            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
13743            assert_eq!(
13744                d.status.as_deref(),
13745                Some(&*format!("reloaded {}", d.file_name()))
13746            );
13747            // The reloaded tree is live, not the old parse.
13748            d.caret = d.source.find("three").unwrap();
13749            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
13750        }
13751    }
13752
13753    #[test]
13754    fn reload_clamps_the_caret_and_drops_the_selection() {
13755        let mut d = doc_with("reload_caret", "a long first line\n");
13756        d.caret = 12;
13757        d.anchor = Some(4);
13758        std::fs::write(&d.path, "short\n").unwrap();
13759        d.reload();
13760        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
13761        assert_eq!(
13762            d.anchor, None,
13763            "a selection over bytes that changed is a lie"
13764        );
13765        assert!(d.selection().is_none());
13766
13767        // A caret the file still has room for stays put.
13768        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
13769        d.caret = 2;
13770        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
13771        d.reload();
13772        assert_eq!(d.caret, 2);
13773    }
13774
13775    /// A silent reload is something that happened *to* a reader — a formatter,
13776    /// a `git checkout` — so it has to be undoable like anything else that
13777    /// changes the document, and undoable as one step rather than as however
13778    /// many the file happens to differ by.
13779    #[test]
13780    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
13781        let mut d = doc_with("reload_undo", "body\n");
13782        d.insert("x");
13783        assert_eq!(d.source, "xbody\n");
13784        std::fs::write(&d.path, "replaced\n").unwrap();
13785        d.reload();
13786        assert_eq!(d.source, "replaced\n");
13787        assert!(!d.dirty, "a reload lands clean");
13788
13789        // One ^Z takes the whole swap off, and hands back the unsaved work it
13790        // replaced — which is unsaved again, because the file no longer says it.
13791        d.undo();
13792        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
13793        assert!(d.dirty, "and what it comes back to is unsaved");
13794        // …and the history under it is still there.
13795        d.undo();
13796        assert_eq!(
13797            d.source, "body\n",
13798            "the typing before the reload undoes too"
13799        );
13800        // Redo walks back up through the reload.
13801        d.redo();
13802        d.redo();
13803        assert_eq!(d.source, "replaced\n");
13804    }
13805
13806    /// A file rewritten with the bytes it already had is not an edit, so it
13807    /// must not leave an undo step behind for something nobody did.
13808    #[test]
13809    fn reloading_identical_bytes_pushes_no_undo_step() {
13810        let mut d = doc_with("reload_same", "body\n");
13811        d.insert("x");
13812        std::fs::write(&d.path, "xbody\n").unwrap();
13813        d.reload();
13814        assert_eq!(d.source, "xbody\n");
13815        assert!(!d.dirty, "the file now says what the buffer does");
13816        d.undo();
13817        assert_eq!(
13818            d.source, "body\n",
13819            "one step back is the typing, not a no-op"
13820        );
13821    }
13822
13823    #[test]
13824    fn a_reload_that_cant_read_leaves_the_document_alone() {
13825        let mut d = doc_with("reload_gone", "body\n");
13826        d.insert("x");
13827        std::fs::remove_file(&d.path).unwrap();
13828        d.reload();
13829        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
13830        assert!(d.dirty);
13831        assert!(
13832            d.status.as_deref().unwrap().starts_with("reload failed:"),
13833            "{:?}",
13834            d.status
13835        );
13836
13837        // And an untitled document has nothing to reload from.
13838        let mut d = Doc::blank().unwrap();
13839        d.insert("typed");
13840        d.reload();
13841        assert_eq!(d.source, "typed");
13842        assert_eq!(d.status.as_deref(), Some("no file to reload"));
13843    }
13844
13845    #[test]
13846    fn a_read_only_document_refuses_every_door() {
13847        let mut d = doc_with("readonly", "one two three\n");
13848        d.insert("x");
13849        assert!(d.dirty, "writable first, so the undo step exists");
13850        d.set_read_only(true);
13851        let before = d.source.clone();
13852        d.insert("y");
13853        d.backspace();
13854        d.undo();
13855        d.redo();
13856        assert_eq!(d.source, before, "no door moved a byte");
13857        d.set_read_only(false);
13858        d.undo();
13859        assert_ne!(d.source, before, "off again, the same doors work");
13860    }
13861
13862    /// The doors that go to twig's own verbs rather than through the splice.
13863    /// Typed text in the rendered view under the default markup mode is the
13864    /// everyday one — it is what a keystroke in leaf-web or the Apple views
13865    /// becomes — and it walked straight past the gate.
13866    #[test]
13867    fn a_read_only_document_refuses_the_doors_around_the_splice() {
13868        let mut d = wysiwyg_doc(
13869            "readonly-doors",
13870            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
13871        );
13872        d.set_markup_mode(MarkupMode::None);
13873        d.set_read_only(true);
13874        let before = d.source.clone();
13875        d.place_caret(3, false);
13876        d.insert("y");
13877        d.insert_link("https://example.com");
13878        d.insert_image("a.png", "alt");
13879        d.insert_thematic_break();
13880        d.insert_footnote();
13881        d.place_caret(0, false);
13882        d.place_caret(3, true);
13883        d.toggle(InlineKind::Strong);
13884        d.toggle_heading(2);
13885        d.set_block(BlockKind::Paragraph);
13886        d.toggle_list(false);
13887        d.toggle_blockquote();
13888        d.toggle_task_item();
13889        d.newline();
13890        d.indent();
13891        d.set_code_language("rust");
13892        let in_cell = d.source.find("| c").unwrap() + 2;
13893        d.place_caret(in_cell, false);
13894        assert!(d.caret_in_table(), "the caret is in the grid");
13895        assert!(!d.cell_line_break(), "the cell break reports the refusal");
13896        assert_eq!(d.source, before, "no door moved a byte");
13897        assert!(!d.dirty, "nothing to save");
13898        d.set_read_only(false);
13899        d.place_caret(3, false);
13900        d.insert("y");
13901        assert_ne!(d.source, before, "off again, the same doors work");
13902    }
13903
13904    #[test]
13905    fn a_selection_quote_carries_its_context_on_char_boundaries() {
13906        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
13907        let start = d.source.find("exact").unwrap();
13908        d.place_caret(start, false);
13909        d.place_caret(start + "exact".len(), true);
13910        let q = d.selection_quote(3).unwrap();
13911        assert_eq!(q.exact, "exact");
13912        assert_eq!(
13913            q.prefix, "你好 ",
13914            "chars, not bytes — the multibyte pair counts as two"
13915        );
13916        assert_eq!(q.suffix, " 世界");
13917        assert_eq!(&d.source[q.start..q.end], "exact");
13918        // At the edges the context clips rather than erring.
13919        d.place_caret(0, false);
13920        d.place_caret(6, true);
13921        let q = d.selection_quote(40).unwrap();
13922        assert_eq!(q.prefix, "");
13923        assert_eq!(q.exact, "before");
13924        // No selection is no quote.
13925        d.place_caret(0, false);
13926        assert!(d.selection_quote(3).is_none());
13927    }
13928
13929    #[test]
13930    fn highlights_are_kept_sorted_and_answer_point_queries() {
13931        let mut d = doc_with("hl", "one two three\n");
13932        d.set_highlights(vec![
13933            Highlight {
13934                start: 8,
13935                end: 13,
13936                id: "b".into(),
13937                color: None,
13938                marker: None,
13939            },
13940            Highlight {
13941                start: 0,
13942                end: 3,
13943                id: "a".into(),
13944                color: Some("#ffe066".into()),
13945                marker: None,
13946            },
13947            Highlight {
13948                start: 5,
13949                end: 5,
13950                id: "empty".into(),
13951                color: None,
13952                marker: None,
13953            },
13954        ]);
13955        assert_eq!(
13956            d.highlights()
13957                .iter()
13958                .map(|h| h.id.as_str())
13959                .collect::<Vec<_>>(),
13960            ["a", "b"],
13961            "sorted by start, the empty range dropped"
13962        );
13963        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
13964        assert_eq!(d.highlight_at(3), None, "end is exclusive");
13965        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
13966        d.set_highlights(Vec::new());
13967        assert!(d.highlights().is_empty(), "a replace is a replace");
13968    }
13969
13970    /// `Highlight::covering` and the cursor over it are what both painters ask
13971    /// per glyph, so they have to answer the same as the scan they replaced —
13972    /// including in the gaps, which is where most glyphs are.
13973    #[test]
13974    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
13975        let hl = |start: usize, end: usize, id: &str| Highlight {
13976            start,
13977            end,
13978            id: id.into(),
13979            color: None,
13980            marker: None,
13981        };
13982        // Disjoint, as search hits are: in a range, in a gap, and past the end.
13983        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
13984        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
13985        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
13986        assert_eq!(
13987            Highlight::covering(&hits, 105),
13988            None,
13989            "a gap covers nothing"
13990        );
13991        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
13992        assert_eq!(Highlight::covering(&hits, 9_999), None);
13993        assert_eq!(Highlight::covering(&[], 0), None);
13994
13995        // Nested: first by start, so a hit inside an annotation still resolves
13996        // to the annotation — and the range that stops short doesn't mask it.
13997        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
13998        assert_eq!(
13999            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
14000            Some("outer")
14001        );
14002        assert_eq!(
14003            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
14004            Some("outer")
14005        );
14006    }
14007
14008    /// The cursor is an optimisation, so the only thing worth asserting is that
14009    /// it is not also a change of answer — at every offset, over a list with a
14010    /// nest in it, walked forwards and then backwards.
14011    #[test]
14012    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
14013        let hl = |start: usize, end: usize, id: &str| Highlight {
14014            start,
14015            end,
14016            id: id.into(),
14017            color: None,
14018            marker: None,
14019        };
14020        let mut list = vec![
14021            hl(0, 20, "outer"),
14022            hl(5, 10, "inner"),
14023            hl(30, 33, "hit"),
14024            hl(40, 43, "hit"),
14025        ];
14026        list.sort_by_key(|h| (h.start, h.end));
14027
14028        let mut cursor = HighlightCursor::new(&list);
14029        for offset in 0..50 {
14030            assert_eq!(
14031                cursor.at(offset).map(|h| h.id.as_str()),
14032                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
14033                "cursor disagrees at {offset}"
14034            );
14035        }
14036        // Backwards: the cursor re-seats rather than answering from where it
14037        // had got to, so a painter that revisits a row is still told the truth.
14038        for offset in (0..50).rev() {
14039            assert_eq!(
14040                cursor.at(offset).map(|h| h.id.as_str()),
14041                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
14042                "cursor disagrees walking back at {offset}"
14043            );
14044        }
14045    }
14046}