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 what is behind it — which `Doc` built it, and the (revision, wrap,
527/// reveal line) it was built from — is core's business.
528///
529/// The document is part of it because the rest is not unique to one: two
530/// documents opened at the same width are both at revision zero with no reveal
531/// line, and a frontend holding one copy of a map across the two would take
532/// the second's key for the first's and paint the wrong document.
533#[derive(Clone, PartialEq, Eq, Debug)]
534pub struct VisualKey(u64, Option<(u64, Option<usize>, Option<Range<usize>>)>);
535
536pub struct Doc {
537    editor: Editor,
538    pub format: Format,
539    pub path: PathBuf,
540    /// Current source, refreshed from the editor after every successful edit.
541    pub source: String,
542    /// The caret, as a byte offset into `source` (always on a char boundary).
543    pub caret: usize,
544    /// The selection's fixed end, if a selection is active; the moving end is
545    /// the caret. `None` means no selection.
546    pub anchor: Option<usize>,
547    pub dirty: bool,
548    pub status: Option<String>,
549    pub view: View,
550    /// Whether the document refuses to change — a *reading* surface over the
551    /// same rendering, selection, and navigation the editor has.
552    ///
553    /// Enforced here rather than by each frontend hiding its input paths,
554    /// because every mutation funnels through a few doors —
555    /// [`splice_exact`](Self::splice_exact), [`undo`](Self::undo),
556    /// [`redo`](Self::redo), and the handful of inserts that go to twig's own
557    /// verbs directly rather than through the splice (a typed literal, a link,
558    /// an image, a rule, a footnote, a cell's line break) — and guarded doors
559    /// are a guarantee where a frontend's suppressed keyboard is a hope. A
560    /// gated door reports exactly like a rolled-back splice, a path every
561    /// caller already handles. `a_read_only_document_refuses_every_door` is
562    /// the list; a new `self.editor.insert_*` call belongs on it.
563    read_only: bool,
564    /// The host-painted ranges, kept sorted by start — see [`Highlight`].
565    /// State like the selection rather than like the text: no edit history,
566    /// no dirty bit, redrawn from whatever the host last set.
567    highlights: Vec<Highlight>,
568    /// How much of the source markup the rich view exposes — a frontend preference (see
569    /// [`MarkupMode`]). Its two axes are read apart: the rendering one by
570    /// [`reveal_line`](Self::reveal_line), the editing one by
571    /// [`insert`](Self::insert).
572    markup_mode: MarkupMode,
573    /// Whether soft breaks fold into the reflowed paragraph or render where
574    /// they were written (see [`LineFlow`]) — an independent frontend
575    /// preference the WYSIWYG builder consults when it lays out a block.
576    line_flow: LineFlow,
577    /// The kind of the last edit, for coalescing: twig owns the undo *history*
578    /// (see `undo`/`redo`), but "what counts as one undo step" is a frontend-UX
579    /// call, so leaf decides when a run continues and tells twig to coalesce.
580    last_edit_kind: Option<EditKind>,
581    /// The inline marks the user has toggled *at a collapsed caret* with no
582    /// selection — "start typing bold here". Held as the XOR delta from the marks
583    /// already in force at [`pending_at`](Self::pending_at): a set bit means
584    /// "flip this kind for the next typed text", so it both turns a mark on where
585    /// none is (type into bold) and off where one already covers the caret (type
586    /// past the bold you're standing in). [`Doc::insert`] realises it onto the
587    /// freshly typed text and then clears it — a mark once realised is carried by
588    /// the caret sitting inside the run, not by this delta.
589    pending_marks: InlineMarks,
590    /// The caret offset [`pending_marks`](Self::pending_marks) applies to. The
591    /// delta is live only while the caret still stands here with no selection;
592    /// any motion or edit ([`move_to`](Self::move_to), a splice, a click) drops
593    /// it, so a toggled-but-never-typed format doesn't leak onto text elsewhere.
594    pending_at: Option<usize>,
595    /// The source as of the last open/save — `dirty` is `source != clean_source`,
596    /// so undoing back to the saved state correctly clears the modified flag.
597    clean_source: String,
598    /// A hash of the bytes leaf last read from `path` or wrote to it; `None`
599    /// while the document has no file behind it. [`Doc::disk_state`] compares
600    /// the file against this to catch an edit made *outside* leaf before a save
601    /// silently overwrites it — `clean_source` only knows what leaf itself did.
602    ///
603    /// A hash, not an mtime: mtime is the cheap answer and the wrong one — two
604    /// writes inside one filesystem timestamp tick are indistinguishable, a
605    /// clock that steps backwards (or a writer that restores an mtime) hides a
606    /// real change, and a `touch` invents one. The whole point of the watermark
607    /// is to not clobber someone's work, so it reads the bytes and compares what
608    /// is actually there. That costs a file read per question, which is why the
609    /// question is asked on a user event (focus, save) and not every frame.
610    disk_hash: Option<u64>,
611    /// The "sticky" display column vertical motion aims for, in the active
612    /// view's grid. Set on the first `move_up`/`move_down` of a run and
613    /// reused by every subsequent one in that run, so passing through a
614    /// shorter line doesn't permanently forget the original column. Any
615    /// horizontal motion or edit clears it.
616    ///
617    /// A column, not a character index: dropping down a line of `你好` onto one
618    /// of ASCII has to land under the glyph the caret was drawn beneath, which
619    /// is the only thing the user can see to aim by. Where the goal falls inside
620    /// a wide character on the target line, the mapping resolves it to that
621    /// character — the caret lands on it rather than between its cells.
622    goal_col: Option<usize>,
623    /// The rendered map for the WYSIWYG view; empty in the source view. Movement
624    /// and clicks read it to stay in visible space.
625    pub vmap: VisualMap,
626    /// The syntax map for the source view; empty in the WYSIWYG view, which
627    /// styles resolved glyphs instead. Built by [`Doc::build_source`] — a
628    /// frontend that never calls it paints raw source unstyled, which is what
629    /// every frontend did before this map existed.
630    pub smap: SourceMap,
631    /// The revision `smap` was built from, or `None` before the first build.
632    /// The map is a pure function of the text alone — no width, no caret, no
633    /// reveal line — so unlike [`vmap_key`](Self::vmap_key) the revision is the
634    /// whole key.
635    smap_key: Option<u64>,
636    /// Everything the map is built from, as one number: bumped whenever the
637    /// document's text changes, and never by a motion, a selection, or a save.
638    /// A frontend can hold work against it — see [`Doc::revision`].
639    revision: u64,
640    /// How many history steps stand behind the caret, and how many ahead of
641    /// it — the answer to a native Edit menu's "may Undo be enabled?", which
642    /// twig's history does not ask itself. Counted at [`refresh`](Self::refresh),
643    /// the funnel every edit comes through, and moved back and forth by
644    /// [`undo`](Self::undo)/[`redo`](Self::redo). An upper bound rather than
645    /// an exact depth: a coalesced run of typing is one of twig's steps but
646    /// several of these, and twig's own cap on history is not mirrored here.
647    /// Neither error can make `can_undo` false while a step remains, which is
648    /// the only property a menu needs; the one place the bound can be wrong the
649    /// other way — the cap has retired every step — is reconciled the moment
650    /// twig reports nothing to undo.
651    undo_steps: usize,
652    redo_steps: usize,
653    /// What `vmap` was built from, or `None` before the first build. The map is
654    /// a pure function of `(revision, wrap, reveal line)`, so when those haven't
655    /// moved, rebuilding it produces the identical map — see
656    /// [`Doc::build_visual`].
657    ///
658    /// The reveal line ([`Doc::reveal_line`]) is the caret's, and is `None` in
659    /// every mode but [`MarkupMode::Full`] — so outside that mode the key is
660    /// text and width alone, and a caret motion still rebuilds nothing.
661    vmap_key: Option<(u64, Option<usize>, Option<Range<usize>>)>,
662    /// Which `Doc` this is, distinct from every other one built in this
663    /// process. Folded into [`VisualKey`] so that a map stashed by a frontend
664    /// can never be mistaken for another document's — see
665    /// [`Doc::visual_key`]. Nothing else reads it.
666    identity: u64,
667    /// Per-block row cache backing the incremental rebuild: when the text
668    /// changes, only the top-level blocks whose bytes moved are re-rendered and
669    /// the rest are reused shifted (see [`wysiwyg::BlockCache`]). Persists across
670    /// builds; a pure accelerator, so it's never read for correctness.
671    block_cache: wysiwyg::BlockCache,
672    /// How many visual rows each block image reserves, keyed by its destination —
673    /// set by the frontend through [`Doc::set_media_rows`] once it has decoded and
674    /// measured the pictures. Core does no image I/O, so this is the only way it
675    /// learns a picture's height; a destination not in the map reserves the bare
676    /// one-row placeholder. Threaded into the builder so [`wysiwyg::build_cached`]
677    /// sizes each placeholder, and folded into `vmap_key` so a height change
678    /// rebuilds the map.
679    media_rows: HashMap<String, usize>,
680
681    // View geometry the renderer stamps each frame, so mouse events can map a
682    // screen cell back to a byte offset.
683    pub scroll: usize,
684    pub body_origin: (u16, u16),
685    /// Width of the body rectangle last painted by the frontend. Zero means
686    /// unknown (used by tests or a frontend that has not drawn yet).
687    pub body_width: u16,
688    pub body_height: u16,
689    /// The caret as of the last frame drawn, or `None` before the first.
690    ///
691    /// Scrolling is the viewport's business, not the caret's: the view follows
692    /// the caret when the caret *moves*, but a wheel that doesn't touch the
693    /// caret has to be free to scroll away from it — otherwise the view is
694    /// pinned to the caret and stops dead at the edge of the document you can
695    /// see. Comparing against this is what tells the two apart, and it catches a
696    /// caret set by any route, including a frontend assigning the field itself.
697    pub drawn_caret: Option<usize>,
698}
699
700/// The Markdown extensions every leaf document is parsed with — four of them,
701/// each departing from twig's defaults for a reason leaf can state.
702///
703/// `html_elements` promotes embedded raw HTML (`<img>`, `<picture>`,
704/// `<source>`, …) into semantic AST nodes, so a picture becomes a real `image`
705/// node the frontends can frame and rasterize instead of opaque `raw_block`
706/// text. `directives` turns on generic `:::name{.class}` fenced-div containers
707/// (`directive` nodes), which a host app uses for its own semantics (diaryx's
708/// `:::vis{.audience}` visibility blocks) — core renders any directive as a
709/// plain tinted container, agnostic of `name`.
710///
711/// `highlight` and `highlight_colors` are the pair that makes Markdown read
712/// `==text==` as a `mark` node, and `==🔴 text==` as one carrying a
713/// `data-color`. leaf already had somewhere to put both: the
714/// [`Mark`](crate::Role::Mark) role and the ⌘⇧M highlight button predate them,
715/// and until twig 3.3 a Markdown document could only ever *receive* a highlight
716/// from a Djot one it was converted from — the button wrote `==…==` and the
717/// reparse read it straight back as text.
718/// They are on together because a colour is inert without the highlight itself,
719/// and a document that writes `==🔴 x==` means the colour by it.
720///
721/// Every flag is inert for non-Markdown formats, so it's safe to pass them
722/// unconditionally. Threading this through every constructor (not just `open`)
723/// keeps `from_source`, `blank`, and `reload` parsing the same document the same
724/// way — twig reparses with these same flags after each edit.
725pub(crate) fn parse_extensions() -> MarkdownExtensions {
726    MarkdownExtensions {
727        html_elements: true,
728        directives: true,
729        highlight: true,
730        highlight_colors: true,
731        ..Default::default()
732    }
733}
734
735/// Build an editor over `bytes` in `format` with leaf's [`parse_extensions`],
736/// mapping twig's error into the `anyhow` context every constructor shares.
737fn new_editor(bytes: &[u8], format: Format) -> Result<Editor> {
738    Editor::new_ext(bytes, format, parse_extensions()).map_err(|e| anyhow!("twig parse: {e}"))
739}
740
741/// Does `format` spell a table as a **pipe table** — the one grid twig's table
742/// editor knows how to emit?
743///
744/// This is the single capability leaf still has to answer for itself, and the
745/// only hand-maintained format list left in this file. Every other gesture is
746/// [`Format::supports`], which is twig's own answer read across the C ABI — but
747/// twig deliberately leaves the table ops out of that query, because they read
748/// no `Syntax` table at all. They rewrite a grid that is already in the source
749/// and refuse on *position*, never on format. Handed a caret inside an HTML
750/// `<table>`, `table_insert_row` therefore re-emits the whole element as
751/// `| a | b |` and reports success — a real splice, a clean reparse, an honest
752/// `dirty` flag, and nothing downstream able to tell it from a good edit.
753///
754/// So the list is narrow on purpose. `Format` is `#[non_exhaustive]`, and the
755/// wildcard answers "no" for a format leaf has never heard of: a new twig
756/// language that *does* spell pipe tables loses its grid controls until this
757/// line is updated, which shows up as a missing button. The other default hands
758/// it to [`Doc::table_op`], which rewrites documents it cannot spell.
759fn spells_pipe_tables(format: Format) -> bool {
760    matches!(format, Format::Markdown | Format::Djot)
761}
762
763/// Which of leaf's authoring controls this document's format can actually
764/// spell — one flag per toolbar button, resolved once so a frontend can build
765/// its chrome instead of discovering each refusal on a click.
766///
767/// Every field but [`table`](Self::table) is `Format::supports_with` on the
768/// gesture the matching [`Doc`] method calls, so this record cannot drift from
769/// what the ops do; `table` is [`spells_pipe_tables`], the one answer twig
770/// doesn't export.
771///
772/// `supports_with` rather than `supports` because two of these are facts about
773/// the *parse options* as much as about the format. `Format::supports` answers
774/// for twig's defaults, and leaf never parses with those — it parses with
775/// [`parse_extensions`], and a document's toolbar has to describe the document
776/// it is over. A Markdown editor holding `highlight` authors `==text==`; one
777/// without it would mint bytes its own reparse hands back as plain text, which
778/// is why twig asks before it writes.
779///
780/// **The formats are ragged, and that is the point.** A single per-document
781/// boolean was enough while the two authorable formats were Markdown and djot
782/// and everything else spelled nothing. HTML is neither: it writes seven of the
783/// eight inline marks as a tag pair, plus `<code>`, `<hr>` and an in-cell
784/// `<br>`, and spells no heading marker, no line prefix, no fence, no task box,
785/// no link — because its versions of those have a different *shape*, not a
786/// different alphabet. So ⌘B works in an HTML document and ⌘1 does not, and no
787/// one flag can say that. Markdown and djot differ from each other too:
788/// `^superscript^` is djot-only, and an in-cell `<br>` is Markdown-only.
789#[derive(Clone, Copy, Debug, Eq, PartialEq)]
790pub struct Capabilities {
791    /// ⌘B — `InlineKind::Strong`.
792    pub bold: bool,
793    /// ⌘I — `InlineKind::Emph`.
794    pub italic: bool,
795    /// Inline code — `InlineKind::Verbatim`.
796    pub code: bool,
797    /// Highlight — `InlineKind::Mark`. Djot spells it, and so does Markdown
798    /// under the `highlight` extension [`parse_extensions`] turns on: the
799    /// button writes `==text==`, which is what the reparse reads back.
800    pub mark: bool,
801    /// ⌘U — `InlineKind::Insert`, which every format that marks at all spells.
802    pub underline: bool,
803    /// Strikethrough — `InlineKind::Delete`. Markdown spells GFM's `~~text~~`
804    /// out of the box, since twig parses it out of the box.
805    pub strike: bool,
806    /// The highlight *palette* — [`Doc::set_mark_color`]. Narrower than
807    /// [`mark`](Self::mark) and deliberately its own flag: Markdown spells a
808    /// colour on a highlight (`==🔴 text==`) and djot spells only the highlight,
809    /// so a toolbar offering the swatches wherever the button lights would offer
810    /// them in a document that cannot write one. Pair with
811    /// [`Doc::caret_in_mark`], which asks the other question — the palette needs
812    /// a highlight to colour as much as a format that spells one.
813    pub mark_color: bool,
814    pub superscript: bool,
815    pub subscript: bool,
816    /// Heading levels and "make this a paragraph" — [`Doc::set_block`].
817    pub heading: bool,
818    pub blockquote: bool,
819    pub bullet_list: bool,
820    pub ordered_list: bool,
821    /// The checkbox controls: giving an item a box, and ticking one.
822    pub task: bool,
823    pub link: bool,
824    /// Covers [`Doc::insert_media`] too — see the note there on why the three
825    /// media kinds stand or fall together.
826    pub image: bool,
827    /// The horizontal-rule button. HTML spells this one (`<hr>`).
828    pub thematic_break: bool,
829    /// The footnote button — [`Doc::insert_footnote`]. Markdown and djot spell
830    /// the pair; HTML has no footnote of its own, so the button goes away rather
831    /// than writing brackets that would render as brackets.
832    pub footnote: bool,
833    /// Setting a fenced block's language — a control only ever offered with the
834    /// caret already in a fence.
835    pub code_language: bool,
836    /// The grid controls: insert/delete/move a row or column, set a column's
837    /// alignment. Pair with [`Doc::caret_in_table`], which asks the other
838    /// question — an HTML `<table>` holds the caret and still can't be edited.
839    pub table: bool,
840    /// Shift+Return inside a cell. Markdown and HTML spell it; djot has no
841    /// idiomatic in-cell break.
842    pub cell_line_break: bool,
843}
844
845impl Capabilities {
846    /// Resolve every flag for `format`, as leaf parses it. Pure and cheap —
847    /// twig computes each from a static table — but a frontend that wants to
848    /// hold them can.
849    ///
850    /// The extensions are not a parameter because they are not a choice a
851    /// caller makes: every leaf document is parsed with [`parse_extensions`],
852    /// so the format is the whole of what varies.
853    pub fn of(format: Format) -> Self {
854        let exts = parse_extensions();
855        let supports = |g| format.supports_with(exts, g);
856        let inline = |k| supports(Gesture::ToggleInline(k));
857        let container = |k| supports(Gesture::ToggleBlockContainer(k));
858        Self {
859            bold: inline(InlineKind::Strong),
860            italic: inline(InlineKind::Emph),
861            code: inline(InlineKind::Verbatim),
862            mark: inline(InlineKind::Mark),
863            underline: inline(InlineKind::Insert),
864            strike: inline(InlineKind::Delete),
865            mark_color: supports(Gesture::SetMarkColor),
866            superscript: inline(InlineKind::Superscript),
867            subscript: inline(InlineKind::Subscript),
868            heading: supports(Gesture::SetBlock),
869            blockquote: container(BlockContainerKind::BlockQuote),
870            bullet_list: container(BlockContainerKind::BulletList),
871            ordered_list: container(BlockContainerKind::OrderedList),
872            // Both halves of the checkbox story, and leaf offers no control that
873            // needs only one: the item gesture mints the box, the checked one
874            // ticks it, and a format spelling a `task_marker` spells both.
875            task: supports(Gesture::ToggleTaskItem) && supports(Gesture::ToggleTaskChecked),
876            link: supports(Gesture::InsertLink),
877            image: supports(Gesture::InsertImage),
878            thematic_break: supports(Gesture::InsertThematicBreak),
879            footnote: supports(Gesture::InsertFootnote),
880            code_language: supports(Gesture::SetCodeLanguage),
881            table: spells_pipe_tables(format),
882            cell_line_break: supports(Gesture::InsertLineBreak),
883        }
884    }
885}
886
887/// The source of [`Doc::identity`], one per document ever built.
888static NEXT_IDENTITY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
889
890impl Doc {
891    #[cfg(feature = "fs")]
892    pub fn open(path: PathBuf) -> Result<Self> {
893        let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
894        Self::from_disk_bytes(path, bytes)
895    }
896
897    /// An empty document *named* `path`, for a file that isn't there yet — what
898    /// every other terminal editor gives you when you name a file that doesn't
899    /// exist. It is a real named document, not a [`Doc::blank`]: `is_untitled`
900    /// is false, so ⌘S writes straight to `path` with no Save As detour, and
901    /// the header shows the name the user asked for.
902    ///
903    /// The format comes from the extension, exactly as [`Doc::open`] reads it —
904    /// so `leaf notes.dj` starts a djot buffer rather than the Markdown
905    /// [`Doc::blank`] has to assume for want of a name. An extension leaf can't
906    /// parse is still an error: a mistyped flag or a stray argument should say
907    /// so, not open a buffer promising to save somewhere.
908    ///
909    /// The watermark is the hash of *no bytes*, not `None`, and that is the
910    /// whole trick: `None` means untitled, and would leave [`Doc::disk_state`]
911    /// answering [`DiskState::Untitled`] for a document that has a path and
912    /// intends to write to it. Hashing `""` instead makes the answers the true
913    /// ones — [`DiskState::Missing`] while the file still isn't there (a save
914    /// recreates it, which is exactly what this is for), and
915    /// [`DiskState::Changed`] if somebody creates it underneath us between
916    /// launch and save, so the frontend's overwrite prompt guards a new file as
917    /// it guards an opened one.
918    ///
919    /// Nothing is written here. A buffer that is never typed into never touches
920    /// the filesystem, and a `path` whose directory doesn't exist is allowed to
921    /// open — the write is where that fails, and it says so then.
922    #[cfg(feature = "fs")]
923    pub fn create(path: PathBuf) -> Result<Self> {
924        Self::from_disk_bytes(path, Vec::new())
925    }
926
927    /// [`Doc::open`] when the file is there, [`Doc::create`] when it isn't —
928    /// the call a CLI frontend wants for its path argument.
929    ///
930    /// The decision is made from the failed read itself rather than a `exists()`
931    /// check first, so there is no window between the two for the file to appear
932    /// or vanish in. Only `NotFound` opens a new buffer: a permissions error or
933    /// a directory in the way is still an error, because pretending those are
934    /// "no file yet" would offer to save over something leaf couldn't read.
935    #[cfg(feature = "fs")]
936    pub fn open_or_create(path: PathBuf) -> Result<Self> {
937        match std::fs::read(&path) {
938            Ok(bytes) => Self::from_disk_bytes(path, bytes),
939            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::create(path),
940            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
941        }
942    }
943
944    /// The shared body of [`Doc::open`] and [`Doc::create`]: bytes that are (or
945    /// stand in for) the file at `path`, parsed as the format its extension
946    /// names. Keeping the two on one path is what makes a new file's document
947    /// identical in every respect to an opened one but its contents.
948    #[cfg(feature = "fs")]
949    fn from_disk_bytes(path: PathBuf, bytes: Vec<u8>) -> Result<Self> {
950        let format = detect_format(&path)?;
951        let editor = new_editor(&bytes, format)?;
952        let source = String::from_utf8(bytes).map_err(|_| anyhow!("document is not UTF-8"))?;
953        let disk_hash = Some(hash_bytes(source.as_bytes()));
954        // Store the document's *absolute* path. A relative one (`leaf README.md`)
955        // has an empty parent, so a frontend can't resolve a relative image
956        // destination (`![](pic.png)`) against the document's directory and the
957        // picture silently falls back to its text placeholder. `absolute` is
958        // purely lexical — it prefixes the current directory and normalizes, but
959        // reads nothing and resolves no symlinks — so `file_name` and save are
960        // unchanged; it only gives `path.parent()` something to join against.
961        let path = std::path::absolute(&path).unwrap_or(path);
962        Ok(Doc::from_parts(editor, format, path, source, disk_hash))
963    }
964
965    /// Build a document from an in-memory string, the format named explicitly —
966    /// the portable, filesystem-free counterpart to [`Doc::open`] (which reads a
967    /// path and sniffs the format from its extension). A wasm or FFI host, which
968    /// has no path to read, uses this: it hands over bytes it fetched however it
969    /// could, and later persists [`Doc::source`] however it can (a browser
970    /// download, `localStorage`, a backend `PUT`) and calls [`Doc::mark_saved`].
971    ///
972    /// No file backs the result, so it starts untitled ([`Doc::is_untitled`] is
973    /// true) exactly like a [`Doc::blank`] that has been given content.
974    pub fn from_source(source: String, format: Format) -> Result<Self> {
975        let editor = new_editor(source.as_bytes(), format)?;
976        Ok(Doc::from_parts(
977            editor,
978            format,
979            PathBuf::new(),
980            source,
981            None,
982        ))
983    }
984
985    /// An untitled, empty document — the `+` button and a `leaf` launched with
986    /// no file argument. Nothing on disk backs it until a [`Doc::save_as`].
987    ///
988    /// It is Markdown, because a format has to be chosen before a name exists to
989    /// read one from: `detect_format` reads the extension and an untitled
990    /// document has neither. Markdown is what leaf's own files are, what its
991    /// block markers are already written for (`insert_block_prefix`), and the
992    /// extension a Save As will overwhelmingly pick — a wrong guess here would
993    /// mean typing djot into a buffer parsing it as Markdown. Note that Save As
994    /// *doesn't* revisit this: see [`Doc::save_as`].
995    pub fn blank() -> Result<Self> {
996        let format = Format::Markdown;
997        let editor = new_editor(b"", format)?;
998        // An empty `path` is the untitled marker (`path` is a public `PathBuf`
999        // field two frontends already read; making it an `Option` to say this
1000        // would break both). `is_untitled` is the question to ask, not the
1001        // representation to copy.
1002        Ok(Doc::from_parts(
1003            editor,
1004            format,
1005            PathBuf::new(),
1006            String::new(),
1007            None,
1008        ))
1009    }
1010
1011    /// The fields every constructor agrees on, so `open` and `blank` can't drift
1012    /// apart in the ones neither of them has an opinion about.
1013    // `identity` is taken from a counter rather than from the `Doc`'s address,
1014    // which moves — a session that holds one is moved into and out of
1015    // containers freely, and an identity that changed with it would defeat the
1016    // one comparison it exists for.
1017    fn from_parts(
1018        editor: Editor,
1019        format: Format,
1020        path: PathBuf,
1021        source: String,
1022        disk_hash: Option<u64>,
1023    ) -> Self {
1024        Doc {
1025            editor,
1026            format,
1027            path,
1028            disk_hash,
1029            clean_source: source.clone(),
1030            source,
1031            caret: 0,
1032            anchor: None,
1033            dirty: false,
1034            status: None,
1035            read_only: false,
1036            highlights: Vec::new(),
1037            // leaf opens in the rich-text (WYSIWYG) view by default — the
1038            // markup-resolved surface is leaf's differentiator. Frontends can
1039            // still start in source view explicitly (e.g. a CLI flag), and ⌘e/⌥w
1040            // toggles at runtime.
1041            view: View::Wysiwyg,
1042            // `None` by default — the clean surface Diaryx ships, with typed
1043            // syntax kept literal; a markup-fluent frontend can climb the
1044            // ladder to `Shortcuts` or `Full`.
1045            markup_mode: MarkupMode::default(),
1046            // Fold by default — flowing prose that reflows to the viewport, the
1047            // behaviour every frontend had before this preference existed.
1048            line_flow: LineFlow::default(),
1049            last_edit_kind: None,
1050            pending_marks: InlineMarks::empty(),
1051            pending_at: None,
1052            goal_col: None,
1053            vmap: VisualMap::default(),
1054            smap: SourceMap::default(),
1055            // No map yet — the first `build_source` always builds.
1056            smap_key: None,
1057            revision: 0,
1058            undo_steps: 0,
1059            redo_steps: 0,
1060            // No map yet — the first `build_visual` always builds.
1061            vmap_key: None,
1062            identity: NEXT_IDENTITY.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
1063            block_cache: wysiwyg::BlockCache::default(),
1064            media_rows: HashMap::new(),
1065            scroll: 0,
1066            body_origin: (0, 0),
1067            body_width: 0,
1068            body_height: 0,
1069            drawn_caret: None,
1070        }
1071    }
1072
1073    /// Whether this document has no file behind it yet — a [`Doc::blank`] that
1074    /// has never been saved. The question a ⌘S handler asks to know it should
1075    /// open a Save As picker instead ([`Doc::save`] won't guess a name), and the
1076    /// header asks to know the name it shows is a placeholder.
1077    pub fn is_untitled(&self) -> bool {
1078        self.path.as_os_str().is_empty()
1079    }
1080
1081    pub fn toggle_view(&mut self) {
1082        self.view = match self.view {
1083            View::Source => View::Wysiwyg,
1084            View::Wysiwyg => View::Source,
1085        };
1086        self.scroll = 0;
1087        self.status = None;
1088        // Entering WYSIWYG, the caret may be sitting in now-hidden frontmatter;
1089        // lift it to the first rendered offset.
1090        self.clamp_caret();
1091    }
1092
1093    /// The current markup-exposure preference (see [`MarkupMode`]).
1094    pub fn markup_mode(&self) -> MarkupMode {
1095        self.markup_mode
1096    }
1097
1098    /// Set the markup-exposure preference. Both of its axes take effect at
1099    /// once: the editing one on the next [`insert`](Self::insert), and the
1100    /// rendering one on the next build — which is why this drops the cached
1101    /// visual map and the per-block render cache, exactly as
1102    /// [`set_line_flow`](Self::set_line_flow) does.
1103    pub fn set_markup_mode(&mut self, mode: MarkupMode) {
1104        if self.markup_mode == mode {
1105            return;
1106        }
1107        self.markup_mode = mode;
1108        // Neither cache is keyed on the mode, and moving between `Full` and the
1109        // hidden modes changes every row the caret's line renders to — so
1110        // invalidate both explicitly.
1111        self.vmap_key = None;
1112        self.block_cache = wysiwyg::BlockCache::default();
1113    }
1114
1115    /// The source byte range of the line the caret sits on, when that line
1116    /// should render its raw delimiters — `None` in every mode and view that
1117    /// hides them, which is what the builder reads as "reveal nothing".
1118    ///
1119    /// A *source* line (newline to newline), not a visual row: a wrapped
1120    /// paragraph and a `LineFlow::Preserve` soft break both split one source
1121    /// line across several rows, and revealing half a delimiter pair because the
1122    /// other half wrapped would be worse than revealing neither. The range
1123    /// excludes the terminating newline and is empty-but-present on a blank
1124    /// line, which reveals nothing but still keys the caches correctly.
1125    ///
1126    /// Only in [`View::Wysiwyg`]: source view already shows every byte, so
1127    /// there is nothing there to reveal.
1128    pub(crate) fn reveal_line(&self) -> Option<Range<usize>> {
1129        if !self.markup_mode.reveals_caret_line() || self.view != View::Wysiwyg {
1130            return None;
1131        }
1132        Some(source_line_range(&self.source, self.caret))
1133    }
1134
1135    /// The current soft-break flow preference (see [`LineFlow`]).
1136    pub fn line_flow(&self) -> LineFlow {
1137        self.line_flow
1138    }
1139
1140    /// Set the soft-break flow preference. The mode changes how every block lays
1141    /// out, so a change drops the cached visual map and the per-block render
1142    /// cache, forcing the next [`build_visual`] to rebuild under the new flow.
1143    ///
1144    /// [`build_visual`]: Self::build_visual
1145    pub fn set_line_flow(&mut self, mode: LineFlow) {
1146        if self.line_flow == mode {
1147            return;
1148        }
1149        self.line_flow = mode;
1150        // Both caches are keyed on `(revision, wrap)`, neither of which moved —
1151        // so invalidate them explicitly, or the next build would reuse rows laid
1152        // out under the old flow.
1153        self.vmap_key = None;
1154        self.block_cache = wysiwyg::BlockCache::default();
1155    }
1156
1157    pub fn view_name(&self) -> &'static str {
1158        match self.view {
1159            View::Source => "source",
1160            View::Wysiwyg => "wysiwyg",
1161        }
1162    }
1163
1164    /// Rebuild the WYSIWYG visual map for the current tree at `width` columns
1165    /// (called by the renderer each frame it's in the WYSIWYG view).
1166    /// Build the WYSIWYG map, wrapped at `width` display columns.
1167    ///
1168    /// Cheap to call every frame, which is what both frontends do: the map is a
1169    /// pure function of the document and the wrap width, so a call that would
1170    /// rebuild the same map returns the one already built. Only an edit (or a
1171    /// resize) pays.
1172    ///
1173    /// That isn't a micro-optimisation. A frontend repaints for reasons that have
1174    /// nothing to do with the text — a blinking caret, a scroll, a focus change —
1175    /// and rebuilding here is O(document): 23 ms on a 1 MB file, of which 5 ms is
1176    /// marshalling twig's AST across the C ABI. Paid twice a second by the GUI's
1177    /// blink timer, that was 14% of a core spent redrawing an unchanged document.
1178    /// (`cargo run --release -p leaf-core --example bench` for the numbers.)
1179    pub fn build_visual(&mut self, width: usize) {
1180        self.build_map(Some(width));
1181    }
1182
1183    /// Build the WYSIWYG map with each block as a single unwrapped row — for a
1184    /// frontend (the GUI) that wraps at its own proportional pixel width rather
1185    /// than a fixed character column.
1186    pub fn build_visual_unwrapped(&mut self) {
1187        self.build_map(None);
1188    }
1189
1190    /// Build the source view's syntax map ([`Doc::smap`]) — the styling for
1191    /// [`View::Source`], the way [`build_visual`](Self::build_visual) is the
1192    /// styling for [`View::Wysiwyg`].
1193    ///
1194    /// A frontend calls this before painting raw source. One that doesn't gets
1195    /// an empty map and paints unstyled text, so this is additive: nothing
1196    /// breaks by not calling it.
1197    ///
1198    /// Built at most once per revision, and the revision is the whole key — the
1199    /// map has no width and no caret in it, so it survives every resize, every
1200    /// motion, and every selection change.
1201    ///
1202    /// The builds it does do cost a whole-arena marshal, which is precisely what
1203    /// the WYSIWYG path works to avoid, so this has no incremental path where
1204    /// that one has two. From `cargo run --release -p leaf-core --example
1205    /// bench`, per keystroke, against the WYSIWYG build the source view is
1206    /// *not* doing:
1207    ///
1208    /// |  size |  nodes | marshal | `source::build` | (`wysiwyg::build`) |
1209    /// |------:|-------:|--------:|----------------:|-------------------:|
1210    /// |  10 KB|    613 |  0.16 ms|         0.07 ms |            0.28 ms |
1211    /// | 100 KB|  6 097 |  0.84 ms|         0.38 ms |            2.43 ms |
1212    /// |   1 MB| 60 601 |  5.67 ms|         3.12 ms |           23.39 ms |
1213    ///
1214    /// Linear, two thirds of it the marshal, and the build itself five to seven
1215    /// times cheaper than the one it stands in for at every size. Comfortable
1216    /// well past any document a person edits in a terminal — a megabyte is where
1217    /// it would want [`Editor::dirty_range`] and the same splice treatment
1218    /// `build_spliced` gives the other map. The door is open; nothing has needed
1219    /// it yet.
1220    pub fn build_source(&mut self) {
1221        if self.smap_key == Some(self.revision) {
1222            return;
1223        }
1224        let nodes = self.nodes();
1225        self.smap = source::build(&nodes, &self.source);
1226        self.smap_key = Some(self.revision);
1227    }
1228
1229    /// Tell the model how many visual rows each block image should reserve, keyed
1230    /// by the image's destination. A terminal frontend calls this once it has
1231    /// decoded and measured its pictures — core does no image I/O, so this is the
1232    /// only way it learns a height — and the next [`Doc::build_visual`] lays each
1233    /// placeholder out that tall (the label row plus blank filler rows the
1234    /// frontend paints the raster over). A destination left out of the map falls
1235    /// back to the bare one-row placeholder, which is also what a frontend that
1236    /// can't draw pictures (or lays them out in its own units, like the GUI) gets
1237    /// by never calling this.
1238    ///
1239    /// Cheap to call every frame with the same map: only a *change* invalidates
1240    /// the built map (and the block-row cache, since a height isn't part of a
1241    /// block's bytes and so wouldn't otherwise re-render it). Steady state is a
1242    /// no-op, so a frontend can just hand over its current measurements each frame.
1243    pub fn set_media_rows(&mut self, rows: HashMap<String, usize>) {
1244        if self.media_rows == rows {
1245            return;
1246        }
1247        self.media_rows = rows;
1248        // A height lives outside the block's source bytes, so the content-keyed
1249        // block cache would hand back the old-height rows on a hit. Drop it (and
1250        // the splice layout it carries) so the next build re-renders every block
1251        // at the new heights, and force that build by clearing the map key.
1252        self.block_cache = wysiwyg::BlockCache::default();
1253        self.vmap_key = None;
1254    }
1255
1256    /// The revision the document's text is at — bumped by every edit, undo,
1257    /// redo, and reload, and by nothing else. A frontend caches against this to
1258    /// tell a repaint that needs new work from one that doesn't.
1259    ///
1260    /// It counts *edits*, not distinct texts: typing `x` and deleting it again
1261    /// lands on the same text two revisions later. Work is only ever rebuilt
1262    /// needlessly, never wrongly reused.
1263    pub fn revision(&self) -> u64 {
1264        self.revision
1265    }
1266
1267    /// The identity of the map presently in [`vmap`](Self::vmap) — what the last
1268    /// [`build_visual`](Self::build_visual) built it from, or the identity of an
1269    /// unbuilt map before the first one.
1270    ///
1271    /// This is *not* [`revision`](Self::revision). The revision says where the
1272    /// text is; this says where the map is, and the two part company the moment
1273    /// an edit lands, until something rebuilds. A frontend that keeps its own
1274    /// copy of the map — leaf-ratatui stashes core's before splicing filler rows
1275    /// under an oversized heading — compares this against the value it held when
1276    /// it took the copy, and learns whether `vmap` is still the map it stashed
1277    /// or one somebody else has since rebuilt. Restoring a copy over a newer
1278    /// map would paint a stale document; restoring nothing hands core's
1279    /// incremental rebuild a map it never built.
1280    ///
1281    /// "Somebody else" includes another document. The key names the `Doc`
1282    /// as well as the build, so a frontend that draws two documents through
1283    /// one stash — a host with several buffers, or one that opens the next
1284    /// document where the last one stood — never has the copy it took of one
1285    /// accepted by the other, however alike their builds are.
1286    pub fn visual_key(&self) -> VisualKey {
1287        VisualKey(self.identity, self.vmap_key.clone())
1288    }
1289
1290    /// The map, built at most once per `(revision, wrap)`. `clamp_caret` still
1291    /// runs on every call: the caret moves without the document changing, and
1292    /// keeping it on a legal stop is this function's job either way.
1293    fn build_map(&mut self, wrap: Option<usize>) {
1294        // Under `MarkupMode::Full` the map is a function of the caret's *line*
1295        // as well as the text, so the line joins the key: moving within a line
1296        // still reuses the map, and crossing into another one rebuilds it. In
1297        // every other mode `reveal_line` is `None` and the key is what it was,
1298        // so caret motion goes on costing nothing.
1299        let reveal = self.reveal_line();
1300        let key = (self.revision, wrap, reveal.clone());
1301        if self.vmap_key.as_ref() != Some(&key) {
1302            // Enumerate the top-level blocks cheaply — no whole-arena marshal.
1303            // A subtree is pulled only for the block(s) that actually changed, so
1304            // the FFI marshal shrinks from O(document) to O(edited block).
1305            let top = self.top_blocks();
1306
1307            // Fast path: when twig reports a dirty byte range, try to patch the
1308            // previous map in place — a single-block edit moves the prefix,
1309            // shifts the suffix, and re-renders only one block. `build_spliced`
1310            // returns `None` (and we fall back to the always-correct full rebuild)
1311            // whenever the edit reshaped the block structure, hit a table, or
1312            // there's no previous map to patch.
1313            // Preserve soft breaks as written when the flow preference asks for
1314            // it — the builder renders each as its own visual row instead of
1315            // folding it into the reflowed paragraph.
1316            let preserve_soft = self.line_flow == LineFlow::Preserve;
1317            let spliced = match self.editor.dirty_range() {
1318                Some(dirty) => {
1319                    let prev = std::mem::take(&mut self.vmap);
1320                    let source = &self.source;
1321                    let cache = &mut self.block_cache;
1322                    let media_rows = &self.media_rows;
1323                    let editor = &mut self.editor;
1324                    wysiwyg::build_spliced(
1325                        prev,
1326                        source,
1327                        wrap,
1328                        preserve_soft,
1329                        &top,
1330                        dirty,
1331                        media_rows,
1332                        reveal.clone(),
1333                        cache,
1334                        |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1335                    )
1336                }
1337                None => None,
1338            };
1339            self.vmap = spliced.unwrap_or_else(|| {
1340                let source = &self.source;
1341                let cache = &mut self.block_cache;
1342                let media_rows = &self.media_rows;
1343                let editor = &mut self.editor;
1344                wysiwyg::build_cached(
1345                    &top,
1346                    source,
1347                    wrap,
1348                    preserve_soft,
1349                    media_rows,
1350                    reveal,
1351                    cache,
1352                    |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1353                )
1354            });
1355            // Acknowledge the dirty range so the next edit's range starts fresh.
1356            self.editor.clear_dirty();
1357            self.vmap_key = Some(key);
1358        }
1359        self.clamp_caret();
1360    }
1361
1362    fn nodes(&mut self) -> Vec<FlatNode> {
1363        self.editor.nodes().unwrap_or_default()
1364    }
1365
1366    /// The document's top-level blocks for the incremental render. See
1367    /// [`wysiwyg::top_blocks`] for why this isn't simply `child_spans(None)`.
1368    fn top_blocks(&mut self) -> Vec<QueryMatch> {
1369        wysiwyg::top_blocks(&mut self.editor)
1370    }
1371
1372    pub fn format_name(&self) -> &'static str {
1373        // `Format` is `#[non_exhaustive]` as of twig 3.0, so the wildcard is
1374        // required. It also covers `Asciidoc`, which twig parses but cannot
1375        // serialize — leaf never opens a document in it (see `Doc::open`).
1376        match self.format {
1377            Format::Djot => "djot",
1378            Format::Markdown => "markdown",
1379            Format::Xml => "xml",
1380            Format::Html => "html",
1381            _ => "unknown",
1382        }
1383    }
1384
1385    /// Whether this document's format offers *any* door in — `false` only for a
1386    /// wholly parse-only format (XML, AsciiDoc), where every gesture refuses and
1387    /// a frontend may as well open the file read-only.
1388    ///
1389    /// This is a much weaker claim than the name suggests, and driving per-button
1390    /// state from it is exactly the mistake to avoid: HTML answers `true` because
1391    /// it spells the inline marks with a tag pair (`<strong>`, `<em>`, `<code>`)
1392    /// while a heading, a quote, a list, a task box, a link and a code fence all
1393    /// remain unspellable there. Ask [`capabilities`](Self::capabilities) — or
1394    /// [`supports`](Self::supports) — per control.
1395    pub fn authorable(&self) -> bool {
1396        self.format.is_authorable()
1397    }
1398
1399    /// Whether this document can spell `gesture`, which is twig's own answer
1400    /// rather than a copy of it: `Format::supports_with` reads the same
1401    /// `Syntax` table the `Editor` method consults before refusing, chosen by
1402    /// the very [`parse_extensions`] this document's editor reparses with — so
1403    /// what the toolbar offers and what the splice will accept are one table.
1404    ///
1405    /// It is a fact about the *document*, not about the caret. `true` does not
1406    /// promise the gesture succeeds where it is standing — a link over a table
1407    /// border still fails — only that it will not fail with
1408    /// `UnsupportedFormat`. Gray out on `false`; don't read `true` as "this
1409    /// will work here".
1410    pub fn supports(&self, gesture: Gesture) -> bool {
1411        self.format.supports_with(parse_extensions(), gesture)
1412    }
1413
1414    /// Every control's enabled state in one read — what a toolbar builds itself
1415    /// from when a document opens or its format changes. See [`Capabilities`].
1416    pub fn capabilities(&self) -> Capabilities {
1417        Capabilities::of(self.format)
1418    }
1419
1420    /// Refuse a gesture this document's format cannot spell, saying so in the
1421    /// status line. `true` means the caller must return without calling twig.
1422    ///
1423    /// Most of these refusals duplicate one twig would make anyway, and they are
1424    /// made here regardless because a message naming the *document's* format
1425    /// reads better than one naming twig's internals. Two of them are not
1426    /// duplicates and are the reason this is a guard rather than an error
1427    /// translation:
1428    ///
1429    /// - The table family (see [`table_op`](Self::table_op)) consults no
1430    ///   `Syntax` table, so twig does not refuse it at all.
1431    /// - [`toggle`](Self::toggle) at a collapsed caret never reaches twig — it
1432    ///   arms a sticky mark for text not yet typed, which is a promise `insert`
1433    ///   could not keep.
1434    fn refuse_unsupported(&mut self, what: &str, gesture: Gesture) -> bool {
1435        self.refuse_unless(what, self.supports(gesture))
1436    }
1437
1438    /// [`refuse_unsupported`](Self::refuse_unsupported) against a capability leaf
1439    /// answers itself — today only [`spells_pipe_tables`].
1440    fn refuse_unless(&mut self, what: &str, supported: bool) -> bool {
1441        if supported {
1442            return false;
1443        }
1444        self.status = Some(format!("{what}: not supported in {}", self.format_name()));
1445        true
1446    }
1447
1448    /// The name to show for this document. An untitled one has no file to name
1449    /// it, and both frontends put this straight on screen — an empty path
1450    /// renders as an empty header, so it says so instead.
1451    pub fn file_name(&self) -> String {
1452        if self.is_untitled() {
1453            return "untitled".into();
1454        }
1455        self.path
1456            .file_name()
1457            .map(|s| s.to_string_lossy().into_owned())
1458            .unwrap_or_else(|| self.path.display().to_string())
1459    }
1460
1461    /// The selection as an ordered `[start, end)` byte range, or `None` when the
1462    /// caret and anchor coincide (an empty selection is no selection).
1463    pub fn selection(&self) -> Option<(usize, usize)> {
1464        self.anchor
1465            .map(|a| (a.min(self.caret), a.max(self.caret)))
1466            .filter(|(s, e)| s != e)
1467    }
1468
1469    /// The selected text, or `None` when there's no selection — the source
1470    /// slice a copy/cut hands to the system clipboard.
1471    pub fn selected_text(&self) -> Option<&str> {
1472        self.selection().map(|(s, e)| &self.source[s..e])
1473    }
1474
1475    /// The selection as a quote with a little of what surrounds it — the shape
1476    /// a host that cites, annotates, or searches for a passage wants, cut from
1477    /// the **source** rather than from anything rendered, so the quote is
1478    /// findable in the document again by plain string search.
1479    ///
1480    /// `context` is a count of characters (not bytes) on each side, clipped at
1481    /// the document's edges; the slices land on char boundaries by
1482    /// construction. `None` when nothing is selected.
1483    pub fn selection_quote(&self, context: usize) -> Option<Quote> {
1484        let (start, end) = self.selection()?;
1485        let mut before = start;
1486        for _ in 0..context {
1487            match self.source[..before].chars().next_back() {
1488                Some(c) => before -= c.len_utf8(),
1489                None => break,
1490            }
1491        }
1492        let mut after = end;
1493        for _ in 0..context {
1494            match self.source[after..].chars().next() {
1495                Some(c) => after += c.len_utf8(),
1496                None => break,
1497            }
1498        }
1499        Some(Quote {
1500            exact: self.source[start..end].to_string(),
1501            prefix: self.source[before..start].to_string(),
1502            suffix: self.source[end..after].to_string(),
1503            start,
1504            end,
1505        })
1506    }
1507
1508    /// Whether the document refuses to change — see the field.
1509    pub fn read_only(&self) -> bool {
1510        self.read_only
1511    }
1512
1513    /// Turn the read-only gate on or off. A frontend preference like
1514    /// [`set_markup_mode`](Self::set_markup_mode): nothing about the document
1515    /// itself changes, only what may be done to it from here on.
1516    pub fn set_read_only(&mut self, on: bool) {
1517        self.read_only = on;
1518    }
1519
1520    /// The host-painted ranges, sorted by start — see [`Highlight`].
1521    pub fn highlights(&self) -> &[Highlight] {
1522        &self.highlights
1523    }
1524
1525    /// Replace the host-painted ranges wholesale. The whole set each time,
1526    /// rather than add/remove verbs: the host owns the list (it derives it
1527    /// from its own state — annotations, search hits), and a replace can
1528    /// never leave the two disagreeing about what should be on screen.
1529    pub fn set_highlights(&mut self, mut highlights: Vec<Highlight>) {
1530        highlights.retain(|h| h.start < h.end);
1531        highlights.sort_by_key(|h| (h.start, h.end));
1532        self.highlights = highlights;
1533    }
1534
1535    /// The highlight covering source `offset`, if one does — first by start
1536    /// when several overlap, which makes overlapping washes resolvable rather
1537    /// than undefined. What a frontend asks when the reader activates a spot.
1538    ///
1539    /// [`Highlight::covering`] is the whole of it: the frontends paint by
1540    /// asking the same question per glyph, against a slice they were handed
1541    /// rather than against a `Doc`, and one answer for both is what keeps a
1542    /// wash and an activation agreeing about which range a spot is in.
1543    pub fn highlight_at(&self, offset: usize) -> Option<&Highlight> {
1544        Highlight::covering(&self.highlights, offset)
1545    }
1546
1547    /// The AST breadcrumb at the caret (root → deepest), e.g.
1548    /// `doc › para › strong`. Read live from twig via `ancestors_at`.
1549    pub fn breadcrumb(&mut self) -> String {
1550        match self.editor.ancestors_at(self.caret) {
1551            Ok(chain) => chain
1552                .iter()
1553                .map(|m| m.kind.as_str())
1554                .collect::<Vec<_>>()
1555                .join(" › "),
1556            Err(_) => String::new(),
1557        }
1558    }
1559
1560    // ── editing ──────────────────────────────────────────────────────────────
1561
1562    /// Replace the byte range `[start, end)` with `text`, re-anchoring the caret
1563    /// after it. The public form of the internal splice — a pixel frontend that
1564    /// hit-tests to a byte offset (or an IME that hands back an explicit range)
1565    /// edits through this, the same twig `edit_range` the caret ops use.
1566    pub fn edit(&mut self, start: usize, end: usize, text: &str) {
1567        self.splice(start, end, text, EditKind::Other);
1568    }
1569
1570    /// Insert typed `text` at the caret, replacing the selection if there is one.
1571    /// A single typed character coalesces with the run of typing before it; a
1572    /// newline or a multi-character insert is its own undo step.
1573    ///
1574    /// Typed input only — clipboard text goes through [`paste`](Self::paste).
1575    pub fn insert(&mut self, text: &str) {
1576        // The read-only gate, up front: the paths below reach twig by several
1577        // verbs, not all of them through the splice — see the field.
1578        if self.read_only {
1579            return;
1580        }
1581        // Typing against a block picture would dissolve it — see
1582        // `open_paragraph_at_block_media`. Give the text a paragraph first, so
1583        // what the caret was standing beside stays a picture.
1584        self.open_paragraph_at_block_media(text);
1585        // Armed sticky marks (⌘b with no selection) turn the next typed text
1586        // bold/italic/… and then retire — see `insert_with_marks`. Whitespace is
1587        // the exception: it takes no mark of its own and keeps the delta armed
1588        // for the character behind it — see `insert_space_with_marks`.
1589        let pending = self.pending_here();
1590        if !pending.is_empty() && self.selection().is_none() && !text.is_empty() {
1591            if text.trim().is_empty() {
1592                self.insert_space_with_marks(self.caret, text, pending);
1593            } else {
1594                self.insert_with_marks(self.caret, text, pending);
1595            }
1596            return;
1597        }
1598        // `MarkupMode::None`: typed syntax stays literal — twig escapes
1599        // anything that would open markup, so a Diaryx user never mints
1600        // formatting by keyboard (it comes from commands instead). The other two
1601        // rungs of the ladder author markup from what you type, which is the
1602        // whole difference between them and this one. Only in the rendered view
1603        // (source view is for typing raw markup) and only where the format has a
1604        // literal spelling at all: escaping is a backslash before a byte from the
1605        // format's own alphabet, and a format with no such alphabet (HTML escapes
1606        // with entities, XML spells nothing) would have `\&` written into it,
1607        // which is two literal characters and not an escape. Marks (⌘b) still
1608        // format — that path returned above; and leaf's own structural inserts go
1609        // through `insert_raw`, never here, so a list marker or quote gutter is
1610        // written as the markup it is.
1611        if !self.markup_mode.authors()
1612            && self.view == View::Wysiwyg
1613            && !text.is_empty()
1614            && self.supports(Gesture::InsertLiteral)
1615        {
1616            self.insert_literal_typed(text);
1617            return;
1618        }
1619        self.insert_raw(text);
1620    }
1621
1622    /// Insert `text` verbatim at the caret (replacing any selection) — the plain
1623    /// path with no Hidden-mode literal escaping. leaf's own structural inserts
1624    /// (a list marker, a quote gutter, an in-cell `<br>`) call this: they ARE
1625    /// markup by design and must not be escaped.
1626    fn insert_raw(&mut self, text: &str) {
1627        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
1628        self.splice(s, e, text, typed_edit_kind(text));
1629    }
1630
1631    /// Open a paragraph for text about to be inserted at one of a block media's
1632    /// two caret stops, and leave the caret standing in it.
1633    ///
1634    /// A block image is a paragraph whose entire content is the picture, and the
1635    /// caret's only homes on it are in front of it and just past it (see
1636    /// [`VisualMap::block_media_stop`]). Text inserted at either offset joins
1637    /// *that* paragraph — and a paragraph holding anything besides the image is
1638    /// no longer a block image but a line of text with an inline one in it. The
1639    /// frontend that was painting a photo there paints a text run instead; the
1640    /// picture is still in the file, and nothing said a word. Those two offsets
1641    /// are also exactly where a click on the picture lands, so the whole accident
1642    /// is one tap and one keystroke.
1643    ///
1644    /// So the break goes in first and the text lands in the new empty paragraph —
1645    /// what pressing Return before typing would have done, which is a habit no
1646    /// one should have to learn from losing a photo. A no-op everywhere else, and
1647    /// over a selection (which is replaced, not joined into).
1648    ///
1649    /// A picture inside a quote or a list leaves its container, because `\n\n`
1650    /// ends the block. The alternative is worse: the `\n> ` / next-item
1651    /// continuation [`newline`](Self::newline) writes stays in the same
1652    /// *paragraph*, which is the thing being prevented.
1653    ///
1654    /// Only in the rendered view. Source view is for typing raw markup, where
1655    /// putting a character against an image is exactly what it looks like.
1656    fn open_paragraph_at_block_media(&mut self, text: &str) {
1657        if self.view != View::Wysiwyg || text.is_empty() || text == "\n" {
1658            return;
1659        }
1660        if self.selection().is_some() {
1661            return;
1662        }
1663        // The map may be a revision behind (nothing has drawn since the last
1664        // edit), and this asks it about offsets — a stale answer would splice a
1665        // break into the wrong place. Free when it is already current, which it
1666        // is whenever a frontend drew a frame between keystrokes.
1667        self.rebuild_map();
1668        let at = self.caret;
1669        let Some((side, _)) = self.vmap.block_media_stop(at) else {
1670            return;
1671        };
1672        if !self.splice(at, at, "\n\n", EditKind::Other) {
1673            return;
1674        }
1675        // The break is part of the keystroke, not an edit of its own: leave the
1676        // run marked as typing so the character about to arrive folds into it and
1677        // one undo puts the document back the way it was found. (A paste, or a
1678        // multi-character insert, is `EditKind::Other` and stays its own step —
1679        // as it would have been anywhere else in the document.)
1680        self.last_edit_kind = Some(EditKind::Insert);
1681        if side == MediaStop::Before {
1682            // The break went in above the picture and the caret rode to the end
1683            // of it — which is still hard against the picture. Step back onto the
1684            // blank line it opened, so the text lands above rather than in front.
1685            self.caret = at;
1686        }
1687    }
1688
1689    /// A delete key pressed at one of a block picture's two caret stops, handled
1690    /// as the picture being an *atom* rather than a run of bytes. Returns whether
1691    /// the key was consumed.
1692    ///
1693    /// The caret rests in front of a block image and just past it, never inside
1694    /// its markup — which the rendered view doesn't show. So the byte a delete
1695    /// key nominally takes there is one the writer cannot see, and taking it
1696    /// leaves the picture as broken markup rather than as anything anyone asked
1697    /// for: Backspace at the stop past `![](p.png)` removes the closing paren, and
1698    /// a photo becomes the literal text `![](p.png`. That is how a picture goes
1699    /// missing from a document with nobody having touched it — the same
1700    /// dissolution [`open_paragraph_at_block_media`](Self::open_paragraph_at_block_media)
1701    /// prevents from the typing side, and it cost this repository's own test vault
1702    /// a photo before it was found.
1703    ///
1704    /// So the key aimed *at* the picture deletes the picture, whole — Backspace
1705    /// when it is behind the caret, Delete when it is in front — which is what
1706    /// every editor does with an embed, and one undo away. The key aimed *away*
1707    /// from it would otherwise delete the paragraph break and merge a neighbour
1708    /// into the picture's own paragraph, which dissolves it just as surely; it
1709    /// steps the caret over the boundary instead and leaves the
1710    /// next press to delete in the block it has reached — the same "first press
1711    /// steps out of the atom, second press deletes" every delete key here gets,
1712    /// word-deletes included (⌥⌫ in front of a picture is aimed at the prose
1713    /// above, and reaches it on the second press rather than taking the break and
1714    /// the picture with it on the first).
1715    fn delete_around_block_media(&mut self, forward: bool) -> bool {
1716        // The map answers about offsets, so it has to be this revision's — see
1717        // the same call in `open_paragraph_at_block_media`.
1718        self.rebuild_map();
1719        let Some((side, span)) = self.vmap.block_media_stop(self.caret) else {
1720            return false;
1721        };
1722        let aimed_at_it = side
1723            == if forward {
1724                MediaStop::Before
1725            } else {
1726                MediaStop::After
1727            };
1728        if !aimed_at_it {
1729            let over = if forward {
1730                self.vmap.stop_after(self.caret)
1731            } else {
1732                self.vmap.stop_before(self.caret)
1733            };
1734            if let Some(off) = over.filter(|&o| o >= self.caret_floor()) {
1735                self.caret = off;
1736                self.anchor = None;
1737                self.goal_col = None;
1738            }
1739            return true;
1740        }
1741        // Take the break that held the picture apart from its neighbour with it,
1742        // so the delete doesn't leave a blank paragraph standing where the
1743        // picture was. The last arm is a picture that is the whole document.
1744        let (from, to) = if self.source[..span.start].ends_with("\n\n") {
1745            (span.start - 2, span.end)
1746        } else if self.source[span.end..].starts_with("\n\n") {
1747            (span.start, span.end + 2)
1748        } else {
1749            (span.start, span.end)
1750        };
1751        self.splice(from.max(self.caret_floor()), to, "", EditKind::Other);
1752        true
1753    }
1754
1755    /// The Hidden-mode typing path: replace any selection, then insert `text`
1756    /// escaped so it stays literal. When it replaces a selection the two edits
1757    /// fold into one undo step, so an overwrite undoes atomically (and restores
1758    /// the selection) exactly as a plain one does.
1759    fn insert_literal_typed(&mut self, text: &str) {
1760        let kind = typed_edit_kind(text);
1761        match self.selection() {
1762            Some((s, e)) => {
1763                if !self.splice(s, e, "", EditKind::Other) {
1764                    return;
1765                }
1766                // Typing over a whole marked run takes its delimiters with it
1767                // (the empty content couldn't hold them — see
1768                // `repair_mark_edges`) and leaves its marks armed at the caret.
1769                // The text taking the run's place inherits them, exactly as it
1770                // would have by landing inside a run that survived.
1771                let pending = self.pending_here();
1772                if !pending.is_empty() && !text.trim().is_empty() {
1773                    self.insert_with_marks(self.caret, text, pending);
1774                    return;
1775                }
1776                self.insert_literal_at(self.caret, text, kind, true);
1777            }
1778            None => {
1779                self.insert_literal_at(self.caret, text, kind, false);
1780            }
1781        }
1782    }
1783
1784    /// The sticky-mark delta that is live right now: the marks armed by [`toggle`]
1785    /// at a collapsed caret, but only while the caret still stands where they
1786    /// were armed and nothing is selected. Empty otherwise, so a stale delta
1787    /// never styles text it wasn't meant for.
1788    fn pending_here(&self) -> InlineMarks {
1789        if self.anchor.is_none() && self.pending_at == Some(self.caret) {
1790            self.pending_marks
1791        } else {
1792            InlineMarks::empty()
1793        }
1794    }
1795
1796    /// Drop the armed sticky marks — any caret motion, selection, or edit does
1797    /// this, so "start bold here" only ever applies at the exact spot it was
1798    /// asked for.
1799    fn clear_pending(&mut self) {
1800        self.pending_marks = InlineMarks::empty();
1801        self.pending_at = None;
1802    }
1803
1804    /// Insert `text` at `at` carrying the armed sticky `marks`: a mark not yet in
1805    /// force is wrapped around the freshly typed text; a mark the caret already
1806    /// stands inside is *shed* — the text is inserted past the run's end so it
1807    /// lands unmarked ("type normally again"). The caret comes to rest inside any
1808    /// added runs, so continued typing inherits the marks with no re-wrapping,
1809    /// and the delta is cleared: the marks now live in the document, not here.
1810    fn insert_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
1811        let base = self.mark_spans_at(at);
1812        let base_set: InlineMarks = base.iter().map(|(k, _)| *k).collect();
1813        // Nothing to shed, and a run of exactly these marks standing just behind
1814        // the caret: carry on writing *that* run rather than opening a second
1815        // one beside it.
1816        if base_set.is_empty() && self.rejoin_run(at, text, marks) {
1817            return;
1818        }
1819        // Shed the marks we're turning off: step the insertion point past the
1820        // end of each run the caret sits in, so the new text falls outside it.
1821        let mut ins_at = at;
1822        for (kind, span) in &base {
1823            if marks.contains(*kind) {
1824                ins_at = ins_at.max(span.end);
1825            }
1826        }
1827        if !self.splice_exact(ins_at, ins_at, text, EditKind::Other) {
1828            return;
1829        }
1830        // The plain splice inserted exactly `text` at `ins_at`; that byte range
1831        // is the content every added mark wraps.
1832        let (mut cs, mut ce) = (ins_at, ins_at + text.len());
1833        for kind in marks.iter() {
1834            if !base_set.contains(kind) {
1835                let (ncs, nce) = self.wrap_span(cs, ce, kind);
1836                cs = ncs;
1837                ce = nce;
1838            }
1839        }
1840        self.caret = ce.min(self.source.len());
1841        self.anchor = None;
1842        self.last_edit_kind = None;
1843        // Realised: the marks are in the document now, and the caret sits inside
1844        // them, so there is no delta left to carry. Arm nothing, but remember the
1845        // spot so a *further* toggle before typing starts a clean delta here.
1846        self.pending_marks = InlineMarks::empty();
1847        self.pending_at = Some(self.caret);
1848        self.clamp_caret();
1849        self.record_caret();
1850    }
1851
1852    /// Carry on the marked run just behind `at` — moving its closing delimiters
1853    /// out past the new text — instead of opening a second run of the same marks
1854    /// beside it. Returns whether it did.
1855    ///
1856    /// This is the far half of the mark-edge rule (see [`splice`](Self::splice)).
1857    /// A space typed after a bold word steps the caret out of the run, because
1858    /// `**bold **` is not bold; the next character has to step back *in*, or the
1859    /// writer who typed one bold phrase is left with `**bold** **and**` — two
1860    /// runs that read the same to a reader but spell the file in a way nobody
1861    /// wrote. Only whitespace may stand in the gap (a run doesn't reach across
1862    /// words it isn't marking), and the marks behind it must be exactly the ones
1863    /// armed — a run of *some* other kind is a neighbour, not this phrase.
1864    fn rejoin_run(&mut self, at: usize, text: &str, marks: InlineMarks) -> bool {
1865        if text.is_empty() || text.trim() != text {
1866            return false;
1867        }
1868        let gap_at = self.source[..at].trim_end_matches([' ', '\t']).len();
1869        // Walk in through the delimiters stacked at that point, innermost last:
1870        // `***both*** ` closes two runs with one `***`, and rejoining means
1871        // getting behind all of them.
1872        let (mut cut, mut kinds) = (gap_at, InlineMarks::empty());
1873        while let Some((kind, content_end)) = self
1874            .editor
1875            .ancestors_at(prev_boundary(&self.source, cut))
1876            .unwrap_or_default()
1877            .into_iter()
1878            .filter(|m| m.span.end == cut)
1879            .find_map(|m| Some((inline_kind(&m.kind)?, m.content_span.clone()?.end)))
1880        {
1881            if content_end >= cut {
1882                break; // a mark with no closing delimiter to step behind
1883            }
1884            kinds.insert(kind);
1885            cut = content_end;
1886        }
1887        if cut == gap_at || kinds != marks {
1888            return false;
1889        }
1890        // Re-spell the tail: the gap, then the new text, then the delimiters that
1891        // used to close in front of them — read out of the document rather than
1892        // written from a table, so whatever twig spells them with is what moves.
1893        let tail = format!(
1894            "{}{text}{}",
1895            &self.source[gap_at..at],
1896            &self.source[cut..gap_at]
1897        );
1898        if !self.splice_exact(cut, at, &tail, EditKind::Other) {
1899            return false;
1900        }
1901        self.caret = (cut + (at - gap_at) + text.len()).min(self.source.len());
1902        self.anchor = None;
1903        self.last_edit_kind = None;
1904        self.pending_marks = InlineMarks::empty();
1905        self.pending_at = Some(self.caret);
1906        self.clamp_caret();
1907        self.record_caret();
1908        true
1909    }
1910
1911    /// Insert typed whitespace at a caret with sticky marks armed. Whitespace is
1912    /// never itself wrapped: a mark around a space draws nothing a reader can
1913    /// see, and in Markdown and Djot it draws its own delimiters instead
1914    /// (`** **`). So the space goes in unmarked — outside any run the armed
1915    /// marks are shedding — and the marks stay armed for the character after it,
1916    /// which rejoins the run (see [`rejoin_run`](Self::rejoin_run)).
1917    fn insert_space_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
1918        let base = self.mark_spans_at(at);
1919        // What the *next* character carries: the armed delta resolved against the
1920        // marks in force here, which the space must not quietly drop.
1921        let want = base
1922            .iter()
1923            .map(|(k, _)| *k)
1924            .collect::<InlineMarks>()
1925            .xor(marks);
1926        let mut ins_at = at;
1927        for (kind, span) in &base {
1928            if marks.contains(*kind) {
1929                ins_at = ins_at.max(span.end);
1930            }
1931        }
1932        if !self.splice(ins_at, ins_at, text, typed_edit_kind(text)) {
1933            return;
1934        }
1935        self.rearm(want);
1936        self.record_caret();
1937    }
1938
1939    /// Wrap `[s, e)` in `kind` via twig and return the byte span the *content*
1940    /// (not the delimiters) occupies afterwards. Markdown/Djot inline delimiters
1941    /// are symmetric (`**`…`**`, `_`…`_`, `` ` ``…`` ` ``), so the bytes twig
1942    /// added split evenly around the content — half the growth on each side.
1943    fn wrap_span(&mut self, s: usize, e: usize, kind: InlineKind) -> (usize, usize) {
1944        // The read-only gate — this door reaches twig without the splice.
1945        if self.read_only {
1946            return (s, e);
1947        }
1948        match self.editor.toggle_inline(s, e, kind) {
1949            Ok(change) => {
1950                self.last_edit_kind = None;
1951                self.refresh();
1952                self.dirty = self.source != self.clean_source;
1953                let added = (change.new.end - change.new.start).saturating_sub(e - s);
1954                let half = added / 2;
1955                (change.new.start + half, change.new.end - half)
1956            }
1957            // Unsupported here (e.g. mark on Markdown): leave the text unwrapped
1958            // rather than lose the keystroke.
1959            Err(e2) => {
1960                self.status = Some(format!("{kind:?}: {e2}"));
1961                (s, e)
1962            }
1963        }
1964    }
1965
1966    /// The safe offset to splice a block-level break at, given a caret that may
1967    /// sit exactly between an inline mark's content and its own closing
1968    /// delimiter (`content_span.end == off < span.end` for some enclosing mark
1969    /// — the WYSIWYG caret's natural resting place at the end of `**bold**`
1970    /// with nothing following it on the line: the closing `**` renders no
1971    /// glyph of its own, so the caret's "end of line" offset lands right
1972    /// before it). Splicing a paragraph/list/quote break at `off` itself would
1973    /// sever the delimiter from its content, stranding it alone on the new
1974    /// line. Walks out to the *outermost* such mark's `span.end` instead, so
1975    /// nested marks closing at the same point (`**_x_**`) all clear together.
1976    /// A no-op everywhere else — mid-run, or past real trailing content, no
1977    /// mark's `content_span` ends exactly at `off`.
1978    fn skip_trailing_close_delims(&mut self, off: usize) -> usize {
1979        let off = off.min(self.source.len());
1980        self.editor
1981            .ancestors_at(off)
1982            .unwrap_or_default()
1983            .into_iter()
1984            .filter(|m| inline_kind(&m.kind).is_some())
1985            .filter(|m| off < m.span.end && m.content_span.as_ref().is_some_and(|c| c.end == off))
1986            .map(|m| m.span.end)
1987            .max()
1988            .unwrap_or(off)
1989    }
1990
1991    /// The offset a *delete* aimed at the character before `off` should stop at,
1992    /// when `off` is the start of a run's text and the bytes behind it are that
1993    /// run's opening delimiter. The rich view draws no glyph for a `**`, so the
1994    /// byte behind the caret at the start of a bold word is not a character the
1995    /// writer can see, let alone one they aimed Backspace at: taking it leaves
1996    /// `a *bold** c` — the styling gone and a literal asterisk in its place. The
1997    /// delete steps over the whole delimiter to the visible character in front of
1998    /// it instead. Walks out to the *outermost* mark opening there, so
1999    /// `**_x_**` clears every delimiter at once, and is a no-op anywhere else.
2000    fn skip_leading_open_delims(&mut self, off: usize) -> usize {
2001        let off = off.min(self.source.len());
2002        self.editor
2003            .ancestors_at(off)
2004            .unwrap_or_default()
2005            .into_iter()
2006            .filter(|m| inline_kind(&m.kind).is_some())
2007            .filter(|m| {
2008                m.span.start < off && m.content_span.as_ref().is_some_and(|c| c.start == off)
2009            })
2010            .map(|m| m.span.start)
2011            .min()
2012            .unwrap_or(off)
2013    }
2014
2015    /// `off` moved *inside* the run whose closing delimiters end there — the
2016    /// other offset the rich view draws in the same place, since a `**` renders
2017    /// no glyph of its own. `**bold**` has a caret home on each side of its
2018    /// closing delimiter, one column apart on screen and eight bytes and a whole
2019    /// run apart in the file, and a plain ← lands on the outer one whenever a
2020    /// space follows the phrase. The inner one is what the writer is pointing at
2021    /// there: the end of their bold word. Walks in through every mark closing at
2022    /// that point, innermost last, so `***both***` lands inside both. A no-op
2023    /// anywhere else — mid-run, or in prose, no mark's span ends at `off`.
2024    fn step_inside_close_delims(&mut self, off: usize) -> usize {
2025        let mut off = off.min(self.source.len());
2026        loop {
2027            let inner = self
2028                .editor
2029                .ancestors_at(prev_boundary(&self.source, off))
2030                .unwrap_or_default()
2031                .into_iter()
2032                .filter(|m| inline_kind(&m.kind).is_some() && m.span.end == off)
2033                .filter_map(|m| m.content_span.clone().map(|c| c.end))
2034                .filter(|&end| end < off)
2035                .max();
2036            match inner {
2037                Some(end) => off = end,
2038                None => return off,
2039            }
2040        }
2041    }
2042
2043    /// The mirror at the opening edge: `off` moved inside the run whose
2044    /// delimiters *start* there, onto the first character of its text. See
2045    /// [`step_inside_close_delims`](Self::step_inside_close_delims).
2046    fn step_inside_open_delims(&mut self, off: usize) -> usize {
2047        let mut off = off.min(self.source.len());
2048        loop {
2049            let inner = self
2050                .editor
2051                .ancestors_at(off)
2052                .unwrap_or_default()
2053                .into_iter()
2054                .filter(|m| inline_kind(&m.kind).is_some() && m.span.start == off)
2055                .filter_map(|m| m.content_span.clone().map(|c| c.start))
2056                .filter(|&start| start > off)
2057                .min();
2058            match inner {
2059                Some(start) => off = start,
2060                None => return off,
2061            }
2062        }
2063    }
2064
2065    /// The inline mark kinds whose span covers `off`, each with that span — the
2066    /// span-carrying sibling of [`marks_at`](Self::marks_at), which reports node
2067    /// ids instead. Used to shed a mark by stepping past the end of its run.
2068    fn mark_spans_at(&mut self, off: usize) -> Vec<(InlineKind, std::ops::Range<usize>)> {
2069        let off = off.min(self.source.len());
2070        self.editor
2071            .ancestors_at(off)
2072            .unwrap_or_default()
2073            .into_iter()
2074            .filter(|m| off < m.span.end)
2075            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.span.clone())))
2076            .collect()
2077    }
2078
2079    /// Insert clipboard `text` at the caret, replacing the selection if there is
2080    /// one — always its own undo step, whatever its length.
2081    ///
2082    /// Provenance is the whole point, and only the caller has it. `insert` reads
2083    /// a lone character as a keystroke and folds it into the run around it,
2084    /// which is right for typing and wrong for a one-character paste: that paste
2085    /// would vanish mid-run on an undo it was never part of, and the characters
2086    /// the user actually typed would go with it. Length can't tell the two
2087    /// apart — `⌘V` of `x` and typing `x` are the same string — so the door the
2088    /// caller comes through is what says which happened.
2089    pub fn paste(&mut self, text: &str) {
2090        // Pasting against a block picture dissolves it exactly as typing does,
2091        // and for the same reason — see `open_paragraph_at_block_media`.
2092        self.open_paragraph_at_block_media(text);
2093        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2094        self.splice(s, e, text, EditKind::Other);
2095    }
2096
2097    /// Replace `[start, end)` with `text` as one step of an IME composition —
2098    /// the same splice as [`edit`](Self::edit), but marked so the run of steps
2099    /// folds into a single undo.
2100    ///
2101    /// A composition is *one* act of writing. Typing `かんじ` and picking 感じ is a
2102    /// dozen calls here, each replacing the last one's provisional bytes, and an
2103    /// undo step per call means undoing a word means pressing ⌘Z until the reading
2104    /// unspools backwards through kana — the intermediate states were never text
2105    /// the user wrote. Only the frontend knows a call is provisional (the bytes
2106    /// look like any other edit), so the door the caller comes through is what
2107    /// says so, exactly as it is for [`paste`](Self::paste) versus
2108    /// [`insert`](Self::insert).
2109    ///
2110    /// Pair with [`end_composition`](Self::end_composition), or the *next*
2111    /// composition folds into this one.
2112    pub fn edit_composing(&mut self, start: usize, end: usize, text: &str) {
2113        self.splice(start, end, text, EditKind::Compose);
2114    }
2115
2116    /// Close the open composition run, so the next one is its own undo step.
2117    /// Call when the IME commits or withdraws a composition.
2118    ///
2119    /// Only clears a *composition* run: a frontend that reports an end it never
2120    /// began (some IMEs unmark unprompted) would otherwise split the run of
2121    /// typing around it into two undo steps for no reason the user can see.
2122    pub fn end_composition(&mut self) {
2123        if self.last_edit_kind == Some(EditKind::Compose) {
2124            self.last_edit_kind = None;
2125        }
2126    }
2127
2128    // ── the clipboard's rich flavor ──────────────────────────────────────────
2129
2130    /// The selection rendered as HTML, for the clipboard's `text/html` flavor —
2131    /// what lets a paste into Docs/Mail/Slack keep its formatting. `None` when
2132    /// nothing is selected, or when the selection doesn't render (the caller
2133    /// still has [`selected_text`](Self::selected_text), which is what to publish
2134    /// as `text/plain` either way).
2135    ///
2136    /// **The fragment is a source substring, and that is the honest limit here.**
2137    /// It's parsed standalone, so a selection whose meaning depends on its
2138    /// surroundings converts as what it literally says rather than what it looks
2139    /// like on screen: half a list item is a paragraph, a row torn out of a table
2140    /// is the text of a row, the `**` of a bold run selected without its closing
2141    /// `**` is two asterisks. Every one of those still *renders* — there's no
2142    /// error to report — it just renders as the fragment and not as the document.
2143    /// Widening the range to whole blocks would publish text the user didn't
2144    /// select, which is a worse lie than a fragment being a fragment; the plain
2145    /// flavor has the same substring, so the two flavors at least agree.
2146    pub fn selection_html(&mut self) -> Option<String> {
2147        let (start, end) = self.selection()?;
2148        let inline = self.selection_is_inline(start, end);
2149        let html = html::render_fragment(&self.source[start..end], self.format)?;
2150        Some(match inline {
2151            true => html::strip_sole_paragraph(html),
2152            false => html,
2153        })
2154    }
2155
2156    /// Paste the clipboard's `text/html` flavor, converting it to this document's
2157    /// format first. Its own undo step, like any [`paste`](Self::paste).
2158    ///
2159    /// Returns whether it landed. `false` means the HTML didn't convert to
2160    /// anything worth pasting — the caller should fall back to the plain flavor
2161    /// rather than treat it as an error. The `html` module has the full list of
2162    /// what that covers: a table twig won't build, markup it doesn't recognise,
2163    /// an empty result.
2164    pub fn paste_html(&mut self, html: &str) -> bool {
2165        match html::parse_fragment(html, self.format) {
2166            Some(source) => {
2167                self.paste(&source);
2168                true
2169            }
2170            None => false,
2171        }
2172    }
2173
2174    /// Does the selection live *inside* a single top-level block?
2175    ///
2176    /// The question [`selection_html`](Self::selection_html) needs and the
2177    /// fragment can't answer: `**bold**` renders as `<p><strong>bold</strong></p>`
2178    /// whether the user selected one word of a sentence or a whole paragraph, and
2179    /// only the document knows which. Selecting a word and pasting into Docs
2180    /// should extend the line you paste into; selecting the paragraph should make
2181    /// a paragraph. So a selection strictly within one block is inline (its `<p>`
2182    /// is an artifact of standalone parsing), and one that covers a whole block —
2183    /// or spans two — keeps its structure.
2184    ///
2185    /// Reads the block from twig rather than guessing from the bytes:
2186    /// `ancestors_at` is `[doc, block, …inline]`, so index 1 is the top-level
2187    /// block containing an offset, and two ends inside the same one cannot have
2188    /// crossed a block boundary.
2189    fn selection_is_inline(&mut self, start: usize, end: usize) -> bool {
2190        // The last *character*, not `end - 1`: the selection's end is exclusive
2191        // and may sit mid-codepoint's-worth of bytes past the last char.
2192        let Some((off, _)) = self.source[start..end].char_indices().next_back() else {
2193            return false;
2194        };
2195        let (Some(head), Some(tail)) =
2196            (self.top_block_span(start), self.top_block_span(start + off))
2197        else {
2198            return false;
2199        };
2200        head == tail && !(start <= head.start && end >= head.end)
2201    }
2202
2203    /// The byte span of the top-level block containing `offset`, or `None` at an
2204    /// offset that belongs to no block (the blank line between two of them).
2205    fn top_block_span(&mut self, offset: usize) -> Option<std::ops::Range<usize>> {
2206        self.editor
2207            .ancestors_at(offset)
2208            .ok()?
2209            .get(1)
2210            .map(|m| m.span.clone())
2211    }
2212
2213    // ── indentation ──────────────────────────────────────────────────────────
2214
2215    /// One indent level.
2216    ///
2217    /// Two spaces, not the four both frontends type for Tab today, because in a
2218    /// markdown document four columns isn't a width — it's a *meaning*. Four
2219    /// spaces at the head of a line is markdown's indented-code-block marker, so
2220    /// one Tab on a paragraph would reparse it into code and style it as such;
2221    /// two cannot, and the line stays the prose it was. Two is also exactly
2222    /// where a `- ` bullet's content starts, so an indented line lands under its
2223    /// parent item's text instead of beside it — the column a list-aware indent
2224    /// has to hit anyway, which keeps this width from being relitigated later.
2225    const INDENT: &'static str = "  ";
2226
2227    /// Indent the selected lines — or the caret's line, with no selection — by
2228    /// one level (Tab).
2229    pub fn indent(&mut self) {
2230        self.reindent(true);
2231        // Nesting changes an ordered list's numbering (the nested item restarts,
2232        // its old siblings resume) — keep the source markers in step.
2233        self.renumber_here();
2234        // Nesting an empty `-` item under a text line reparses that text as a
2235        // setext heading; swap the dash for a `*` before it can (a no-op unless
2236        // the collapse actually happened).
2237        self.avoid_setext_collapse();
2238    }
2239
2240    /// Take one indent level back off the selected lines, or the caret's line
2241    /// (Shift+Tab). A line with no indentation is left exactly as it is.
2242    ///
2243    /// A line with *less* than a full level gives back what it has rather than
2244    /// refusing: outdent's job is to walk a line left, and real documents — hand
2245    /// written, or reflowed by some other editor — are full of indentation that
2246    /// was never a clean multiple of anything. Refusing there would strand the
2247    /// line at a depth Shift+Tab couldn't undo.
2248    pub fn outdent(&mut self) {
2249        self.reindent(false);
2250        self.renumber_here();
2251    }
2252
2253    /// The body of [`indent`](Self::indent) / [`outdent`](Self::outdent).
2254    ///
2255    /// One splice across the whole line range, never one per line: a Tab is one
2256    /// thing the user did, so it has to be one undo step and one reparse. Per
2257    /// line, twig would reparse the document once per line and leave a stack of
2258    /// steps that Shift+⌘Z walks back one line at a time.
2259    fn reindent(&mut self, add: bool) {
2260        let (sel_start, sel_end) = self.selection().unwrap_or((self.caret, self.caret));
2261        let start = source_line_range(&self.source, sel_start).start;
2262        let end = source_line_range(&self.source, sel_end).end;
2263        let region = self.source[start..end].to_string();
2264        let lines: Vec<&str> = region.split('\n').collect();
2265        // A blank line has no text to move, and padding it would leave nothing
2266        // but trailing whitespace — but Tab on a blank line *is* a request for
2267        // indentation to type into, so the skip only applies where the op has
2268        // other lines to do real work on.
2269        let skip_blank = add && lines.len() > 1;
2270
2271        let mut out = String::with_capacity(region.len() + lines.len() * Self::INDENT.len());
2272        let mut deltas: Vec<isize> = Vec::with_capacity(lines.len());
2273        let mut line_off = start;
2274        for (i, full) in lines.iter().enumerate() {
2275            if i > 0 {
2276                out.push('\n');
2277            }
2278            // A list item moves by having its whole leading prefix *replaced*,
2279            // never by having spaces pushed in front of the line. twig spells
2280            // both prefixes, so the quote markers, the parent's indent and an
2281            // ordered marker's extra column all come out right without leaf
2282            // measuring any of them — and a line that only looks like an item
2283            // (a Djot continuation) reports no marker and is left to the plain
2284            // path, where a Tab is just a Tab.
2285            let marker = self.list_marker_on_line(line_off);
2286            let own = marker
2287                .as_ref()
2288                .map(|m| m.marker_start - m.line_start)
2289                .unwrap_or(0);
2290            let delta = if add {
2291                if skip_blank && full.trim().is_empty() {
2292                    out.push_str(full);
2293                    0
2294                } else if marker.is_some() && self.first_item_of_list(line_off) {
2295                    // The first item of a list has no preceding sibling to nest
2296                    // under, so a Tab here can't spell a sub-list — twig would
2297                    // reparse the shoved-over marker as the same list, only
2298                    // indented, which Shift+Tab then can't cleanly undo. Leave the
2299                    // item where it is, the way every list editor refuses to
2300                    // over-indent a list's first line.
2301                    out.push_str(full);
2302                    0
2303                } else if marker.is_some() {
2304                    // Nesting means standing where a *continuation* of this line
2305                    // would stand: past the parent's marker, inside its content
2306                    // column. That is `continuation_prefix`, less a checkbox.
2307                    let new = self.nesting_prefix_at(line_off);
2308                    let delta = new.len() as isize - own as isize;
2309                    out.push_str(&new);
2310                    out.push_str(&full[own..]);
2311                    delta
2312                } else {
2313                    out.push_str(Self::INDENT);
2314                    out.push_str(full);
2315                    Self::INDENT.len() as isize
2316                }
2317            } else if marker.is_some() {
2318                // Unnesting is the mirror: stand where the parent item's own
2319                // line starts, which drops exactly the level it contributed.
2320                let new = self.outdent_prefix_at(line_off);
2321                let delta = new.len() as isize - own as isize;
2322                out.push_str(&new);
2323                out.push_str(&full[own..]);
2324                delta
2325            } else {
2326                // A plain line gives back the ordinary step.
2327                let strip = outdent_width(full, Self::INDENT.len());
2328                out.push_str(&full[strip..]);
2329                -(strip as isize)
2330            };
2331            deltas.push(delta);
2332            line_off += full.len() + 1;
2333        }
2334        // Nothing to give back. Returning before the splice keeps an outdent at
2335        // column zero from spending an undo step on a document it never changed.
2336        if deltas.iter().all(|d| *d == 0) {
2337            return;
2338        }
2339
2340        // Every line's text keeps its offset *within the line*, so the caret is
2341        // remapped by its column, not by its byte offset — which the prefixes on
2342        // the lines above it have already invalidated.
2343        let remap = |off: usize| -> usize {
2344            let (mut old_ls, mut new_ls) = (start, start);
2345            for (line, delta) in lines.iter().zip(&deltas) {
2346                let old_le = old_ls + line.len();
2347                let new_len = (line.len() as isize + delta) as usize;
2348                if off <= old_le {
2349                    let col = (off - old_ls) as isize;
2350                    return new_ls + ((col + delta).max(0) as usize).min(new_len);
2351                }
2352                old_ls = old_le + 1;
2353                new_ls += new_len + 1;
2354            }
2355            start + out.len()
2356        };
2357        let placed = match self.selection() {
2358            // Keep the rewritten region selected, the way a container toggle
2359            // keeps its own: it leaves a second Tab aimed at the same lines
2360            // rather than at whatever the shifted offsets now happen to cover.
2361            Some(_) => (start + out.len(), Some(start)),
2362            None => (remap(self.caret), None),
2363        };
2364
2365        // A rolled-back splice leaves the old source in place, where every offset
2366        // computed above addresses text that was never written.
2367        if !self.splice(start, end, &out, EditKind::Other) {
2368            return;
2369        }
2370        // `splice` re-anchors to the end of the `Change`, which for a whole-region
2371        // rewrite is the last line's end — nowhere the caret was. Place it, then
2372        // re-record the caret so this is the state redo restores, not the one
2373        // `splice` left behind from the `Change`.
2374        self.caret = placed.0.min(self.source.len());
2375        self.anchor = placed.1;
2376        self.clamp_caret();
2377        self.record_caret();
2378    }
2379
2380    /// The Enter key.
2381    ///
2382    /// In source view it's a literal newline. In WYSIWYG it's **AST-aware**: a
2383    /// bare `\n` is only a markdown soft break (same paragraph), so the block the
2384    /// caret is in decides what actually gets written.
2385    ///
2386    ///   - paragraph            → twig's [`Editor::split_block`], which parts the
2387    ///                            block at the caret and reopens its container
2388    ///   - list item            → likewise: the next item, its indent, quote
2389    ///                            prefix and `[ ]` box all reproduced by twig —
2390    ///                            except an *empty* item, which exits the list
2391    ///   - block quote          → likewise: a new paragraph inside the quote
2392    ///   - heading              → a new *paragraph*, not another heading
2393    ///   - code block           → a literal newline (stay in the block)
2394    ///   - blank line           → a literal newline (one Backspace undoes it)
2395    ///   - [`LineFlow::Preserve`] → a single soft break, which renders as a
2396    ///                            visible line
2397    ///
2398    /// Where `split_block` is used it replaces markup leaf used to spell by hand,
2399    /// and it is better at it: it drops the whitespace the caret was sitting in
2400    /// front of instead of stranding it at the head of the second half, and it
2401    /// knows continuations leaf's marker scan never covered — a checklist item
2402    /// continues as an *unchecked* checklist item rather than a plain bullet.
2403    ///
2404    /// The exceptions above are exceptions because `split_block` is either wrong
2405    /// there or refuses: parting a fence yields two fences with the code split
2406    /// between them, parting a heading yields a second heading where every editor
2407    /// gives a paragraph, and a blank line, an empty item, a setext heading and a
2408    /// table all report an error rather than a split.
2409    pub fn newline(&mut self) {
2410        if self.view == View::Source {
2411            self.insert_raw("\n");
2412            return;
2413        }
2414        // Enter over a selection replaces it with a paragraph break.
2415        if let Some((s, e)) = self.selection() {
2416            self.splice(s, e, "\n\n", EditKind::Other);
2417            return;
2418        }
2419        // A caret resting exactly between an inline mark's content and its own
2420        // closing delimiter (`**bold**` with nothing after it on the line —
2421        // the WYSIWYG caret's natural end-of-line position) must not splice a
2422        // block break there: every path below eventually does via
2423        // `insert_raw`/`self.caret`, and splicing before the hidden closing
2424        // delimiter would strand it alone on the new line.
2425        self.caret = self.skip_trailing_close_delims(self.caret);
2426        // The block the caret is in. `block_offset_for_caret` nudges off a line
2427        // end (where the caret sits at the doc level); on a bare line (e.g. an
2428        // empty list item) fall back to the caret so the enclosing list/quote is
2429        // still visible in the ancestors.
2430        let off = self.block_offset_for_caret().unwrap_or(self.caret);
2431        let kinds: Vec<Kind> = self
2432            .editor
2433            .ancestors_at(off)
2434            .map(|c| c.into_iter().map(|m| m.kind).collect())
2435            .unwrap_or_default();
2436        let has = |k: Kind| kinds.contains(&k);
2437
2438        if has(Kind::CodeBlock) {
2439            self.insert_raw("\n");
2440            return;
2441        }
2442        // An *empty* list item exits the list — the standard double-Enter — which
2443        // `split_block` reports as an error rather than a split (there is no
2444        // content to part), so it stays leaf's. `list_marker_on_line` is itself
2445        // the AST gate — it answers from the tree, so a `- ` that reads as a
2446        // marker byte-for-byte but opens no item (a setext underline, a Djot
2447        // continuation line) never reaches here.
2448        if let Some(marker) = self.list_marker_on_line(self.caret)
2449            && self.item_is_empty(&marker)
2450        {
2451            self.exit_list(&marker);
2452            return;
2453        }
2454        // On an *empty* paragraph line, a lone Enter should add a single blank line,
2455        // not another full paragraph break — so it moves down one line and one
2456        // Backspace undoes it, not two. (`split_block` errors here too.)
2457        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
2458        let line_end = self.source[self.caret..]
2459            .find('\n')
2460            .map_or(self.source.len(), |i| self.caret + i);
2461        if self.source[line_start..line_end].trim().is_empty() {
2462            self.insert_raw("\n");
2463            return;
2464        }
2465        // In `Preserve` flow a soft break is a *visible* line the author means to
2466        // make, so Enter writes a single `\n` and typing continues the same
2467        // paragraph on the next line — the behaviour of an ordinary text editor.
2468        // A second Enter then lands on the blank line above and takes the
2469        // empty-line branch, so double-Enter still promotes to a full paragraph
2470        // break; and Backspace, which deletes a lone `\n` over a soft break,
2471        // undoes a single Enter symmetrically. In `Fold` flow a lone `\n` would
2472        // render as an invisible space, so Enter keeps making the paragraph break
2473        // that actually shows.
2474        //
2475        // Only in running prose. A list or a quote has a continuation of its own
2476        // to write, and a `\n` there is not a soft line but a lost container.
2477        let in_container = has(Kind::ListItem) || has(Kind::TaskListItem) || has(Kind::BlockQuote);
2478        if self.line_flow == LineFlow::Preserve && !in_container {
2479            self.insert_raw("\n");
2480            return;
2481        }
2482        // A heading gets a *paragraph*, never a second heading: Enter at the end
2483        // of a title is how every editor is asked for the body under it, and
2484        // `split_block` would repeat the `#` instead. Whitespace at the split
2485        // point goes with the break rather than opening the new paragraph, which
2486        // is what `split_block` does everywhere else.
2487        if has(Kind::Heading) {
2488            let mut end = self.caret;
2489            while self.source.as_bytes().get(end) == Some(&b' ') {
2490                end += 1;
2491            }
2492            self.splice(self.caret, end, "\n\n", EditKind::Other);
2493            return;
2494        }
2495        self.split_block_here();
2496    }
2497
2498    /// Part the block at the caret with twig's [`Editor::split_block`], leaving
2499    /// the caret in the second half.
2500    ///
2501    /// twig reopens whatever the first half was inside of — the bullet with its
2502    /// indent, the quote's `>`, a checklist item's `[ ]` — which is the whole
2503    /// reason this replaced the markup leaf used to spell from the line's bytes.
2504    /// It renumbers nothing, though: a new item mid-list is written with its
2505    /// neighbour's number, so [`renumber_here`](Self::renumber_here) still runs
2506    /// behind it, folded into the same undo step.
2507    ///
2508    /// Falls back to a plain paragraph break if twig declines, so an unhandled
2509    /// shape still moves the caret down rather than swallowing the keystroke.
2510    fn split_block_here(&mut self) {
2511        // The read-only gate — this door reaches twig without the splice.
2512        if self.read_only {
2513            return;
2514        }
2515        match self.editor.split_block(self.caret) {
2516            Ok(change) => {
2517                self.last_edit_kind = None;
2518                self.refresh();
2519                self.anchor = None;
2520                self.caret = change.new.end;
2521                self.dirty = self.source != self.clean_source;
2522                self.status = None;
2523                self.clamp_caret();
2524                self.record_caret();
2525                // Aimed at the new block's *start*: the caret twig leaves is one
2526                // past the marker it wrote, where there is no list in reach.
2527                self.renumber_at(change.new.start);
2528            }
2529            Err(_) => self.insert_raw("\n\n"),
2530        }
2531    }
2532
2533    /// Whether the item on the marker's line carries no content — the shape
2534    /// double-Enter reads as "I'm done with this list."
2535    fn item_is_empty(&self, line: &ListMarker) -> bool {
2536        let content_start = line.content_start().min(self.source.len());
2537        let line_end = self.source[self.caret..]
2538            .find('\n')
2539            .map(|i| self.caret + i)
2540            .unwrap_or(self.source.len());
2541        self.source[content_start..line_end.max(content_start)]
2542            .trim()
2543            .is_empty()
2544    }
2545
2546    /// Leave the list: replace the empty item's marker with a blank line, so the
2547    /// caret lands in a fresh paragraph below it.
2548    ///
2549    /// Inside a quote the blank line has to stay quoted (a bare one would end the
2550    /// quote), and the caret's new line keeps the `> ` it was already behind —
2551    /// leaving the list without also leaving the quote.
2552    fn exit_list(&mut self, line: &ListMarker) {
2553        let prefix = self.quote_prefix_at(line.marker_start);
2554        let blank = prefix.trim_end();
2555        self.splice(
2556            line.line_start,
2557            self.caret,
2558            &format!("{blank}\n{prefix}"),
2559            EditKind::Other,
2560        );
2561    }
2562
2563    /// What a line continuing the containers at `off` has to open with — the
2564    /// quote markers reproduced, each enclosing item's marker as its width in
2565    /// spaces. Also the column a nested item's marker stands in, which is what
2566    /// makes it Tab's answer.
2567    fn continuation_prefix_at(&mut self, off: usize) -> String {
2568        self.editor
2569            .document()
2570            .and_then(|mut d| d.continuation_prefix(off))
2571            .map(|p| p.text)
2572            .unwrap_or_default()
2573    }
2574
2575    /// The column a *nested list* may open at inside the item at `off` — which
2576    /// is not always where the item's own text continues.
2577    ///
2578    /// twig counts a task item's `[ ] ` box as part of its marker, correctly:
2579    /// it is markup a rich view hides, and the item's own wrapped text does
2580    /// stand past it. But a nested list may only open at the *list* marker's
2581    /// column, and four columns further in is an indented continuation of the
2582    /// paragraph instead — `- [ ] a` + `      - [ ] b` is one item, not two.
2583    /// So the box's own width goes back.
2584    ///
2585    /// The one place leaf still reads a checkbox's spelling. It goes when twig
2586    /// reports the list marker's column apart from the box; `checked` is what
2587    /// says a box is there at all, so only its width is being measured here.
2588    fn nesting_prefix_at(&mut self, off: usize) -> String {
2589        let cont = self.continuation_prefix_at(off);
2590        let Some(item) = self.innermost_list_item(off) else {
2591            return cont;
2592        };
2593        if item.checked.is_none() {
2594            return cont;
2595        }
2596        let box_width = item
2597            .marker_span
2598            .and_then(|m| self.source.get(m))
2599            .and_then(|marker| marker.rfind('[').map(|i| marker.len() - i))
2600            .unwrap_or(0);
2601        // The trailing columns are the ones the item's own marker contributed,
2602        // so trimming from the end leaves any quote prefix standing.
2603        cont[..cont.len().saturating_sub(box_width)].to_string()
2604    }
2605
2606    /// Where the line of the item *containing* the item at `off` begins — the
2607    /// prefix Shift+Tab moves back to, which gives up exactly the level the
2608    /// parent contributed. The quote prefix alone for a top-level item, which
2609    /// has no level left to give.
2610    fn outdent_prefix_at(&mut self, off: usize) -> String {
2611        let items: Vec<usize> = self
2612            .editor
2613            .document()
2614            .and_then(|mut d| d.ancestors_at_caret(off))
2615            .map(|c| {
2616                c.into_iter()
2617                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2618                    .map(|m| m.span.start)
2619                    .collect()
2620            })
2621            .unwrap_or_default();
2622        // The second-innermost item is the parent; its own line's indent is the
2623        // target. `list_marker_on_line` gives that line's prefix directly.
2624        let parent = items.len().checked_sub(2).map(|i| items[i]);
2625        match parent.and_then(|p| self.list_marker_on_line(p)) {
2626            Some(m) => self.source[m.line_start..m.marker_start].to_string(),
2627            None => self.quote_prefix_at(off),
2628        }
2629    }
2630
2631    /// The block-quote prefix in force at `off` — `""` outside a quote, `"> "`
2632    /// inside one, `"> > "` inside two.
2633    ///
2634    /// Assembled from each enclosing quote's own [`FlatNode::marker_span`], so
2635    /// the `>` and the space after it are twig's spelling rather than leaf's.
2636    /// The whole line prefix can't answer this: it also carries the indent of
2637    /// whatever the quote holds, which a blank separator line must *not* repeat.
2638    fn quote_prefix_at(&mut self, off: usize) -> String {
2639        let Ok(chain) = self
2640            .editor
2641            .document()
2642            .and_then(|mut d| d.ancestors_at_caret(off))
2643        else {
2644            return String::new();
2645        };
2646        let quotes: Vec<usize> = chain
2647            .iter()
2648            .filter(|m| m.kind == Kind::BlockQuote)
2649            .map(|m| m.node_id as usize)
2650            .collect();
2651        let Ok(nodes) = self.editor.nodes() else {
2652            return String::new();
2653        };
2654        quotes
2655            .iter()
2656            .filter_map(|id| nodes.get(*id)?.marker_span.clone())
2657            .filter_map(|s| self.source.get(s))
2658            .collect()
2659    }
2660
2661    /// Whether the item at `off` sits inside another one — the test Backspace
2662    /// uses to choose between outdenting and dropping the marker.
2663    ///
2664    /// Counted from the AST rather than from the line's leading whitespace,
2665    /// which is indentation in Markdown and, in Djot, may be nothing at all.
2666    fn item_is_nested(&mut self, off: usize) -> bool {
2667        self.editor
2668            .document()
2669            .and_then(|mut d| d.ancestors_at_caret(off))
2670            .map(|c| {
2671                c.into_iter()
2672                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2673                    .count()
2674                    > 1
2675            })
2676            .unwrap_or(false)
2677    }
2678
2679    /// The innermost list item containing `probe`, under twig's **caret**
2680    /// containment rule — a block's end is inside it.
2681    ///
2682    /// Half-open containment can't answer this. An empty item's span is exactly
2683    /// its marker, so the caret sitting after `- ` is one past the end and the
2684    /// item it is plainly in tests as out of reach; that is the shape
2685    /// double-Enter has to recognise to leave the list.
2686    fn innermost_list_item(&mut self, probe: usize) -> Option<FlatNode> {
2687        let chain = self
2688            .editor
2689            .document()
2690            .and_then(|mut d| d.ancestors_at_caret(probe))
2691            .ok()?;
2692        let id = chain
2693            .iter()
2694            .rev()
2695            .find(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)?
2696            .node_id as usize;
2697        self.editor.nodes().ok()?.get(id).cloned()
2698    }
2699
2700    /// The list marker opening `off`'s line, per twig — `None` when that line
2701    /// opens no list item.
2702    ///
2703    /// [`Document::line_prefix`] is the whole hidden run from the line start:
2704    /// `>   1. ` is a quote's marker, an indent, and an item's marker together,
2705    /// and it is `None` on a *continuation* line, which opens nothing. That last
2706    /// case is the one leaf could never get right by reading bytes. `- a\n  - b`
2707    /// is two items in Markdown and one in Djot, where a marker cannot interrupt
2708    /// a paragraph and `  - b` is literal text — identical bytes, and only the
2709    /// parser knows which document it is looking at.
2710    ///
2711    /// The item's own marker is separated out via its
2712    /// [`FlatNode::marker_span`], so `marker_start` splits the prefix into what
2713    /// the containers around it contribute and what the item does.
2714    fn list_marker_on_line(&mut self, off: usize) -> Option<ListMarker> {
2715        let off = off.min(self.source.len());
2716        let prefix = self.editor.document().ok()?.line_prefix(off).ok()??;
2717        // The prefix belongs to a list only when an item's marker closes it —
2718        // a heading's `# ` or a bare quote's `> ` is a prefix too.
2719        let item = self.innermost_list_item(prefix.end.min(self.source.len()))?;
2720        let marker = item.marker_span.clone()?;
2721        if marker.end != prefix.end {
2722            return None;
2723        }
2724        Some(ListMarker {
2725            line_start: prefix.start,
2726            marker_start: marker.start,
2727            text: self.source.get(prefix)?.to_string(),
2728        })
2729    }
2730
2731    /// Whether the list item on `line_start`'s line is the **first item** of its
2732    /// list — the one Tab must not nest, because nesting needs a preceding
2733    /// sibling to become the new parent and a first item has none. `false` for a
2734    /// line that isn't a list item, and for an item with a sibling above it (the
2735    /// one Tab *can* nest). Gated on the AST, not the marker bytes: `- ` reads
2736    /// the same in a setext underline that opens no list at all.
2737    fn first_item_of_list(&mut self, line_start: usize) -> bool {
2738        let Some(marker) = self.list_marker_on_line(line_start) else {
2739            return false;
2740        };
2741        // Probe just inside the marker, where the item's own node is in reach —
2742        // the marker offset itself can resolve to the enclosing list, not the
2743        // `list_item`, whose span starts at the marker.
2744        let probe = marker.content_start().min(self.source.len());
2745        let Some(item) = self.innermost_list_item(probe) else {
2746            return false;
2747        };
2748        let Ok(nodes) = self.editor.nodes() else {
2749            return false;
2750        };
2751        match item.parent {
2752            // First when the parent list opens with this very item.
2753            Some(pid) => nodes
2754                .get(pid.0 as usize)
2755                .is_some_and(|p| p.first_child == Some(item.id)),
2756            // A parentless item is trivially the first (and only) one.
2757            None => true,
2758        }
2759    }
2760
2761    pub fn backspace(&mut self) {
2762        if let Some((s, e)) = self.selection() {
2763            self.splice(s, e, "", EditKind::Other);
2764            return;
2765        }
2766        // WYSIWYG: Backspace at the very start of a list item's content is a
2767        // structural key, not a character delete — it walks the "un-indent, then
2768        // un-list" ladder every list editor gives that keystroke (outdent a
2769        // nested item, strip a top-level one's marker to a paragraph). In source
2770        // view the `- ` is visible text the user is deleting a byte of, so it
2771        // keeps its literal meaning there, like Enter does.
2772        if self.view != View::Source && self.backspace_list_start() {
2773            return;
2774        }
2775        // WYSIWYG: and the same at the start of a heading's content — the `# `
2776        // there is markup the rich view hides, not text the user typed.
2777        if self.view != View::Source && self.backspace_heading_start() {
2778            return;
2779        }
2780        // WYSIWYG: at a block picture's stops, a byte-at-a-time delete would take
2781        // the markup apart under a caret that cannot see it — see
2782        // `delete_around_block_media`.
2783        if self.view != View::Source && self.delete_around_block_media(false) {
2784            return;
2785        }
2786        // WYSIWYG: Backspace on a *blank line* deletes back to the previous caret
2787        // stop, not a single newline. On a line with no text of its own, the byte
2788        // before the caret is a `\n` that spells part of a block boundary — the gap
2789        // between two blocks, drawn but never a caret home. Removing just it strands
2790        // the caret in that gap and leaves an odd blank line the eye reads as one
2791        // separator but the caret can't land on: the "extra newline" left behind
2792        // after leaving a list (Enter, Enter) or a paragraph and pressing Backspace.
2793        // Deleting to the previous stop instead collapses the whole break at once,
2794        // landing the caret at the end of the block above. Two blank lines in a row
2795        // are one stop apart, so this still removes exactly one — the lone-Enter /
2796        // lone-Backspace symmetry the empty-line case is built on is untouched.
2797        if self.view != View::Source
2798            && self.caret > self.caret_floor()
2799            && self.caret_on_blank_line()
2800            && let Some(stop) = self.vmap.stop_before(self.caret)
2801        {
2802            let stop = stop.max(self.caret_floor());
2803            if stop < self.caret {
2804                self.splice(stop, self.caret, "", EditKind::Delete);
2805                return;
2806            }
2807        }
2808        if self.caret > self.caret_floor() {
2809            // An in-cell `<br>` draws as one newline glyph, so Backspace over it
2810            // takes the whole tag — a single-byte step would leave a broken `<br`
2811            // showing in the cell. Rich view only (source view edits the literal).
2812            if self.view != View::Source
2813                && let Some((start, end)) = self.cell_break_at(BreakEdge::Backward)
2814            {
2815                let start = start.max(self.caret_floor());
2816                if start < end {
2817                    self.splice(start, end, "", EditKind::Delete);
2818                    return;
2819                }
2820            }
2821            // Aim the delete at the character the writer can *see* behind the
2822            // caret, never at a delimiter the rich view drew nothing for. Two
2823            // steps, and either can apply: from the far side of a run's closing
2824            // `**` step back into the run (the caret is drawn at the end of its
2825            // word), and at the start of a run's text step out past its opening
2826            // `**` to the character in front of it, leaving the run standing.
2827            // Without them a plain Backspace unspells the phrase it is editing
2828            // and leaves a literal asterisk on screen.
2829            let end = if self.view == View::Source {
2830                self.caret
2831            } else {
2832                let inside = self.step_inside_close_delims(self.caret);
2833                self.skip_leading_open_delims(inside)
2834                    .max(self.caret_floor())
2835            };
2836            // Never delete back across the floor — that would eat hidden
2837            // frontmatter the WYSIWYG caret can't even see.
2838            let mut prev = prev_boundary(&self.source, end).max(self.caret_floor());
2839            // Take a hidden escape backslash with the char it escapes: the rich
2840            // view draws `\*` as a single `*`, so Backspace over it must delete
2841            // both bytes, never strand the `\` as a lone visible backslash (the
2842            // mirror of the Hidden-mode typing that wrote the escape). Source view
2843            // shows the `\`, so there it is an ordinary character.
2844            if self.view != View::Source
2845                && prev > self.caret_floor()
2846                && self.is_hidden_escape(prev - 1)
2847            {
2848                prev -= 1;
2849            }
2850            if prev < end {
2851                self.splice(prev, end, "", EditKind::Delete);
2852            }
2853        }
2854    }
2855
2856    /// Whether the caret's own source line holds nothing but whitespace — an
2857    /// empty paragraph, or the blank line a block boundary is spelled with. The
2858    /// test for [`backspace`](Self::backspace)'s stop-wise delete: such a line has
2859    /// no text of its own, so the newline before the caret belongs to the gap
2860    /// between blocks rather than to any word the caret is editing.
2861    fn caret_on_blank_line(&self) -> bool {
2862        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
2863        let line_end = self.source[self.caret..]
2864            .find('\n')
2865            .map_or(self.source.len(), |i| self.caret + i);
2866        self.source[line_start..line_end].trim().is_empty()
2867    }
2868
2869    /// The source span of an in-cell hard break (`<br>`) touching the caret on the
2870    /// `edge` side — the byte range to delete whole. A table row is one source
2871    /// line, so its break is spelled `<br>` yet drawn as a single newline glyph
2872    /// (see `wysiwyg.rs`); a delete over it must take every byte, or a one-byte
2873    /// step strands a broken `<br` in the cell. `Backward` matches a break ending
2874    /// at the caret (Backspace), `Forward` one starting at it (Delete). `None`
2875    /// when no such break is adjacent. Only the in-cell break is spelled `<br>`
2876    /// (an ordinary hard break is `  \n`), so the leading `<` alone tells them
2877    /// apart — no ancestor walk needed. Rich view only; source view shows the
2878    /// literal tag and deletes it a byte at a time.
2879    fn cell_break_at(&mut self, edge: BreakEdge) -> Option<(usize, usize)> {
2880        let caret = self.caret;
2881        let nodes = self.nodes();
2882        let src = self.source.as_bytes();
2883        nodes
2884            .iter()
2885            .find(|n| {
2886                n.kind == Kind::HardBreak
2887                    && n.span.start < n.span.end
2888                    && src.get(n.span.start) == Some(&b'<')
2889                    && match edge {
2890                        BreakEdge::Backward => n.span.end == caret,
2891                        BreakEdge::Forward => n.span.start == caret,
2892                    }
2893            })
2894            .map(|n| (n.span.start, n.span.end))
2895    }
2896
2897    /// Whether the source byte at `off` is a backslash twig consumed as an escape
2898    /// (hidden in the rich view), as against a literal backslash (drawn). A
2899    /// backslash escapes exactly an ASCII-punctuation character (the CommonMark /
2900    /// Djot rule twig follows), so `\` + punctuation is the whole test — no AST
2901    /// round-trip needed.
2902    fn is_hidden_escape(&self, off: usize) -> bool {
2903        let b = self.source.as_bytes();
2904        b.get(off) == Some(&b'\\') && b.get(off + 1).is_some_and(u8::is_ascii_punctuation)
2905    }
2906
2907    /// Backspace's list behaviour: when the caret sits exactly at the start of a
2908    /// list item's content (right after its marker), outdent the item if it's
2909    /// nested, else strip the marker so it becomes a paragraph. Returns whether
2910    /// it acted — `false` leaves Backspace its ordinary character delete.
2911    fn backspace_list_start(&mut self) -> bool {
2912        let Some(marker) = self.list_marker_on_line(self.caret) else {
2913            return false;
2914        };
2915        // Only right after the marker. That the line opens a real item is
2916        // already settled: `list_marker_on_line` answers from the tree.
2917        if self.caret != marker.content_start() {
2918            return false;
2919        }
2920        if self.item_is_nested(marker.marker_start) {
2921            // Nested: give back one level, keeping the marker and carrying the
2922            // caret with it.
2923            self.outdent();
2924        } else {
2925            // Top level: drop the marker, leaving a paragraph, then renumber the
2926            // siblings the removed item was counted among. Only the marker goes —
2927            // a quote prefix in front of it still has a quote to hold up.
2928            self.splice(marker.marker_start, self.caret, "", EditKind::Other);
2929            self.renumber_here();
2930        }
2931        true
2932    }
2933
2934    /// Backspace's heading behaviour: with the caret exactly at the start of an
2935    /// ATX heading's content — right after the `#` marker the rich view hides —
2936    /// strip the marker so the line becomes a paragraph. The peer of
2937    /// [`backspace_list_start`](Self::backspace_list_start)'s ladder, and the same
2938    /// reasoning: hidden block markup is structure, so the keystroke over it is
2939    /// structural.
2940    ///
2941    /// Without this the ordinary delete takes the space out of `# Title` and
2942    /// leaves `#Title`, which is no longer a heading at all — the hash the view
2943    /// had been hiding surfaces as literal text the user has to delete a second
2944    /// time, having never typed it. A closing sequence (`# Title #`, hidden at the
2945    /// other end) goes with the marker for the same reason.
2946    ///
2947    /// Returns whether it acted; `false` leaves Backspace its character delete.
2948    fn backspace_heading_start(&mut self) -> bool {
2949        let caret = self.caret;
2950        // The heading whose content opens exactly at the caret. A bare `#` has no
2951        // content span at all — its content starts (and ends) where the line does.
2952        let Some((span, content_end, marker)) = self.nodes().iter().find_map(|n| {
2953            let (start, end) = match &n.content_span {
2954                Some(c) => (c.start, c.end),
2955                None => (n.span.end, n.span.end),
2956            };
2957            (n.kind == Kind::Heading && start == caret)
2958                .then(|| (n.span.clone(), end, n.marker_span.clone()))
2959        }) else {
2960            return false;
2961        };
2962        // twig reports the marker's own extent, so there is nothing to walk back
2963        // over and no `#` in this file. A setext heading has no marker — its
2964        // content opens the line — so it falls through to the ordinary delete,
2965        // as does anything else sitting at a content start.
2966        // `m.end == caret` is what excludes a setext heading, whose marker is the
2967        // underline *after* the content rather than a prefix before it.
2968        let Some(marker) = marker.filter(|m| m.end == caret) else {
2969            return false;
2970        };
2971        let start = marker.start;
2972        // A closing `#` sequence is hidden too, so it can't be left behind. Only
2973        // when the tail really is one: trailing spaces alone are nothing to strip.
2974        let tail = &self.source[content_end..span.end];
2975        if tail.contains('#') && tail.chars().all(|c| c == '#' || c.is_whitespace()) {
2976            let kept = self.source[caret..content_end].to_string();
2977            self.splice(start, span.end, &kept, EditKind::Other);
2978            // The splice leaves the caret past the text it re-wrote; the caret
2979            // belongs where the content now starts, which is where it already was.
2980            self.caret = start;
2981            self.record_caret();
2982        } else {
2983            self.splice(start, caret, "", EditKind::Other);
2984        }
2985        true
2986    }
2987
2988    pub fn delete_forward(&mut self) {
2989        if let Some((s, e)) = self.selection() {
2990            self.splice(s, e, "", EditKind::Other);
2991        } else if self.caret < self.source.len() {
2992            // The mirror of Backspace's: forward-delete in front of a picture
2993            // would eat the `!` off its markup and leave a link where a photo was.
2994            if self.view != View::Source && self.delete_around_block_media(true) {
2995                return;
2996            }
2997            // Delete forward over an in-cell `<br>` takes the whole tag, the mirror
2998            // of Backspace's swallow (see `cell_break_at`) — else a byte-step
2999            // strands a broken `<br` in the cell.
3000            if self.view != View::Source
3001                && let Some((start, end)) = self.cell_break_at(BreakEdge::Forward)
3002            {
3003                self.splice(start, end, "", EditKind::Delete);
3004                return;
3005            }
3006            // The mirror of Backspace's two steps: from in front of a run's
3007            // opening `**` step into it, onto the first letter of its text, and
3008            // at the end of a run's text step out past its closing `**` to the
3009            // character beyond. Either way Delete takes the character it looks
3010            // like it is pointing at, and never a delimiter drawn as nothing.
3011            // The caret then settles back inside the run it was standing in —
3012            // see `settle_inside_close_delims`.
3013            let from = if self.view == View::Source {
3014                self.caret
3015            } else {
3016                let inside = self.step_inside_open_delims(self.caret);
3017                self.skip_trailing_close_delims(inside)
3018            };
3019            let next = next_boundary(&self.source, from);
3020            if from < next {
3021                self.splice(from, next, "", EditKind::Delete);
3022            }
3023        }
3024    }
3025
3026    /// Delete from the caret back to the start of the previous word (⌥⌫ /
3027    /// Ctrl+⌫). Deletes the selection instead when one is active.
3028    pub fn delete_word_back(&mut self) {
3029        if let Some((s, e)) = self.selection() {
3030            self.splice(s, e, "", EditKind::Other);
3031        } else {
3032            // A word back from just past a picture is a word *of its markup*, and
3033            // a word back from in front of one runs through the paragraph break
3034            // into the prose above — dissolving the picture either way. See
3035            // `delete_around_block_media`.
3036            if self.view != View::Source && self.delete_around_block_media(false) {
3037                return;
3038            }
3039            let start = self.word_left_from(self.caret).max(self.caret_floor());
3040            if start < self.caret {
3041                let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3042                self.splice(s, e, "", EditKind::Delete);
3043            }
3044        }
3045    }
3046
3047    /// Delete from the caret forward to the end of the next word (⌥⌦ /
3048    /// Ctrl+Del). Deletes the selection instead when one is active.
3049    pub fn delete_word_forward(&mut self) {
3050        if let Some((s, e)) = self.selection() {
3051            self.splice(s, e, "", EditKind::Other);
3052        } else {
3053            // The mirror: a word forward from in front of a picture is its markup.
3054            if self.view != View::Source && self.delete_around_block_media(true) {
3055                return;
3056            }
3057            let end = self.word_right_from(self.caret);
3058            if end > self.caret {
3059                let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3060                self.splice(s, e, "", EditKind::Delete);
3061            }
3062        }
3063    }
3064
3065    /// Delete from the caret back to the start of its line (⌘⌫). Deletes the
3066    /// selection instead when one is active, as every other delete here does.
3067    ///
3068    /// The line is the view's own — the one Home and End work on, so in WYSIWYG
3069    /// a soft-wrapped row is a line. It is not Home's *target*, though: Home
3070    /// stops at the first character and this takes the indentation with it, the
3071    /// way Cocoa's `deleteToBeginningOfLine:` does. Stopping at the text would
3072    /// leave an indent behind that nothing can then ask to delete, where a caret
3073    /// left at column 0 is one press of Home away from either.
3074    pub fn delete_to_line_start(&mut self) {
3075        if let Some((s, e)) = self.selection() {
3076            self.splice(s, e, "", EditKind::Other);
3077            return;
3078        }
3079        // Never back across the floor: hidden frontmatter isn't on this line, or
3080        // on any line the WYSIWYG caret can see.
3081        let (start, _) = self.line_span();
3082        let start = start.max(self.caret_floor());
3083        if start < self.caret {
3084            let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3085            self.splice(s, e, "", EditKind::Delete);
3086        }
3087    }
3088
3089    /// Kill from the caret to the end of its line (^K). Deletes the selection
3090    /// instead when one is active.
3091    ///
3092    /// At the end of the line it does nothing, rather than pulling the line
3093    /// below up into this one. Joining has no meaning to give it in both views
3094    /// at once: a WYSIWYG line ends at a soft wrap as often as at a newline, and
3095    /// there is nothing there to delete, while the newline a *source* line ends
3096    /// with is only half of the blank line that separates two paragraphs —
3097    /// deleting one leaves a soft break, which is not the join it looks like.
3098    /// The views agreeing is worth more than emacs' second press, and Delete is
3099    /// already the key that joins.
3100    pub fn delete_to_line_end(&mut self) {
3101        if let Some((s, e)) = self.selection() {
3102            self.splice(s, e, "", EditKind::Other);
3103            return;
3104        }
3105        let (_, end) = self.line_span();
3106        if end > self.caret {
3107            let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3108            self.splice(s, e, "", EditKind::Delete);
3109        }
3110    }
3111
3112    /// Grow a WYSIWYG word-delete to swallow any inline node it empties.
3113    ///
3114    /// A glyph-space range covers what the user can see, which for `**bold**` is
3115    /// the word and never the delimiters around it — so deleting the word on its
3116    /// own leaves `a **** c`, markup wrapped around nothing. They asked for the
3117    /// word, and the styling was the word's; the two go together. Only the
3118    /// node's delimiters are taken, and those are hidden here anyway, so nothing
3119    /// visible outside the range is lost.
3120    ///
3121    /// Repeated to a fixed point: emptying `***bold***` empties the emph inside
3122    /// the strong, and only then is the strong empty too.
3123    fn widen_over_emptied_inlines(&mut self, start: usize, end: usize) -> (usize, usize) {
3124        if self.view == View::Source {
3125            return (start, end);
3126        }
3127        let nodes = self.nodes();
3128        let (mut s, mut e) = (start, end);
3129        loop {
3130            let mut grew = false;
3131            for n in nodes.iter().filter(|n| wysiwyg::is_inline(n)) {
3132                let Some(text) = inline_content_span(n, &self.source) else {
3133                    continue;
3134                };
3135                // Some of its text survives, so the node still has a job.
3136                if text.start < s || text.end > e {
3137                    continue;
3138                }
3139                if n.span.start < s || n.span.end > e {
3140                    s = s.min(n.span.start);
3141                    e = e.max(n.span.end);
3142                    grew = true;
3143                }
3144            }
3145            if !grew {
3146                return (s, e);
3147            }
3148        }
3149    }
3150
3151    /// One splice of document text, keeping the **mark-edge rule**: an inline
3152    /// mark's content never begins or ends with whitespace. In Markdown and Djot
3153    /// a delimiter standing against a space is not a delimiter at all — `**bold **`
3154    /// is four literal asterisks around a word, and a rich view drawing the
3155    /// document faithfully has no choice but to show them. That is correct
3156    /// rendering of what the file says, and nobody typing a space after a bold
3157    /// word meant to say it.
3158    ///
3159    /// So the space goes *outside* the run instead — `**bold** ` — which is the
3160    /// same document to a reader and a live one to a parser. The caret follows it
3161    /// out and keeps the marks armed (see [`rearm`](Self::rearm)), so the next
3162    /// character rejoins the run (see [`rejoin_run`](Self::rejoin_run)) and the
3163    /// writer sees one unbroken bold phrase, never a flash of raw syntax.
3164    ///
3165    /// Every ordinary edit — typing, deleting, pasting, an IME step — comes
3166    /// through here, so the rule holds however the whitespace arrives at the
3167    /// edge. The repair is decided *after* the plain edit, by asking whether the
3168    /// mark actually died: a code span's backticks aren't whitespace-sensitive
3169    /// (`` `code ` `` is still code), and nothing is re-spelled when nothing broke.
3170    fn splice(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3171        let fix = self.mark_edge_fix(start, end, text);
3172        if !self.splice_exact(start, end, text, kind) {
3173            return false;
3174        }
3175        if let Some(fix) = fix {
3176            self.repair_mark_edges(fix);
3177        }
3178        if text.is_empty() && end > start {
3179            self.settle_inside_close_delims();
3180        }
3181        true
3182    }
3183
3184    /// After a delete, take a caret left standing past a run's closing delimiters
3185    /// back inside the run.
3186    ///
3187    /// A delete leaves the caret where the deleted bytes began, and when those
3188    /// bytes were the last thing after a marked phrase — the space the mark-edge
3189    /// rule pushed out of `**bold** `, say — that spot is the far side of the
3190    /// closing `**`. The rich view has nothing to draw there: the delimiters are
3191    /// hidden, so the caret shows at the end of the word either way, and the two
3192    /// offsets are one place on screen with two different meanings. Typing at the
3193    /// outer one lands past the run, so the writer who backspaced a space out of
3194    /// their bold phrase watches the next character come out plain, and the
3195    /// toolbar button go dark, with the caret never appearing to move.
3196    ///
3197    /// The end of the run's text is the caret's home there — a delete that took
3198    /// away everything after a phrase leaves the caret at the end of that phrase,
3199    /// which is inside it — so it settles onto that
3200    /// ([`step_inside_close_delims`](Self::step_inside_close_delims) does the
3201    /// walk, through every mark closing at the point): the word stays bold, the
3202    /// button stays lit, and the next character carries on the phrase.
3203    ///
3204    /// Rich view only, and only where a mark really closes at the caret — mid-run
3205    /// or in plain prose no span ends there and the caret stays put. The opening
3206    /// edge is left alone on purpose: a caret in front of a run inherits from the
3207    /// text on its left, which is the plain text outside.
3208    fn settle_inside_close_delims(&mut self) {
3209        if self.view != View::Wysiwyg {
3210            return;
3211        }
3212        let at = self.step_inside_close_delims(self.caret);
3213        if at != self.caret {
3214            self.caret = at;
3215            self.clear_pending();
3216            self.record_caret();
3217        }
3218    }
3219
3220    /// The splice exactly as asked, with no mark-edge repair — for the callers
3221    /// that are *writing* the delimiters themselves ([`insert_with_marks`](Self::insert_with_marks)
3222    /// and [`rejoin_run`](Self::rejoin_run)) and place their own offsets around
3223    /// the bytes they inserted.
3224    ///
3225    /// One `edit_range` through twig, then re-anchor the caret from the returned
3226    /// `Change` and refresh the cached source. A reparse-breaking edit (rare for
3227    /// Markdown/Djot) leaves the document untouched and reports.
3228    ///
3229    /// Returns whether the edit landed — for a caller that has offsets of its
3230    /// own to place afterwards, which a rolled-back splice would leave pointing
3231    /// into text that never came to exist.
3232    fn splice_exact(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3233        // The read-only gate, for every edit at once — see the field.
3234        if self.read_only {
3235            return false;
3236        }
3237        // twig records an undo step for every edit; when this one continues a
3238        // run of the same kind (typing, deleting), tell twig to fold it into the
3239        // step before it so the whole run undoes at once.
3240        let coalesce = kind != EditKind::Other && self.last_edit_kind == Some(kind);
3241        // Hand twig the pre-edit caret before the splice, so the undo step it
3242        // retires carries where the caret was standing.
3243        self.record_caret();
3244        match self.editor.edit_range(start, end, text) {
3245            Ok(change) => {
3246                if coalesce {
3247                    let _ = self.editor.coalesce_last_undo();
3248                }
3249                self.last_edit_kind = Some(kind);
3250                self.refresh();
3251                self.caret = change.new.end;
3252                self.anchor = None;
3253                self.goal_col = None;
3254                self.clear_pending();
3255                self.dirty = self.source != self.clean_source;
3256                self.status = None;
3257                // And the post-edit caret, so a later redo restores it.
3258                self.record_caret();
3259                true
3260            }
3261            // The edit was rolled back, so twig's history did not move and
3262            // neither may ours: pushing here would leave a step with no edit
3263            // under it and shift every later undo onto the wrong caret.
3264            Err(e) => {
3265                self.status = Some(format!("edit: {e}"));
3266                false
3267            }
3268        }
3269    }
3270
3271    /// The re-spelling that would keep the mark-edge rule for the edit
3272    /// `[start, end)` → `text`, or `None` when the edit leaves no whitespace
3273    /// against a delimiter and the plain splice is already right. Computed
3274    /// *before* the edit, while the run's spans and delimiters can still be read
3275    /// off the document; applied afterwards, and only if the mark really died —
3276    /// see [`repair_mark_edges`](Self::repair_mark_edges).
3277    ///
3278    /// Rich view only. Source view is for typing raw markup, where a space put
3279    /// against a `**` is exactly the character it looks like.
3280    fn mark_edge_fix(&mut self, start: usize, end: usize, text: &str) -> Option<MarkEdgeFix> {
3281        if self.view != View::Wysiwyg || start > end || end > self.source.len() {
3282            return None;
3283        }
3284        // Every inline mark standing over the edit, outermost first, with the
3285        // content span that says where its delimiters are.
3286        let chain: Vec<(InlineKind, std::ops::Range<usize>, std::ops::Range<usize>)> = self
3287            .editor
3288            .ancestors_at(start)
3289            .unwrap_or_default()
3290            .into_iter()
3291            .filter_map(|m| {
3292                let kind = inline_kind(&m.kind)?;
3293                let content = m.content_span.clone()?;
3294                Some((kind, m.span.clone(), content))
3295            })
3296            .collect();
3297        // The innermost run whose *content* holds the whole edit: the one whose
3298        // text is being changed, rather than one the edit merely sits under.
3299        let (kind, span, content) = chain
3300            .iter()
3301            .rev()
3302            .find(|(_, _, c)| c.start <= start && end <= c.end)?
3303            .clone();
3304        // What that content becomes. Whitespace at either end of it is what
3305        // would put out the mark.
3306        let body = format!(
3307            "{}{text}{}",
3308            &self.source[content.start..start],
3309            &self.source[end..content.end]
3310        );
3311        let (lead, trail) = if body.trim().is_empty() {
3312            // Nothing but whitespace left: there is no content to mark at all,
3313            // and the delimiters go with it rather than closing on a space.
3314            (body.len(), 0)
3315        } else {
3316            (
3317                body.len() - body.trim_start().len(),
3318                body.len() - body.trim_end().len(),
3319            )
3320        };
3321        // Nothing against a delimiter, and something still between them: the
3322        // plain edit stands. An emptied run is broken just as surely (`**b**`
3323        // with the `b` deleted is the literal `****`) and is re-spelt as the
3324        // nothing it now says.
3325        if lead == 0 && trail == 0 && !body.is_empty() {
3326            return None;
3327        }
3328        // Marks that open or close exactly where this one does — `***both***` is
3329        // two runs sharing an edge — spell their delimiters as one run of bytes,
3330        // so the whitespace has to clear all of them together.
3331        let (mut open_at, mut close_at) = (span.start, span.end);
3332        for _ in 0..chain.len() {
3333            match chain.iter().find(|(_, _, c)| c.start == open_at) {
3334                Some((_, s, _)) => open_at = s.start,
3335                None => break,
3336            }
3337        }
3338        for _ in 0..chain.len() {
3339            match chain.iter().find(|(_, _, c)| c.end == close_at) {
3340                Some((_, s, _)) => close_at = s.end,
3341                None => break,
3342            }
3343        }
3344        let open = &self.source[open_at..content.start];
3345        let close = &self.source[content.end..close_at];
3346        let core = &body[lead..body.len() - trail];
3347        let respelt = if core.is_empty() {
3348            body.clone()
3349        } else {
3350            format!(
3351                "{}{open}{core}{close}{}",
3352                &body[..lead],
3353                &body[body.len() - trail..]
3354            )
3355        };
3356        // The caret sits just past the inserted text within the new content —
3357        // which, when that lands in the whitespace, is now outside the delimiters.
3358        let pos = (start - content.start) + text.len();
3359        let caret = if core.is_empty() || pos <= lead {
3360            open_at + pos
3361        } else if pos >= lead + core.len() {
3362            open_at + lead + open.len() + core.len() + close.len() + (pos - lead - core.len())
3363        } else {
3364            open_at + lead + open.len() + (pos - lead)
3365        };
3366        Some(MarkEdgeFix {
3367            kind,
3368            probe: content.start,
3369            start: open_at,
3370            end: close_at + text.len() - (end - start),
3371            text: respelt,
3372            caret,
3373            // The marks in force here, resolved against any armed sticky delta —
3374            // what the writer is typing in, and so what has to still be true on
3375            // the far side of the delimiter the caret just stepped over.
3376            want: chain
3377                .iter()
3378                .filter(|(_, s, _)| start < s.end)
3379                .map(|(k, _, _)| *k)
3380                .collect::<InlineMarks>()
3381                .xor(self.pending_here()),
3382        })
3383    }
3384
3385    /// Apply a [`MarkEdgeFix`] — but only if the edit it was computed for really
3386    /// did break the mark. Whether whitespace at a delimiter is fatal is the
3387    /// format's business, not leaf's: `**bold **` is no longer strong, while
3388    /// `` `code ` `` is still perfectly good verbatim, and Djot's braced spellings
3389    /// don't care either. Asking the parser afterwards settles it for every kind
3390    /// and format at once, and costs a re-spelling only where one is due.
3391    ///
3392    /// The repair rides along with the edit that caused it — one undo step puts
3393    /// back what the writer typed, not a delimiter shuffle they never saw.
3394    fn repair_mark_edges(&mut self, fix: MarkEdgeFix) {
3395        if fix.end > self.source.len() {
3396            return;
3397        }
3398        if self.marks_at(fix.probe).iter().any(|(k, _)| *k == fix.kind) {
3399            return; // still a mark: these delimiters don't mind the whitespace
3400        }
3401        let resumed = self.last_edit_kind;
3402        if !self.splice_exact(fix.start, fix.end, &fix.text, EditKind::Other) {
3403            return;
3404        }
3405        let _ = self.editor.coalesce_last_undo();
3406        // The keystroke owns the undo step, so the run of typing it belongs to
3407        // keeps coalescing over the repair rather than breaking in two here.
3408        self.last_edit_kind = resumed;
3409        self.caret = fix.caret.min(self.source.len());
3410        self.anchor = None;
3411        self.goal_col = None;
3412        self.rearm(fix.want);
3413        self.clamp_caret();
3414        self.record_caret();
3415    }
3416
3417    /// Arm whatever sticky delta reproduces `want` at the caret — the marks the
3418    /// writer is typing in, carried across an edit that moved the caret out of
3419    /// the run holding them. Arms nothing when the caret already stands in
3420    /// exactly those marks, but still remembers the spot, so a further ⌘b starts
3421    /// a clean delta here (see [`toggle`](Self::toggle)).
3422    fn rearm(&mut self, want: InlineMarks) {
3423        let here: InlineMarks = self
3424            .marks_at(self.caret)
3425            .into_iter()
3426            .map(|(k, _)| k)
3427            .collect();
3428        self.pending_marks = want.xor(here);
3429        self.pending_at = Some(self.caret);
3430    }
3431
3432    /// Insert `text` at `at` as a *literal* run via twig's `insert_literal`,
3433    /// which backslash-escapes any character that would otherwise open markup in
3434    /// this format and position (`*` → `\*`, a line-start `#` → `\#`). The mirror
3435    /// of [`splice`](Self::splice) for the Hidden reveal mode's typing path, with
3436    /// the same caret re-anchor, coalescing, and rollback contract. `at` must be
3437    /// a collapsed point — a selection is deleted by the caller first, since
3438    /// `insert_literal` inserts rather than replaces.
3439    fn insert_literal_at(
3440        &mut self,
3441        at: usize,
3442        text: &str,
3443        kind: EditKind,
3444        force_coalesce: bool,
3445    ) -> bool {
3446        // The read-only gate: this door goes to twig directly, not through
3447        // `splice_exact`, so it guards itself — see the field.
3448        if self.read_only {
3449            return false;
3450        }
3451        // `force_coalesce` folds this into the immediately preceding edit (the
3452        // selection-delete of an overwrite) so the pair is one undo step; else it
3453        // coalesces only when it continues a run of the same-kind typing.
3454        let coalesce =
3455            force_coalesce || (kind != EditKind::Other && self.last_edit_kind == Some(kind));
3456        // The mark-edge rule holds for typed text however it is spelled — see
3457        // `splice`. Only an insert twig passed through unchanged can use it,
3458        // since a fix is measured in the bytes that actually land, and an escape
3459        // adds bytes this couldn't have counted.
3460        let fix = self.mark_edge_fix(at, at, text);
3461        self.record_caret();
3462        match self.editor.insert_literal(at, text) {
3463            Ok(change) => {
3464                if coalesce {
3465                    let _ = self.editor.coalesce_last_undo();
3466                }
3467                self.last_edit_kind = Some(kind);
3468                self.refresh();
3469                self.caret = change.new.end;
3470                self.anchor = None;
3471                self.goal_col = None;
3472                self.clear_pending();
3473                self.dirty = self.source != self.clean_source;
3474                self.status = None;
3475                self.record_caret();
3476                if let Some(fix) = fix.filter(|_| change.new.end - change.new.start == text.len()) {
3477                    self.repair_mark_edges(fix);
3478                }
3479                true
3480            }
3481            Err(e) => {
3482                self.status = Some(format!("edit: {e}"));
3483                false
3484            }
3485        }
3486    }
3487
3488    /// After a structural list edit (a new item, a nest/unnest), renumber the
3489    /// ordered list the caret sits in so its source markers run `1, 2, 3, …`
3490    /// again — a raw splice leaves them stale (`1. 2. 2. 3.`). twig does the
3491    /// renumber as its own edit; fold it into the edit that triggered it so the
3492    /// two undo as one, and only when it actually changed the source (a no-op or
3493    /// a caret outside any ordered list must not coalesce the real edit into the
3494    /// step before it).
3495    fn renumber_here(&mut self) {
3496        self.renumber_at(self.caret);
3497    }
3498
3499    /// [`renumber_here`](Self::renumber_here) aimed somewhere other than the
3500    /// caret — for an edit that leaves the caret one past the item it just wrote,
3501    /// where twig resolves no list to renumber.
3502    fn renumber_at(&mut self, off: usize) {
3503        // The read-only gate — this door reaches twig without the splice.
3504        if self.read_only {
3505            return;
3506        }
3507        let before = self.source.clone();
3508        if self.editor.renumber_ordered_lists(off).is_err() {
3509            return; // not inside an ordered list — nothing to renumber
3510        }
3511        self.refresh();
3512        if self.source != before {
3513            let _ = self.editor.coalesce_last_undo();
3514            self.dirty = self.source != self.clean_source;
3515            self.clamp_caret();
3516            self.record_caret();
3517        }
3518    }
3519
3520    /// Repair the one trap a list edit can spring on itself. An *empty* `-`
3521    /// sub-item written directly beneath a text line reparses that text as a
3522    /// setext heading — `- hello\n  - ` is `<h2>hello</h2>`, because a lone `-`
3523    /// is also a setext-H2 underline (twig is right; pandoc agrees). `*` and `+`
3524    /// bullets can't underline anything, so swap the dash for a `*`: the item
3525    /// stays an empty nested bullet, the parent stays prose, and the source
3526    /// round-trips instead of hiding a heading the user never asked for. Folded
3527    /// into the triggering edit's undo step, the way renumbering is.
3528    ///
3529    /// Gated on the collapse having actually happened (the swapped dash was
3530    /// swallowed into a `heading`), so a real setext heading the author wrote —
3531    /// or a `- x` with content, which can't underline anything — is never
3532    /// touched. This has to live in the *edit*, not the renderer: leaving the
3533    /// hazardous bytes on disk and only painting over them would ship a file
3534    /// every other CommonMark tool reads as a heading.
3535    ///
3536    /// This one keeps its own byte scan, and has to: the hazard is precisely
3537    /// that the dash stopped being a list marker, so [`list_marker_on_line`] —
3538    /// which asks twig which lines open an item — reports nothing here. There is
3539    /// no node to ask about. It is also the last Markdown spelling leaf writes on
3540    /// purpose rather than for want of an answer; once twig spells continuations
3541    /// itself, avoiding the trap becomes twig's, and this goes.
3542    ///
3543    /// [`list_marker_on_line`]: Self::list_marker_on_line
3544    fn avoid_setext_collapse(&mut self) {
3545        let caret = self.caret.min(self.source.len());
3546        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
3547        let bytes = self.source.as_bytes();
3548        let mut dash = line_start;
3549        while matches!(bytes.get(dash), Some(b' ' | b'\t')) {
3550            dash += 1;
3551        }
3552        // A dash bullet is the only marker that doubles as a setext underline.
3553        if bytes.get(dash) != Some(&b'-') {
3554            return;
3555        }
3556        // Only an *empty* item is a bare underline; `- x` carries content and
3557        // can't fold the line above into a heading.
3558        let line_end = self.source[dash..]
3559            .find('\n')
3560            .map_or(self.source.len(), |i| dash + i);
3561        if !self.source[dash + 1..line_end].trim().is_empty() {
3562            return;
3563        }
3564        // The tell: that dash was swallowed into a `heading`. A properly nested
3565        // empty item sits under a `list_item`, with no heading in reach. Probe
3566        // the dash byte itself (well inside the heading), not the caret, whose
3567        // end-of-line offset can fall on the half-open span boundary.
3568        let collapsed = self
3569            .editor
3570            .ancestors_at(dash)
3571            .map(|c| c.into_iter().any(|m| m.kind == Kind::Heading))
3572            .unwrap_or(false);
3573        if !collapsed {
3574            return;
3575        }
3576        let caret = self.caret;
3577        if self.splice(dash, dash + 1, "*", EditKind::Other) {
3578            // Same width, so the caret keeps its column; fold into the edit that
3579            // triggered this so Tab stays one undo step.
3580            let _ = self.editor.coalesce_last_undo();
3581            self.caret = caret.min(self.source.len());
3582            self.clamp_caret();
3583            self.record_caret();
3584        }
3585    }
3586
3587    fn snapshot(&self) -> CaretState {
3588        CaretState {
3589            caret: self.caret,
3590            anchor: self.anchor,
3591        }
3592    }
3593
3594    /// Hand twig the current caret and selection as the blob for the live
3595    /// document state. Called before an edit — so the step twig retires records
3596    /// where the caret was, and undo can restore it — and again once the op has
3597    /// placed the caret, so redo restores where the edit left it.
3598    ///
3599    /// This is the whole of leaf's undo-caret bookkeeping now. twig carries the
3600    /// caret through its own history, so coalescing falls out for free (folding
3601    /// two twig steps into one drops the intermediate blob, keeping the run's
3602    /// first) and the parallel stacks that had to march in lockstep — and could
3603    /// silently drift out of it — are gone.
3604    fn record_caret(&mut self) {
3605        let _ = self.editor.set_caret_blob(&self.snapshot().to_blob());
3606    }
3607
3608    /// Toggle an inline mark over the selection (Bold / Italic / Code / …). Keeps
3609    /// the toggled region selected so a second press cleanly reverses it.
3610    pub fn toggle(&mut self, kind: InlineKind) {
3611        // The read-only gate — this door reaches twig without the splice.
3612        if self.read_only {
3613            return;
3614        }
3615        // Ahead of the no-selection branch below: arming a mark for text not yet
3616        // typed is a promise `insert` cannot keep in a format with no delimiters
3617        // to spell it with. Per *kind*, not per format — Markdown spells five
3618        // of the eight marks (highlight among them, under the `highlight`
3619        // extension leaf parses with), djot all eight, HTML seven.
3620        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleInline(kind)) {
3621            return;
3622        }
3623        let Some((s, e)) = self.selection() else {
3624            // No selection: arm the mark for the next text typed here, the way a
3625            // word processor does. `⌘b`, type, `⌘b` again toggles bold on and off
3626            // in the flow of typing without ever selecting anything — the delta
3627            // is realised onto the freshly typed text by `insert`. A fresh caret
3628            // position starts the delta over from the marks actually in force.
3629            if self.pending_at != Some(self.caret) {
3630                self.pending_marks = InlineMarks::empty();
3631                self.pending_at = Some(self.caret);
3632            }
3633            self.pending_marks.flip(kind);
3634            self.status = None;
3635            return;
3636        };
3637        // Whitespace at the edge of a selection is not part of what was chosen —
3638        // a double-click takes the space after the word with it — and a mark
3639        // cannot close against one anyway: `**word **` is four literal asterisks
3640        // (the mark-edge rule, see `splice`). Mark the words, leave the spaces.
3641        let picked = &self.source[s..e];
3642        let (s, e) = (
3643            s + (picked.len() - picked.trim_start().len()),
3644            e - (picked.len() - picked.trim_end().len()),
3645        );
3646        if s >= e {
3647            self.status = Some(format!("{kind:?}: nothing selected to mark"));
3648            return;
3649        }
3650        // Styling a selection is a one-shot act, not a sticky mode.
3651        self.clear_pending();
3652        self.record_caret();
3653        match self.editor.toggle_inline(s, e, kind) {
3654            Ok(change) => {
3655                self.last_edit_kind = None; // structural edit is its own undo step
3656                self.refresh();
3657                self.anchor = Some(change.new.start);
3658                self.caret = change.new.end;
3659                self.dirty = self.source != self.clean_source;
3660                self.status = None;
3661                self.record_caret();
3662            }
3663            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
3664        }
3665    }
3666
3667    /// Whether the caret stands in a highlight — what a frontend asks to enable
3668    /// or disable its highlight-colour controls, the way
3669    /// [`caret_in_table`](Self::caret_in_table) gates the grid ones.
3670    ///
3671    /// A fact about the *caret*, and the other half of
3672    /// [`Capabilities::mark_color`], which is the fact about the format. A
3673    /// frontend needs both: djot spells a highlight and no colour for it, so a
3674    /// caret standing in `{=word=}` answers `true` here and still has no palette
3675    /// to offer.
3676    ///
3677    /// The rule is [`active_inline_marks`](Self::active_inline_marks)' rule, so
3678    /// the palette appears exactly where the Highlight button is lit — with one
3679    /// deliberate exception: a mark *armed* at a bare caret and not yet typed
3680    /// into lights the button and answers `false` here, because there is no node
3681    /// to colour until the text exists.
3682    pub fn caret_in_mark(&mut self) -> bool {
3683        self.mark_offset().is_some()
3684    }
3685
3686    /// The offset [`set_mark_color`](Self::set_mark_color) speaks for — the one
3687    /// standing in the highlight the gesture means — or `None` when neither end
3688    /// of what is selected is in one.
3689    ///
3690    /// The caret first, and the selection's *start* after it, because of what
3691    /// [`toggle`](Self::toggle) leaves behind: a fresh `==word==` is selected
3692    /// whole, with the caret at its far edge, one past the closing `==` and so
3693    /// (by `marks_at`' half-open rule) not in the mark at all. Highlight a word
3694    /// and colour it — the two presses a coloured highlight is made of — would
3695    /// otherwise refuse on the second, having just written the highlight the
3696    /// author is pointing at.
3697    fn mark_offset(&mut self) -> Option<usize> {
3698        let in_mark = |d: &mut Self, off: usize| {
3699            d.marks_at(off)
3700                .into_iter()
3701                .any(|(k, _)| k == InlineKind::Mark)
3702                .then_some(off)
3703        };
3704        let caret = self.caret.min(self.source.len());
3705        in_mark(self, caret).or_else(|| {
3706            let start = self.selection()?.0;
3707            in_mark(self, start)
3708        })
3709    }
3710
3711    /// The colour of the highlight at the caret — `None` both when the caret is
3712    /// in no highlight and when the highlight it is in names no colour, which
3713    /// are the same answer to "which swatch is lit".
3714    ///
3715    /// The innermost mark, by span, for the same reason
3716    /// [`current_heading_level`](Self::current_heading_level) walks the tree:
3717    /// what the caret is *in* is the deepest node containing it. A `data-color`
3718    /// naming a colour this build has no variant for reads as `None` — the
3719    /// renderer already draws that as a plain highlight rather than guessing,
3720    /// and the toolbar agrees with the renderer.
3721    pub fn mark_color_at_caret(&mut self) -> Option<MarkColor> {
3722        let at = self.mark_offset()?;
3723        self.mark_color_at(at)
3724    }
3725
3726    /// [`mark_color_at_caret`](Self::mark_color_at_caret) at a given offset —
3727    /// the innermost `mark` covering it, and the colour it names.
3728    fn mark_color_at(&mut self, off: usize) -> Option<MarkColor> {
3729        self.nodes()
3730            .into_iter()
3731            .filter(|n| n.kind == Kind::Mark)
3732            .filter(|n| n.span.start <= off && off < n.span.end)
3733            .min_by_key(|n| n.span.end - n.span.start)
3734            .and_then(|n| MarkColor::from_attrs(&n.attrs))
3735    }
3736
3737    /// Colour the highlight at the caret, or clear its colour with `None` — the
3738    /// palette behind a toolbar's Highlight button.
3739    ///
3740    /// Markdown only, and the one gesture whose availability is a fact about the
3741    /// *parse extensions* rather than about the format alone: the colour is
3742    /// spelled `==🔴 text==`, an emoji twig reads back out of the content and
3743    /// records as the mark's `data-color`, and only an editor parsing with
3744    /// `highlight_colors` (which [`parse_extensions`] turns on for every leaf
3745    /// document) reads it back that way. Djot spells the highlight and no colour
3746    /// for it, so this refuses there — see [`Capabilities::mark_color`].
3747    ///
3748    /// **A colour is a property of a highlight that already exists.** There is
3749    /// no "highlight this in red" here, because that is two splices and would be
3750    /// two undo steps under one press; a frontend that wants it calls
3751    /// [`toggle`](Self::toggle) with [`InlineKind::Mark`] first, which is the
3752    /// order the two buttons already sit in. With no highlight at the caret this
3753    /// says so in the status line and writes nothing.
3754    ///
3755    /// The caret keeps its place in the *text*: the splice is entirely in the
3756    /// prefix between the opening `==` and the first word, so an offset past it
3757    /// rides the emoji's width, and one standing on the prefix itself lands
3758    /// where the prefix now ends.
3759    pub fn set_mark_color(&mut self, color: Option<MarkColor>) {
3760        // The read-only gate — this door reaches twig without the splice.
3761        if self.read_only {
3762            return;
3763        }
3764        if self.refuse_unsupported("highlight colour", Gesture::SetMarkColor) {
3765            return;
3766        }
3767        let Some(at) = self.mark_offset() else {
3768            self.status = Some("highlight colour: no highlight at the caret".into());
3769            return;
3770        };
3771        // Clearing a colour a highlight hasn't got is twig's one *successful*
3772        // no-op, and the `Change` it hands back then describes whatever edit came
3773        // before it — a stale span that would drag the caret somewhere it never
3774        // was. Answer it here, where the question is cheap, rather than trusting
3775        // a change that isn't one.
3776        if color.is_none() && self.mark_color_at(at).is_none() {
3777            self.status = None;
3778            return;
3779        }
3780        self.record_caret();
3781        match self.editor.set_mark_color(at, color.map(twig_mark_color)) {
3782            Ok(change) => {
3783                // Re-anchored from the offsets as they were, *before* `refresh`
3784                // sees the new bytes: the caret it clamps is one standing inside
3785                // a prefix that didn't exist a moment ago, and walking it back to
3786                // a char boundary of the emoji loses the place this is restoring.
3787                let caret = reanchor(self.caret, &change);
3788                let anchor = self.anchor.map(|a| reanchor(a, &change));
3789                self.last_edit_kind = None; // structural edit is its own undo step
3790                self.refresh();
3791                self.caret = caret;
3792                self.anchor = anchor;
3793                self.dirty = self.source != self.clean_source;
3794                self.status = None;
3795                self.clamp_caret();
3796                self.record_caret();
3797            }
3798            Err(e) => self.status = Some(format!("highlight colour: {e}")),
3799        }
3800    }
3801
3802    /// One press of a colour swatch: colour the highlight at the caret, or —
3803    /// over a selection that isn't highlighted yet — highlight it and colour it,
3804    /// as **one** undo step.
3805    ///
3806    /// [`set_mark_color`](Self::set_mark_color) is the exact gesture and stays
3807    /// one splice; this is the compound every toolbar actually presses, and it
3808    /// lives here rather than in each frontend because the rule it encodes —
3809    /// what a swatch means when there is no highlight under it yet — is one
3810    /// answer, not one per frontend. The two splices are folded into a single
3811    /// history step, so the press that made a red highlight is taken back by a
3812    /// single undo rather than leaving an uncoloured one behind.
3813    ///
3814    /// `None` clears the colour, and over an unhighlighted selection means
3815    /// simply "highlight this" — the same thing the Highlight button does.
3816    /// A bare caret in no highlight is left alone with a status line, because
3817    /// [`toggle`](Self::toggle) there arms a mark for text not yet typed and a
3818    /// colour cannot be armed with it.
3819    pub fn highlight(&mut self, color: Option<MarkColor>) {
3820        if self.caret_in_mark() || self.selection().is_none() {
3821            self.set_mark_color(color);
3822            return;
3823        }
3824        self.toggle(InlineKind::Mark);
3825        // The format may not spell a highlight at all (`toggle` said so), and
3826        // there is nothing to colour if it doesn't.
3827        if self.status.is_some() {
3828            return;
3829        }
3830        let before = self.revision;
3831        self.set_mark_color(color);
3832        // Only fold when the colour really spliced. `highlight(None)` over a
3833        // fresh highlight is a no-op by design, and coalescing there would eat
3834        // the *previous* edit into the toggle instead.
3835        if self.revision != before {
3836            let _ = self.editor.coalesce_last_undo();
3837        }
3838    }
3839
3840    /// Convert the block at the caret to a heading level or paragraph.
3841    pub fn set_block(&mut self, kind: BlockKind) {
3842        // The read-only gate — this door reaches twig without the splice.
3843        if self.read_only {
3844            return;
3845        }
3846        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::SetBlock) {
3847            return;
3848        }
3849        self.record_caret();
3850        // A blank line has no node to convert, and twig opens a block there
3851        // rather than declining — so the caret's own offset is the right thing
3852        // to hand it when `block_offset_for_caret` finds nothing.
3853        let offset = self.block_offset_for_caret().unwrap_or(self.caret);
3854        match self.editor.set_block(offset, kind) {
3855            Ok(change) => {
3856                self.last_edit_kind = None;
3857                self.refresh();
3858                // Opening a block on a blank line writes a marker the caret
3859                // belongs *after*; converting an existing one moves nothing.
3860                self.caret = self.caret.max(change.new.end);
3861                self.clamp_caret();
3862                self.anchor = None;
3863                self.dirty = self.source != self.clean_source;
3864                self.status = None;
3865                self.record_caret();
3866            }
3867            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
3868        }
3869    }
3870
3871    /// Whether `off` is inside a text block (paragraph, heading, code block…).
3872    fn has_block_at(&mut self, off: usize) -> bool {
3873        self.editor.ancestors_at(off).ok().is_some_and(|chain| {
3874            chain
3875                .iter()
3876                .any(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
3877        })
3878    }
3879
3880    /// The offset to hand twig's `set_block`: the caret when it is already inside
3881    /// a block, otherwise nudged onto the previous character (a caret at a line
3882    /// end sits at the doc level, outside the block). `None` when the caret is on
3883    /// a blank line — a new paragraph with no block node to convert.
3884    fn block_offset_for_caret(&mut self) -> Option<usize> {
3885        let caret = self.caret.min(self.source.len());
3886        if self.has_block_at(caret) {
3887            return Some(caret);
3888        }
3889        // Nudge to the previous character — but never across a newline: that would
3890        // target the previous block, and a blank line genuinely has no block.
3891        if let Some((i, ch)) = self.source[..caret].char_indices().next_back()
3892            && ch != '\n'
3893            && self.has_block_at(i)
3894        {
3895            return Some(i);
3896        }
3897        None
3898    }
3899
3900    /// The heading level of the text block at the caret, or `None` when that
3901    /// block is not a heading.
3902    pub fn current_heading_level(&mut self) -> Option<u32> {
3903        let caret = self.caret;
3904        self.nodes()
3905            .into_iter()
3906            .filter(|n| n.kind == Kind::Heading)
3907            .find(|n| n.span.start <= caret && caret <= n.span.end)
3908            .and_then(|n| n.level)
3909    }
3910
3911    /// The inline marks in force at the caret (or over the selection) — what a
3912    /// toolbar draws lit, and the block-level [`Doc::current_heading_level`]'s
3913    /// inline counterpart. Cheap enough to call every frame: one twig
3914    /// `ancestors_at` query per caret (two with a selection), each walking root
3915    /// → deepest node at one offset. It never snapshots the tree the way
3916    /// `current_heading_level` does, and the returned set is a `Copy` bitset, so
3917    /// the only allocation is twig's own small ancestor `Vec`.
3918    ///
3919    /// **A selection reports a mark only when the mark covers *all* of it.**
3920    /// That's what every real toolbar means by an active button — Bold lit over
3921    /// a half-bold selection would claim a press turns bold *off*, when
3922    /// [`Doc::toggle`] hands the range to twig and gets the whole thing bolded.
3923    /// Whole-coverage is asked as "is the same mark node standing over both the
3924    /// first and the last character?": inline nodes are contiguous, so one node
3925    /// covering both ends covers every byte between them. Two touching runs
3926    /// (`**a****b**`) are two nodes, and correctly light nothing.
3927    ///
3928    /// At a bare caret a mark is active when the caret stands inside the mark's
3929    /// span — `span.start <= caret < span.end`, delimiters included, which is
3930    /// what makes the boundaries behave. In `a **bold** b` the offsets from the
3931    /// opening `*` (2) through the last byte of the closing `**` (9) are all
3932    /// bold, so the WYSIWYG caret both before `b` and after `d` (the delimiters
3933    /// are hidden, and those offsets are 4 and 8) reports bold — matching where
3934    /// typing would actually land inside the marked run. The offset one past the
3935    /// mark (10) is the text after it and reports nothing, at the end of the
3936    /// buffer exactly as in the middle.
3937    pub fn active_inline_marks(&mut self) -> InlineMarks {
3938        let Some((start, end)) = self.selection() else {
3939            // The marks actually in force at the caret, flipped by any armed
3940            // sticky delta — so `⌘b` at a bare caret lights the Bold button
3941            // immediately, before a single character is typed.
3942            let base: InlineMarks = self
3943                .marks_at(self.caret)
3944                .into_iter()
3945                .map(|(k, _)| k)
3946                .collect();
3947            return base.xor(self.pending_here());
3948        };
3949        // The selection's *last character*, not its exclusive end: `end` is the
3950        // offset one past the selection, which for a selection ending exactly at
3951        // a mark's close is already outside it (`[4,10)` of `a **bold** b` is
3952        // entirely bold, but offset 10 is the space after).
3953        let last = prev_boundary(&self.source, end);
3954        let head = self.marks_at(start);
3955        let tail = self.marks_at(last);
3956        head.into_iter()
3957            .filter(|m| tail.contains(m))
3958            .map(|(k, _)| k)
3959            .collect()
3960    }
3961
3962    /// The inline marks whose span covers `off`, each with the id of the node
3963    /// carrying it — the id is what lets a selection tell one mark node from
3964    /// another of the same kind.
3965    fn marks_at(&mut self, off: usize) -> Vec<(InlineKind, u32)> {
3966        let off = off.min(self.source.len());
3967        self.editor
3968            .ancestors_at(off)
3969            .unwrap_or_default()
3970            .into_iter()
3971            // `span.end` is the offset one *past* the mark, so it isn't in it.
3972            // twig already resolves a boundary to whatever starts there — in
3973            // `**bold** x` offset 8 is the following text, not the strong — but
3974            // when nothing follows, the tie has nobody to break for and the
3975            // chain still ends at the mark. That would make the answer at the
3976            // last offset of the document depend on whether the file happens to
3977            // end in a newline; the rule is `span.start <= off < span.end`, and
3978            // it's the same rule at the end of a buffer as in the middle.
3979            .filter(|m| off < m.span.end)
3980            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.node_id)))
3981            .collect()
3982    }
3983
3984    /// Toggle a heading at the caret: if the block is already this heading level,
3985    /// revert it to a paragraph; otherwise convert it to this heading level.
3986    /// This gives the heading commands the same toggle feel as bold/italic/code —
3987    /// re-applying a heading a line already has turns it back into body text.
3988    pub fn toggle_heading(&mut self, level: u32) {
3989        if self.current_heading_level() == Some(level) {
3990            self.set_block(BlockKind::Paragraph);
3991        } else {
3992            self.set_block(BlockKind::Heading(level));
3993        }
3994    }
3995
3996    /// Toggle a block quote around the selection, or around the block at the
3997    /// caret — the toolbar's Quote button.
3998    pub fn toggle_blockquote(&mut self) {
3999        self.toggle_container(BlockContainerKind::BlockQuote);
4000    }
4001
4002    /// Toggle a numbered (`ordered`) or bulleted list over the selection, or
4003    /// over the block at the caret — one op with the kind as a flag, the way
4004    /// `toggle_heading` takes its level, so a frontend needs no twig type to
4005    /// name the two buttons.
4006    ///
4007    /// Pressing the *other* list's button while in a list converts in place
4008    /// rather than nesting, so the pair reads as one three-state control
4009    /// (bulleted / numbered / neither) rather than two independent wrappers.
4010    pub fn toggle_list(&mut self, ordered: bool) {
4011        self.toggle_container(if ordered {
4012            BlockContainerKind::OrderedList
4013        } else {
4014            BlockContainerKind::BulletList
4015        });
4016    }
4017
4018    // ── Task list items ──────────────────────────────────────────────────────
4019    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
4020    // inline content of the item's first paragraph rather than part of its
4021    // marker, so adding or removing one must leave the item's continuation
4022    // indentation alone, and an item inside a quote is found past the quote
4023    // markers. leaf names the gesture and the offset; the spelling is twig's.
4024
4025    /// Whether the list item at the caret carries a checkbox, and which way it
4026    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
4027    /// item or no item at all. What a toolbar reads to light its checkbox button.
4028    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
4029        self.task_checked_at(self.caret)
4030    }
4031
4032    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
4033    /// offset — what a frontend asks before deciding a click landed on a box.
4034    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
4035        self.innermost_list_item(offset.min(self.source.len()))?
4036            .checked
4037    }
4038
4039    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
4040    /// A no-op with a reported reason when the caret is in no task item — minting
4041    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
4042    pub fn toggle_task_checked(&mut self) {
4043        self.toggle_task_at(self.caret);
4044    }
4045
4046    /// Tick or untick the task item covering `offset` — what a *click* on a
4047    /// rendered checkbox is. Separate from the caret form because a click carries
4048    /// its own offset and must not first move the caret there: ticking a box
4049    /// three paragraphs away should not take the cursor with it.
4050    pub fn toggle_task_at(&mut self, offset: usize) {
4051        // The read-only gate — this door reaches twig without the splice.
4052        if self.read_only {
4053            return;
4054        }
4055        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
4056            return;
4057        }
4058        let offset = offset.min(self.source.len());
4059        self.record_caret();
4060        match self.editor.toggle_task_checked(offset) {
4061            Ok(_) => self.after_task_edit(),
4062            Err(e) => self.status = Some(format!("task: {e}")),
4063        }
4064    }
4065
4066    /// Give the list item at the caret a checkbox, or take its checkbox away —
4067    /// the gesture that converts between a plain bullet and a task. A new box
4068    /// arrives unticked.
4069    pub fn toggle_task_item(&mut self) {
4070        // The read-only gate — this door reaches twig without the splice.
4071        if self.read_only {
4072            return;
4073        }
4074        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
4075            return;
4076        }
4077        let caret = self.caret.min(self.source.len());
4078        self.record_caret();
4079        match self.editor.toggle_task_item(caret) {
4080            Ok(_) => self.after_task_edit(),
4081            Err(e) => self.status = Some(format!("task: {e}")),
4082        }
4083    }
4084
4085    /// Settle after a task gesture. The caret rides its old byte offset and is
4086    /// clamped back in: a box is three or four bytes on the item's first line, so
4087    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
4088    /// real stop either way.
4089    fn after_task_edit(&mut self) {
4090        self.last_edit_kind = None;
4091        self.refresh();
4092        self.anchor = None;
4093        self.dirty = self.source != self.clean_source;
4094        self.status = None;
4095        self.clamp_caret();
4096        self.record_caret();
4097    }
4098
4099    // ── Tables ───────────────────────────────────────────────────────────────
4100    // A table is a grid, and twig edits it as one — add/remove/move a row or
4101    // column, set a column's alignment — re-spelling the whole table in a single
4102    // splice. Every gesture is anchored at the caret's cell. leaf just names the
4103    // gesture and re-reads the result; the whole table's numbering, borders, and
4104    // delimiter are twig's to keep straight.
4105
4106    /// Whether the caret is inside a table — what a frontend asks to enable or
4107    /// disable its table controls.
4108    ///
4109    /// An HTML `<table>` still answers `true`: the caret really is in a table,
4110    /// and the reason the grid controls stay dark there is
4111    /// [`Capabilities::table`], which is a fact about the document's format
4112    /// rather than about the caret. A frontend needs both.
4113    pub fn caret_in_table(&mut self) -> bool {
4114        let caret = self.caret.min(self.source.len());
4115        self.editor
4116            .ancestors_at(caret)
4117            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
4118            .unwrap_or(false)
4119    }
4120
4121    /// One grid op, guarded and settled — the shared body of the seven below.
4122    ///
4123    /// The guard is why this exists rather than seven copies of the same three
4124    /// lines, and it is the one guard leaf cannot delegate to twig. The table
4125    /// editor is the gesture family that consults no `Syntax` table (it spells a
4126    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
4127    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
4128    /// grid as a *pipe table* and reports success, swapping the element out for
4129    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
4130    /// downstream could tell that from a successful edit — the splice is real,
4131    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
4132    /// stopping at the door rather than detecting after the fact. See
4133    /// [`spells_pipe_tables`].
4134    fn table_op(
4135        &mut self,
4136        what: &str,
4137        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
4138    ) {
4139        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
4140            return;
4141        }
4142        self.record_caret();
4143        let at = self.caret;
4144        let r = op(&mut self.editor, at);
4145        self.apply_table(r, what);
4146    }
4147
4148    /// Insert an empty row below (`below`) or above the caret's row.
4149    pub fn table_insert_row(&mut self, below: bool) {
4150        self.table_op("table row", |e, at| e.table_insert_row(at, below));
4151    }
4152
4153    /// Delete the caret's row (not the header, not the last body row).
4154    pub fn table_delete_row(&mut self) {
4155        self.table_op("table row", |e, at| e.table_delete_row(at));
4156    }
4157
4158    /// Insert an empty column right (`right`) or left of the caret's column.
4159    pub fn table_insert_column(&mut self, right: bool) {
4160        self.table_op("table column", |e, at| e.table_insert_column(at, right));
4161    }
4162
4163    /// Delete the caret's column (unless it is the only one).
4164    pub fn table_delete_column(&mut self) {
4165        self.table_op("table column", |e, at| e.table_delete_column(at));
4166    }
4167
4168    /// Set the caret's column to `alignment`.
4169    pub fn table_set_alignment(&mut self, alignment: Alignment) {
4170        self.table_op("table alignment", |e, at| {
4171            e.table_set_alignment(at, alignment)
4172        });
4173    }
4174
4175    /// Move the caret's row one place down (`down`) or up, within the body rows.
4176    pub fn table_move_row(&mut self, down: bool) {
4177        self.table_op("table row", |e, at| e.table_move_row(at, down));
4178    }
4179
4180    /// Move the caret's column one place right (`right`) or left.
4181    pub fn table_move_column(&mut self, right: bool) {
4182        self.table_op("table column", |e, at| e.table_move_column(at, right));
4183    }
4184
4185    /// Settle the caret and document flags after a table op (or report its
4186    /// error). twig re-spells the whole table, so the caret rides its old byte
4187    /// offset and is clamped back into the rebuilt bytes — near enough to where
4188    /// it was, since the op preserves the cells' content and order around it.
4189    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
4190        match result {
4191            Ok(()) => {
4192                self.last_edit_kind = None;
4193                self.refresh();
4194                self.anchor = None;
4195                self.clamp_caret();
4196                self.dirty = self.source != self.clean_source;
4197                self.status = None;
4198                self.record_caret();
4199            }
4200            Err(e) => self.status = Some(format!("{what}: {e}")),
4201        }
4202    }
4203
4204    /// One `toggle_block_container` over the block-level target.
4205    ///
4206    /// leaf says *where*; twig decides everything else — which blocks the range
4207    /// covers, whether that means wrapping, unwrapping, nesting or converting,
4208    /// and how this document's format spells the prefix. The rule that a
4209    /// container only comes off when the range covers every block it holds is
4210    /// what the re-anchoring below is built around.
4211    fn toggle_container(&mut self, kind: BlockContainerKind) {
4212        // The read-only gate — this door reaches twig without the splice.
4213        if self.read_only {
4214            return;
4215        }
4216        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
4217            return;
4218        }
4219        let selected = self.selection();
4220        // A blank line holds no block, and twig opens an *empty* container on one
4221        // — since 3.2.0; it used to decline the range with `NotFound`, which is
4222        // why this used to lend it a scratch paragraph to wrap. Worth knowing
4223        // here because the line-for-line caret mapping below cannot describe it:
4224        // opening one under a paragraph writes the blank line the format needs
4225        // above the marker too, so the rewritten region has a line the old one
4226        // didn't, and "the same line, the same distance from its end" lands on
4227        // that new blank instead of in the container.
4228        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
4229        // Without a selection the target is the caret's own block, resolved the
4230        // way `set_block` resolves it — a caret at a line end sits at the doc
4231        // level and has to be nudged back onto the block it looks like it's in.
4232        // An empty range is enough: twig widens to the whole lines it touches.
4233        let (start, end) = match selected {
4234            Some(range) => range,
4235            None => {
4236                let off = self.block_offset_for_caret().unwrap_or(self.caret);
4237                (off, off)
4238            }
4239        };
4240        self.record_caret();
4241        match self.editor.toggle_block_container(start, end, kind) {
4242            Ok(change) => {
4243                // Read the caret's place out of the *pre-edit* source, before
4244                // `refresh` swaps that source out from under it.
4245                let place = (selected.is_none() && !opened_empty)
4246                    .then(|| self.caret_line_tail(&change.old));
4247                self.last_edit_kind = None; // structural edit is its own undo step
4248                self.refresh();
4249                match place {
4250                    // Both land the caret at the far end of what twig wrote, and
4251                    // differ only in what they leave selected.
4252                    //
4253                    // From a selection: select what the container now holds, the
4254                    // way `toggle` keeps its marked region selected — and for a
4255                    // stronger reason than symmetry: a container comes *off* only
4256                    // a range covering every block it holds, so a selection left
4257                    // on its old bytes (now short by a prefix per line) would nest
4258                    // on the second press instead of reversing the first.
4259                    //
4260                    // From a blank line: nothing to select, and the end of the
4261                    // region is exactly past the bare `> ` / `- ` twig wrote —
4262                    // the caret standing inside the container that was asked for.
4263                    None => {
4264                        self.anchor = (!opened_empty).then_some(change.new.start);
4265                        self.caret = change.new.end;
4266                    }
4267                    Some(place) => {
4268                        self.anchor = None;
4269                        self.caret = self.line_tail_offset(&change.new, place);
4270                    }
4271                }
4272                self.dirty = self.source != self.clean_source;
4273                self.status = None;
4274                self.clamp_caret();
4275                self.record_caret();
4276            }
4277            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
4278        }
4279    }
4280
4281    /// The caret's place inside the region a container toggle is rewriting, in
4282    /// the only terms the rewrite preserves: which of the region's lines it sits
4283    /// on, and how many bytes of that line lie ahead of it.
4284    ///
4285    /// A container's markup goes in at column 0 and never touches what follows
4286    /// on the line, so that pair survives the edit exactly where a byte offset
4287    /// does not — a caret left on its old offset slides back by one prefix per
4288    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
4289    /// `> ` it just asked for.
4290    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
4291        let caret = self.caret.clamp(old.start, old.end);
4292        let line = self.source[old.start..caret].matches('\n').count();
4293        let end = self.source[caret..old.end]
4294            .find('\n')
4295            .map_or(old.end, |i| caret + i);
4296        (line, end - caret)
4297    }
4298
4299    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
4300    /// region: the offset `tail` bytes back from the end of the region's `line`.
4301    ///
4302    /// Both walks are clamped rather than trusted, because the one op that does
4303    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
4304    /// the items back apart with blank lines between them — and a caret landing
4305    /// on the nearest line of the right item beats one landing out of the region
4306    /// entirely.
4307    fn line_tail_offset(
4308        &self,
4309        new: &std::ops::Range<usize>,
4310        (line, tail): (usize, usize),
4311    ) -> usize {
4312        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
4313        let mut start = 0;
4314        for _ in 0..line {
4315            match region[start..].find('\n') {
4316                Some(i) => start += i + 1,
4317                None => break,
4318            }
4319        }
4320        let end = region[start..]
4321            .find('\n')
4322            .map_or(region.len(), |i| start + i);
4323        new.start + end.saturating_sub(tail).max(start)
4324    }
4325
4326    /// Link the selection to `destination` — the toolbar's Link button. With no
4327    /// selection it acts at the caret, which re-points a link the caret is
4328    /// already standing in (twig replaces an existing link's destination and
4329    /// keeps its text) and otherwise spells a link that has no text of its own:
4330    /// an autolink (`<https://x.dev>`) where the destination is one, and
4331    /// `[destination](destination)` where it isn't.
4332    ///
4333    /// `destination` reaches twig raw. Escaping it is format knowledge and the
4334    /// two formats genuinely disagree — Markdown ends a destination at the first
4335    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
4336    /// itself — so the side holding the document is the side that gets to spell
4337    /// it. A destination twig can't carry at all (one with a newline) comes back
4338    /// as an error rather than a quietly rewritten URL.
4339    pub fn insert_link(&mut self, destination: &str) {
4340        if self.read_only || self.refuse_unsupported("link", Gesture::InsertLink) {
4341            return;
4342        }
4343        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
4344        self.record_caret();
4345        match self.editor.insert_link(start, end, destination) {
4346            Ok(change) => {
4347                self.last_edit_kind = None;
4348                self.refresh();
4349                match self.link_text_span(change.new.start) {
4350                    // A link with text of its own: select it, so typing replaces
4351                    // a `[dest](dest)`'s stand-in label and a second press
4352                    // re-points what the first one linked.
4353                    Some(text) => {
4354                        self.anchor = (text.start != text.end).then_some(text.start);
4355                        self.caret = text.end;
4356                    }
4357                    // An autolink is finished the moment it's written — its text
4358                    // *is* the URL. Leaving it selected would aim the next press
4359                    // at the one shape twig still wraps instead of re-points.
4360                    None => {
4361                        self.anchor = None;
4362                        self.caret = change.new.end;
4363                    }
4364                }
4365                self.dirty = self.source != self.clean_source;
4366                self.status = None;
4367                self.clamp_caret();
4368                self.record_caret();
4369            }
4370            Err(e) => self.status = Some(format!("link: {e}")),
4371        }
4372    }
4373
4374    /// Insert a block-level image at the caret: `![alt](destination)`. Any
4375    /// selection becomes the alt text (so "select a caption, insert image" labels
4376    /// it); with no selection, `alt` is used — empty for none. The caret lands
4377    /// just past the inserted image.
4378    ///
4379    /// Both halves go through twig (`insert_literal` for the alt text,
4380    /// `insert_image` for the image), so neither is spelled here. That used to be a
4381    /// `format!`, and it was wrong the first time an app inserted a real filename:
4382    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
4383    /// not an image at all — and the fix is per-format, since moving into the
4384    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
4385    pub fn insert_image(&mut self, destination: &str, alt: &str) {
4386        if self.read_only || self.refuse_unsupported("image", Gesture::InsertImage) {
4387            return;
4388        }
4389        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
4390        self.record_caret();
4391        // With no selection and an explicit `alt`, the alt text has to exist in the
4392        // document before it can be the image's — and it is raw caller input, so
4393        // it goes in through `insert_literal`, which escapes it for the format
4394        // rather than letting a `]` in someone's caption close the image early.
4395        let (start, end) = if start == end && !alt.is_empty() {
4396            match self.editor.insert_literal(start, alt) {
4397                Ok(change) => (change.new.start, change.new.end),
4398                Err(e) => {
4399                    self.status = Some(format!("image: {e}"));
4400                    return;
4401                }
4402            }
4403        } else {
4404            (start, end)
4405        };
4406        match self.editor.insert_image(start, end, destination) {
4407            Ok(change) => {
4408                self.last_edit_kind = None;
4409                self.refresh();
4410                // Just past the image, nothing selected — where a caret belongs
4411                // after inserting one.
4412                self.anchor = None;
4413                self.caret = change.new.end;
4414                self.dirty = self.source != self.clean_source;
4415                self.status = None;
4416                self.clamp_caret();
4417                self.record_caret();
4418            }
4419            Err(e) => self.status = Some(format!("image: {e}")),
4420        }
4421    }
4422
4423    /// Insert a block-level image, video, or audio at the caret. The image case
4424    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
4425    /// HTML elements, which is the only spelling Markdown and Djot have for them:
4426    ///
4427    /// ```text
4428    /// <video src="clip.mp4" controls>alt</video>
4429    /// <audio src="take.mp3" controls>alt</audio>
4430    /// ```
4431    ///
4432    /// HTML rather than a `::video{…}` directive deliberately. A directive means
4433    /// something only to an app that knows the vocabulary, so the document would
4434    /// read as literal punctuation everywhere else; `<video>` is what every other
4435    /// renderer already understands, and what leaf's own reader picks back up
4436    /// through `html_elements` promotion (see [`parse_extensions`]).
4437    ///
4438    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
4439    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
4440    /// `html_elements`. Before that only the multi-line form parsed as a block at
4441    /// all, and this wrote three lines to work around it.
4442    ///
4443    /// `controls` is always written: a player with no transport is a still frame
4444    /// the reader can't do anything with. Any selection becomes the element's
4445    /// fallback text, exactly as it becomes an image's alt.
4446    ///
4447    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
4448    /// applies, and bites harder here: a `"` in `destination` closes the
4449    /// attribute. A frontend taking these from a file picker is fine; one taking
4450    /// them from free text should keep them tame.
4451    ///
4452    /// [`MediaInfo`]: crate::MediaInfo
4453    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
4454        if kind == MediaKind::Image {
4455            return self.insert_image(destination, alt);
4456        }
4457        // Gated on the *image* gesture, not on one of its own — there isn't one,
4458        // since the bytes below are spelled here rather than by twig, and an HTML
4459        // document would in fact parse them. The button is one control with three
4460        // kinds behind it, and two of them working in a format where the third
4461        // cannot is a worse surface than three that agree — especially as
4462        // `insert_image` is the kind anyone reaches for first.
4463        if self.refuse_unsupported("media", Gesture::InsertImage) {
4464            return;
4465        }
4466        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
4467        let alt_text = self
4468            .selected_text()
4469            .map(str::to_string)
4470            .unwrap_or_else(|| alt.to_string());
4471        let tag = match kind {
4472            MediaKind::Audio => "audio",
4473            _ => "video",
4474        };
4475        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
4476        self.edit(start, end, &markup);
4477    }
4478
4479    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
4480    /// button. Spelling and placement are both twig's; leaf used to write `---`
4481    /// itself, which was the Markdown spelling in a djot document too.
4482    ///
4483    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
4484    /// mid-paragraph and lands it after the caret's whole block. To get a rule
4485    /// *at* the caret — the paragraph parted in two around it, which is what a
4486    /// rule button is understood to do — the paragraph is first divided with
4487    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
4488    /// the offset `split_block` returns puts the rule after the *second* half
4489    /// instead, which is a rule in the right document and the wrong place.
4490    ///
4491    /// Only a plain paragraph is split. Everywhere else the rule simply lands
4492    /// after the block, which is both twig's own answer and the better one:
4493    /// splitting a fenced code block would leave two fences with a rule between
4494    /// them, and splitting a list item would mint an item nobody asked for on the
4495    /// way to a rule that lands after the list regardless. A table and a setext
4496    /// heading refuse the split outright, so they take the same path by
4497    /// themselves.
4498    pub fn insert_thematic_break(&mut self) {
4499        if self.read_only || self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak)
4500        {
4501            return;
4502        }
4503        self.caret = self.skip_trailing_close_delims(self.caret);
4504        // A selection is replaced by the rule, so collapse it first and let the
4505        // split-and-rule below run from the caret it leaves behind.
4506        if let Some((s, e)) = self.selection() {
4507            self.splice(s, e, "", EditKind::Other);
4508        }
4509        self.anchor = None;
4510        self.record_caret();
4511        let at = self.caret;
4512        if self.caret_in_bare_paragraph() {
4513            // A failure here is not fatal: the rule still lands after the block,
4514            // which is exactly what this call was trying to improve on.
4515            let _ = self.editor.split_block(at);
4516        }
4517        match self.editor.insert_thematic_break(at) {
4518            Ok(change) => {
4519                self.last_edit_kind = None;
4520                self.refresh();
4521                self.anchor = None;
4522                self.caret = change.new.end;
4523                self.dirty = self.source != self.clean_source;
4524                self.status = None;
4525                self.clamp_caret();
4526                self.record_caret();
4527            }
4528            Err(e) => self.status = Some(format!("thematic break: {e}")),
4529        }
4530    }
4531
4532    /// Whether the caret sits in a paragraph and nothing else — no list item, no
4533    /// quote, no fence, no table. The one shape where parting the block around
4534    /// the caret is unambiguously what a rule button means; see
4535    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
4536    /// container is left to take the rule after itself.
4537    fn caret_in_bare_paragraph(&mut self) -> bool {
4538        let caret = self.caret.min(self.source.len());
4539        let Ok(chain) = self.editor.ancestors_at(caret) else {
4540            return false;
4541        };
4542        let mut in_para = false;
4543        for m in chain {
4544            match m.kind {
4545                Kind::Para => in_para = true,
4546                Kind::ListItem
4547                | Kind::TaskListItem
4548                | Kind::BlockQuote
4549                | Kind::CodeBlock
4550                | Kind::Table => return false,
4551                _ => {}
4552            }
4553        }
4554        in_para
4555    }
4556
4557    /// The destination of the link under the caret — what a Link prompt shows so
4558    /// ⌘K on an existing link edits its URL instead of asking for it again.
4559    /// `None` when the caret stands in no link.
4560    ///
4561    /// An autolink carries no separate destination: its text *is* the URL, so
4562    /// that's what comes back for one.
4563    pub fn link_destination_at_caret(&mut self) -> Option<String> {
4564        self.link_destination_at(self.caret)
4565    }
4566
4567    /// The destination of the link at `off`.
4568    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
4569    /// the caret isn't.
4570    ///
4571    /// The offset form exists for the same reason
4572    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
4573    /// the document somewhere else — a footnote's text in a popover, say — has
4574    /// rows and runs but no caret in them, and still needs to know which of those
4575    /// runs a reader can follow.
4576    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
4577        self.nodes()
4578            .into_iter()
4579            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
4580            .filter(|n| n.span.start <= off && off < n.span.end)
4581            .max_by_key(|n| n.span.start)
4582            .and_then(|n| n.destination.or(n.text))
4583    }
4584
4585    /// Where the locator `id` lands in this document — the `#v2` half of a
4586    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
4587    /// answers to it.
4588    ///
4589    /// The other end of a link, and the reason this exists: without it a
4590    /// destination has only file granularity, so following a citation into a
4591    /// chapter drops the reader at the top of it to hunt for the verse. Which is
4592    /// also why it is a *document* query rather than a caret one — the document
4593    /// being asked is usually not the one the reader is in.
4594    ///
4595    /// Three readings, tried in order, because the same `#some-heading` is
4596    /// written three ways across the formats leaf opens:
4597    ///
4598    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
4599    ///    the auto-ids djot mints for its headings. The only exact answer, so it
4600    ///    goes first — a document that says `{#v1}` has settled the question.
4601    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
4602    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
4603    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
4604    ///    authored anywhere land on a djot heading.
4605    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
4606    ///    none and `{#custom}` is literal text in a Markdown heading — so for
4607    ///    the format most vaults are written in, the heading's own words are the
4608    ///    only thing a fragment can name. This is the rule every Markdown
4609    ///    renderer already follows, which is what makes `#a-heading` mean in
4610    ///    diaryx what it means on the web.
4611    ///
4612    /// Ties go to the earliest match, then to the widest: a duplicated id is the
4613    /// document's mistake and the first one is the answer every anchor
4614    /// implementation gives, while preferring the wider span picks the section
4615    /// over the heading that opens it — more for a peek to show, same place to
4616    /// land.
4617    pub fn locate(&mut self, id: &str) -> Option<Landing> {
4618        let id = id.trim();
4619        if id.is_empty() {
4620            return None;
4621        }
4622        let nodes = self.nodes();
4623
4624        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
4625        // is picking, among nodes that start together, the one that ends last.
4626        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
4627            matches
4628                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
4629                .map(|n| Landing {
4630                    start: n.span.start,
4631                    end: n.span.end,
4632                })
4633        };
4634
4635        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
4636            return Some(landing);
4637        }
4638        let want = slug(id);
4639        if want.is_empty() {
4640            return None;
4641        }
4642        if let Some(landing) = pick(
4643            &mut nodes
4644                .iter()
4645                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
4646        ) {
4647            return Some(landing);
4648        }
4649
4650        // A heading by its words. Its span is one line, so the end comes from
4651        // where the *section* it opens gives out — the next heading that is not
4652        // under it, or the end of the document. A Markdown heading has no
4653        // section node to ask (twig only builds those for djot), and a peek that
4654        // showed the heading alone would answer "what does that say" with the
4655        // title of the thing it says.
4656        let heading = nodes
4657            .iter()
4658            .filter(|n| n.kind == Kind::Heading)
4659            .filter(|n| {
4660                n.content_span
4661                    .clone()
4662                    .and_then(|s| self.source.get(s))
4663                    .is_some_and(|text| slug(text) == want)
4664            })
4665            .min_by_key(|n| n.span.start)?;
4666        let level = heading.level.unwrap_or(u32::MAX);
4667        let end = nodes
4668            .iter()
4669            .filter(|n| n.kind == Kind::Heading)
4670            .filter(|n| n.span.start > heading.span.start)
4671            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
4672            .map(|n| n.span.start)
4673            .min()
4674            .unwrap_or(self.source.len());
4675        Some(Landing {
4676            start: heading.span.start,
4677            end,
4678        })
4679    }
4680
4681    /// Write a footnote at the caret — the toolbar's Footnote button, and the
4682    /// one gesture in the footnote story that *authors* rather than follows.
4683    ///
4684    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
4685    /// the `[^1]:` definition at the end of the document. Half a footnote is not
4686    /// a footnote — a bare reference with nothing defining it renders as literal
4687    /// brackets — so a single button that wrote only the reference would leave
4688    /// the author to hand-spell the other half in a document that had just
4689    /// stopped showing them what the first half meant. One edit also means one
4690    /// undo takes both back.
4691    ///
4692    /// The definition's body is left empty and **the caret lands in it**, which
4693    /// is the whole point of pressing the button: nobody wants a reference to a
4694    /// note they have not written yet. Getting back to where they were writing
4695    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
4696    /// the same return leg a reader following a reference already uses, so the
4697    /// author is left standing on the near end of a round trip that works.
4698    ///
4699    /// A selection collapses to its *end* rather than being replaced: a
4700    /// reference annotates the words before it, so "select the claim, add a
4701    /// footnote" should mark that claim, not consume it.
4702    pub fn insert_footnote(&mut self) {
4703        if self.read_only || self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
4704            return;
4705        }
4706        let at = self.selection().map_or(self.caret, |(_, end)| end);
4707        self.anchor = None;
4708        self.caret = at;
4709        self.record_caret();
4710        let label = self.next_footnote_label();
4711        match self.editor.insert_footnote(at, &label) {
4712            Ok(change) => {
4713                self.last_edit_kind = None;
4714                self.refresh();
4715                self.anchor = None;
4716                // `change.new` runs from the reference to the end of the
4717                // document, so its start is the `[^1]` just written and
4718                // `footnote_at` resolves it to the note the same way a reader's
4719                // tap does — and to the note's *body*, which is already a caret
4720                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
4721                // and has none), so this needs no snap on top. The fallback is
4722                // the reference's own offset: a format that spelled the pair some
4723                // way leaf can't read back should still leave the caret on the
4724                // edit rather than at the far end of a document it just grew.
4725                self.caret = self
4726                    .footnote_at(change.new.start)
4727                    .and_then(|note| note.offset)
4728                    .unwrap_or(change.new.start);
4729                self.dirty = self.source != self.clean_source;
4730                self.status = None;
4731                self.clamp_caret();
4732                self.record_caret();
4733            }
4734            Err(e) => self.status = Some(format!("footnote: {e}")),
4735        }
4736    }
4737
4738    /// The label to give a footnote the author has not named: the lowest counting
4739    /// number no footnote in the document is already wearing.
4740    ///
4741    /// twig takes the label rather than minting one, because it holds no opinion
4742    /// about what a document's footnotes should be called — and it is right not
4743    /// to. Numbering them is what every author of a numbered note expects, and
4744    /// re-using a taken number would silently point the new reference at somebody
4745    /// else's note (twig reuses an existing definition rather than appending a
4746    /// second one, which is the right rule for citing a note twice on purpose and
4747    /// exactly the wrong accident to have by default).
4748    ///
4749    /// *References* are counted alongside definitions, not just definitions: a
4750    /// document carrying a dangling `[^2]` has a 2 that means something to
4751    /// whoever wrote it, and minting a definition for it here would answer a
4752    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
4753    /// count entirely — they take no number, so they block none.
4754    fn next_footnote_label(&mut self) -> String {
4755        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
4756            .into_iter()
4757            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
4758            .filter_map(|label| label.parse().ok())
4759            .collect();
4760        taken.extend(
4761            self.nodes()
4762                .into_iter()
4763                .filter(|n| n.kind == Kind::FootnoteReference)
4764                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
4765                .filter_map(|label| label.parse::<u32>().ok()),
4766        );
4767        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
4768    }
4769
4770    /// The footnote reference under the caret, resolved to the note it names.
4771    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
4772    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
4773        self.footnote_at(self.caret)
4774    }
4775
4776    /// The footnote reference at `off`, resolved to the note it names — what a
4777    /// frontend shows when a reader activates a `[^1]`.
4778    ///
4779    /// A reference is not a link node, so
4780    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
4781    /// (and should not) answer for one: a link names a destination to leave for,
4782    /// a reference names a note that is already in this document. Following one
4783    /// is a move within the page, which is why this hands back an `offset`
4784    /// rather than something to open.
4785    ///
4786    /// Offset-based rather than caret-only because the gesture that wants this
4787    /// most is the one that must not move the caret: a pointer hovering a `[1]`
4788    /// asks what note it names without disturbing where the reader was typing.
4789    /// The caret is just the offset a click already placed —
4790    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
4791    ///
4792    /// `None` when `off` stands in no reference. A reference whose note the
4793    /// document never defines is *not* `None` — it answers with the label it
4794    /// looked for and no text, which is what lets a frontend say so instead of
4795    /// silently doing nothing.
4796    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
4797        // Innermost-wins by latest start, the rule its link sibling uses.
4798        let span = self
4799            .nodes()
4800            .into_iter()
4801            .filter(|n| n.kind == Kind::FootnoteReference)
4802            .filter(|n| n.span.start <= off && off < n.span.end)
4803            .max_by_key(|n| n.span.start)?
4804            .span;
4805        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();
4806
4807        // The note itself. Definitions are roots beside `doc` rather than
4808        // children of it, so they're asked for directly — see
4809        // `wysiwyg::footnote_definitions`.
4810        let note = wysiwyg::footnote_definitions(&mut self.editor)
4811            .into_iter()
4812            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
4813        let Some(note) = note else {
4814            return Some(FootnoteRef {
4815                label,
4816                text: None,
4817                offset: None,
4818                end: None,
4819            });
4820        };
4821        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
4822        Some(FootnoteRef {
4823            label,
4824            text: body
4825                .clone()
4826                .and_then(|b| self.source.get(b))
4827                .map(str::to_string),
4828            // The body's start, not the definition's — see `FootnoteRef::offset`.
4829            offset: body.clone().map(|b| b.start),
4830            end: body.map(|b| b.end),
4831        })
4832    }
4833
4834    /// The footnote *definition* the caret stands in, and where the reference
4835    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
4836    /// at the caret's offset.
4837    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
4838        self.footnote_definition_at(self.caret)
4839    }
4840
4841    /// The footnote definition spanning `off`, and where the reference that
4842    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
4843    ///
4844    /// The mirror image, deliberately: the same gesture that takes a reader from
4845    /// `[1]` down to the note takes them from the note back up to `[1]`, so
4846    /// following a footnote is a round trip rather than a fall. It needs no
4847    /// memory of how the reader arrived — the document says where the reference
4848    /// is — which is what makes it work for a reader who scrolled to the notes
4849    /// themselves, and what keeps it right after an edit moves either end.
4850    ///
4851    /// `None` when `off` stands in no definition. A definition nothing cites is
4852    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
4853    /// its label and no offset, so a frontend can say "nothing refers to this"
4854    /// rather than offer a jump that goes nowhere.
4855    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
4856        // Definitions are roots beside `doc`, so `nodes()` — which walks the
4857        // document body — never reports one. They're asked for directly, the way
4858        // `footnote_at` asks for the note it resolves to.
4859        //
4860        // Closed at the end, unlike the half-open test its neighbours use. A
4861        // definition's span stops at its last content byte — the newline ending
4862        // the line is outside it — so `span.end` is the caret stop at the end of
4863        // the note's own row, not the first byte of anything after. Excluding it
4864        // meant the one caret an author is guaranteed to have, the one left
4865        // sitting at the end of the note they just typed, was in no definition at
4866        // all: writing a note and then asking to go back to its reference
4867        // answered nothing. Two definitions in a row still can't both match —
4868        // there is a blank line between them — and `max_by_key` decides anyway.
4869        let note = wysiwyg::footnote_definitions(&mut self.editor)
4870            .into_iter()
4871            .filter(|m| m.span.start <= off && off <= m.span.end)
4872            .max_by_key(|m| m.span.start)?;
4873        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();
4874
4875        // The earliest reference carrying this label. `min` rather than a `find`,
4876        // because `nodes()` reports a flattened walk whose order is twig's
4877        // business, not document order. Bound first: the walk needs `&mut self`
4878        // and reading the labels back out needs `&self.source`.
4879        let nodes = self.nodes();
4880        let offset = nodes
4881            .into_iter()
4882            .filter(|n| n.kind == Kind::FootnoteReference)
4883            .filter(|n| {
4884                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
4885            })
4886            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
4887            .map(|n| n.span.start + 2)
4888            .min();
4889        Some(FootnoteDef { label, offset })
4890    }
4891
4892    /// The destination of the image under the caret — what an image prompt shows
4893    /// so editing an existing image starts from its current URL instead of blank,
4894    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
4895    /// `None` when the caret stands in no image. A caret resting just after a
4896    /// block image (its trailing stop) is still "in" it — the half-open span test
4897    /// excludes that offset, which is the intended precision: past the image is
4898    /// past it.
4899    pub fn image_destination_at_caret(&mut self) -> Option<String> {
4900        let off = self.caret;
4901        self.nodes()
4902            .into_iter()
4903            .filter(|n| n.kind == Kind::Image)
4904            .filter(|n| n.span.start <= off && off < n.span.end)
4905            .max_by_key(|n| n.span.start)
4906            .and_then(|n| n.destination)
4907    }
4908
4909    /// The language of the fenced code block the caret stands in — what a
4910    /// language prompt shows so editing it starts from the current value rather
4911    /// than blank. `None` when the caret is in no code block, or in one whose
4912    /// fence carries no language (or an indented block, which has no fence).
4913    pub fn code_language_at_caret(&mut self) -> Option<String> {
4914        let start = self.code_block_start_at_caret()?;
4915        wysiwyg::code_language(&self.source, start)
4916    }
4917
4918    /// Whether the caret stands in a fenced code block — the one a language
4919    /// prompt could edit. A frontend gates its "set language" affordance on this
4920    /// (an indented block, which can't carry a language, reports `false`).
4921    pub fn caret_in_fenced_code(&mut self) -> bool {
4922        self.code_block_start_at_caret()
4923            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
4924    }
4925
4926    /// Set (or clear, with `""`) the language of the fenced code block the caret
4927    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
4928    /// block, and a reported error for a language the format's fence cannot
4929    /// carry.
4930    ///
4931    /// twig rewrites the info string, so the fence's own width — measured
4932    /// against a body neither side touches — is kept, and a language holding a
4933    /// space, a line end or the fence character is refused rather than written
4934    /// out to reparse as something else. Leaf used to splice over the info span
4935    /// itself and `trim()` the input, which handled the one bad case it had
4936    /// thought of.
4937    pub fn set_code_language(&mut self, lang: &str) {
4938        // The read-only gate — this door reaches twig without the splice.
4939        if self.read_only {
4940            return;
4941        }
4942        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
4943            return;
4944        }
4945        if self.code_block_start_at_caret().is_none() {
4946            return;
4947        }
4948        let lang = lang.trim();
4949        // `None` clears the info string; `Some("")` asks for an empty one. Both
4950        // write a bare fence, and the prompt's empty value means "clear".
4951        let want = (!lang.is_empty()).then_some(lang);
4952        self.record_caret();
4953        match self.editor.set_code_language(self.caret, want) {
4954            Ok(_) => {
4955                self.last_edit_kind = None;
4956                self.refresh();
4957                self.anchor = None;
4958                self.dirty = self.source != self.clean_source;
4959                self.status = None;
4960                self.clamp_caret();
4961                self.record_caret();
4962            }
4963            Err(e) => self.status = Some(format!("code language: {e}")),
4964        }
4965    }
4966
4967    /// The `span.start` of the code block covering the caret — the anchor
4968    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
4969    /// in none.
4970    fn code_block_start_at_caret(&mut self) -> Option<usize> {
4971        let off = self.caret;
4972        self.nodes()
4973            .into_iter()
4974            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
4975            .max_by_key(|n| n.span.start)
4976            .map(|n| n.span.start)
4977    }
4978
4979    /// The source range of the text inside the link covering `off` — what sits
4980    /// between its `[` and `]`. `None` when twig reports no link there.
4981    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
4982        self.nodes()
4983            .into_iter()
4984            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
4985            // the other's `span.start`; the link that starts latest at or before
4986            // `off` is the one `off` is actually in.
4987            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
4988            .max_by_key(|n| n.span.start)
4989            .and_then(|n| n.content_span)
4990    }
4991
4992    // ── undo / redo ───────────────────────────────────────────────────────────
4993    // twig owns the history of *bytes* (it owns the buffer) and now carries the
4994    // caret through it too: `record_caret` stashes each state's caret in twig's
4995    // opaque per-step blob, and undo/redo hand it back with the source they
4996    // restore. So leaf keeps no history of its own — no parallel stacks to march
4997    // in lockstep and silently drift out of it.
4998
4999    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
5000    /// where they were when that step began.
5001    pub fn undo(&mut self) {
5002        if self.read_only {
5003            return;
5004        }
5005        let (undone, redoable) = (self.undo_steps, self.redo_steps);
5006        match self.editor.undo() {
5007            Ok(Some(change)) => {
5008                self.after_history(change);
5009                // `refresh` counted the restore as an edit; it was a step back.
5010                self.undo_steps = undone.saturating_sub(1);
5011                self.redo_steps = redoable + 1;
5012            }
5013            Ok(None) => {
5014                self.undo_steps = 0;
5015                self.status = Some("nothing to undo".into());
5016            }
5017            Err(e) => self.status = Some(format!("undo: {e}")),
5018        }
5019    }
5020
5021    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
5022    /// selection back where that step originally left them.
5023    pub fn redo(&mut self) {
5024        if self.read_only {
5025            return;
5026        }
5027        let (undone, redoable) = (self.undo_steps, self.redo_steps);
5028        match self.editor.redo() {
5029            Ok(Some(change)) => {
5030                self.after_history(change);
5031                // `refresh` counted the restore as an edit; it was a step forward.
5032                self.undo_steps = undone + 1;
5033                self.redo_steps = redoable.saturating_sub(1);
5034            }
5035            Ok(None) => {
5036                self.redo_steps = 0;
5037                self.status = Some("nothing to redo".into());
5038            }
5039            Err(e) => self.status = Some(format!("redo: {e}")),
5040        }
5041    }
5042
5043    /// Refresh the cached source and put the caret back where the step being
5044    /// undone/redone had it, clearing any active run.
5045    ///
5046    /// The caret comes from twig's blob for the restored state (what
5047    /// `record_caret` stored). `change` is only the fallback for a state with no
5048    /// blob — a caret at the end of the restored text, which is where this always
5049    /// landed before the blobs were kept. It is the edit site, not where the user
5050    /// was standing, so it's a floor and not the behaviour: undoing should hand
5051    /// back the document *and* the place you were working, which for an edit made
5052    /// anywhere but under the caret are two different places.
5053    fn after_history(&mut self, change: Change) {
5054        self.refresh();
5055        match self
5056            .editor
5057            .caret_blob()
5058            .ok()
5059            .and_then(|b| CaretState::from_blob(&b))
5060        {
5061            Some(state) => {
5062                self.caret = state.caret.min(self.source.len());
5063                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
5064            }
5065            None => {
5066                self.caret = change.new.end.min(self.source.len());
5067                self.anchor = None;
5068            }
5069        }
5070        self.goal_col = None;
5071        self.last_edit_kind = None;
5072        self.dirty = self.source != self.clean_source;
5073        self.status = None;
5074        self.clamp_caret();
5075    }
5076
5077    // ── the file ──────────────────────────────────────────────────────────────
5078
5079    #[cfg(feature = "fs")]
5080    pub fn save(&mut self) {
5081        if self.is_untitled() {
5082            // No path to write and no name to invent: ⌘S on an untitled document
5083            // is a Save As, and only a frontend has a picker to ask with. Say so
5084            // rather than failing at the filesystem with an empty path.
5085            self.status = Some("untitled — save as…".into());
5086            return;
5087        }
5088        let path = self.path.clone();
5089        if self.write(&path) {
5090            self.mark_saved();
5091        }
5092    }
5093
5094    /// Save As: write the document to `path` and *move* it there — `self.path`
5095    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
5096    /// what Save As means; a copy would leave the user editing a document whose
5097    /// name is no longer where their keystrokes go.
5098    ///
5099    /// The move only happens if the bytes actually landed. A failed write leaves
5100    /// the path, `dirty`, and the disk watermark exactly as they were, with the
5101    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
5102    /// must never come away believing it was saved.
5103    ///
5104    /// An existing `path` is overwritten, and the caller is the one that knows
5105    /// whether to ask first: a Save As picker has already run that prompt, and a
5106    /// second confirmation from down here would be the same question twice.
5107    ///
5108    /// `format` does **not** follow the new extension. The buffer is parsed as
5109    /// the format it was opened with, and re-reading it as another one is a
5110    /// conversion — a different, lossy operation that would throw away the undo
5111    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
5112    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
5113    /// until it's reopened.
5114    #[cfg(feature = "fs")]
5115    pub fn save_as(&mut self, path: PathBuf) {
5116        if !self.write(&path) {
5117            return;
5118        }
5119        self.path = path;
5120        self.mark_saved();
5121    }
5122
5123    /// Put `source` on disk at `path`, reporting whether it got there. The one
5124    /// place leaf writes a document, so a save and a Save As can't disagree
5125    /// about what a failure looks like.
5126    #[cfg(feature = "fs")]
5127    fn write(&mut self, path: &Path) -> bool {
5128        match std::fs::write(path, self.source.as_bytes()) {
5129            Ok(()) => true,
5130            Err(e) => {
5131                self.status = Some(format!("save failed: {e}"));
5132                false
5133            }
5134        }
5135    }
5136
5137    /// Re-base the document's saved watermark to the current bytes: clears
5138    /// `dirty`, records `source` as the new clean state (so undoing back to here
5139    /// clears the flag again), and re-stamps the on-disk hash.
5140    ///
5141    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
5142    /// the hook a **filesystem-free host** calls itself once it has persisted
5143    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
5144    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
5145    /// are already where that host wants them, and this just tells the model they
5146    /// are safe.
5147    pub fn mark_saved(&mut self) {
5148        self.clean_source = self.source.clone();
5149        self.dirty = false;
5150        // The bytes on disk are now ours, so this is the new watermark: without
5151        // re-stamping it, every save would report its own work as an external
5152        // change forever after.
5153        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
5154        self.status = Some(format!("saved {}", self.file_name()));
5155    }
5156
5157    /// What the file looks like now against the bytes leaf last read or wrote.
5158    ///
5159    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
5160    /// so this is a filesystem round-trip, not a per-frame question — ask it
5161    /// when a window regains focus, on a timer, or before a save.
5162    ///
5163    /// This *only* reports the file. Whether the document also has unsaved edits
5164    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
5165    /// [`DiskState::Changed`] means a save overwrites someone's work and a
5166    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
5167    /// it has no way to ask — so it hands a frontend both halves and lets it put
5168    /// the question to the person who can answer it.
5169    #[cfg(feature = "fs")]
5170    pub fn disk_state(&self) -> DiskState {
5171        let Some(want) = self.disk_hash else {
5172            return DiskState::Untitled;
5173        };
5174        match std::fs::read(&self.path) {
5175            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
5176            Ok(_) => DiskState::Changed,
5177            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
5178            Err(_) => DiskState::Unreadable,
5179        }
5180    }
5181
5182    /// Re-read the file and replace the document with what's there — the other
5183    /// answer to a [`DiskState::Changed`].
5184    ///
5185    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
5186    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
5187    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
5188    /// document shouldn't have to argue with a guard.
5189    ///
5190    /// **The undo history survives, and the reload is one step in it.** The
5191    /// whole buffer is spliced with the file's bytes through the same door every
5192    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
5193    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
5194    /// swapped the document out from under a reader gives them back what they
5195    /// were looking at, marked dirty, and ^Z again carries on into whatever they
5196    /// had done before it. This used to build a fresh parse and drop the stack,
5197    /// on the reasoning that twig's history belongs to the buffer and these are
5198    /// different bytes; that is true of *rebasing* a step onto them and not of
5199    /// recording the swap itself as one, which is all this is. A splice twig
5200    /// won't take falls back to the fresh parse, and only that path still costs
5201    /// the history.
5202    ///
5203    /// The caret keeps its byte offset, clamped to the new length; the selection
5204    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
5205    /// file changed, so it can't know where the caret "still" is. Clamping keeps
5206    /// it where the user left it in the common case (a change further down the
5207    /// file, or none in the text they're sitting in), and never puts it
5208    /// somewhere invalid. A selection has two such offsets and no such excuse —
5209    /// silently reinterpreting one over changed bytes would arm the *next*
5210    /// keystroke to delete something the user never selected.
5211    ///
5212    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
5213    /// document alone with a status.
5214    #[cfg(feature = "fs")]
5215    pub fn reload(&mut self) {
5216        if self.is_untitled() {
5217            self.status = Some("no file to reload".into());
5218            return;
5219        }
5220        let bytes = match std::fs::read(&self.path) {
5221            Ok(b) => b,
5222            Err(e) => {
5223                self.status = Some(format!("reload failed: {e}"));
5224                return;
5225            }
5226        };
5227        let Ok(source) = String::from_utf8(bytes) else {
5228            self.status = Some("reload failed: file is not UTF-8".into());
5229            return;
5230        };
5231        // Already these bytes — someone saved a file back unchanged, or leaf's
5232        // own write is being read back. Re-baseline against it and stop: a
5233        // splice of the text onto itself would put an undo step on the stack for
5234        // something nobody did.
5235        if source == self.source {
5236            self.disk_hash = Some(hash_bytes(source.as_bytes()));
5237            self.clean_source = source;
5238            self.dirty = false;
5239            self.status = Some(format!("reloaded {}", self.file_name()));
5240            return;
5241        }
5242        let caret = self.caret;
5243        // The pre-reload caret, so undoing the swap puts it back where the
5244        // reader was standing — the same bracketing `splice_exact` does.
5245        self.record_caret();
5246        if self
5247            .editor
5248            .edit_range(0, self.source.len(), &source)
5249            .is_ok()
5250        {
5251            self.refresh();
5252        } else {
5253            // twig wouldn't take the splice. Start over from the bytes, which is
5254            // what this always did, and is the one path that still costs the
5255            // history — `format` is the format this document *is*, not what the
5256            // (unchanged) name now says, see `save_as`.
5257            match new_editor(source.as_bytes(), self.format) {
5258                Ok(editor) => {
5259                    self.editor = editor;
5260                    self.source = source.clone();
5261                    // Not going through `refresh`, so the revision has to move
5262                    // here or every frontend keeps painting the old file from
5263                    // cache.
5264                    self.revision += 1;
5265                }
5266                Err(e) => {
5267                    self.status = Some(format!("reload failed: {e}"));
5268                    return;
5269                }
5270            }
5271        }
5272        self.disk_hash = Some(hash_bytes(source.as_bytes()));
5273        self.clean_source = self.source.clone();
5274        self.caret = caret.min(self.source.len());
5275        self.anchor = None;
5276        self.goal_col = None;
5277        self.last_edit_kind = None;
5278        self.dirty = false;
5279        self.status = Some(format!("reloaded {}", self.file_name()));
5280        self.clamp_caret();
5281        // And the post-reload caret, so a redo restores it.
5282        self.record_caret();
5283    }
5284
5285    /// Re-read the source from twig after it has changed the document. The one
5286    /// funnel every edit, undo, and redo comes through — so it's where the
5287    /// revision moves, and anything cached against the text dies here.
5288    fn refresh(&mut self) {
5289        if let Ok(s) = self.editor.source_str() {
5290            self.source = s;
5291        }
5292        self.revision += 1;
5293        // An edit is a step onto the history and the end of anything undone;
5294        // `undo`/`redo` come through here too and correct this after.
5295        self.undo_steps += 1;
5296        self.redo_steps = 0;
5297        self.clamp_caret();
5298    }
5299
5300    /// Whether [`undo`](Self::undo) has a step to take back — for a native
5301    /// Edit menu to enable its item by. See the note on `undo_steps` for what
5302    /// "has" means here.
5303    pub fn can_undo(&self) -> bool {
5304        !self.read_only && self.undo_steps > 0
5305    }
5306
5307    /// Whether [`redo`](Self::redo) has an undone step to restore.
5308    pub fn can_redo(&self) -> bool {
5309        !self.read_only && self.redo_steps > 0
5310    }
5311
5312    // ── caret movement ─────────────────────────────────────────────────────────
5313    // `extend` grows the selection (Shift+motion): it pins the anchor on the
5314    // first extended step and moves only the caret; an un-extended motion drops
5315    // the selection.
5316
5317    /// Place the caret at byte `offset` (clamped to a char boundary), extending
5318    /// the selection when `extend` is set. The public form of `move_to`, for a
5319    /// frontend that hit-tests pixels straight to a source offset.
5320    pub fn place_caret(&mut self, offset: usize, extend: bool) {
5321        self.goal_col = None;
5322        let before = self.caret;
5323        // A pixel hit-test can land between the visible caret stops — in the
5324        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
5325        // Snap to the nearest real stop so the caret can't come to rest where it
5326        // would draw in one place and type in another. The `(row, col)` click
5327        // path (`click`) already snaps this way through `offset_of_pos`; the
5328        // source view reaches every byte, so it snaps to nothing.
5329        let target = match self.view {
5330            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
5331            // The source view reaches every byte, so there is no stop to snap
5332            // to — but "every byte" still means every *character* boundary. A
5333            // caret resting inside a multi-byte character draws nowhere real
5334            // and panics the next time anything slices there.
5335            View::Source => self.char_boundary_at_or_before(offset),
5336        };
5337        self.move_to(target, extend);
5338        self.clamp_caret();
5339        self.debug_assert_on_a_stop(before);
5340    }
5341
5342    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
5343    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
5344    /// grab the metadata) while the source view still selects the literal whole.
5345    pub fn select_all(&mut self) {
5346        self.anchor = Some(self.caret_floor());
5347        self.caret = self.source.len();
5348        self.goal_col = None;
5349        self.last_edit_kind = None;
5350        self.status = None;
5351    }
5352
5353    /// Select the word (or whitespace / punctuation run) at `offset` — the
5354    /// double-click gesture. Anchors on the run's start with the caret at its
5355    /// end so a following Shift-motion extends from the far edge.
5356    pub fn select_word_at(&mut self, offset: usize) {
5357        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
5358        self.anchor = Some(s);
5359        self.caret = e;
5360        self.goal_col = None;
5361        self.last_edit_kind = None;
5362        self.status = None;
5363        self.clamp_caret();
5364    }
5365
5366    /// Select the whole enclosing text block (paragraph, heading, list item's
5367    /// text…) at `offset` — the triple-click gesture. Reads the range straight
5368    /// from the AST (twig's `content_span`), so it selects the entire *logical*
5369    /// paragraph even when that paragraph soft-wraps across several visual rows —
5370    /// where a visual-row-based select breaks down, because one source offset at
5371    /// a wrap boundary belongs to two rows at once.
5372    pub fn select_block_at(&mut self, offset: usize) {
5373        let off = offset.min(self.source.len());
5374        let range = self
5375            .editor
5376            .ancestors_at(off)
5377            .ok()
5378            .and_then(|chain| {
5379                // Ancestors run root → deepest; the deepest node that is neither
5380                // an inline span nor a multi-block container is the text block
5381                // the caret sits in (a paragraph, a heading, a code block…).
5382                chain
5383                    .into_iter()
5384                    .rev()
5385                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
5386                    .map(|m| m.content_span.unwrap_or(m.span))
5387            })
5388            .unwrap_or_else(|| source_line_range(&self.source, off));
5389        self.anchor = Some(range.start.min(self.source.len()));
5390        self.caret = range.end.min(self.source.len());
5391        self.goal_col = None;
5392        self.last_edit_kind = None;
5393        self.status = None;
5394        self.clamp_caret();
5395    }
5396
5397    /// Select the exact source range `[start, end)` — anchor at `start`, caret
5398    /// at `end` — without snapping either end to a visible caret stop.
5399    ///
5400    /// The one caret verb that takes a range it was *handed* rather than one it
5401    /// worked out, for a host that already knows the bytes it means: a search
5402    /// hit, an annotation's footprint, a quote re-anchored through
5403    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
5404    /// wrong tool for that, and not by a little — it snaps to the nearest
5405    /// *visible* stop, and where a range butts up against a hidden delimiter
5406    /// the nearest stop is the one before it, so selecting the "needle" of
5407    /// `**needle**` comes back with "needl" and an edit against it strands the
5408    /// "e".
5409    ///
5410    /// What `place_caret` does that is bookkeeping rather than snapping still
5411    /// happens here, because a host handing in a range is not asking to opt out
5412    /// of the invariants:
5413    ///
5414    /// - both ends are clamped into the document and up to
5415    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
5416    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
5417    ///   types into the metadata;
5418    /// - both land on character boundaries, so nothing slices a `é` in half;
5419    /// - the sticky vertical goal column is dropped, and any armed inline mark
5420    ///   disarmed, since a range from outside inherits neither.
5421    ///
5422    /// An empty range is a caret rather than a selection —
5423    /// [`selection`](Self::selection) reports `None` for it, as it does for any
5424    /// anchor that has met the caret.
5425    pub fn select_range(&mut self, start: usize, end: usize) {
5426        let floor = self.caret_floor();
5427        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
5428        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
5429        self.anchor = Some(anchor);
5430        self.caret = caret;
5431        self.goal_col = None;
5432        self.status = None;
5433        self.last_edit_kind = None;
5434        self.clear_pending();
5435    }
5436
5437    /// `offset` itself if it is a character boundary, else the boundary before
5438    /// it. An offset that isn't one draws nowhere real and panics the next time
5439    /// anything slices there.
5440    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
5441        let mut o = offset.min(self.source.len());
5442        while o > 0 && !self.source.is_char_boundary(o) {
5443            o -= 1;
5444        }
5445        o
5446    }
5447
5448    /// The lowest source offset the caret may occupy in the active view. In
5449    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
5450    /// the first rendered offset; the source view reaches everything, so it's 0.
5451    fn caret_floor(&self) -> usize {
5452        match self.view {
5453            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
5454            View::Source => 0,
5455        }
5456    }
5457
5458    /// Land in a table cell with its whole content selected — the anchor at the
5459    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
5460    /// like tabbing into a form field: the text comes up selected, so typing
5461    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
5462    /// end`) collapses to a plain caret home (an empty selection is no selection).
5463    fn select_cell(&mut self, start: usize, end: usize) {
5464        self.select_range(start, end);
5465    }
5466
5467    fn move_to(&mut self, offset: usize, extend: bool) {
5468        if extend {
5469            if self.anchor.is_none() {
5470                self.anchor = Some(self.caret);
5471            }
5472        } else {
5473            self.anchor = None;
5474        }
5475        self.caret = offset.min(self.source.len()).max(self.caret_floor());
5476        self.status = None;
5477        // A caret move ends the current typing/deletion run, so the next edit
5478        // starts a fresh undo group rather than coalescing across the gap.
5479        self.last_edit_kind = None;
5480        // Moving away disarms any sticky mark — "start bold" applies only where
5481        // it was asked for, not wherever the caret next lands.
5482        self.clear_pending();
5483    }
5484
5485    // In the source view, motion walks source bytes / source lines. In the
5486    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
5487    // what steps the caret cleanly over hidden delimiters.
5488
5489    pub fn move_left(&mut self, extend: bool) {
5490        self.goal_col = None;
5491        if !extend && let Some((s, _e)) = self.selection() {
5492            self.move_to(s, false);
5493            return;
5494        }
5495        let target = match self.view {
5496            View::Source => {
5497                if self.caret > 0 {
5498                    prev_boundary(&self.source, self.caret)
5499                } else {
5500                    0
5501                }
5502            }
5503            // Walks caret *stops*, not columns: decoration (a table border, a
5504            // cell's padding) is stepped over in one press, and a hidden
5505            // delimiter never holds the caret up.
5506            View::Wysiwyg => self.vmap.stop_before(self.caret).unwrap_or(self.caret),
5507        };
5508        let before = self.caret;
5509        self.move_to(target, extend);
5510        self.debug_assert_on_a_stop(before);
5511    }
5512
5513    pub fn move_right(&mut self, extend: bool) {
5514        self.goal_col = None;
5515        if !extend && let Some((_s, e)) = self.selection() {
5516            self.move_to(e, false);
5517            return;
5518        }
5519        let target = match self.view {
5520            View::Source => {
5521                if self.caret < self.source.len() {
5522                    next_boundary(&self.source, self.caret)
5523                } else {
5524                    self.caret
5525                }
5526            }
5527            View::Wysiwyg => self.vmap.stop_after(self.caret).unwrap_or(self.caret),
5528        };
5529        let before = self.caret;
5530        self.move_to(target, extend);
5531        self.debug_assert_on_a_stop(before);
5532    }
5533
5534    /// Move to the start of the previous word (⌥← / Ctrl+←).
5535    pub fn move_word_left(&mut self, extend: bool) {
5536        self.goal_col = None;
5537        let before = self.caret;
5538        let target = self.word_left_from(self.caret);
5539        self.move_to(target, extend);
5540        self.debug_assert_on_a_stop(before);
5541    }
5542
5543    /// Move to the end of the next word (⌥→ / Ctrl+→).
5544    pub fn move_word_right(&mut self, extend: bool) {
5545        self.goal_col = None;
5546        let before = self.caret;
5547        let target = self.word_right_from(self.caret);
5548        self.move_to(target, extend);
5549        self.debug_assert_on_a_stop(before);
5550    }
5551
5552    // Word boundaries are found in the space the *view* is in. The source view
5553    // walks the source, because there the source is what's rendered. WYSIWYG
5554    // walks the rendered text instead: `**` is invisible to the user, so it has
5555    // to be invisible to word motion too — a caret parked inside one draws in
5556    // the column after `bold` and types two bytes earlier, and a word-delete
5557    // that stops there shreds the markup into `a ** c`.
5558
5559    /// The word boundary to the left of `off` in the active view's space.
5560    fn word_left_from(&self, off: usize) -> usize {
5561        match self.view {
5562            View::Source => prev_word(&self.source, off),
5563            View::Wysiwyg => self.glyph_word_left(off),
5564        }
5565    }
5566
5567    /// The word boundary to the right of `off` in the active view's space.
5568    fn word_right_from(&self, off: usize) -> usize {
5569        match self.view {
5570            View::Source => next_word(&self.source, off),
5571            View::Wysiwyg => self.glyph_word_right(off),
5572        }
5573    }
5574
5575    /// The character class of the glyph drawn at stop `off`.
5576    ///
5577    /// Read from the source, because a stop points at the source byte its glyph
5578    /// came from — the source *is* where the rendered character is written. What
5579    /// makes the walk glyph space rather than source space is that it only ever
5580    /// visits stops, and the hidden bytes between them have none.
5581    fn class_at(&self, off: usize) -> Class {
5582        self.source
5583            .get(off..)
5584            .and_then(|s| s.chars().next())
5585            .map_or(Class::Space, classify)
5586    }
5587
5588    /// [`next_word`] in glyph space: skip any leading separators, then consume
5589    /// the following word run, with the stop table standing in for the source's
5590    /// characters.
5591    fn glyph_word_right(&self, from: usize) -> usize {
5592        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
5593            return from;
5594        };
5595        let mut in_word = false;
5596        loop {
5597            match self.class_at(off) {
5598                Class::Word => in_word = true,
5599                _ if in_word => return off,
5600                _ => {}
5601            }
5602            match self.vmap.stop_after(off) {
5603                Some(next) => off = next,
5604                None => return off,
5605            }
5606        }
5607    }
5608
5609    /// [`prev_word`] in glyph space: skip separators walking left, then consume
5610    /// the preceding word run.
5611    fn glyph_word_left(&self, from: usize) -> usize {
5612        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
5613            return from;
5614        };
5615        let mut in_word = false;
5616        while let Some(prev) = self.vmap.stop_before(off) {
5617            match self.class_at(prev) {
5618                Class::Word => in_word = true,
5619                _ if in_word => return off,
5620                _ => {}
5621            }
5622            off = prev;
5623        }
5624        off
5625    }
5626
5627    /// After a motion that walks the visual map, the caret must be *on* the map.
5628    /// A stop is the only offset where the caret draws and edits in the same
5629    /// place, and it's the invariant both a caret parked inside an emoji and one
5630    /// parked inside a `**` were quietly breaking.
5631    ///
5632    /// Only when the caret actually moved: a walk with nowhere to go leaves it
5633    /// where it was, which is wherever the floor or a frontend put it rather
5634    /// than somewhere this motion chose.
5635    fn debug_assert_on_a_stop(&self, before: usize) {
5636        debug_assert!(
5637            self.view != View::Wysiwyg
5638                || self.vmap.num_rows() == 0
5639                || self.caret == before
5640                || self.vmap.is_stop(self.caret),
5641            "motion left the caret at {}, which is not a caret stop: it would draw in \
5642             one place and type in another",
5643            self.caret
5644        );
5645    }
5646
5647    // Up and Down run off the ends of the document rather than stopping dead at
5648    // them: Up from the first row lands at the document's start, Down from the
5649    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
5650    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
5651    // reaching the end of the text is what a reader means by it.
5652    //
5653    // The views used to disagree here by accident rather than by decision: the
5654    // source view fell into the edge behaviour through `row_col_to_offset`
5655    // clamping an out-of-range row to the end of the string, while WYSIWYG had
5656    // no row below to walk to and did nothing at all. They share the rule now,
5657    // each in its own space — the source view reaches every byte, WYSIWYG only
5658    // the offsets it draws.
5659
5660    pub fn move_up(&mut self, extend: bool) {
5661        let (row, col) = self.caret_pos();
5662        let goal = self.goal_col.unwrap_or(col);
5663        let target = match self.view {
5664            View::Source => match row.checked_sub(1) {
5665                Some(r) => row_col_to_offset(&self.source, r, goal),
5666                None => self.reachable_start(),
5667            },
5668            // A table's border rules are drawn but hold no caret, so Up steps
5669            // over them to the row that does.
5670            View::Wysiwyg => match self.vmap.navigable_above(row) {
5671                Some(r) => self.row_target(r, goal),
5672                None => self.reachable_start(),
5673            },
5674        };
5675        self.step_vertical(target, goal, extend);
5676    }
5677
5678    pub fn move_down(&mut self, extend: bool) {
5679        let (row, col) = self.caret_pos();
5680        let goal = self.goal_col.unwrap_or(col);
5681        let target = match self.view {
5682            View::Source => match self.source_row_below(row) {
5683                Some(r) => row_col_to_offset(&self.source, r, goal),
5684                None => self.reachable_end(),
5685            },
5686            View::Wysiwyg => match self.vmap.navigable_below(row) {
5687                Some(r) => self.row_target(r, goal),
5688                None => self.reachable_end(),
5689            },
5690        };
5691        self.step_vertical(target, goal, extend);
5692    }
5693
5694    /// Land a vertical motion at `target`, latching the `goal` column it aimed
5695    /// with so the rest of the run keeps aiming there.
5696    ///
5697    /// A motion with nowhere to go changes *nothing*, the goal column included:
5698    /// the latch used to run before the early return at the top of the document,
5699    /// so an Up that did nothing still armed a column, and the next Down aimed
5700    /// at one the caret had never been in.
5701    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
5702        let before = self.caret;
5703        if target == before {
5704            return;
5705        }
5706        self.goal_col = Some(goal);
5707        self.move_to(target, extend);
5708        self.debug_assert_on_a_stop(before);
5709    }
5710
5711    /// The source line below `row`, or `None` when `row` is the last one. Lines
5712    /// are counted by newline, so a trailing one leaves a real, empty last line
5713    /// for the caret to sit on — the document ends below it, not on it.
5714    fn source_row_below(&self, row: usize) -> Option<usize> {
5715        let last = self.source.bytes().filter(|&b| b == b'\n').count();
5716        (row < last).then_some(row + 1)
5717    }
5718
5719    /// Where a vertical motion aiming at the `goal` column lands on visual row
5720    /// `r`: the column clamped to the row, mapped to its offset, then held
5721    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
5722    /// column belongs to the row below, and a gutter's column 0 points at the
5723    /// block rather than at this row.
5724    fn row_target(&self, r: usize, goal: usize) -> usize {
5725        let (start, end) = self.row_bounds(r);
5726        self.vmap
5727            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
5728            .clamp(start, end)
5729    }
5730
5731    /// The first and last offsets the caret can reach in the active view.
5732    ///
5733    /// Not the same span in both: the source view shows every byte, so it can
5734    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
5735    /// sits below the first stop, and a document's trailing newline is drawn
5736    /// nowhere and so sits past the last.
5737    fn reachable_start(&self) -> usize {
5738        match self.view {
5739            View::Source => 0,
5740            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
5741        }
5742    }
5743
5744    fn reachable_end(&self) -> usize {
5745        match self.view {
5746            View::Source => self.source.len(),
5747            View::Wysiwyg => self
5748                .vmap
5749                .stop_at_or_before(self.source.len())
5750                .unwrap_or(self.caret),
5751        }
5752    }
5753
5754    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
5755    /// including the space a soft wrap ate off its end, which is drawn on this
5756    /// row however much the offset past it belongs to the next one.
5757    fn row_span(&self, r: usize) -> (usize, usize) {
5758        let start = self
5759            .vmap
5760            .row_start(r)
5761            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
5762        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
5763        (start.min(end), end)
5764    }
5765
5766    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
5767    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
5768    /// this row's last position is the one before it — the offset before the
5769    /// space the wrap ate, where the caret draws just past the row's last word
5770    /// and types there too.
5771    ///
5772    /// Aiming at the shared offset instead is what stalled End: it is the row's
5773    /// last *column*, so End pressed on the row reached it and then read back as
5774    /// the row below's start, where a second press ran on to that row's end and
5775    /// the next to the one after — End walking down the paragraph a row a press.
5776    fn row_bounds(&self, r: usize) -> (usize, usize) {
5777        let (start, end) = self.row_span(r);
5778        let wraps = self
5779            .vmap
5780            .navigable_below(r)
5781            .and_then(|b| self.vmap.row_start(b))
5782            .is_some_and(|off| off == end);
5783        match wraps {
5784            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
5785            false => (start, end),
5786        }
5787    }
5788
5789    /// The `[start, end]` of the line Home and End aim at: the visual row in
5790    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
5791    ///
5792    /// A soft-wrapped row is a line here, because it is one to the eye and the
5793    /// eye is what these keys are aimed by — a reader pressing End means the end
5794    /// of the line they can see. (`select_block_at` wants the opposite and reads
5795    /// the AST for it: a triple-click grabs the whole paragraph, however many
5796    /// rows it folds into.)
5797    fn line_bounds(&self) -> (usize, usize) {
5798        let (row, _) = self.caret_pos();
5799        match self.view {
5800            View::Source => {
5801                let start = line_start(&self.source, row);
5802                (start, line_end_from(&self.source, start))
5803            }
5804            View::Wysiwyg => self.row_bounds(row),
5805        }
5806    }
5807
5808    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
5809    /// *drawn* — what a kill takes.
5810    ///
5811    /// The two part only at a soft wrap, over the space the wrap ate: the caret
5812    /// can't stand after it (that offset opens the row below, and End stopping
5813    /// there would walk), but it is on this row, and a kill that spared it would
5814    /// leave a double space behind where the row's text had been. Deleting it
5815    /// joins nothing — a wrap is drawn, not written.
5816    fn line_span(&self) -> (usize, usize) {
5817        let (row, _) = self.caret_pos();
5818        match self.view {
5819            View::Source => self.line_bounds(),
5820            View::Wysiwyg => self.row_span(row),
5821        }
5822    }
5823
5824    /// The first offset in `[start, end]` holding something other than
5825    /// whitespace, or `end` when the line holds nothing else — where Home aims.
5826    ///
5827    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
5828    /// so a hidden delimiter is never taken for the line's first character (nor
5829    /// landed on), and the source view steps the source it is showing.
5830    fn first_non_space(&self, start: usize, end: usize) -> usize {
5831        let mut off = start;
5832        while off < end {
5833            if self.class_at(off) != Class::Space {
5834                return off;
5835            }
5836            off = match self.view {
5837                View::Source => next_boundary(&self.source, off),
5838                View::Wysiwyg => match self.vmap.stop_after(off) {
5839                    Some(next) => next,
5840                    None => return end,
5841                },
5842            };
5843        }
5844        end
5845    }
5846
5847    /// Home: to the first character on the line, or to column 0 when the caret
5848    /// is already on it — the two-press toggle every editor spells this way.
5849    /// The indentation is somewhere the caret has to be able to reach and almost
5850    /// never where a reader is headed, so it costs the second press.
5851    pub fn move_home(&mut self, extend: bool) {
5852        self.goal_col = None;
5853        let (start, end) = self.line_bounds();
5854        let text = self.first_non_space(start, end);
5855        let target = if self.caret == text { start } else { text };
5856        let before = self.caret;
5857        self.move_to(target, extend);
5858        self.debug_assert_on_a_stop(before);
5859    }
5860
5861    /// End: to the end of the line.
5862    pub fn move_end(&mut self, extend: bool) {
5863        self.goal_col = None;
5864        let (_, end) = self.line_bounds();
5865        let before = self.caret;
5866        self.move_to(end, extend);
5867        self.debug_assert_on_a_stop(before);
5868    }
5869
5870    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
5871    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
5872    /// when the caret isn't in a table, or is already in the last/first cell — the
5873    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
5874    /// meaning everywhere else.
5875    pub fn cell_hop(&mut self, forward: bool) -> bool {
5876        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
5877            return false;
5878        };
5879        // Flatten to document (row-major) order and step one cell either way.
5880        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
5881        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
5882        let next = if forward {
5883            i.checked_add(1)
5884        } else {
5885            i.checked_sub(1)
5886        };
5887        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
5888            return false; // at the table's edge; leave Tab to the frontend
5889        };
5890        self.select_cell(start, end);
5891        true
5892    }
5893
5894    /// Move the caret to the cell directly above (`down == false`) or below in
5895    /// the same column, landing with the cell's whole content selected (see
5896    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
5897    /// when the caret isn't in a table), so the frontend can fall through — the
5898    /// vertical counterpart of [`Self::cell_hop`].
5899    ///
5900    /// A ragged row that is short a column clamps to its last cell, so Down never
5901    /// falls out of the table over a gap the row above happened to have.
5902    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
5903        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
5904            return false;
5905        };
5906        let target = match down {
5907            true => r + 1,
5908            false if r == 0 => return false,
5909            false => r - 1,
5910        };
5911        let Some(row) = grid.get(target) else {
5912            return false;
5913        };
5914        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
5915            return false;
5916        };
5917        self.select_cell(start, end);
5918        true
5919    }
5920
5921    /// The table containing `off` as a row-major grid of `(start, end)` cell
5922    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
5923    /// isn't in a table. Read straight off the visual map's laid-out grid, so
5924    /// every cell (an empty one included, whose derived home twig gives no
5925    /// `content_span` for) is present and in the order Tab walks them.
5926    // Grid, row, column — three returns that only ever travel together, and a
5927    // named type for the pair of them would be read at one call site.
5928    #[allow(clippy::type_complexity)]
5929    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
5930        for t in &self.vmap.tables {
5931            let mut pos = None;
5932            let grid: Vec<Vec<(usize, usize)>> = t
5933                .grid
5934                .iter()
5935                .enumerate()
5936                .map(|(r, row)| {
5937                    row.cells
5938                        .iter()
5939                        .enumerate()
5940                        .map(|(c, cell)| {
5941                            if pos.is_none() && off >= cell.start && off <= cell.end {
5942                                pos = Some((r, c));
5943                            }
5944                            (cell.start, cell.end)
5945                        })
5946                        .collect()
5947                })
5948                .collect();
5949            if let Some((r, c)) = pos {
5950                return Some((grid, r, c));
5951            }
5952        }
5953        None
5954    }
5955
5956    // ── table key policy ──────────────────────────────────────────────────────
5957    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
5958    // as one policy every frontend shares, rather than each re-deriving it. Each
5959    // reports whether it acted *as a table key*; a `false` hands the key back to
5960    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
5961    // everywhere else.
5962
5963    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
5964    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
5965    /// back and simply stays put at the very first cell. `false` when the caret
5966    /// isn't in a table.
5967    pub fn cell_tab(&mut self, forward: bool) -> bool {
5968        if !self.caret_in_table() {
5969            return false;
5970        }
5971        if self.cell_hop(forward) {
5972            return true;
5973        }
5974        // Off the last cell: grow the table by a row and step into its first
5975        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
5976        if forward {
5977            self.append_row_and_enter(0);
5978        }
5979        true
5980    }
5981
5982    /// Return inside a table: drop to the cell below in the same column,
5983    /// appending a new row when the caret is already in the last one. `false`
5984    /// when the caret isn't in a table, so the frontend inserts a newline.
5985    pub fn cell_return(&mut self) -> bool {
5986        if !self.caret_in_table() {
5987            return false;
5988        }
5989        if self.cell_move_vertical(true) {
5990            return true;
5991        }
5992        // Already on the last row: grow one below and drop into the same column.
5993        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
5994        self.append_row_and_enter(col);
5995        true
5996    }
5997
5998    /// Append a row below the caret's (last) row and land in `col` of it. The
5999    /// caret is in the last row, so twig's "insert below" makes the fresh row the
6000    /// table's new last — but twig re-spells the whole table, moving every byte,
6001    /// so the destination is read back from the rebuilt grid by the table's
6002    /// position (stable across a row insert), not from the pre-edit caret.
6003    fn append_row_and_enter(&mut self, col: usize) {
6004        let table = self.caret_table_index();
6005        self.table_insert_row(true);
6006        self.rebuild_map();
6007        let Some((start, end)) = table
6008            .and_then(|ti| self.vmap.tables.get(ti))
6009            .and_then(|t| t.grid.last())
6010            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
6011            .map(|cell| (cell.start, cell.end))
6012        else {
6013            return;
6014        };
6015        self.select_cell(start, end);
6016    }
6017
6018    /// The index, among the document's tables, of the one the caret sits in —
6019    /// `None` when it's in none. Used to re-find a table after an edit re-spells
6020    /// it (a row insert leaves the table order unchanged).
6021    fn caret_table_index(&self) -> Option<usize> {
6022        let off = self.caret;
6023        self.vmap.tables.iter().position(|t| {
6024            t.grid
6025                .iter()
6026                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
6027        })
6028    }
6029
6030    /// Shift+Return inside a table: insert a hard line break *within* the current
6031    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
6032    /// table, so the frontend inserts an ordinary line break.
6033    ///
6034    /// A table row is a single source line, so the newline-spelled hard break
6035    /// can't live in a cell. twig spells the in-cell break the format's way
6036    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
6037    /// break round-trips as structure the renderer reads back as a line — not the
6038    /// opaque raw HTML the old raw-splice left behind.
6039    ///
6040    /// Djot has no idiomatic in-cell break, so twig refuses it
6041    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
6042    /// would render as the literal text `<br>`. The gesture is still *consumed*
6043    /// there — returning `false` would let the frontend insert a real newline,
6044    /// which splits the one-line row — it just leaves the cell unchanged and says
6045    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
6046    ///
6047    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
6048    /// have to be read together: djot is not the only `false`, and naming it in
6049    /// the message was already a guess that HTML — which spells the break as its
6050    /// own `<br>` — would have made wrong.
6051    pub fn cell_line_break(&mut self) -> bool {
6052        if self.read_only || !self.caret_in_table() {
6053            return false;
6054        }
6055        self.record_caret();
6056        match self.editor.insert_line_break(self.caret) {
6057            Ok(change) => {
6058                self.last_edit_kind = None;
6059                self.refresh();
6060                self.caret = change.new.end;
6061                self.anchor = None;
6062                self.goal_col = None;
6063                self.clamp_caret();
6064                self.dirty = self.source != self.clean_source;
6065                self.status = None;
6066                self.record_caret();
6067            }
6068            Err(twig::Error::UnsupportedFormat) => {
6069                self.status = Some(format!(
6070                    "in-cell line breaks aren't supported in {}",
6071                    self.format_name()
6072                ));
6073            }
6074            Err(_) => {}
6075        }
6076        true
6077    }
6078
6079    /// Rebuild the visual map at the width the last build used. A structural edit
6080    /// bumps the revision and swaps the source in, but leaves the *map* stale;
6081    /// when a single gesture edits and then moves over the result (Tab appending
6082    /// a row, then stepping into it), the move needs the map to already show the
6083    /// edit rather than waiting for the frontend's next frame.
6084    fn rebuild_map(&mut self) {
6085        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
6086        self.build_map(wrap);
6087    }
6088
6089    /// Move the caret to the very start of the document (⌘↑ on macOS,
6090    /// Ctrl+Home on Windows/Linux).
6091    pub fn move_doc_start(&mut self, extend: bool) {
6092        self.goal_col = None;
6093        self.move_to(0, extend);
6094    }
6095
6096    /// Move the caret to the very end of the document (⌘↓ on macOS,
6097    /// Ctrl+End on Windows/Linux).
6098    pub fn move_doc_end(&mut self, extend: bool) {
6099        self.goal_col = None;
6100        let end = self.source.len();
6101        self.move_to(end, extend);
6102    }
6103
6104    /// Point the caret at the body cell `(row, col)` the mouse landed on —
6105    /// `col` being a cell of the terminal grid, which is what a display column
6106    /// is. A click on the far cell of a wide character lands at that
6107    /// character's start; the mapping's own doc-comments carry the rule.
6108    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
6109        self.goal_col = None;
6110        let target = match self.view {
6111            View::Source => row_col_to_offset(&self.source, row, col),
6112            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
6113        };
6114        let before = self.caret;
6115        self.move_to(target, extend);
6116        self.debug_assert_on_a_stop(before);
6117    }
6118
6119    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
6120    /// screen if it has moved since the last frame, and never scroll past the
6121    /// last of `rows`.
6122    ///
6123    /// Only if it has *moved* — that's the whole point. Revealing the caret on
6124    /// every frame ties the viewport to it, and a scroll wheel that fights the
6125    /// caret for the viewport loses: the view snaps back the instant it tries to
6126    /// pass the caret's row, so the document can't be scrolled beyond what's
6127    /// already on screen. A caret move is the frontend's cue to follow; a scroll
6128    /// with the caret sitting still is the reader's cue to leave it alone.
6129    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
6130        if self.drawn_caret != Some(self.caret) {
6131            if caret_row < self.scroll {
6132                self.scroll = caret_row;
6133            } else if height > 0 && caret_row >= self.scroll + height {
6134                self.scroll = caret_row + 1 - height;
6135            }
6136            self.drawn_caret = Some(self.caret);
6137        }
6138        self.scroll = self.scroll.min(rows.saturating_sub(1));
6139    }
6140
6141    /// The caret's screen position `(row, col)` in the active view's grid, with
6142    /// `col` a display column: the cell to draw the caret in, which on a line of
6143    /// `你好` or emoji is not the count of characters before it.
6144    pub fn caret_pos(&self) -> (usize, usize) {
6145        match self.view {
6146            View::Source => offset_to_row_col(&self.source, self.caret),
6147            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
6148        }
6149    }
6150
6151    fn clamp_caret(&mut self) {
6152        if self.caret > self.source.len() {
6153            self.caret = self.source.len();
6154        }
6155        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
6156        // any selection anchor) to the first rendered offset.
6157        let floor = self.caret_floor();
6158        if self.caret < floor {
6159            self.caret = floor;
6160        }
6161        if let Some(a) = self.anchor
6162            && a < floor
6163        {
6164            self.anchor = Some(floor);
6165        }
6166        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
6167            self.caret -= 1;
6168        }
6169    }
6170}
6171
6172// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
6173
6174// Left/right motion and backspace/delete step by *grapheme cluster*, not
6175// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
6176// marks moves and deletes as the single character a user sees. Grapheme
6177// boundaries are a superset of char boundaries, so the caret stays valid for twig.
6178
6179/// How an insert of `text` groups for undo: a single typed character folds into
6180/// the run of typing around it, while a newline or a multi-character insert is a
6181/// step of its own.
6182fn typed_edit_kind(text: &str) -> EditKind {
6183    if text.chars().take(2).count() == 1 && text != "\n" {
6184        EditKind::Insert
6185    } else {
6186        EditKind::Other
6187    }
6188}
6189
6190fn prev_boundary(s: &str, i: usize) -> usize {
6191    let mut cursor = GraphemeCursor::new(i, s.len(), true);
6192    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
6193}
6194
6195fn next_boundary(s: &str, i: usize) -> usize {
6196    let mut cursor = GraphemeCursor::new(i, s.len(), true);
6197    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
6198}
6199
6200// ── word boundaries ──────────────────────────────────────────────────────────
6201// The shared primitive behind word-wise motion, word deletion, and
6202// double-click-to-select-a-word. A "word" is a maximal run of one character
6203// class; whitespace and punctuation are their own classes, so motion skips
6204// cleanly between them the way native text fields do.
6205
6206#[derive(PartialEq, Eq, Clone, Copy)]
6207enum Class {
6208    Word,
6209    Space,
6210    Other,
6211}
6212
6213/// The source range of an inline node's own visible text — the part of it a
6214/// WYSIWYG caret can reach, as against the delimiters that only spell it.
6215/// `None` for a node with no interior to empty (a `str`, a break).
6216///
6217/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
6218/// one delimiter in from the span — the same place the renderer maps it to. A
6219/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
6220/// against the source rather than trusted: a range guessed wrong here is text
6221/// deleted wrong.
6222fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
6223    if let Some(span) = n.content_span.clone() {
6224        return Some(span);
6225    }
6226    match n.kind.as_str() {
6227        "verbatim" | "inline_math" => {
6228            let text = n.text.as_ref()?;
6229            let start = n.span.start + 1;
6230            let range = start..start + text.len();
6231            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
6232        }
6233        _ => None,
6234    }
6235}
6236
6237/// The `id` a node declares, or `None` for one that declares none — the
6238/// attribute djot writes for a `{#v1}` and mints for a heading.
6239///
6240/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
6241/// names nothing, so it reads as absent rather than as the empty string.
6242fn declared_id(n: &FlatNode) -> Option<&str> {
6243    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
6244}
6245
6246/// A heading's words reduced to the form a link fragment spells them in:
6247/// lowercase, runs of anything else collapsed to a single `-`, with none left
6248/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
6249///
6250/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
6251/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
6252/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
6253/// any other language is still a heading someone will link to. Underscores
6254/// survive for the same reason they do on the web: they are word characters
6255/// wherever identifiers are written.
6256fn slug(text: &str) -> String {
6257    let mut out = String::new();
6258    let mut pending = false;
6259    for c in text.chars() {
6260        if c.is_alphanumeric() || c == '_' {
6261            if pending && !out.is_empty() {
6262                out.push('-');
6263            }
6264            pending = false;
6265            out.extend(c.to_lowercase());
6266        } else {
6267            pending = true;
6268        }
6269    }
6270    out
6271}
6272
6273fn is_block_container(kind: &Kind) -> bool {
6274    matches!(
6275        kind,
6276        Kind::Doc
6277            | Kind::Section
6278            | Kind::BlockQuote
6279            | Kind::BulletList
6280            | Kind::OrderedList
6281            | Kind::TaskList
6282            | Kind::ListItem
6283            | Kind::TaskListItem
6284            // Every `container` — a directive in any of its three forms, or a
6285            // promoted HTML element. A *text* directive is really inline, so
6286            // claiming it here is a small overreach, and the deliberate one this
6287            // function's kind-only peer `is_inline_kind` documents: the pair is
6288            // consulted together, and answering "block container" for something
6289            // inline is what keeps an ancestor walk from stopping short of the
6290            // paragraph that actually holds it.
6291            | Kind::Container
6292    )
6293}
6294
6295/// The `[start, end)` byte range of the source line containing `off` (newline
6296/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
6297/// line between paragraphs).
6298fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
6299    let off = off.min(s.len());
6300    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
6301    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
6302    start..end
6303}
6304
6305/// How many leading bytes an outdent takes off `line`: a whole indent level
6306/// where the line has one, and whatever it has where it has less.
6307///
6308/// A leading tab counts as a level on its own. It's indentation some other
6309/// editor wrote, and one tab is one level everywhere it came from — measuring it
6310/// in spaces it doesn't contain would leave it untouchable.
6311fn outdent_width(line: &str, unit: usize) -> usize {
6312    if line.starts_with('\t') {
6313        return 1;
6314    }
6315    line.bytes().take(unit).take_while(|b| *b == b' ').count()
6316}
6317
6318/// A list marker found at the head of a line, together with everything before it
6319/// that a sibling line has to repeat.
6320///
6321/// The three offsets differ only inside a block quote, where `>   - b` opens with
6322/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
6323/// `line_start == marker_start`, and `text` is the plain `"  - "`.
6324#[derive(Clone, Debug)]
6325struct ListMarker {
6326    /// The line's first byte.
6327    line_start: usize,
6328    /// Where the marker proper begins, past any quote prefix. The offset to hand
6329    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
6330    marker_start: usize,
6331    /// `line_start` through the marker's trailing space — quote prefix, indent
6332    /// and bullet together, which is what the next item's line opens with.
6333    text: String,
6334}
6335
6336impl ListMarker {
6337    /// Where the item's content starts — one past the marker's trailing space.
6338    fn content_start(&self) -> usize {
6339        self.line_start + self.text.len()
6340    }
6341}
6342
6343fn classify(c: char) -> Class {
6344    if c == '_' || c.is_alphanumeric() {
6345        Class::Word
6346    } else if c.is_whitespace() {
6347        Class::Space
6348    } else {
6349        Class::Other
6350    }
6351}
6352
6353/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
6354/// skip any leading separators, then consume the following word run.
6355fn next_word(s: &str, i: usize) -> usize {
6356    let mut off = i;
6357    let mut in_word = false;
6358    for c in s[i..].chars() {
6359        if classify(c) == Class::Word {
6360            in_word = true;
6361        } else if in_word {
6362            break;
6363        }
6364        off += c.len_utf8();
6365    }
6366    off
6367}
6368
6369/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
6370/// skip separators walking left, then consume the preceding word run.
6371fn prev_word(s: &str, i: usize) -> usize {
6372    let mut off = i;
6373    let mut in_word = false;
6374    for c in s[..i].chars().rev() {
6375        if classify(c) == Class::Word {
6376            in_word = true;
6377        } else if in_word {
6378            break;
6379        }
6380        off -= c.len_utf8();
6381    }
6382    off
6383}
6384
6385/// The `[start, end)` run of same-class characters surrounding `off` — the
6386/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
6387/// the run ending there is used.
6388fn word_range_at(s: &str, off: usize) -> (usize, usize) {
6389    if s.is_empty() {
6390        return (0, 0);
6391    }
6392    let off = off.min(s.len());
6393    let reference = if off < s.len() {
6394        s[off..].chars().next()
6395    } else {
6396        s[..off].chars().next_back()
6397    };
6398    let Some(rc) = reference else {
6399        return (off, off);
6400    };
6401    let class = classify(rc);
6402
6403    let mut start = off;
6404    for c in s[..start].chars().rev() {
6405        if classify(c) == class {
6406            start -= c.len_utf8();
6407        } else {
6408            break;
6409        }
6410    }
6411    let mut end = off;
6412    for c in s[end..].chars() {
6413        if classify(c) == class {
6414            end += c.len_utf8();
6415        } else {
6416            break;
6417        }
6418    }
6419    (start, end)
6420}
6421
6422/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
6423/// the line's start — terminal cells, not characters, so the column names the
6424/// cell the caret is drawn in even on a line of `你好` or emoji.
6425fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
6426    let off = off.min(s.len());
6427    let mut row = 0;
6428    let mut line_start = 0;
6429    for (i, &b) in s.as_bytes().iter().enumerate() {
6430        if i >= off {
6431            break;
6432        }
6433        if b == b'\n' {
6434            row += 1;
6435            line_start = i + 1;
6436        }
6437    }
6438    (row, wysiwyg::text_width(&s[line_start..off]))
6439}
6440
6441/// The byte offset at display column `col` of `row` (clamped to that line's
6442/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
6443///
6444/// A column landing *inside* a character — the second cell of `你`, or any cell
6445/// but the first of an emoji — resolves to that character's start, which is the
6446/// column the caret would have been drawn at to begin with. So both cells of a
6447/// wide character mean the character, and every offset survives the round trip
6448/// out to a column and back. The walk steps by grapheme cluster for the same
6449/// reason the caret does: a cluster is the character, and the cells belong to it
6450/// rather than to the codepoints spelling it.
6451fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
6452    let start = line_start(s, row);
6453    let end = line_end_from(s, start);
6454    let mut off = start;
6455    let mut at = 0; // the display column `off` sits at
6456    while off < end {
6457        let next = next_boundary(s, off).min(end);
6458        let cells = wysiwyg::text_width(&s[off..next]);
6459        if at + cells > col {
6460            break; // `col` is one of this cluster's own cells
6461        }
6462        at += cells;
6463        off = next;
6464    }
6465    off
6466}
6467
6468fn line_start(s: &str, row: usize) -> usize {
6469    if row == 0 {
6470        return 0;
6471    }
6472    let mut r = 0;
6473    for (i, &b) in s.as_bytes().iter().enumerate() {
6474        if b == b'\n' {
6475            r += 1;
6476            if r == row {
6477                return i + 1;
6478            }
6479        }
6480    }
6481    s.len()
6482}
6483
6484fn line_end_from(s: &str, start: usize) -> usize {
6485    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
6486}
6487
6488/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
6489/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
6490/// twig applies writing the mark out, so the toolbar can light the same button
6491/// that made the node.
6492///
6493/// `None` for every other kind, including the inline nodes that aren't marks at
6494/// all (`str`, `link`, `image`, the math and break kinds): they're things a
6495/// caret stands in, not formatting a button toggles.
6496fn inline_kind(kind: &Kind) -> Option<InlineKind> {
6497    Some(match kind {
6498        Kind::Strong => InlineKind::Strong,
6499        Kind::Emph => InlineKind::Emph,
6500        Kind::Verbatim => InlineKind::Verbatim,
6501        Kind::Mark => InlineKind::Mark,
6502        Kind::Superscript => InlineKind::Superscript,
6503        Kind::Subscript => InlineKind::Subscript,
6504        Kind::Insert => InlineKind::Insert,
6505        Kind::Delete => InlineKind::Delete,
6506        _ => return None,
6507    })
6508}
6509
6510/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
6511/// a highlight's opening `==`.
6512///
6513/// Two enums for one closed vocabulary, and the duplication is the boundary
6514/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
6515/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
6516/// the editor writes. Spelled as a match rather than routed through the two
6517/// crates' name strings so that a colour added on either side is a compile
6518/// error here, where the pairing is decided, rather than a runtime `None` that
6519/// would read as "clear the colour".
6520fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
6521    match color {
6522        MarkColor::Red => twig::MarkColor::Red,
6523        MarkColor::Orange => twig::MarkColor::Orange,
6524        MarkColor::Yellow => twig::MarkColor::Yellow,
6525        MarkColor::Green => twig::MarkColor::Green,
6526        MarkColor::Blue => twig::MarkColor::Blue,
6527        MarkColor::Purple => twig::MarkColor::Purple,
6528        MarkColor::Brown => twig::MarkColor::Brown,
6529    }
6530}
6531
6532/// Where an offset lands after a splice it didn't make — twig's own rule, from
6533/// [`Change`]: shift anything at or past the replaced range's end by the length
6534/// the replacement gained or lost, and leave anything before it alone.
6535///
6536/// An offset *inside* the replaced range has no text of its own to ride any
6537/// more, and lands at the end of what replaced it: for
6538/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
6539/// the prefix is cleared, which then sits where the highlighted text begins.
6540fn reanchor(off: usize, change: &Change) -> usize {
6541    if off < change.old.start {
6542        return off;
6543    }
6544    if off < change.old.end {
6545        return change.new.end;
6546    }
6547    (off + change.new.end).saturating_sub(change.old.end)
6548}
6549
6550/// A watermark for a file's contents (see `Doc::disk_hash`).
6551///
6552/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
6553/// watermark is compared only against one taken by the same process moments
6554/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
6555/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
6556fn hash_bytes(bytes: &[u8]) -> u64 {
6557    use std::hash::{Hash, Hasher};
6558    let mut h = std::collections::hash_map::DefaultHasher::new();
6559    bytes.hash(&mut h);
6560    h.finish()
6561}
6562
6563#[cfg(feature = "fs")]
6564fn detect_format(path: &Path) -> Result<Format> {
6565    let ext = path
6566        .extension()
6567        .and_then(|e| e.to_str())
6568        .unwrap_or("")
6569        .to_ascii_lowercase();
6570    Ok(match ext.as_str() {
6571        "dj" | "djot" => Format::Djot,
6572        "md" | "markdown" => Format::Markdown,
6573        "xml" => Format::Xml,
6574        "html" | "htm" => Format::Html,
6575        other => return Err(anyhow!("unknown document extension: .{other}")),
6576    })
6577}
6578
6579#[cfg(test)]
6580mod tests {
6581    use super::*;
6582
6583    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
6584    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
6585    /// without one is a view no user is ever in.
6586    fn doc_in(view: View, name: &str, body: &str) -> Doc {
6587        // The fixture name doubles as the temp file's, so two tests picking the
6588        // same one raced under the parallel runner and read each other's body —
6589        // a green suite proving the wrong thing. The counter makes that
6590        // unreachable rather than asking every future caller to notice.
6591        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
6592        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6593        let mut p = std::env::temp_dir();
6594        p.push(format!("leaf_test_{name}_{seq}.md"));
6595        std::fs::write(&p, body).unwrap();
6596        let mut d = Doc::open(p).unwrap();
6597        d.view = view;
6598        if view == View::Wysiwyg {
6599            d.build_visual(80);
6600        }
6601        d
6602    }
6603
6604    // Source-view document for the source-behaviour tests. `Doc::open` now
6605    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
6606    // `wysiwyg_doc` builds the rich-text variant on top of this.
6607    fn doc_with(name: &str, body: &str) -> Doc {
6608        doc_in(View::Source, name, body)
6609    }
6610
6611    /// Every visual row's drawn text — what the reader actually sees, which is
6612    /// the only thing the reveal preference is supposed to change.
6613    fn drawn_rows(d: &Doc) -> Vec<String> {
6614        d.vmap
6615            .rows
6616            .iter()
6617            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6618            .collect()
6619    }
6620
6621    /// Put the caret at the first byte of `needle` and rebuild, so the row under
6622    /// it becomes the revealed line.
6623    fn caret_at(d: &mut Doc, needle: &str) {
6624        d.caret = d.source.find(needle).expect("needle in source");
6625        d.build_visual(80);
6626    }
6627
6628    #[test]
6629    fn blockquote_after_a_list_is_not_bulleted() {
6630        // twig nests a following top-level block quote under the `bullet_list`
6631        // (a direct child, not a `list_item`). The map must render it de-nested —
6632        // `│ quote`, never `• │ quote` — with a blank separator, like any block
6633        // that follows a list. Regression for the "combined list + blockquote" bug.
6634        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
6635        d.build_visual(80);
6636        let rows: Vec<String> = d
6637            .vmap
6638            .rows
6639            .iter()
6640            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
6641            .collect();
6642        assert!(
6643            rows.iter().any(|r| r == "│ quote"),
6644            "block quote should render on its own gutter, got rows: {rows:?}"
6645        );
6646        assert!(
6647            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
6648            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
6649        );
6650    }
6651
6652    // ── the map is built at most once per (revision, wrap) ───────────────────
6653    //
6654    // A frontend repaints for reasons that have nothing to do with the text — a
6655    // blinking caret, a scroll — and rebuilding the map is O(document). These
6656    // pin *that the cache fires*, which a passing suite can't tell you: a cache
6657    // that never hits is invisible to every other test in this file.
6658    //
6659    // The probe is to wreck the built map and ask for it again. A rebuild
6660    // repairs it; a cache hit hands the wreckage straight back. Nothing else
6661    // can distinguish the two from outside.
6662
6663    #[test]
6664    fn a_rebuild_with_nothing_changed_reuses_the_map() {
6665        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
6666        d.build_visual(80);
6667        assert!(!d.vmap.rows.is_empty());
6668        d.vmap.rows.clear(); // wreck it
6669        d.build_visual(80);
6670        assert!(
6671            d.vmap.rows.is_empty(),
6672            "the map was rebuilt though nothing changed — the cache never fired"
6673        );
6674    }
6675
6676    #[test]
6677    fn an_edit_rebuilds_the_map() {
6678        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
6679        d.build_visual(80);
6680        let before = d.revision();
6681        d.vmap.rows.clear();
6682        d.insert("x");
6683        d.build_visual(80);
6684        assert!(d.revision() > before, "an edit must move the revision");
6685        assert!(
6686            !d.vmap.rows.is_empty(),
6687            "an edited document must not paint from a stale map"
6688        );
6689    }
6690
6691    #[test]
6692    fn a_width_change_rebuilds_the_map() {
6693        // The map is a function of the wrap width too, so a resize is a miss
6694        // even though the text is untouched.
6695        let mut d = doc_in(
6696            View::Wysiwyg,
6697            "cache_width",
6698            "one two three four five six\n",
6699        );
6700        d.build_visual(80);
6701        d.vmap.rows.clear();
6702        d.build_visual(12);
6703        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
6704        // And the unwrapped map is its own key, not the same as any width.
6705        d.vmap.rows.clear();
6706        d.build_visual_unwrapped();
6707        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
6708    }
6709
6710    #[test]
6711    fn a_motion_does_not_rebuild_the_map() {
6712        // The whole point: moving the caret changes nothing the map is built
6713        // from. If a motion bumped the revision, every arrow key would cost a
6714        // full rebuild and the cache would be worthless.
6715        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
6716        d.build_visual(80);
6717        let rev = d.revision();
6718        d.move_right(false);
6719        d.move_right(true);
6720        d.move_down(false);
6721        assert_eq!(d.revision(), rev, "a motion must not move the revision");
6722        d.vmap.rows.clear();
6723        d.build_visual(80);
6724        assert!(
6725            d.vmap.rows.is_empty(),
6726            "a motion should not rebuild the map"
6727        );
6728    }
6729
6730    #[test]
6731    fn saving_does_not_rebuild_the_map() {
6732        // Saving changes `dirty`, not the text.
6733        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
6734        d.insert("x");
6735        d.build_visual(80);
6736        let rev = d.revision();
6737        d.save();
6738        assert_eq!(d.revision(), rev, "a save must not move the revision");
6739        assert!(!d.dirty, "the save should have cleaned the document");
6740    }
6741
6742    #[test]
6743    fn a_reload_rebuilds_the_map() {
6744        // Reload replaces the text without going through `refresh`, so it has to
6745        // move the revision itself — else the editor paints the old file.
6746        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
6747        d.build_visual(80);
6748        let rev = d.revision();
6749        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
6750        d.reload();
6751        assert!(d.revision() > rev, "a reload must move the revision");
6752        d.build_visual(80);
6753        let text: String = d
6754            .vmap
6755            .rows
6756            .iter()
6757            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
6758            .collect();
6759        assert!(
6760            text.contains("wholly new"),
6761            "the reloaded text should be on screen, got {text:?}"
6762        );
6763    }
6764
6765    // ── golden-case harness ──────────────────────────────────────────────────
6766    // The pattern the whole parity suite can reuse: write a fixture with the
6767    // caret marked by `|`, run one action, and compare the rendered result —
6768    // also caret-marked — against the expected string. One readable line per
6769    // behavior, and it exercises the exact `Doc` ops both frontends call.
6770
6771    /// Split a `|`-marked fixture into `(source, caret_offset)`.
6772    fn parse_caret(marked: &str) -> (String, usize) {
6773        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
6774        (marked.replacen('|', "", 1), caret)
6775    }
6776
6777    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
6778    /// selection) so a result reads like the fixtures.
6779    fn render_caret(d: &Doc) -> String {
6780        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
6781        // so the caret always renders inside its own selection.
6782        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
6783        if let Some((s, e)) = d.selection() {
6784            marks.push((s, 0, '['));
6785            marks.push((e, 2, ']'));
6786        }
6787        // Insert right-to-left: descending offset, then descending rank.
6788        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
6789        let mut out = d.source.clone();
6790        for (at, _, ch) in marks {
6791            out.insert(at, ch);
6792        }
6793        out
6794    }
6795
6796    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
6797    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
6798        golden_in(View::Source, name, marked, action)
6799    }
6800
6801    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
6802    /// the same fixture has to read the same way in both.
6803    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
6804        let (src, caret) = parse_caret(marked);
6805        let mut d = doc_in(view, name, &src);
6806        d.caret = caret;
6807        action(&mut d);
6808        render_caret(&d)
6809    }
6810
6811    #[test]
6812    fn word_motion_walks_word_by_word() {
6813        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
6814        assert_eq!(
6815            g("hello wor|ld", |d| d.move_word_left(false)),
6816            "hello |world"
6817        );
6818        assert_eq!(
6819            g("hello| world", |d| d.move_word_left(false)),
6820            "|hello world"
6821        );
6822        assert_eq!(
6823            g("hel|lo world", |d| d.move_word_right(false)),
6824            "hello| world"
6825        );
6826        assert_eq!(
6827            g("hello| world", |d| d.move_word_right(false)),
6828            "hello world|"
6829        );
6830        // Punctuation is its own class, so motion stops at the boundary.
6831        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
6832    }
6833
6834    #[test]
6835    fn word_motion_extends_the_selection_when_asked() {
6836        assert_eq!(
6837            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
6838            "hello [world|]"
6839        );
6840    }
6841
6842    #[test]
6843    fn delete_word_removes_a_whole_word() {
6844        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
6845        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
6846        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
6847        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
6848    }
6849
6850    // ── Home / End ───────────────────────────────────────────────────────────
6851
6852    #[test]
6853    fn home_toggles_between_the_line_s_text_and_its_margin() {
6854        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
6855        // indent to the markup it spells everywhere it means one, so the fixture
6856        // with whitespace left to walk is a code block, which is verbatim.
6857        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
6858        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
6859        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
6860        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
6861        // A line with no indentation has one place to go, so the toggle is a
6862        // no-op rather than a trip to nowhere.
6863        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
6864        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
6865
6866        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
6867        let indent = d.source.find("    indented").unwrap();
6868        d.caret = indent + 6; // inside "indented"
6869        d.move_home(false);
6870        assert_eq!(
6871            d.caret,
6872            indent + 4,
6873            "wysiwyg: Home aims at the code line's text"
6874        );
6875        d.move_home(false);
6876        assert_eq!(
6877            d.caret, indent,
6878            "wysiwyg: the second press takes the indent"
6879        );
6880        d.move_home(false);
6881        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
6882    }
6883
6884    #[test]
6885    fn end_takes_the_line_the_view_is_showing() {
6886        // The line differs by view for the same document, and that is the point:
6887        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
6888        // as a space on one row and the source view as two lines.
6889        let mut d = doc_with("end_src", "one two\nthree\n");
6890        d.caret = 1;
6891        d.move_end(false);
6892        assert_eq!(d.caret, 7, "source: the end of the source line");
6893
6894        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
6895        d.caret = 1;
6896        d.move_end(false);
6897        assert_eq!(
6898            d.caret, 13,
6899            "wysiwyg: the end of the row, soft break and all"
6900        );
6901    }
6902
6903    #[test]
6904    fn home_and_end_extend_the_selection_when_asked() {
6905        for (view, tag) in VIEWS {
6906            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
6907            d.caret = 6;
6908            d.move_end(true);
6909            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
6910            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
6911            d.caret = 6;
6912            d.move_home(true);
6913            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
6914        }
6915    }
6916
6917    // ── kill to the line's start / end ───────────────────────────────────────
6918
6919    #[test]
6920    fn kill_to_the_line_start_and_end_in_both_views() {
6921        for (view, tag) in VIEWS {
6922            // The gap that reads as a paragraph break in each view: the source
6923            // view's lines are the renderer's rows only where the source says so.
6924            let gap = if view == View::Source { "\n" } else { "\n\n" };
6925            let mut d = doc_in(
6926                view,
6927                &format!("kill_end_{tag}"),
6928                &format!("one two{gap}three\n"),
6929            );
6930            d.caret = 3;
6931            d.delete_to_line_end();
6932            assert_eq!(
6933                d.source,
6934                format!("one{gap}three\n"),
6935                "{tag}: ^K to the line's end"
6936            );
6937            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
6938
6939            let mut d = doc_in(
6940                view,
6941                &format!("kill_start_{tag}"),
6942                &format!("one two{gap}three\n"),
6943            );
6944            d.caret = 7; // the end of the first line
6945            d.delete_to_line_start();
6946            assert_eq!(
6947                d.source,
6948                format!("{gap}three\n"),
6949                "{tag}: ⌘⌫ to the line's start"
6950            );
6951            assert_eq!(d.caret, 0, "{tag}");
6952        }
6953    }
6954
6955    #[test]
6956    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
6957        // The decision: at the boundary both kills do nothing, rather than
6958        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
6959        // at a soft wrap as often as at a newline, where there is nothing
6960        // written to delete — and a source newline is only half of the blank
6961        // line between two paragraphs, so taking it leaves a soft break rather
6962        // than the join it looks like. Backspace and Delete are the keys for it.
6963        for (view, tag) in VIEWS {
6964            let gap = if view == View::Source { "\n" } else { "\n\n" };
6965            let src = format!("one{gap}three\n");
6966            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
6967            d.caret = 3; // the end of "one"
6968            d.delete_to_line_end();
6969            assert_eq!(
6970                d.source, src,
6971                "{tag}: ^K at the line's end joined it to the next"
6972            );
6973
6974            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
6975            d.caret = 3 + gap.len(); // the start of "three"
6976            d.delete_to_line_start();
6977            assert_eq!(
6978                d.source, src,
6979                "{tag}: ⌘⌫ at the line's start joined it to the last"
6980            );
6981        }
6982    }
6983
6984    #[test]
6985    fn a_kill_takes_the_selection_when_there_is_one() {
6986        // What every other delete here does with one, so these two as well.
6987        for (view, tag) in VIEWS {
6988            for (name, kill) in [
6989                (
6990                    "end",
6991                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
6992                ),
6993                ("start", |d: &mut Doc| d.delete_to_line_start()),
6994            ] {
6995                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
6996                d.anchor = Some(4);
6997                d.caret = 7; // "two"
6998                kill(&mut d);
6999                assert_eq!(
7000                    d.source, "one  three\n",
7001                    "{tag}: {name} ignored the selection"
7002                );
7003                assert_eq!(d.selection(), None, "{tag}: {name}");
7004            }
7005        }
7006    }
7007
7008    #[test]
7009    fn a_kill_takes_the_markup_it_empties_with_it() {
7010        // The same hazard a word-delete has: a WYSIWYG range covers what the
7011        // user can see, which for `**bold**` is the word and never the
7012        // delimiters, so a kill that stopped at the text would leave `a ****` —
7013        // markup wrapped around nothing.
7014        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
7015        d.caret = d.source.find("bold").unwrap();
7016        d.delete_to_line_end();
7017        assert_eq!(d.source, "a \n");
7018    }
7019
7020    #[test]
7021    fn a_kill_is_undone_in_one_step() {
7022        for (view, tag) in VIEWS {
7023            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
7024            d.caret = 3;
7025            d.delete_to_line_end();
7026            assert_eq!(d.source, "one\n", "{tag}");
7027            d.undo();
7028            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
7029        }
7030    }
7031
7032    #[test]
7033    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
7034        // Regression: triple-click used move_home/move_end over visual rows, so
7035        // it only worked on a paragraph's first row (a wrap-boundary offset maps
7036        // to the earlier row). select_block_at reads the AST, so every offset in
7037        // the paragraph selects the whole thing.
7038        let body = "one two three four five six seven eight\n";
7039        let mut d = doc_with("sel_block", body);
7040        d.view = View::Wysiwyg;
7041        d.build_visual(12); // force the paragraph to wrap into several rows
7042        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
7043        let para = (0, "one two three four five six seven eight".len());
7044        for off in [0usize, 8, 19, 28, 38] {
7045            d.caret = 0;
7046            d.anchor = None;
7047            d.select_block_at(off);
7048            assert_eq!(
7049                d.selection(),
7050                Some(para),
7051                "offset {off} should select the paragraph"
7052            );
7053        }
7054    }
7055
7056    #[test]
7057    fn select_block_uses_content_span_for_a_heading() {
7058        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
7059        d.select_block_at(4); // inside "Title"
7060        // content_span excludes the "# " marker.
7061        assert_eq!(d.selected_text(), Some("Title"));
7062        d.select_block_at(10); // inside "body"
7063        assert_eq!(d.selected_text(), Some("body"));
7064    }
7065
7066    #[test]
7067    fn select_all_spans_the_document() {
7068        let mut d = doc_with("sel_all", "abc\n\ndef\n");
7069        d.select_all();
7070        assert_eq!(d.selection(), Some((0, d.source.len())));
7071    }
7072
7073    #[test]
7074    fn select_word_at_picks_the_surrounding_word() {
7075        let mut d = doc_with("sel_word", "hello world\n");
7076        d.select_word_at(8); // inside "world"
7077        assert_eq!(d.selection(), Some((6, 11)));
7078        // Double-clicking at end-of-word still grabs the word to its left.
7079        d.select_word_at(5); // the space between the words
7080        assert_eq!(d.selection(), Some((5, 6)));
7081    }
7082
7083    #[test]
7084    fn word_helpers_respect_utf8_boundaries() {
7085        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
7086        assert_eq!(
7087            golden("utf8", "|café ok", |d| d.move_word_right(false)),
7088            "café| ok"
7089        );
7090        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
7091    }
7092
7093    #[test]
7094    fn typing_inserts_at_the_caret_and_advances_it() {
7095        let mut d = doc_with("type", "hello\n");
7096        d.insert("Hi ");
7097        assert_eq!(d.source, "Hi hello\n");
7098        assert_eq!(d.caret, 3);
7099        assert!(d.dirty);
7100    }
7101
7102    #[test]
7103    fn backspace_deletes_the_char_before_the_caret() {
7104        let mut d = doc_with("bs", "hello\n");
7105        d.caret = 3; // after "hel"
7106        d.backspace();
7107        assert_eq!(d.source, "helo\n");
7108        assert_eq!(d.caret, 2);
7109    }
7110
7111    #[test]
7112    fn typing_replaces_the_selection() {
7113        let mut d = doc_with("replace", "a word b\n");
7114        d.anchor = Some(2);
7115        d.caret = 6; // "word" selected
7116        d.insert("X");
7117        assert_eq!(d.source, "a X b\n");
7118        assert_eq!(d.caret, 3);
7119        assert_eq!(d.anchor, None);
7120    }
7121
7122    #[test]
7123    fn toggle_bold_wraps_then_unwraps_the_selection() {
7124        let mut d = doc_with("bold", "a word b\n");
7125        d.anchor = Some(2);
7126        d.caret = 6;
7127        d.toggle(InlineKind::Strong);
7128        assert_eq!(d.source, "a **word** b\n");
7129        // The toggled region stays selected, so a second toggle reverses it.
7130        d.toggle(InlineKind::Strong);
7131        assert_eq!(d.source, "a word b\n");
7132        d.toggle(InlineKind::Strong);
7133        assert_eq!(d.source, "a **word** b\n");
7134    }
7135
7136    #[test]
7137    fn toggle_code_wraps_then_unwraps_the_selection() {
7138        let mut d = doc_with("code_rt", "a word b\n");
7139        d.anchor = Some(2);
7140        d.caret = 6;
7141        d.toggle(InlineKind::Verbatim);
7142        assert_eq!(d.source, "a `word` b\n");
7143        d.toggle(InlineKind::Verbatim);
7144        assert_eq!(d.source, "a word b\n");
7145    }
7146
7147    #[test]
7148    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
7149        // ⌘b at a bare caret, then type: the text comes out bold with no
7150        // selection ever made — the word-processor "start bold here" gesture.
7151        let mut d = doc_with("sticky_wrap", "xy\n");
7152        d.caret = 1; // between x and y
7153        d.toggle(InlineKind::Strong);
7154        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
7155        d.insert("A");
7156        assert_eq!(d.source, "x**A**y\n");
7157    }
7158
7159    #[test]
7160    fn sticky_bold_lights_the_toolbar_before_any_typing() {
7161        // The button must light the instant ⌘b is pressed, or the mode is
7162        // invisible until the first character lands.
7163        let mut d = doc_with("sticky_light", "xy\n");
7164        d.caret = 1;
7165        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
7166        d.toggle(InlineKind::Strong);
7167        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7168    }
7169
7170    #[test]
7171    fn sticky_bold_toggled_off_types_normally_again() {
7172        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
7173        // in the flow of typing, the exact sequence the user described.
7174        let mut d = doc_with("sticky_off", "\n");
7175        d.caret = 0;
7176        d.toggle(InlineKind::Strong);
7177        d.insert("a");
7178        d.insert("b"); // continues inside the run, no re-arming
7179        assert_eq!(d.source, "**ab**\n");
7180        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
7181        d.insert("c");
7182        assert_eq!(d.source, "**ab**c\n");
7183    }
7184
7185    #[test]
7186    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
7187        // Once a mark is realised the caret sits inside the run, so plain typing
7188        // extends it rather than starting a second, adjacent bold span.
7189        let mut d = doc_with("sticky_cont", "\n");
7190        d.caret = 0;
7191        d.toggle(InlineKind::Emph);
7192        d.insert("h");
7193        d.insert("i");
7194        assert_eq!(d.source, "*hi*\n");
7195    }
7196
7197    #[test]
7198    fn moving_the_caret_disarms_a_sticky_mark() {
7199        // Arming a mark and then moving away must not style text elsewhere.
7200        let mut d = doc_with("sticky_disarm", "xy\n");
7201        d.caret = 0;
7202        d.toggle(InlineKind::Strong);
7203        d.move_right(false); // caret 0 → 1, disarms
7204        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
7205        d.insert("A");
7206        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
7207    }
7208
7209    #[test]
7210    fn stacked_sticky_marks_apply_together() {
7211        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
7212        let mut d = doc_with("sticky_stack", "\n");
7213        d.caret = 0;
7214        d.toggle(InlineKind::Strong);
7215        d.toggle(InlineKind::Emph);
7216        d.insert("x");
7217        // Land the caret on the styled character and confirm both marks are live.
7218        d.anchor = Some(d.source.find('x').unwrap());
7219        d.caret = d.anchor.unwrap() + 1;
7220        let marks = d.active_inline_marks();
7221        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
7222        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
7223    }
7224
7225    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
7226
7227    #[test]
7228    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
7229        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
7230        // The space inside the run made `**bold **`, which is *not* bold — four
7231        // literal asterisks — so the rich view drew them, correctly and
7232        // uselessly, until the next character happened to close the run again.
7233        let mut d = wysiwyg_doc("edge_typing", "a \n");
7234        d.caret = 2;
7235        d.toggle(InlineKind::Strong);
7236        for c in "bold".chars() {
7237            d.insert(&c.to_string());
7238        }
7239        assert_eq!(d.source, "a **bold**\n");
7240        d.insert(" ");
7241        assert_eq!(
7242            d.source, "a **bold** \n",
7243            "the space belongs outside the run"
7244        );
7245        assert!(
7246            d.active_inline_marks().contains(InlineKind::Strong),
7247            "bold is still what's being typed, so the button stays lit"
7248        );
7249        // What the writer is looking at while all this happens: their words.
7250        d.build_visual(80);
7251        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
7252        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
7253        for c in "hey".chars() {
7254            d.insert(&c.to_string());
7255        }
7256        assert_eq!(
7257            d.source, "a **bold hey**\n",
7258            "one bold phrase, not two runs"
7259        );
7260    }
7261
7262    #[test]
7263    fn typing_past_a_space_can_still_leave_the_bold_behind() {
7264        // The other half: the marks stay armed across the space, so ⌘b turns
7265        // them off again there and the next word is plain — the run isn't
7266        // rejoined by a caret that was told not to.
7267        let mut d = wysiwyg_doc("edge_shed", "\n");
7268        d.caret = 0;
7269        d.toggle(InlineKind::Strong);
7270        for c in "bold ".chars() {
7271            d.insert(&c.to_string());
7272        }
7273        assert_eq!(d.source, "**bold** \n");
7274        d.toggle(InlineKind::Strong);
7275        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
7276        d.insert("x");
7277        assert_eq!(d.source, "**bold** x\n");
7278    }
7279
7280    #[test]
7281    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
7282        // ⌘b and then a space before any word: the space is not marked (nothing
7283        // is), and the word after it is.
7284        let mut d = wysiwyg_doc("edge_space_first", "a\n");
7285        d.caret = 1;
7286        d.toggle(InlineKind::Strong);
7287        d.insert(" ");
7288        assert_eq!(d.source, "a \n");
7289        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7290        d.insert("b");
7291        assert_eq!(d.source, "a **b**\n");
7292    }
7293
7294    #[test]
7295    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
7296        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
7297        d.caret = 8; // the caret's home at the end of the run's text
7298        d.insert(" ");
7299        assert_eq!(
7300            d.source, "x **bold** \n",
7301            "the space lands past the delimiters"
7302        );
7303        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
7304
7305        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
7306        d.caret = 4; // in front of the "b"
7307        d.insert(" ");
7308        assert_eq!(d.source, "x  **bold** y\n");
7309        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
7310    }
7311
7312    #[test]
7313    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
7314        // Backspace over the last letter of a bold phrase.
7315        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
7316        d.caret = 10; // past the "h"
7317        d.backspace();
7318        assert_eq!(d.source, "a **bold** \n");
7319        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
7320        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7321        d.insert("x");
7322        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
7323    }
7324
7325    #[test]
7326    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
7327        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
7328        // mark, which is only text. The marks live on in the caret instead.
7329        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
7330        d.caret = 5;
7331        d.backspace();
7332        assert_eq!(d.source, "a  c\n");
7333        assert!(d.active_inline_marks().contains(InlineKind::Strong));
7334        d.insert("x");
7335        assert_eq!(d.source, "a **x** c\n");
7336    }
7337
7338    #[test]
7339    fn typing_over_a_whole_bold_word_keeps_it_bold() {
7340        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
7341        d.anchor = Some(4);
7342        d.caret = 8; // the word, not its delimiters
7343        d.insert("x");
7344        assert_eq!(d.source, "a **x** c\n");
7345    }
7346
7347    #[test]
7348    fn a_code_span_keeps_the_space_it_is_given() {
7349        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
7350        // is still verbatim, so nothing is re-spelt. The repair asks the parser
7351        // rather than a table of kinds, and this is the answer it gets.
7352        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
7353        d.caret = 7;
7354        d.insert(" ");
7355        assert_eq!(d.source, "a `code ` c\n");
7356    }
7357
7358    #[test]
7359    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
7360        // A run's closing delimiter has a caret home on each side of it, one
7361        // column apart on screen — and a plain ← off the space after a bold word
7362        // lands on the outer one. The character drawn behind the caret there is
7363        // still the last letter of the phrase, so that is what Backspace takes;
7364        // the byte behind it is a `*` nobody can see.
7365        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
7366        d.caret = 9;
7367        d.move_left(false);
7368        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
7369        d.backspace();
7370        assert_eq!(
7371            d.source, "**bol** x\n",
7372            "a letter of the phrase, not its `*`"
7373        );
7374        assert_eq!(d.caret, 5);
7375
7376        // And the mirror in front of the opening delimiter, where Delete's
7377        // character is the first letter of the run.
7378        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
7379        d.caret = 1;
7380        d.delete_forward();
7381        assert_eq!(d.source, "x**old**\n");
7382        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
7383    }
7384
7385    #[test]
7386    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
7387        // The byte beside the caret at either edge of a bold word is a `*` the
7388        // rich view draws nothing for. Taking it is not the character delete the
7389        // key was pressed for — it unspells the run and puts a literal asterisk
7390        // on screen (`a *bold** c`). The visible character is the one that goes.
7391        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
7392        d.caret = 4; // in front of the "b"
7393        d.backspace();
7394        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
7395
7396        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
7397        d.caret = 8; // past the "d"
7398        d.delete_forward();
7399        assert_eq!(d.source, "a **bold**c\n");
7400        assert_eq!(d.caret, 8, "and the caret stays inside the run");
7401        d.insert("x");
7402        assert_eq!(d.source, "a **boldx**c\n");
7403
7404        // A code span's backticks are hidden the same way, so they are covered
7405        // by the same rule and not by a list of kinds.
7406        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
7407        d.caret = 3;
7408        d.backspace();
7409        assert_eq!(d.source, "a`code` c\n");
7410    }
7411
7412    #[test]
7413    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
7414        // The asterisks are on the screen there and the caret can stand between
7415        // them, so a delete takes exactly the byte it is aimed at.
7416        let mut d = doc_with("edge_open_src", "a **bold** c\n");
7417        d.caret = 4;
7418        d.backspace();
7419        assert_eq!(d.source, "a *bold** c\n");
7420
7421        let mut d = doc_with("edge_close_src", "a **bold** c\n");
7422        d.caret = 8;
7423        d.delete_forward();
7424        assert_eq!(d.source, "a **bold* c\n");
7425    }
7426
7427    #[test]
7428    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
7429        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
7430        // The space had stepped outside the run (the mark-edge rule), taking the
7431        // caret with it, so the delete put it back down on the far side of the
7432        // closing `**` — one place on screen, and the wrong side of it. Typing
7433        // came out plain and the toolbar went dark, with nothing to see.
7434        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
7435        d.caret = 0;
7436        d.toggle(InlineKind::Strong);
7437        for c in "bold".chars() {
7438            d.insert(&c.to_string());
7439        }
7440        d.insert(" ");
7441        assert_eq!(d.source, "**bold** \n");
7442        d.backspace();
7443        assert_eq!(
7444            d.source, "**bold**\n",
7445            "the space goes, the delimiters stay"
7446        );
7447        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
7448        assert!(
7449            d.active_inline_marks().contains(InlineKind::Strong),
7450            "so the button is still lit"
7451        );
7452        d.insert("x");
7453        assert_eq!(
7454            d.source, "**boldx**\n",
7455            "and the next character is still bold"
7456        );
7457    }
7458
7459    #[test]
7460    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
7461        // What the stranded caret did next: the byte behind it was the closing
7462        // `*`, so a second press took that instead of a letter — `**bold*`, the
7463        // styling gone and an asterisk on the screen where the word had been.
7464        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
7465        d.caret = 0;
7466        d.toggle(InlineKind::Strong);
7467        for c in "bold ".chars() {
7468            d.insert(&c.to_string());
7469        }
7470        assert_eq!(d.source, "**bold** \n");
7471        d.backspace();
7472        d.backspace();
7473        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
7474        assert_eq!(d.caret, 5);
7475    }
7476
7477    #[test]
7478    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
7479        // `***both***` closes two runs with one stack of asterisks: the caret has
7480        // to walk in through all of them, or it lands between the emph and the
7481        // strong and types half-marked.
7482        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
7483        d.caret = 11;
7484        d.backspace();
7485        assert_eq!(d.source, "***both***\n");
7486        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
7487        d.insert("x");
7488        assert_eq!(d.source, "***bothx***\n");
7489    }
7490
7491    #[test]
7492    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
7493        // The settle only moves a caret a run actually closed over. Ordinary
7494        // deletes — inside a run, or in plain prose — are untouched.
7495        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
7496        d.caret = 8;
7497        d.backspace();
7498        assert_eq!(d.source, "a **bol** c\n");
7499        assert_eq!(d.caret, 7);
7500
7501        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
7502        d.caret = 5;
7503        d.backspace();
7504        assert_eq!(d.source, "plai\n");
7505        assert_eq!(d.caret, 4);
7506    }
7507
7508    #[test]
7509    fn the_source_view_leaves_a_delete_where_it_landed() {
7510        // The delimiters are on the screen there, so the offset past them is a
7511        // place the caret can be seen to be — nothing to settle.
7512        let mut d = doc_with("edge_bksp_src", "**bold** \n");
7513        d.caret = 9;
7514        d.backspace();
7515        assert_eq!(d.source, "**bold**\n");
7516        assert_eq!(d.caret, 8);
7517    }
7518
7519    #[test]
7520    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
7521        // `***both***` closes two runs with one stack of asterisks; a space that
7522        // clears only the inner one lands against the outer's and breaks that
7523        // instead.
7524        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
7525        d.caret = 9;
7526        d.insert(" ");
7527        assert_eq!(d.source, "a ***both*** \n");
7528        assert_eq!(d.caret, 13);
7529        d.insert("x");
7530        assert_eq!(d.source, "a ***both x***\n");
7531    }
7532
7533    #[test]
7534    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
7535        // The delimiter shuffle is not an edit the writer made, so it is not a
7536        // step they have to undo past.
7537        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
7538        d.caret = 8;
7539        d.insert(" ");
7540        assert_eq!(d.source, "a **bold** \n");
7541        d.undo();
7542        assert_eq!(d.source, "a **bold**\n");
7543    }
7544
7545    #[test]
7546    fn the_source_view_types_the_space_where_it_was_asked_to() {
7547        // The rule is a rich-view courtesy. In the source view the delimiters are
7548        // on the screen and the user is editing the bytes they can see.
7549        let mut d = doc_with("edge_src", "a **bold** c\n");
7550        d.caret = 8;
7551        d.insert(" ");
7552        assert_eq!(d.source, "a **bold ** c\n");
7553    }
7554
7555    #[test]
7556    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
7557        // Double-clicking a word takes the space after it; bolding that must not
7558        // spell `**word **`, which is not bold at all.
7559        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
7560        d.anchor = Some(2);
7561        d.caret = 7; // "word "
7562        d.toggle(InlineKind::Strong);
7563        assert_eq!(d.source, "a **word** b\n");
7564        d.toggle(InlineKind::Strong);
7565        assert_eq!(d.source, "a word b\n");
7566        d.toggle(InlineKind::Strong);
7567        assert_eq!(
7568            d.source, "a **word** b\n",
7569            "reapplying the mark must not wrap stale delimiter offsets"
7570        );
7571        // And a selection of nothing but whitespace has no word to mark.
7572        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
7573        d.anchor = Some(6);
7574        d.caret = 7;
7575        d.toggle(InlineKind::Strong);
7576        assert_eq!(d.source, "a word b\n");
7577        assert!(d.status.is_some());
7578    }
7579
7580    #[test]
7581    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
7582        let mut d = doc_with("head_set", "hello\n");
7583        d.caret = 2; // caret inside the paragraph, no selection
7584        d.set_block(BlockKind::Heading(1));
7585        assert_eq!(d.source, "# hello\n");
7586    }
7587
7588    #[test]
7589    fn set_block_heading_works_in_wysiwyg_view() {
7590        // The app defaults to WYSIWYG; the caret is a source offset either way.
7591        let mut d = wysiwyg_doc("head_wys", "hello\n");
7592        d.caret = 2;
7593        d.set_block(BlockKind::Heading(1));
7594        assert_eq!(d.source, "# hello\n");
7595    }
7596
7597    #[test]
7598    fn toggle_heading_applies_switches_and_reverts() {
7599        let mut d = doc_with("head_toggle", "hello\n");
7600        d.caret = 2;
7601        d.toggle_heading(1);
7602        assert_eq!(d.source, "# hello\n"); // paragraph → H1
7603        d.toggle_heading(2);
7604        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
7605        d.toggle_heading(2);
7606        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
7607    }
7608
7609    #[test]
7610    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
7611        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
7612        // the blank line but the caret rendered on the *next* line, because the
7613        // separator was a non-navigable decoration row. In Preserve flow that
7614        // blank line is a real caret home — the caret must resolve onto it, and
7615        // typing there makes the soft break that continues the paragraph.
7616        let src = "line one:\nsecond line\n";
7617        let mut d = wysiwyg_doc("pre_enter_lineend", src);
7618        d.set_line_flow(LineFlow::Preserve);
7619        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
7620        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
7621        d.newline();
7622        d.build_visual_unwrapped();
7623        assert_eq!(d.source, "line one:\n\nsecond line\n");
7624        assert_eq!(
7625            d.caret, 10,
7626            "caret sits on the new blank line, not the next line"
7627        );
7628        // The blank line is row 1, and the caret resolves onto it — not row 2.
7629        assert_eq!(
7630            d.vmap.pos_of_offset(10),
7631            (1, 0),
7632            "caret renders on the blank row"
7633        );
7634        assert!(
7635            !d.vmap.rows[1].decoration,
7636            "the blank line is navigable in Preserve"
7637        );
7638        // Typing there makes a soft break: one paragraph, three lines.
7639        d.insert("new clause,");
7640        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
7641    }
7642
7643    #[test]
7644    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
7645        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
7646        // that keeps it one paragraph — where Fold would open a second paragraph.
7647        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
7648        d.set_line_flow(LineFlow::Preserve);
7649        d.caret = 3;
7650        d.newline();
7651        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
7652
7653        // End-of-paragraph: Enter then typing continues the same paragraph on a
7654        // new line (a soft break), not a fresh paragraph.
7655        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
7656        d.set_line_flow(LineFlow::Preserve);
7657        d.caret = 3;
7658        d.newline();
7659        d.insert("def");
7660        assert_eq!(
7661            d.source, "abc\ndef\n",
7662            "end-of-line Enter + typing is a soft break"
7663        );
7664    }
7665
7666    #[test]
7667    fn preserve_double_enter_still_makes_a_paragraph() {
7668        // Two Enters in a row promote to a real paragraph break: the second lands
7669        // on the blank line the first opened and takes the empty-line branch.
7670        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
7671        d.set_line_flow(LineFlow::Preserve);
7672        d.caret = 3;
7673        d.newline();
7674        d.newline();
7675        d.insert("def");
7676        assert_eq!(
7677            d.source, "abc\n\ndef\n",
7678            "double Enter is a paragraph break"
7679        );
7680    }
7681
7682    #[test]
7683    fn preserve_backspace_joins_across_a_soft_break() {
7684        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
7685        // soft break it deletes the single newline and joins the two lines.
7686        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
7687        d.set_line_flow(LineFlow::Preserve);
7688        d.build_visual(80);
7689        d.caret = 4; // start of "def", just past the soft break
7690        d.backspace();
7691        assert_eq!(
7692            d.source, "abcdef\n",
7693            "Backspace joins across the soft break"
7694        );
7695        assert_eq!(d.caret, 3, "caret lands where the lines meet");
7696    }
7697
7698    #[test]
7699    fn fold_enter_still_starts_a_new_paragraph() {
7700        // The default flow is unchanged: a lone `\n` would render as an invisible
7701        // space, so Enter keeps opening the paragraph break that actually shows.
7702        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
7703        d.caret = 3;
7704        d.newline();
7705        assert_eq!(
7706            d.source, "abc\n\ndef\n",
7707            "Fold mid-line Enter is a paragraph break"
7708        );
7709    }
7710
7711    #[test]
7712    fn wysiwyg_one_enter_starts_a_new_paragraph() {
7713        // Regression: one Enter left the caret between the two newlines, so typing
7714        // made a soft break (one paragraph) and you needed a second Enter.
7715        let mut d = wysiwyg_doc("wys_enter", "abc\n");
7716        d.caret = 3;
7717        d.newline();
7718        d.insert("def");
7719        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
7720    }
7721
7722    #[test]
7723    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
7724        // Regression: Enter at the caret's natural End-of-line resting place
7725        // after a bold run with nothing following it (on screen: right after
7726        // "bold", before the hidden closing "**") spliced the paragraph break
7727        // at that very byte offset — which sits *before* the closing "**" in
7728        // the source, since the delimiter is hidden and emits no glyph of its
7729        // own for `push_row`'s "end of row" fallback to count. That severed the
7730        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
7731        // "**" alone on the new line instead of leaving "**bold**" intact with
7732        // a fresh empty paragraph after it.
7733        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
7734        d.move_end(false); // the WYSIWYG End key, from caret 0
7735        assert_eq!(
7736            d.caret, 6,
7737            "caret rests right after \"bold\", before the hidden \"**\""
7738        );
7739        d.newline();
7740        assert!(
7741            d.source.starts_with("**bold**"),
7742            "the closing ** must stay attached to \"bold\": got {:?}",
7743            d.source
7744        );
7745        assert_eq!(
7746            d.source, "**bold**\n\n\n",
7747            "a fresh empty paragraph follows the still-intact bold run"
7748        );
7749    }
7750
7751    #[test]
7752    fn source_view_enter_is_a_single_newline() {
7753        let mut d = doc_with("src_enter", "abc\n");
7754        d.caret = 3;
7755        d.newline();
7756        assert_eq!(d.source, "abc\n\n");
7757    }
7758
7759    #[test]
7760    fn heading_applies_at_the_end_of_a_paragraph() {
7761        // The caret at a line end sits at the doc level; set_block must still find
7762        // the block on that line.
7763        let mut d = doc_with("head_end", "abc\n");
7764        d.caret = 3; // end of "abc"
7765        d.toggle_heading(1);
7766        assert_eq!(d.source, "# abc\n");
7767    }
7768
7769    #[test]
7770    fn heading_on_an_empty_new_paragraph_creates_one() {
7771        let mut d = wysiwyg_doc("head_empty", "abc\n");
7772        d.caret = 3;
7773        d.newline(); // caret now on a fresh, empty paragraph
7774        d.toggle_heading(1);
7775        d.insert("Title");
7776        assert!(d.source.contains("# Title"), "got {:?}", d.source);
7777    }
7778
7779    #[test]
7780    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
7781        // The reported bug, end to end: click a blank line with another one under
7782        // it, press H1, type. The text landed in the heading and the caret's
7783        // offset was right (the source view drew it there), but the rich view
7784        // drew it two rows lower, on the trailing blank line — the empty `# `
7785        // heading had left every row below it short by the marker's two bytes,
7786        // and the blank line ended up claiming the heading's own end offset.
7787        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
7788        d.build_visual_unwrapped();
7789        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
7790        d.toggle_heading(1);
7791        for c in "title".chars() {
7792            d.insert(&c.to_string());
7793            d.build_visual_unwrapped(); // as a frontend does, one frame per key
7794        }
7795        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
7796        assert_eq!(
7797            d.caret_pos(),
7798            (4, 5),
7799            "the caret draws at the end of the heading"
7800        );
7801    }
7802
7803    #[test]
7804    fn clicking_an_empty_heading_types_after_its_marker() {
7805        // The same anchor from the other side: the empty heading's row is its own
7806        // caret home, so a click on it must land past the hidden `# `. Landing in
7807        // front of the hashes made the first keystroke un-heading the line.
7808        let mut d = wysiwyg_doc("head_click", "# \n");
7809        d.build_visual_unwrapped();
7810        d.caret = d.vmap.offset_of_pos(0, 0);
7811        d.insert("x");
7812        assert_eq!(d.source, "# x\n");
7813    }
7814
7815    #[test]
7816    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
7817        let mut d = wysiwyg_doc("head_enter", "# Title\n");
7818        d.caret = 7; // end of the heading
7819        d.newline();
7820        d.insert("body");
7821        assert_eq!(d.source, "# Title\n\nbody\n");
7822    }
7823
7824    #[test]
7825    fn wysiwyg_enter_continues_a_bullet_list() {
7826        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
7827        d.caret = 6; // end of "item"
7828        d.newline();
7829        d.insert("two");
7830        assert_eq!(d.source, "- item\n- two\n");
7831    }
7832
7833    #[test]
7834    fn wysiwyg_enter_increments_an_ordered_list() {
7835        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
7836        d.caret = 6; // end of "one"
7837        d.newline();
7838        d.insert("two");
7839        assert_eq!(d.source, "1. one\n2. two\n");
7840    }
7841
7842    #[test]
7843    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
7844        // Regression for the "extra newline" left between a list and the paragraph
7845        // below it. Enter, Enter leaves the list on a fresh empty paragraph
7846        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
7847        // Backspace should then take the caret cleanly back to the end of the list
7848        // item, `- item\n\nnext`, not delete a single newline and strand it on the
7849        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
7850        // no caret can land on. The map is rebuilt between keystrokes exactly as a
7851        // frontend does, since Backspace reads the stop table to place the delete.
7852        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
7853        d.caret = 6; // end of "item"
7854        d.newline();
7855        d.build_visual(80);
7856        d.newline(); // leave the list onto a fresh empty paragraph
7857        d.build_visual(80);
7858        assert_eq!(
7859            d.source, "- item\n\n\n\nnext\n",
7860            "double-Enter opens the empty paragraph"
7861        );
7862        d.backspace();
7863        assert_eq!(
7864            d.source, "- item\n\nnext\n",
7865            "one Backspace collapses the whole gap"
7866        );
7867        assert_eq!(
7868            d.caret, 6,
7869            "and lands the caret back at the end of the list item"
7870        );
7871    }
7872
7873    #[test]
7874    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
7875        // The stop-wise delete must not over-reach when there is no block boundary
7876        // to cross: two blank lines in a row are one caret stop apart, so pressing
7877        // Enter on an empty line and then Backspace removes exactly the one newline
7878        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
7879        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
7880        d.caret = 5; // the empty paragraph the first Enter already opened
7881        d.build_visual(80);
7882        d.newline();
7883        d.build_visual(80);
7884        assert_eq!(
7885            d.source, "abc\n\n\n\n",
7886            "Enter on the blank line adds one newline"
7887        );
7888        d.backspace();
7889        assert_eq!(
7890            d.source, "abc\n\n\n",
7891            "Backspace takes back exactly that one newline"
7892        );
7893    }
7894
7895    #[test]
7896    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
7897        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
7898        d.caret = 6; // end of the empty "- " item
7899        d.newline();
7900        d.insert("p");
7901        assert_eq!(d.source, "- a\n\np\n");
7902    }
7903
7904    #[test]
7905    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
7906        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
7907        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
7908        // not take the list-exit path (which would splice the `- ` away as if
7909        // leaving an empty item); the AST guard sends it to a normal break and
7910        // leaves the underline intact.
7911        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
7912        assert!(
7913            d.nodes().iter().any(|n| n.kind == Kind::Heading),
7914            "precondition: twig parses this as a heading, not a list",
7915        );
7916        d.caret = 7; // on the `- ` underline line
7917        d.newline();
7918        assert!(
7919            d.source.contains("- "),
7920            "the setext underline survives, not spliced away as a list item: {:?}",
7921            d.source,
7922        );
7923    }
7924
7925    #[test]
7926    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
7927        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
7928        d.caret = 7; // end of "abc" inside the fence
7929        d.newline();
7930        d.insert("def");
7931        assert_eq!(d.source, "```\nabc\ndef\n```\n");
7932    }
7933
7934    #[test]
7935    fn wysiwyg_enter_continues_a_block_quote() {
7936        // Enter opens a new *paragraph* inside the quote, not a second line of
7937        // the same one. `> quote\n> more` is a soft break, which under
7938        // `LineFlow::Fold` renders as a space — the keystroke would look like it
7939        // did nothing. The quoted blank line is what makes the break visible, and
7940        // it's the same thing Enter does in running prose.
7941        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
7942        d.caret = 7; // end of "quote"
7943        d.newline();
7944        d.insert("more");
7945        assert_eq!(d.source, "> quote\n>\n> more\n");
7946        // Still one quote, now holding two paragraphs — not a quote and a stray
7947        // line that fell out of it.
7948        let quotes = d
7949            .nodes()
7950            .iter()
7951            .filter(|n| n.kind == Kind::BlockQuote)
7952            .count();
7953        assert_eq!(quotes, 1);
7954    }
7955
7956    #[test]
7957    fn set_block_makes_a_heading_at_the_caret() {
7958        let mut d = doc_with("head", "Title\n\nbody\n");
7959        d.caret = 0;
7960        d.set_block(BlockKind::Heading(2));
7961        assert_eq!(d.source, "## Title\n\nbody\n");
7962        d.set_block(BlockKind::Paragraph);
7963        assert_eq!(d.source, "Title\n\nbody\n");
7964    }
7965
7966    // ── block containers (quote / list) ──────────────────────────────────────
7967
7968    #[test]
7969    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
7970        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
7971        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
7972        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
7973        // A caret at a line end sits at the doc level; the block is still found.
7974        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
7975    }
7976
7977    #[test]
7978    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
7979        // Every source line of the paragraph gets its own `> `, so a caret left
7980        // on its old byte offset falls one prefix per line above it too far
7981        // back — inside the markup it just asked for rather than in its word.
7982        assert_eq!(
7983            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
7984            "> aaa\n> b|bb\n> ccc\n"
7985        );
7986    }
7987
7988    #[test]
7989    fn toggle_blockquote_works_in_wysiwyg_view() {
7990        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
7991        assert_eq!(
7992            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
7993            "> hel|lo\n"
7994        );
7995        assert_eq!(
7996            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
7997            "hel|lo\n"
7998        );
7999    }
8000
8001    #[test]
8002    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
8003        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
8004        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
8005        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
8006        // The *other* kind converts in place instead of nesting, which is what
8007        // makes the two buttons one three-state control.
8008        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
8009        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
8010        // Its own kind, over the only item the list holds, takes it off.
8011        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
8012    }
8013
8014    #[test]
8015    fn toggle_list_works_in_wysiwyg_view() {
8016        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
8017        assert_eq!(
8018            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
8019            "1. hel|lo\n"
8020        );
8021        assert_eq!(
8022            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
8023            "- hel|lo\n"
8024        );
8025        assert_eq!(
8026            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
8027            "hel|lo\n"
8028        );
8029    }
8030
8031    #[test]
8032    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
8033        // The selection has to grow with the markup: twig takes a container off
8034        // only a range covering every block it holds, so the second press can
8035        // reverse the first only if the result is what's selected.
8036        let mut d = doc_with("list_sel", "abc\n\ndef\n");
8037        d.select_all();
8038        d.toggle_list(true);
8039        assert_eq!(d.source, "1. abc\n\n2. def\n");
8040        assert_eq!(d.selection(), Some((0, d.source.len())));
8041        d.toggle_list(true);
8042        assert_eq!(d.source, "abc\n\ndef\n");
8043    }
8044
8045    #[test]
8046    fn toggle_blockquote_nests_a_partly_covered_quote() {
8047        // twig's rule: covering only some of a container's blocks nests, because
8048        // taking the quote off would drag its uncovered siblings out with it.
8049        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
8050        d.caret = 2; // in the first quoted paragraph only
8051        d.toggle_blockquote();
8052        assert_eq!(d.source, "> > a\n>\n> b\n");
8053    }
8054
8055    #[test]
8056    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
8057        // A blank line used to be no block for twig to wrap —
8058        // `toggle_block_container` answered `NotFound` — so Quote and the list
8059        // buttons did nothing on the very line the H1 button works on, and leaf
8060        // lent twig a scratch paragraph to wrap and took it back out again.
8061        // twig 3.2.0 opens an empty container there itself, so what is left here
8062        // is where the caret lands: inside the marker that was just written.
8063        let mut d = doc_with("quote_blank", "\nabc\n");
8064        d.caret = 0;
8065        d.toggle_blockquote();
8066        assert_eq!(d.source, "> \nabc\n");
8067        assert_eq!(
8068            d.caret, 2,
8069            "the caret belongs inside the quote it just opened"
8070        );
8071        assert!(d.status.is_none(), "{:?}", d.status);
8072        assert!(d.dirty);
8073
8074        // And the paragraph below is still its own block: an empty container one
8075        // soft break from `abc` would take that paragraph into the quote with it.
8076        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
8077        d.caret = 0;
8078        d.toggle_blockquote();
8079        d.build_visual(80);
8080        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
8081
8082        // The same from the other side: a blank line directly under a paragraph
8083        // earns the blank line an empty block needs, rather than being read as a
8084        // soft break inside that paragraph.
8085        let mut d = doc_with("list_blank_below", "abc\n");
8086        d.caret = 4;
8087        d.toggle_list(false);
8088        assert_eq!(d.source, "abc\n\n- ");
8089        assert_eq!(d.caret, 7);
8090    }
8091
8092    #[test]
8093    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
8094        // The gesture the rendering fix is for. `newline` inside a quote already
8095        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
8096        // spelling — but the two marker lines it adds belonged to no node until
8097        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
8098        // just made drew as plain prose under the quote.
8099        let mut d = wysiwyg_doc("quote_enter", "> a\n");
8100        d.caret = 3; // past `a`, at the end of the quoted line
8101        d.newline();
8102        assert_eq!(d.source, "> a\n>\n> \n");
8103        d.build_visual(80);
8104        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
8105        // And the caret is on the new line, not stranded on the old one.
8106        assert_eq!(d.caret, 8);
8107    }
8108
8109    #[test]
8110    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
8111        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
8112        // now it is twig's single edit. Either way one ⌘z has to put the blank
8113        // line back rather than undoing into a half-built document.
8114        for open in [
8115            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
8116            &|d: &mut Doc| d.toggle_list(false),
8117            &|d: &mut Doc| d.toggle_list(true),
8118        ] {
8119            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
8120            d.caret = 3;
8121            open(&mut d);
8122            assert_ne!(d.source, "a\n\n\n\nb\n");
8123            d.undo();
8124            assert_eq!(d.source, "a\n\n\n\nb\n");
8125        }
8126    }
8127
8128    #[test]
8129    fn a_container_toggle_is_one_undo_step() {
8130        let mut d = doc_with("quote_undo", "hello\n");
8131        d.caret = 3;
8132        d.insert("X"); // a typing run the structural edit must not fold into
8133        d.toggle_blockquote();
8134        assert_eq!(d.source, "> helXlo\n");
8135        d.undo();
8136        assert_eq!(d.source, "helXlo\n");
8137    }
8138
8139    // ── links ────────────────────────────────────────────────────────────────
8140
8141    #[test]
8142    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
8143        let mut d = doc_with("link_sel", "word here\n");
8144        d.anchor = Some(0);
8145        d.caret = 4;
8146        d.insert_link("http://x.dev");
8147        assert_eq!(d.source, "[word](http://x.dev) here\n");
8148        // The text, not the destination — so a second press re-points the link
8149        // the first one made rather than nesting one inside it.
8150        assert_eq!(d.selected_text(), Some("word"));
8151        d.insert_link("http://y.dev");
8152        assert_eq!(d.source, "[word](http://y.dev) here\n");
8153        assert_eq!(d.selected_text(), Some("word"));
8154    }
8155
8156    #[test]
8157    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
8158        let mut d = doc_with("img_caret", "before after\n");
8159        d.caret = 7; // between "before " and "after"
8160        d.insert_image("cat.png", "a cat");
8161        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
8162        // The caret sits just past the inserted image, nothing selected.
8163        assert_eq!(d.selection(), None);
8164        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
8165    }
8166
8167    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
8168    /// destination at the first space, so the `format!` this used to be wrote
8169    /// something that was not an image at all — and the reader saw the markup as
8170    /// text. twig owns the spelling now, and moves it into the angle form.
8171    #[test]
8172    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
8173        let mut d = doc_with("img_space", "x\n");
8174        d.caret = 0;
8175        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
8176        assert_eq!(
8177            d.source,
8178            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
8179        );
8180        // And it reads back as an image pointing at the unescaped path — the angle
8181        // brackets are spelling, not part of the destination.
8182        d.caret = 2;
8183        assert_eq!(
8184            d.image_destination_at_caret(),
8185            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
8186        );
8187    }
8188
8189    /// A `)` in a caption or a filename must not close the image early.
8190    #[test]
8191    fn insert_image_escapes_a_paren_in_either_half() {
8192        let mut d = doc_with("img_paren", "x\n");
8193        d.caret = 0;
8194        d.insert_image("a)b.png", "");
8195        assert_eq!(d.source, "![](a\\)b.png)x\n");
8196        d.caret = 2;
8197        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
8198    }
8199
8200    #[test]
8201    fn insert_image_uses_the_selection_as_alt_text() {
8202        let mut d = doc_with("img_sel", "caption here\n");
8203        d.anchor = Some(0);
8204        d.caret = 7; // "caption"
8205        d.insert_image("p.png", "ignored fallback");
8206        assert_eq!(d.source, "![caption](p.png) here\n");
8207    }
8208
8209    #[test]
8210    fn insert_image_with_no_alt_leaves_empty_brackets() {
8211        let mut d = doc_with("img_noalt", "\n");
8212        d.caret = 0;
8213        d.insert_image("logo.svg", "");
8214        assert_eq!(d.source, "![](logo.svg)\n");
8215    }
8216
8217    #[test]
8218    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
8219        // The round trip is the point: it's no use writing markup the reader
8220        // can't pick up again. This is the pair that only holds from twig 2.5.1
8221        // on — before it, the one-line form went in fine and came back as a
8222        // paragraph of raw tags, publishing no media at all.
8223        let mut d = doc_with("vid_rt", "\n");
8224        d.caret = 0;
8225        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
8226        assert_eq!(
8227            d.source,
8228            "<video src=\"clip.mp4\" controls>a clip</video>\n"
8229        );
8230
8231        d.build_visual(80);
8232        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
8233        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
8234        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
8235        assert_eq!(d.vmap.media[0].alt, "a clip");
8236    }
8237
8238    #[test]
8239    fn insert_media_spells_audio_with_its_own_tag() {
8240        let mut d = doc_with("aud_rt", "\n");
8241        d.caret = 0;
8242        d.insert_media(MediaKind::Audio, "take.mp3", "");
8243        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
8244        d.build_visual(80);
8245        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
8246    }
8247
8248    #[test]
8249    fn insert_media_uses_the_selection_as_fallback_text() {
8250        // The same courtesy `insert_image` does with alt: select a caption,
8251        // insert, and the caption labels the thing rather than being replaced.
8252        let mut d = doc_with("vid_sel", "the talk here\n");
8253        d.anchor = Some(0);
8254        d.caret = 8; // "the talk"
8255        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
8256        assert_eq!(
8257            d.source,
8258            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
8259        );
8260    }
8261
8262    #[test]
8263    fn insert_media_with_an_image_kind_is_just_insert_image() {
8264        let mut d = doc_with("img_via_media", "\n");
8265        d.caret = 0;
8266        d.insert_media(MediaKind::Image, "logo.svg", "x");
8267        assert_eq!(d.source, "![x](logo.svg)\n");
8268    }
8269
8270    // ── thematic breaks ─────────────────────────────────────────────────────
8271
8272    /// The node the source parses as at `caret` — what confirms an inserted
8273    /// `---` actually reads back as a rule, not stray text or a setext heading.
8274    ///
8275    /// The *narrowest* node covering the offset. Every ancestor covers it too,
8276    /// and since twig 2.8 that includes the `doc` root, which now carries a real
8277    /// span (it reported none before, so taking the first match used to land on
8278    /// the block by luck and now always answers `"doc"`).
8279    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
8280        d.nodes()
8281            .into_iter()
8282            .filter(|n| n.span.start <= caret && caret < n.span.end)
8283            .min_by_key(|n| n.span.end - n.span.start)
8284            .map(|n| n.kind)
8285    }
8286
8287    #[test]
8288    fn a_task_box_toggles_at_the_caret_and_reads_back() {
8289        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
8290        d.caret = 8; // inside "todo"
8291        assert_eq!(d.task_checked_at_caret(), Some(false));
8292        d.toggle_task_checked();
8293        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
8294        assert_eq!(d.task_checked_at_caret(), Some(true));
8295        d.toggle_task_checked();
8296        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
8297    }
8298
8299    #[test]
8300    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
8301        // The whole reason `toggle_task_at` exists apart from the caret form:
8302        // ticking a box elsewhere must not move the cursor out of what's being
8303        // typed.
8304        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
8305        d.caret = 8; // inside "first"
8306        let second = d.source.find("second").unwrap();
8307        d.toggle_task_at(second);
8308        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
8309        assert_eq!(d.caret, 8, "the caret stayed in the first item");
8310    }
8311
8312    #[test]
8313    fn a_plain_item_gains_and_loses_a_box() {
8314        let mut d = doc_with("task_mint", "- plain\n");
8315        d.caret = 4;
8316        assert_eq!(d.task_checked_at_caret(), None);
8317        d.toggle_task_item();
8318        assert_eq!(d.source, "- [ ] plain\n");
8319        assert_eq!(
8320            d.task_checked_at_caret(),
8321            Some(false),
8322            "a new box arrives unticked"
8323        );
8324        d.toggle_task_item();
8325        assert_eq!(d.source, "- plain\n");
8326    }
8327
8328    #[test]
8329    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
8330        // `set checked` must not silently convert a bullet into a task — that is
8331        // `toggle_task_item`'s job, and twig refuses it here.
8332        let mut d = doc_with("task_none", "- plain\n");
8333        d.caret = 4;
8334        d.toggle_task_checked();
8335        assert_eq!(d.source, "- plain\n", "nothing written");
8336        assert!(
8337            d.status.is_some(),
8338            "the refusal should reach the status line"
8339        );
8340    }
8341
8342    #[test]
8343    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
8344        let mut d = doc_with("task_quote", "> - [ ] nested\n");
8345        d.caret = d.source.find("nested").unwrap();
8346        assert_eq!(d.task_checked_at_caret(), Some(false));
8347        d.toggle_task_checked();
8348        assert_eq!(d.source, "> - [x] nested\n");
8349    }
8350
8351    #[test]
8352    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
8353        // A rule is a block, so twig's `insert_thematic_break` alone lands it
8354        // after the whole paragraph. `split_block` parts the paragraph first and
8355        // the rule is aimed at the *first* half, which is what a rule button is
8356        // understood to do — and what leaf spelled by hand until twig grew both
8357        // halves of the gesture.
8358        let mut d = doc_with("hr_mid", "before after\n");
8359        d.caret = 7; // between "before " and "after"
8360        d.insert_thematic_break();
8361        assert_eq!(d.source, "before \n\n---\n\nafter\n");
8362        assert_eq!(d.selection(), None);
8363        assert_eq!(
8364            kind_at(&mut d, "before \n\n".len()),
8365            Some(Kind::ThematicBreak)
8366        );
8367    }
8368
8369    #[test]
8370    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
8371        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
8372        // and leaf wrote the first into both until twig started spelling it.
8373        let mut md = doc_with("hr_md", "para\n");
8374        md.caret = 2;
8375        md.insert_thematic_break();
8376        assert_eq!(md.source, "pa\n\n---\n\nra\n");
8377
8378        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
8379        dj.caret = 2;
8380        dj.insert_thematic_break();
8381        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
8382    }
8383
8384    #[test]
8385    fn clicking_below_a_final_thematic_break_can_type_after_it() {
8386        let mut d = wysiwyg_doc("hr_final_click", "---\n");
8387        d.build_visual(80);
8388        d.click(d.vmap.num_rows() + 2, 0, false);
8389        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
8390        d.insert("after");
8391        assert_eq!(d.source, "---\nafter");
8392    }
8393
8394    #[test]
8395    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
8396        // The same bytes are two documents. In Markdown `  - b` is a nested item
8397        // and the next one belongs beside it, at its indent. In Djot a list
8398        // marker can't interrupt a paragraph, so those bytes are literal text in
8399        // item `a` and there is only one item — writing `  - ` under it would add
8400        // no item at all, just more text, and the new sibling has to go to
8401        // column zero. Both spellings come out of the *enclosing item's* line.
8402        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
8403        md.caret = "- a\n  - b".len();
8404        md.newline();
8405        assert_eq!(md.source, "- a\n  - b\n  - \n");
8406        assert_eq!(list_items(&mut md), 3);
8407
8408        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
8409        dj.view = View::Wysiwyg;
8410        dj.build_visual(80);
8411        dj.caret = "- a\n  - b".len();
8412        dj.newline();
8413        assert_eq!(dj.source, "- a\n  - b\n- \n");
8414        assert_eq!(list_items(&mut dj), 2);
8415
8416        // Where Djot's nesting is real — opened by a blank line — the indent is
8417        // reproduced there too, and the two formats agree again.
8418        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
8419        dj.view = View::Wysiwyg;
8420        dj.build_visual(80);
8421        dj.caret = "- a\n\n  - b".len();
8422        dj.newline();
8423        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
8424        assert_eq!(list_items(&mut dj), 3);
8425    }
8426
8427    #[test]
8428    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
8429        // Tab replaces the line's whole prefix with the one twig spells, so the
8430        // quote markers, the parent's indent and an ordered marker's extra
8431        // column are all its answer rather than leaf's arithmetic.
8432        for (name, body, caret, want) in [
8433            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
8434            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
8435            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
8436            // A checkbox is markup the item's own text wraps past, but a nested
8437            // list may only open at the *list* marker's column — four in from
8438            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
8439            // parses as one item, not two.
8440            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
8441            (
8442                "quoted task",
8443                "> - [ ] a\n> - [ ] b\n",
8444                18,
8445                "> - [ ] a\n>   - [ ] b\n",
8446            ),
8447        ] {
8448            let mut doc = wysiwyg_doc(name, body);
8449            doc.caret = caret;
8450            doc.indent();
8451            assert_eq!(doc.source, want, "{name}");
8452            // The nesting is real, not just indented text.
8453            assert_eq!(list_items(&mut doc), 2, "{name}");
8454        }
8455    }
8456
8457    #[test]
8458    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
8459        // The same bytes, the two formats disagreeing, and a gesture that used
8460        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
8461        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
8462        // so those bytes are literal text inside item `a` — there is nothing to
8463        // outdent, and treating them as a marker turned one item into two, a
8464        // structural edit from a keystroke that should delete one character.
8465        //
8466        // twig's `line_prefix` is what tells them apart: it reports the marker
8467        // on the Markdown line and nothing on the Djot one, which is a
8468        // continuation. No byte scan can reach that answer.
8469        let src = "- a\n  - b\n";
8470        let at = "- a\n  - ".len();
8471
8472        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
8473        md.view = View::Wysiwyg;
8474        md.build_visual(80);
8475        md.caret = at;
8476        md.backspace();
8477        assert_eq!(md.source, "- a\n- b\n");
8478        assert_eq!(list_items(&mut md), 2);
8479
8480        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
8481        dj.view = View::Wysiwyg;
8482        dj.build_visual(80);
8483        dj.caret = at;
8484        dj.backspace();
8485        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
8486        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
8487    }
8488
8489    #[test]
8490    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
8491        // Leaf used to spell the next item from the marker bytes it scanned, and
8492        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
8493        // and dropped out of the checklist. twig reproduces the whole
8494        // continuation, and a fresh item is always unticked however the one above
8495        // it stands.
8496        for (name, body, want) in [
8497            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
8498            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
8499        ] {
8500            let mut doc = wysiwyg_doc(name, body);
8501            doc.caret = body.trim_end_matches('\n').len();
8502            doc.newline();
8503            assert_eq!(doc.source, want, "{name}");
8504            // Both items are checklist items — the new one is a box, not the
8505            // plain bullet the old marker scan left behind — and it is unticked
8506            // whichever way the one above it faces.
8507            let boxes: Vec<Option<bool>> = doc
8508                .nodes()
8509                .iter()
8510                .filter(|n| n.kind == Kind::TaskListItem)
8511                .map(|n| n.checked)
8512                .collect();
8513            assert_eq!(boxes.len(), 2, "{name}");
8514            assert_eq!(boxes[1], Some(false), "{name}");
8515        }
8516    }
8517
8518    #[test]
8519    fn a_split_takes_the_space_the_caret_was_in_front_of() {
8520        // Splicing a break at the caret strands the space the words were parted
8521        // at on the head of the second block, where it reads as an indent nobody
8522        // typed. twig's split consumes it.
8523        for (name, body, caret, want) in [
8524            ("para", "one two\n", 3, "one\n\ntwo\n"),
8525            ("item", "- one two\n", 5, "- one\n- two\n"),
8526            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
8527            // A heading takes leaf's own path, which has to match.
8528            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
8529        ] {
8530            let mut doc = wysiwyg_doc(name, body);
8531            doc.caret = caret;
8532            doc.newline();
8533            assert_eq!(doc.source, want, "{name}");
8534        }
8535    }
8536
8537    #[test]
8538    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
8539        // The one place leaf keeps its own break: `split_block` repeats the `#`,
8540        // and Enter after a title is how the body under it is asked for.
8541        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
8542        doc.caret = "# Title".len();
8543        doc.newline();
8544        doc.insert("body");
8545        assert_eq!(doc.source, "# Title\n\nbody\n");
8546        assert_eq!(
8547            doc.nodes()
8548                .iter()
8549                .filter(|n| n.kind == Kind::Heading)
8550                .count(),
8551            1
8552        );
8553    }
8554
8555    #[test]
8556    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
8557        // A quoted item's marker doesn't open its line, so a scan that starts at
8558        // column zero finds a `>` where it wanted a bullet, calls the line "not a
8559        // list" and hands Enter to the plain-quote branch — which writes `> ` and
8560        // drops the list. The next item has to carry the whole prefix.
8561        for (name, body, want) in [
8562            ("flat", "> - a\n", "> - a\n> - \n"),
8563            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
8564            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
8565            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
8566            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
8567        ] {
8568            let mut doc = wysiwyg_doc(name, body);
8569            doc.caret = body.trim_end_matches('\n').len();
8570            doc.newline();
8571            assert_eq!(doc.source, want, "{name}");
8572            // The marker isn't just spelled right, it parses as an item.
8573            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
8574        }
8575    }
8576
8577    #[test]
8578    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
8579        // Double-Enter exits the list. Unquoted that means a blank line, but a
8580        // *bare* blank line would end the quote too and drop the caret out of it,
8581        // so the separator keeps its `>` and the caret's line keeps its `> `.
8582        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
8583        doc.caret = "> - a\n> - ".len();
8584        doc.newline();
8585        assert_eq!(doc.source, "> - a\n>\n> \n");
8586        assert_eq!(list_items(&mut doc), 1);
8587        // What "still in the quote" means for the next keystroke: the caret sits
8588        // behind the prefix, and what's typed there lands inside the quote as a
8589        // paragraph of its own — not as more of item `a`.
8590        doc.insert("x");
8591        assert_eq!(doc.source, "> - a\n>\n> x\n");
8592        assert!(
8593            doc.editor
8594                .ancestors_at(doc.caret - 1)
8595                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
8596        );
8597    }
8598
8599    #[test]
8600    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
8601        // The marker is hidden block markup, so Backspace over it is structural —
8602        // but only the marker is the list's. Splicing from the line start would
8603        // take the `>` with it and silently unquote the line.
8604        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
8605        doc.caret = "> - ".len();
8606        doc.backspace();
8607        assert_eq!(doc.source, "> a\n");
8608        assert_eq!(list_items(&mut doc), 0);
8609
8610        // A nested one outdents instead, moving the bullet within the quote
8611        // rather than moving the quote.
8612        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
8613        doc.caret = "> - a\n>   - ".len();
8614        doc.backspace();
8615        assert_eq!(doc.source, "> - a\n> - b\n");
8616        assert_eq!(list_items(&mut doc), 2);
8617    }
8618
8619    #[test]
8620    fn only_a_bare_paragraph_is_parted_around_the_caret() {
8621        // The split is deliberately narrow. Parting a fenced block would leave
8622        // two fences with a rule between them, and parting a list item would
8623        // mint an item nobody asked for on the way to a rule that lands after
8624        // the list either way — so both keep the whole block intact and take the
8625        // rule after it. A caret in a quote is likewise left alone.
8626        for (name, body, caret, want) in [
8627            (
8628                "code",
8629                "```\nfn x() {}\n```\n",
8630                8,
8631                "```\nfn x() {}\n```\n\n---\n",
8632            ),
8633            ("list", "- one two\n", 6, "- one two\n\n---\n"),
8634            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n"),
8635        ] {
8636            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
8637            d.caret = caret;
8638            d.insert_thematic_break();
8639            assert_eq!(d.source, want, "{name}: the block should stay whole");
8640        }
8641    }
8642
8643    #[test]
8644    fn insert_thematic_break_replaces_the_selection() {
8645        // Now that the rule lands *at* the caret again, replacing the selection
8646        // is coherent once more: the text goes, and the rule takes its place.
8647        // The space the deletion left leading the second half is consumed by the
8648        // split rather than opening the new paragraph with it.
8649        let mut d = doc_with("hr_sel", "one two three\n");
8650        d.anchor = Some(4);
8651        d.caret = 7; // "two"
8652        d.insert_thematic_break();
8653        assert_eq!(d.source, "one \n\n---\n\nthree\n");
8654        assert_eq!(d.selection(), None);
8655    }
8656
8657    #[test]
8658    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
8659        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
8660        // because writing `---` into one is code, not a rule — twig now walks out
8661        // to the block that owns the caret's line, so there is nothing to refuse.
8662        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
8663        code.caret = 5; // inside the fenced code
8664        code.insert_thematic_break();
8665        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n");
8666        assert_eq!(code.status, None, "no refusal to report any more");
8667
8668        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
8669        table.caret = 3; // in the header row
8670        table.insert_thematic_break();
8671        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n");
8672    }
8673
8674    #[test]
8675    fn insert_thematic_break_in_a_list_item_ends_the_list() {
8676        // The un-indented rule cannot continue the list, so it closes the list
8677        // and lands at the top level rather than nested inside it.
8678        let mut d = doc_with("hr_list", "- one\n- two\n");
8679        d.caret = "- one\n- tw".len(); // mid "two"
8680        d.insert_thematic_break();
8681        d.build_visual(80);
8682        let rule_at = d.source.find("---").unwrap();
8683        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
8684        assert!(
8685            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
8686                && n.span.start <= rule_at
8687                && rule_at < n.span.end),
8688            "the rule must not be nested inside the list"
8689        );
8690    }
8691
8692    #[test]
8693    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
8694        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
8695        // which is the document the gesture was actually asked for.
8696        let mut d = doc_with("hr_quote", "> hello\n");
8697        d.caret = 4; // inside the quoted text
8698        d.insert_thematic_break();
8699        assert_eq!(d.source, "> hello\n>\n> ---\n");
8700        d.build_visual(80);
8701        let rule_at = d.source.find("---").unwrap();
8702        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
8703        assert!(
8704            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
8705                && n.span.start <= rule_at
8706                && rule_at < n.span.end),
8707            "the rule belongs to the quote it was asked for"
8708        );
8709    }
8710
8711    // ── typing against a block picture ────────────────────────────────────────
8712
8713    /// A rendered-view document with the caret parked on one of the picture's two
8714    /// stops, and the map already built — the state a frontend is in between
8715    /// drawing a frame and the next keystroke.
8716    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
8717        let mut d = doc_in(View::Wysiwyg, name, src);
8718        d.build_visual_unwrapped();
8719        let start = src.find("![").unwrap();
8720        d.caret = match side {
8721            MediaStop::Before => start,
8722            MediaStop::After => start + "![](p.png)".len(),
8723        };
8724        d
8725    }
8726
8727    /// The block media the map publishes, after rebuilding it — "is this still a
8728    /// picture, or has it become a line of text with an image in it?"
8729    fn media_count(d: &mut Doc) -> usize {
8730        d.build_visual_unwrapped();
8731        d.vmap.media.len()
8732    }
8733
8734    #[test]
8735    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
8736        // The accident this prevents: tap the blank page under a photo (which
8737        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
8738        // paragraph with an *inline* image — the photo stops being drawn.
8739        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
8740        d.insert("xy");
8741        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
8742        assert_eq!(media_count(&mut d), 1, "still a picture");
8743    }
8744
8745    #[test]
8746    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
8747        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
8748        d.insert("xy");
8749        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
8750        assert_eq!(media_count(&mut d), 1);
8751    }
8752
8753    #[test]
8754    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
8755        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
8756        d.insert("x");
8757        assert_eq!(d.source, "x\n\n![](p.png)\n");
8758        assert_eq!(media_count(&mut d), 1);
8759    }
8760
8761    #[test]
8762    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
8763        // The opened paragraph is part of the keystroke, not an edit the writer
8764        // made — so it undoes with the character, not a step later.
8765        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
8766        d.insert("x");
8767        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
8768        d.undo();
8769        assert_eq!(d.source, "hi\n\n![](p.png)\n");
8770    }
8771
8772    #[test]
8773    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
8774        // ⌘V dissolves the picture exactly as a keystroke does.
8775        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
8776        d.paste("pasted");
8777        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
8778        assert_eq!(media_count(&mut d), 1);
8779    }
8780
8781    #[test]
8782    fn typing_beside_an_inline_image_is_ordinary_editing() {
8783        // An inline image has no placeholder row and no stops of its own. Opening
8784        // a paragraph mid-sentence would be the bug, not the fix.
8785        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
8786        d.build_visual_unwrapped();
8787        d.caret = "see ![](p.png)".len();
8788        d.insert("!");
8789        assert_eq!(d.source, "see ![](p.png)! here\n");
8790    }
8791
8792    #[test]
8793    fn source_view_types_raw_markup_against_an_image_untouched() {
8794        // Source view is for writing the markup itself; a break inserted behind
8795        // the writer's back there would be the editor arguing with them.
8796        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
8797        d.caret = "![](p.png)".len();
8798        d.insert("x");
8799        assert_eq!(d.source, "![](p.png)x\n");
8800    }
8801
8802    #[test]
8803    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
8804        // A selection is replaced, not joined into, so there is nothing to
8805        // protect: the range takes the picture with it.
8806        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
8807        d.anchor = Some(d.caret);
8808        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
8809        d.insert("x");
8810        assert_eq!(d.source, "hi\n\nx\n");
8811    }
8812
8813    #[test]
8814    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
8815        // What this actually cost: a real vault's photo, to one stray Backspace.
8816        // The caret past `![](p.png)` was deleting the closing paren — invisible
8817        // in the rendered view — and the photo became the text `![](p.png`.
8818        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
8819        d.backspace();
8820        assert_eq!(d.source, "hi\n");
8821        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
8822        d.undo();
8823        assert_eq!(
8824            d.source, "hi\n\n![](p.png)\n",
8825            "and comes back in one piece"
8826        );
8827    }
8828
8829    #[test]
8830    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
8831        // Deleting the break here would join the picture to the paragraph above,
8832        // where it is an *inline* image and stops being drawn. Step over the
8833        // boundary; the next press deletes in the paragraph the caret reached.
8834        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
8835        d.backspace();
8836        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
8837        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
8838        d.backspace();
8839        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
8840        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
8841    }
8842
8843    #[test]
8844    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
8845        // The mirror. A byte-step here eats the `!` and leaves a link.
8846        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
8847        d.delete_forward();
8848        assert_eq!(d.source, "hi\n\nbye\n");
8849        assert_eq!(media_count(&mut d), 0);
8850    }
8851
8852    #[test]
8853    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
8854        let mut d = doc_at_picture(
8855            "pic_del_after",
8856            "hi\n\n![](p.png)\n\nbye\n",
8857            MediaStop::After,
8858        );
8859        d.delete_forward();
8860        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
8861        assert_eq!(
8862            d.caret,
8863            d.source.find("bye").unwrap(),
8864            "the caret stepped down to `bye`"
8865        );
8866    }
8867
8868    #[test]
8869    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
8870        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
8871        d.backspace();
8872        assert_eq!(d.source, "\n");
8873        assert_eq!(media_count(&mut d), 0);
8874    }
8875
8876    #[test]
8877    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
8878        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
8879        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
8880        d.delete_word_back();
8881        assert_eq!(d.source, "hi there\n");
8882
8883        // And in front of one it runs *through* the paragraph break into the
8884        // prose above, which merges the picture inline — so it steps out first,
8885        // and the second press deletes the word it was aimed at.
8886        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
8887        d.delete_word_back();
8888        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
8889        d.delete_word_back();
8890        assert_eq!(
8891            d.source, "hi \n\n![](p.png)\n",
8892            "the word above went, the picture stayed"
8893        );
8894        assert_eq!(media_count(&mut d), 1);
8895    }
8896
8897    #[test]
8898    fn source_view_deletes_raw_markup_against_an_image_untouched() {
8899        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
8900        d.caret = "![](p.png)".len();
8901        d.backspace();
8902        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
8903    }
8904
8905    #[test]
8906    fn image_destination_at_caret_reads_the_image_under_the_caret() {
8907        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
8908        d.caret = 3; // inside the image markup
8909        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
8910        // Past the image, the caret is in no image.
8911        d.caret = "![a cat](cat.png)".len();
8912        assert_eq!(d.image_destination_at_caret(), None);
8913    }
8914
8915    #[test]
8916    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
8917        // The image is one placeholder row by default, and `set_media_rows` grows
8918        // it to the height the frontend measured: the label row plus blank
8919        // `decoration` fillers that hold the vertical space a raster is drawn into.
8920        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
8921        assert_eq!(d.vmap.media.len(), 1);
8922        let img_row = d.vmap.media[0].rows_span.start;
8923        assert_eq!(
8924            d.vmap.media[0].rows_span,
8925            img_row..img_row + 1,
8926            "default is one row"
8927        );
8928
8929        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
8930        d.build_visual(80);
8931        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
8932        let span = d.vmap.media[0].rows_span.clone();
8933        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
8934        // The label row carries the mark and its glyphs; the three below are blank
8935        // decoration — drawn, but no caret and no text.
8936        assert!(
8937            d.vmap.rows[span.start].media.is_some(),
8938            "mark rides the first row"
8939        );
8940        for r in (span.start + 1)..span.end {
8941            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
8942            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
8943            assert!(
8944                d.vmap.rows[r].media.is_none(),
8945                "only the first row is marked"
8946            );
8947        }
8948    }
8949
8950    #[test]
8951    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
8952        // The extra rows are pure spacers: the caret's only homes stay the stop in
8953        // front of the image and the one just past it, so walking the document top
8954        // to bottom visits the same offsets whether the image is 1 row or 5.
8955        let body = "ab\n\n![x](p.png)\n\ncd\n";
8956        let stops_at = |rows: usize| -> Vec<usize> {
8957            let mut d = wysiwyg_doc("img_stops", body);
8958            if rows > 1 {
8959                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
8960                d.build_visual(80);
8961            }
8962            d.caret = 0;
8963            let mut seen = vec![d.caret];
8964            loop {
8965                d.move_right(false);
8966                if *seen.last().unwrap() == d.caret {
8967                    break;
8968                }
8969                seen.push(d.caret);
8970            }
8971            seen
8972        };
8973        assert_eq!(
8974            stops_at(1),
8975            stops_at(5),
8976            "reserving rows must not add stops"
8977        );
8978    }
8979
8980    #[test]
8981    fn insert_link_repoints_the_link_at_a_bare_caret() {
8982        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
8983        d.caret = 3; // in the link's text, nothing selected
8984        d.insert_link("http://y.dev");
8985        assert_eq!(d.source, "[word](http://y.dev)\n");
8986        assert_eq!(d.selected_text(), Some("word"));
8987    }
8988
8989    #[test]
8990    fn insert_link_on_an_empty_range_autolinks_a_url() {
8991        // A link with no text of its own is an autolink, and twig spells it —
8992        // `<…>` is the canonical form and needs no text typed into it, so the
8993        // caret lands after it rather than selecting a finished link.
8994        let mut d = doc_with("link_empty", "\n");
8995        d.caret = 0;
8996        d.insert_link("http://x.dev");
8997        assert_eq!(d.source, "<http://x.dev>\n");
8998        assert_eq!(d.selection(), None);
8999        assert_eq!(d.caret, 14);
9000    }
9001
9002    #[test]
9003    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
9004        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
9005        // in Markdown, so a destination that can't autolink doubles as the text
9006        // instead — which is then selected, ready to be typed over.
9007        let mut d = doc_with("link_rel", "\n");
9008        d.caret = 0;
9009        d.insert_link("./notes.md");
9010        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
9011        assert_eq!(d.selection(), Some((1, 11)));
9012        d.insert("Notes");
9013        assert_eq!(d.source, "[Notes](./notes.md)\n");
9014    }
9015
9016    #[test]
9017    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
9018        // The autolink's text is its URL, so re-pointing replaces the whole
9019        // node — the caret must not splice a second link inside the first.
9020        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
9021        d.caret = 10;
9022        d.insert_link("https://y.dev");
9023        assert_eq!(d.source, "see <https://y.dev> ok\n");
9024    }
9025
9026    #[test]
9027    fn code_language_reads_and_edits_through_the_fence() {
9028        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
9029        d.caret = 10; // inside the code body
9030        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
9031        assert!(d.caret_in_fenced_code());
9032
9033        d.set_code_language("python");
9034        assert!(
9035            d.source.starts_with("```python\n"),
9036            "source: {:?}",
9037            d.source
9038        );
9039        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
9040
9041        // Clearing it leaves a bare fence and no label.
9042        d.set_code_language("");
9043        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
9044        assert_eq!(d.code_language_at_caret(), None);
9045
9046        // A caret outside any code block edits nothing.
9047        let mut p = doc_with("code_lang_none", "just prose\n");
9048        assert!(!p.caret_in_fenced_code());
9049        p.set_code_language("rust");
9050        assert_eq!(p.source, "just prose\n");
9051    }
9052
9053    #[test]
9054    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
9055        // Markdown's info string ends at whitespace, so `two words` would write
9056        // a fence that reads back with a different language than the one asked
9057        // for. twig refuses it; leaf reports that and leaves the source alone.
9058        // The old splice trimmed the ends and wrote whatever was left.
9059        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
9060        d.caret = 10;
9061        d.set_code_language("two words");
9062        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
9063        assert!(d.status.is_some(), "the refusal should be reported");
9064        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
9065    }
9066
9067    #[test]
9068    fn link_destination_at_caret_reads_both_spellings() {
9069        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
9070        d.caret = 5;
9071        assert_eq!(
9072            d.link_destination_at_caret().as_deref(),
9073            Some("https://x.dev")
9074        );
9075        d.caret = 0;
9076        assert_eq!(d.link_destination_at_caret(), None);
9077
9078        // An autolink has no `destination`; its text is the URL.
9079        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
9080        a.caret = 10;
9081        assert_eq!(
9082            a.link_destination_at_caret().as_deref(),
9083            Some("https://x.dev")
9084        );
9085        a.caret = 21;
9086        assert_eq!(a.link_destination_at_caret(), None);
9087    }
9088
9089    #[test]
9090    fn locate_finds_the_block_a_declared_id_names() {
9091        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
9092        // verse. The locator has to land on the *verse*, which is the whole
9093        // reason a link carries one.
9094        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
9095                   {#v2}\nYea, I make a record in the language of my father.\n";
9096        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9097        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
9098        assert_eq!(
9099            d.source[v2.start..v2.end].trim_end(),
9100            "Yea, I make a record in the language of my father."
9101        );
9102        // The attribute line is not part of it: `start` is a place to put a
9103        // caret, and `{#v2}` is markup the caret has no business landing in.
9104        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
9105        assert_eq!(d.locate("v99"), None);
9106    }
9107
9108    #[test]
9109    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
9110        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
9111        // Markdown heading is literal text. So `#the-second-part` can only be
9112        // the heading's own words, which is the rule every Markdown renderer
9113        // already follows and therefore the one a link was authored against.
9114        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
9115        let mut d = doc_with("locate_md", src);
9116        let hit = d.locate("the-second-part").expect("the heading's slug");
9117        assert!(d.source[hit.start..].starts_with("## The Second Part"));
9118        // Bounded by the next heading that isn't under it, so a peek shows the
9119        // section rather than only its title.
9120        assert_eq!(
9121            &d.source[hit.start..hit.end],
9122            "## The Second Part\n\nbody\n\n"
9123        );
9124
9125        // A subsection does not end its parent: `# Title` runs to `## Third`'s
9126        // sibling only because there is no other `#`, so it covers the lot.
9127        let title = d.locate("title").expect("the top heading");
9128        assert_eq!(title.end, d.source.len());
9129    }
9130
9131    #[test]
9132    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
9133        // djot mints `Some-Heading-Here`; a link to it is written
9134        // `#some-heading-here` by nearly everything that writes links. Both
9135        // spellings are one question.
9136        let src = "## Some Heading Here\n\nbody\n";
9137        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9138        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
9139        let slugged = d.locate("some-heading-here").expect("the link's spelling");
9140        assert_eq!(exact, slugged);
9141        // The section, not the heading line — there is more to show than a title.
9142        assert_eq!(&d.source[exact.start..exact.end], src);
9143    }
9144
9145    #[test]
9146    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
9147        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
9148        assert_eq!(d.locate(""), None);
9149        assert_eq!(d.locate("   "), None);
9150        // All punctuation: it names nothing, and must not be read as "match the
9151        // first heading whose slug is also empty".
9152        assert_eq!(d.locate("!!!"), None);
9153    }
9154
9155    #[test]
9156    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
9157        // The document's mistake, and the answer every other anchor
9158        // implementation gives — the alternative is for a link to mean whichever
9159        // of the two a walk happened to reach first.
9160        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
9161        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9162        let hit = d.locate("dup").expect("the first `{#dup}`");
9163        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
9164    }
9165
9166    #[test]
9167    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
9168        // The button's whole job: a reference where the caret was, a definition
9169        // to give it meaning, and the caret waiting in the empty note so the
9170        // next keystroke is the note's first word.
9171        let mut d = doc_with("fn_insert", "A claim and more.\n");
9172        d.caret = 7; // just past "A claim"
9173        d.insert_footnote();
9174        assert!(
9175            d.source.starts_with("A claim[^1] and more."),
9176            "{:?}",
9177            d.source
9178        );
9179        assert!(
9180            d.source.contains("[^1]:"),
9181            "the definition too: {:?}",
9182            d.source
9183        );
9184        assert_eq!(d.status, None);
9185
9186        let reference = d.source.find("[^1]").unwrap();
9187        let note = d
9188            .footnote_at(reference + 2)
9189            .expect("the reference just written");
9190        assert_eq!(note.label, "1");
9191        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
9192        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
9193        // …and typing there is typing into the note, not near it.
9194        d.insert("the note");
9195        assert_eq!(
9196            d.footnote_at(reference + 2).and_then(|f| f.text),
9197            Some("the note".to_string())
9198        );
9199    }
9200
9201    #[test]
9202    fn insert_footnote_numbers_past_the_notes_already_written() {
9203        // A second press must not hand back a label somebody else is using: twig
9204        // reuses a defined label rather than appending a rival definition, so a
9205        // repeat of `1` would quietly point the new reference at the old note.
9206        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
9207        d.caret = 7; // past `[^1]`, before " two."
9208        d.insert_footnote();
9209        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
9210        assert_eq!(d.source.matches("[^2]:").count(), 1);
9211    }
9212
9213    #[test]
9214    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
9215        // `[^2]` with no definition is still a 2 that means something to whoever
9216        // wrote it — stepping over it would mint a note for their reference. A
9217        // word label takes no number, so it blocks none.
9218        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
9219        d.caret = d.source.find(" c").unwrap();
9220        d.insert_footnote();
9221        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
9222        assert!(
9223            d.source.starts_with("a[^2] b[^why][^1] c"),
9224            "{:?}",
9225            d.source
9226        );
9227    }
9228
9229    #[test]
9230    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
9231        // A reference annotates the words before it. Consuming the selection —
9232        // which is what an insert normally does — would delete the very claim
9233        // the author selected in order to footnote.
9234        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
9235        d.anchor = Some(2);
9236        d.caret = 7; // "claim" selected
9237        d.insert_footnote();
9238        assert!(
9239            d.source.starts_with("A claim[^1] and more."),
9240            "{:?}",
9241            d.source
9242        );
9243    }
9244
9245    #[test]
9246    fn a_note_just_written_still_knows_where_its_reference_is() {
9247        // The authoring loop in one test: press the button, type the note, ask to
9248        // go back. The caret ends at the note's last byte — which is the *end* of
9249        // the definition's span, the one offset the query used to exclude — so
9250        // this is where the round trip either works or doesn't.
9251        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
9252        d.caret = 7;
9253        d.insert_footnote();
9254        d.insert("the note");
9255        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
9256        let back = d
9257            .footnote_definition_at_caret()
9258            .expect("still in the note we just typed");
9259        assert_eq!(back.label, "1");
9260        // …and following it lands on the reference's label, where a reader's
9261        // return leg lands.
9262        assert_eq!(back.offset, Some(9));
9263        assert_eq!(&d.source[9..10], "1");
9264    }
9265
9266    #[test]
9267    fn insert_footnote_takes_one_undo_for_both_halves() {
9268        // twig writes the pair as a single edit; the point of that is here.
9269        let before = "A claim and more.\n";
9270        let mut d = doc_with("fn_insert_undo", before);
9271        d.caret = 7;
9272        d.insert_footnote();
9273        assert_ne!(d.source, before);
9274        d.undo();
9275        assert_eq!(d.source, before, "one undo takes back both halves");
9276    }
9277
9278    #[test]
9279    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
9280        // HTML is authorable — it spells the inline marks — and has no footnote.
9281        // The refusal says so rather than writing brackets that would render as
9282        // brackets.
9283        let src = "<p>A claim.</p>\n";
9284        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
9285        assert!(!Capabilities::of(Format::Html).footnote);
9286        d.caret = 5;
9287        d.insert_footnote();
9288        assert_eq!(d.source, src, "nothing written");
9289        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
9290    }
9291
9292    #[test]
9293    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
9294        // The empty body is the one place this could go wrong: the definition
9295        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
9296        // byte early would draw up in the paragraph above the note it belongs to.
9297        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
9298        d.place_caret(7, false);
9299        d.insert_footnote();
9300        d.build_visual(80); // the frame a frontend draws after the edit
9301        assert_eq!(
9302            d.vmap.snap_to_stop(d.caret),
9303            d.caret,
9304            "the caret sits on a stop"
9305        );
9306        let (row, _) = d.caret_pos();
9307        assert!(
9308            drawn_rows(&d)[row].contains("[1]"),
9309            "the caret is on the note's row, not above it: {:?}",
9310            drawn_rows(&d)
9311        );
9312    }
9313
9314    #[test]
9315    fn footnote_at_caret_resolves_a_reference_to_its_note() {
9316        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
9317        // blank line, as one has to.
9318        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
9319        d.caret = 9;
9320        let f = d
9321            .footnote_at_caret()
9322            .expect("the caret stands in a reference");
9323        assert_eq!(f.label, "1");
9324        assert_eq!(f.text.as_deref(), Some("the note"));
9325        // The offset points at the note's first word, not at the definition's
9326        // `[` — the marker is decoration with no caret stop on it.
9327        assert_eq!(f.offset, Some(29));
9328        assert_eq!(&d.source[29..37], "the note");
9329        // …and `end` closes the range, so a frontend can ask which rendered rows
9330        // the note occupies rather than re-deriving them from the text.
9331        assert_eq!(f.end, Some(37));
9332        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
9333    }
9334
9335    /// Two definitions in a row: each is its own note, and neither reaches into
9336    /// the other.
9337    ///
9338    /// A djot definition's span used to run past the blank line into the first
9339    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
9340    /// offsets named the *next* note's rows too, showing a reader two footnotes
9341    /// when they had asked about one. twig 3.1 ends the span after the block's
9342    /// own last line; the test outlives the workaround leaf carried for it.
9343    #[test]
9344    fn footnote_at_stops_a_note_at_the_definition_after_it() {
9345        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
9346        for format in [Format::Markdown, Format::Djot] {
9347            let mut d = Doc::from_source(src.to_string(), format).unwrap();
9348            d.caret = 7;
9349            let f = d.footnote_at_caret().expect("a reference");
9350            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
9351            assert_eq!(
9352                &src[f.offset.unwrap()..f.end.unwrap()],
9353                "first note.",
9354                "in {format:?}"
9355            );
9356        }
9357    }
9358
9359    /// The other side of that boundary: a blank line *inside* a definition is
9360    /// interior to it, and the note keeps its second paragraph.
9361    ///
9362    /// This is what the old body scan cost. It stopped at the first line not
9363    /// indented under the note — a blank line is not — so a two-paragraph note
9364    /// came back as its first paragraph, and "go to note" framed half of it.
9365    /// Reading the span twig gives is both simpler and right.
9366    #[test]
9367    fn footnote_at_keeps_a_notes_second_paragraph() {
9368        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
9369        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
9370        d.caret = 7;
9371        let f = d.footnote_at_caret().expect("a reference");
9372        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
9373        // And it stops there — `After.` is the next block, not more note.
9374        assert_eq!(
9375            &src[f.offset.unwrap()..f.end.unwrap()],
9376            f.text.as_deref().unwrap()
9377        );
9378        assert!(!f.text.as_deref().unwrap().contains("After"));
9379    }
9380
9381    #[test]
9382    fn footnote_at_bounds_a_note_whose_body_is_empty() {
9383        // `[^1]:` with nothing after it. The range is empty rather than
9384        // inverted, and still points inside the definition — which is what keeps
9385        // a frontend's row lookup from walking off into the block above.
9386        let src = "A claim[^1].\n\n[^1]:\n";
9387        let mut d = doc_with("fn_empty_body", src);
9388        d.caret = 9;
9389        let f = d.footnote_at_caret().expect("a reference");
9390        assert_eq!(f.text.as_deref(), Some(""));
9391        assert_eq!(f.offset, f.end, "an empty note is an empty range");
9392        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
9393    }
9394
9395    #[test]
9396    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
9397        let mut d = doc_with(
9398            "fn_at_caret_none",
9399            "A claim[^1] and more.\n\n[^1]: the note\n",
9400        );
9401        d.caret = 2; // in the prose
9402        assert_eq!(d.footnote_at_caret(), None);
9403    }
9404
9405    #[test]
9406    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
9407        // The two are deliberately separate: a reference names a note in this
9408        // document, a link names somewhere to leave for, and answering one with
9409        // the other is what made a reference click do nothing at all.
9410        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
9411        d.caret = 3; // the `1` of `[^1]`
9412        assert!(d.footnote_at_caret().is_some());
9413        assert_eq!(
9414            d.link_destination_at_caret(),
9415            None,
9416            "a reference is not a link"
9417        );
9418
9419        d.caret = 10; // inside the link's label
9420        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
9421        assert_eq!(
9422            d.link_destination_at_caret().as_deref(),
9423            Some("https://x.dev")
9424        );
9425    }
9426
9427    #[test]
9428    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
9429        // A `[^99]` the document never defines is a real state — a note deleted
9430        // out from under its reference — and the label is what lets a frontend
9431        // say so. `None` here would be indistinguishable from "not on a
9432        // reference", which is the wrong thing to tell a reader.
9433        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
9434        d.caret = 9;
9435        let f = d
9436            .footnote_at_caret()
9437            .expect("the reference is still a reference");
9438        assert_eq!(f.label, "99");
9439        assert_eq!(f.text, None);
9440        assert_eq!(f.offset, None);
9441    }
9442
9443    #[test]
9444    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
9445        // Labels are not always numbers, and a note's body runs past its first
9446        // line — the indented continuation belongs to the note, so it comes back
9447        // with it (source bytes, verbatim, as documented).
9448        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
9449        let mut d = doc_with("fn_word_label", src);
9450        d.caret = 6;
9451        let f = d
9452            .footnote_at_caret()
9453            .expect("the caret stands in a reference");
9454        assert_eq!(f.label, "note");
9455        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
9456    }
9457
9458    #[test]
9459    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
9460        // The point of the offset form: a pointer hovering a reference asks what
9461        // note it names, and must not drag the caret along to ask.
9462        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
9463        d.caret = 0;
9464        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
9465        assert_eq!(f.label, "1");
9466        assert_eq!(f.text.as_deref(), Some("the note"));
9467        assert_eq!(d.caret, 0, "asking must not move the caret");
9468        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
9469    }
9470
9471    #[test]
9472    fn footnote_definition_at_caret_points_back_at_the_reference() {
9473        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
9474        // the caret can rest on — is at 9.
9475        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
9476        d.caret = 30; // inside the note's body
9477        let f = d
9478            .footnote_definition_at_caret()
9479            .expect("the caret stands in a definition");
9480        assert_eq!(f.label, "1");
9481        assert_eq!(f.offset, Some(9));
9482        assert_eq!(&d.source[7..11], "[^1]");
9483    }
9484
9485    #[test]
9486    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
9487        // The two legs have to meet: wherever `footnote_at` sends the caret, the
9488        // definition query must answer for — otherwise arriving at a note leaves
9489        // the reader somewhere the way back isn't offered.
9490        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
9491        let mut d = doc_with("fn_def_marker", src);
9492        let landed = d.footnote_at(9).unwrap().offset.unwrap();
9493        assert_eq!(
9494            d.footnote_definition_at(landed).and_then(|f| f.offset),
9495            Some(9),
9496            "the note a reference sends you to offers the way back"
9497        );
9498    }
9499
9500    #[test]
9501    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
9502        // The two queries answer for disjoint places, which is what lets one
9503        // gesture mean "down to the note" in one and "back up" in the other
9504        // without either having to remember which way the reader is going.
9505        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
9506        d.caret = 2; // prose
9507        assert_eq!(d.footnote_definition_at_caret(), None);
9508        d.caret = 9; // the reference
9509        assert_eq!(d.footnote_definition_at_caret(), None);
9510        assert!(
9511            d.footnote_at_caret().is_some(),
9512            "which is the reference's own query"
9513        );
9514    }
9515
9516    #[test]
9517    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
9518        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
9519        // note", which is false and leaves a frontend unable to explain why the
9520        // way back is missing.
9521        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
9522        let mut d = doc_with("fn_def_orphan", src);
9523        d.caret = src.find("orphan").unwrap();
9524        let f = d
9525            .footnote_definition_at_caret()
9526            .expect("an orphan is still a definition");
9527        assert_eq!(f.label, "2");
9528        assert_eq!(f.offset, None);
9529    }
9530
9531    #[test]
9532    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
9533        // One label, cited twice. The first is where the reader most likely came
9534        // from, and the only answer that doesn't depend on how they got here.
9535        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
9536        let mut d = doc_with("fn_def_repeat", src);
9537        d.caret = src.find("the note").unwrap();
9538        let f = d.footnote_definition_at_caret().expect("a definition");
9539        assert_eq!(
9540            f.offset,
9541            Some(5),
9542            "the first `[^a]`'s label, not the second's"
9543        );
9544        assert_eq!(&src[3..7], "[^a]");
9545    }
9546
9547    #[test]
9548    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
9549        // Down and back up, each leg found from the document rather than from a
9550        // memory of the other — so it still works for a reader who scrolled to
9551        // the notes instead of jumping there.
9552        //
9553        // `place_caret` rather than assigning `caret`, because that is what a
9554        // frontend calls: it snaps to a real caret stop, and a jump that lands
9555        // on a byte the caret can't rest on would arrive somewhere the return
9556        // leg no longer answers for. `build_map` first, since snapping is a
9557        // no-op until the map exists — which is exactly how this went unnoticed
9558        // when the offsets pointed at the `[^` markers.
9559        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
9560        d.build_map(None);
9561        d.place_caret(9, false);
9562        let down = d
9563            .footnote_at_caret()
9564            .expect("a reference")
9565            .offset
9566            .expect("a note");
9567        d.place_caret(down, false);
9568        let up = d
9569            .footnote_definition_at_caret()
9570            .expect("a definition")
9571            .offset
9572            .expect("a reference");
9573        d.place_caret(up, false);
9574        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
9575        assert_eq!(
9576            d.footnote_at_caret().expect("back on the reference").label,
9577            "1"
9578        );
9579    }
9580
9581    #[test]
9582    fn insert_link_hands_the_destination_to_twig_raw() {
9583        // Escaping is twig's, and format-specific: Markdown ends a destination
9584        // at the first space and needs the `<…>` form, where djot would read
9585        // those angle brackets as part of the URL.
9586        let mut d = doc_with("link_space", "word\n");
9587        d.anchor = Some(0);
9588        d.caret = 4;
9589        d.insert_link("a b");
9590        assert_eq!(d.source, "[word](<a b>)\n");
9591    }
9592
9593    #[test]
9594    fn insert_link_reports_a_destination_no_format_can_carry() {
9595        let mut d = doc_with("link_bad", "word\n");
9596        d.anchor = Some(0);
9597        d.caret = 4;
9598        d.insert_link("a\nb");
9599        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
9600        assert!(
9601            d.status.is_some(),
9602            "InvalidArgument should reach the status line"
9603        );
9604        assert!(!d.dirty);
9605    }
9606
9607    #[test]
9608    fn insert_link_works_in_wysiwyg_view() {
9609        let mut d = wysiwyg_doc("link_wys", "word here\n");
9610        d.anchor = Some(0);
9611        d.caret = 4;
9612        d.insert_link("http://x.dev");
9613        assert_eq!(d.source, "[word](http://x.dev) here\n");
9614        assert_eq!(d.selected_text(), Some("word"));
9615        // The map the caret has to keep riding is rebuilt each frame; motion
9616        // over the fresh one must still land on a real stop (the debug_assert).
9617        d.build_visual(80);
9618        d.move_right(false);
9619        d.move_left(false);
9620    }
9621
9622    #[test]
9623    fn click_maps_a_row_col_to_a_byte_offset() {
9624        let mut d = doc_with("click", "ab\ncd\n");
9625        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
9626        assert_eq!(d.caret, 4);
9627    }
9628
9629    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
9630    // stop just as the `(row, col)` click path does, so the caret can never come
9631    // to rest in the blank gap between two paragraphs — where it would draw in one
9632    // place and type in another.
9633    #[test]
9634    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
9635        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
9636        // caret stop (stops are 0,1,3,4).
9637        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
9638        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
9639        d.place_caret(2, false);
9640        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
9641        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
9642    }
9643
9644    #[test]
9645    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
9646        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
9647        d.place_caret(0, false); // anchor at the start of "A"
9648        d.place_caret(2, true); // drag into the gap
9649        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
9650        let (s, e) = d.selection().expect("a selection");
9651        assert!(
9652            d.vmap.is_stop(s) && d.vmap.is_stop(e),
9653            "selection {s}..{e} off a stop"
9654        );
9655    }
9656
9657    #[test]
9658    fn place_caret_on_a_real_stop_is_left_untouched() {
9659        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
9660        d.place_caret(3, false); // the start of "B" — a genuine stop
9661        assert_eq!(d.caret, 3);
9662    }
9663
9664    // An *empty paragraph* (two blank lines, an intentional blank line the user
9665    // opened) is a real caret stop, unlike the gap — a click into it must stay.
9666    #[test]
9667    fn place_caret_rests_in_an_empty_paragraph() {
9668        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
9669        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
9670        assert!(d.vmap.is_stop(empty));
9671        d.place_caret(empty, false);
9672        assert_eq!(d.caret, empty);
9673    }
9674
9675    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
9676        doc_in(View::Wysiwyg, name, body)
9677    }
9678
9679    /// How many list items the source actually parses into — the check that a
9680    /// marker Leaf wrote is a marker the format agrees is one.
9681    fn list_items(doc: &mut Doc) -> usize {
9682        doc.editor
9683            .nodes()
9684            .unwrap()
9685            .iter()
9686            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
9687            .count()
9688    }
9689
9690    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
9691    /// incremental (`build_spliced` / `build_cached`) path must always match.
9692    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
9693        reference_map_revealing(source, None)
9694    }
9695
9696    /// [`reference_map`] with a reveal line — the ground truth for the
9697    /// `MarkupMode::Full` builds, where the map is a function of the caret's
9698    /// line as well as the text.
9699    fn reference_map_revealing(
9700        source: &str,
9701        reveal: Option<Range<usize>>,
9702    ) -> crate::wysiwyg::VisualMap {
9703        // The same parse `Doc` uses. With twig's plain defaults instead, the two
9704        // sides disagree on what the *document* is before the renderer is even
9705        // reached — a bare `:word` is a text directive to one and prose to the
9706        // other — and the mismatch reads as a splice bug that isn't one.
9707        let mut ed =
9708            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
9709        let nodes = ed.nodes().unwrap();
9710        crate::wysiwyg::build(
9711            &nodes,
9712            source,
9713            None,
9714            false,
9715            &std::collections::HashMap::new(),
9716            reveal,
9717        )
9718    }
9719
9720    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
9721        if a.rows.len() != b.rows.len() {
9722            return true;
9723        }
9724        for (ra, rb) in a.rows.iter().zip(&b.rows) {
9725            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
9726                return true;
9727            }
9728            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
9729                if ga.ch != gb.ch || ga.src != gb.src {
9730                    return true;
9731                }
9732            }
9733        }
9734        false
9735    }
9736
9737    #[test]
9738    fn incremental_build_matches_a_fresh_build_across_edits() {
9739        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
9740        // fast path, gated on twig's `dirty_range`) or falls back to
9741        // `build_cached`. After each edit the map must be byte-identical to a
9742        // from-scratch build — this is the correctness net under the splice.
9743        let docs = [
9744            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
9745            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
9746            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
9747            // A footnote definition is a root beside `doc`, merged back into the
9748            // top-level list by `wysiwyg::top_blocks`. The random edits below
9749            // make and unmake definitions as they go (a deleted `:` turns one
9750            // back into a paragraph, and vice versa), which is exactly the
9751            // structural churn the splice path has to notice and bail out of.
9752            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
9753            // A comment is a top-level block that draws no rows — a layout entry
9754            // at zero rows either side of blocks that do. The edits below type
9755            // into the blocks around it (a splice past a hidden block), and
9756            // break the comment open into prose and back (a structural change).
9757            "intro\n\n<!-- exec -->\n```\ncode\n```\n\nafter the comment\n\n<!-- trail -->\n",
9758            // Link reference definitions: a hidden block that an edit can turn
9759            // into a paragraph (a deleted `:`) and back, and whose own bytes an
9760            // edit can land in.
9761            "see [a] and [b]\n\n[a]: /a\n\nmid text\n\n[b]: /b\n",
9762        ];
9763        // A deterministic mix: mostly single characters (which stay inside one
9764        // block → splice), plus edits that reshape structure (a paragraph break,
9765        // a heading marker, a code fence → fallback), so both paths are exercised.
9766        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
9767        for src in docs {
9768            let mut d = wysiwyg_doc("diff", src);
9769            d.build_visual_unwrapped();
9770            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
9771
9772            for step in 0..60usize {
9773                let len = d.source.len();
9774                let raw = (step * 13 + 5) % (len + 1);
9775                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
9776                let pre = d.source.clone();
9777                let action;
9778                if step % 3 == 0 && pos < len {
9779                    let end = (pos + 1..=len)
9780                        .find(|&i| d.source.is_char_boundary(i))
9781                        .unwrap();
9782                    action = format!("delete [{pos},{end})");
9783                    d.edit(pos, end, "");
9784                } else {
9785                    let ins = inserts[step % inserts.len()];
9786                    action = format!("insert {ins:?} @ {pos}");
9787                    d.edit(pos, pos, ins);
9788                }
9789                d.build_visual_unwrapped();
9790                if maps_differ(&d.vmap, &reference_map(&d.source)) {
9791                    panic!(
9792                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
9793                        d.source
9794                    );
9795                }
9796            }
9797        }
9798    }
9799
9800    /// A frontend is handed [`Doc::vmap`] and may present it differently:
9801    /// leaf-ratatui splices blank filler rows under an oversized heading so the
9802    /// raster it paints there has somewhere to stand, and leaves them in the map
9803    /// because the caret and the mouse both read it between frames. The splice
9804    /// path addresses that map by *row index*, against the block layout the last
9805    /// build recorded — so handed a map with rows in it that no block owns, it
9806    /// laid the re-rendered block over one of the fillers and carried the rows
9807    /// the block really occupied into the suffix. One stranded copy of the
9808    /// edited line, and everything below it a row further down, per keystroke.
9809    ///
9810    /// A map that isn't the one the layout describes is a map this path can't
9811    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
9812    #[test]
9813    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
9814        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
9815        d.build_visual_unwrapped();
9816
9817        // Stand in for the heading filler rows: two blank rows past the heading
9818        // that no block accounts for. Cloning a real row keeps every field
9819        // plausible — it is the row *count* the splice can't survive.
9820        let filler = d.vmap.rows[0].clone();
9821        d.vmap.rows.insert(1, filler.clone());
9822        d.vmap.rows.insert(1, filler);
9823
9824        // An edit inside the last block: the single-block case the splice path
9825        // is for, and the one the frontend hits on every keystroke.
9826        let at = d.source.len() - 1;
9827        d.edit(at, at, "!");
9828        d.build_visual_unwrapped();
9829
9830        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
9831    }
9832
9833    #[test]
9834    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
9835        // The same correctness net as `incremental_build_matches_a_fresh_build_
9836        // across_edits`, under `MarkupMode::Full` — where the map depends on
9837        // the caret's *line* as well as the text, so the two caches have a new
9838        // way to be wrong. Both are exercised: the block cache can hand back
9839        // rows built for a line that is no longer the revealed one, and the
9840        // splice path can reuse a suffix that still has yesterday's line raw.
9841        //
9842        // Caret motion is interleaved with the edits deliberately, because a
9843        // caret that only ever moved with the edit would never cross a line
9844        // without also dirtying it — the case where a stale reveal survives.
9845        let docs = [
9846            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
9847            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
9848        ];
9849        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
9850        for src in docs {
9851            let mut d = wysiwyg_doc("reveal_diff", src);
9852            d.set_markup_mode(MarkupMode::Full);
9853
9854            for step in 0..60usize {
9855                let len = d.source.len();
9856                let raw = (step * 13 + 5) % (len + 1);
9857                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
9858                let pre = d.source.clone();
9859                let action;
9860                if step % 3 == 0 && pos < len {
9861                    let end = (pos + 1..=len)
9862                        .find(|&i| d.source.is_char_boundary(i))
9863                        .unwrap();
9864                    action = format!("delete [{pos},{end})");
9865                    d.edit(pos, end, "");
9866                } else {
9867                    let ins = inserts[step % inserts.len()];
9868                    action = format!("insert {ins:?} @ {pos}");
9869                    d.edit(pos, pos, ins);
9870                }
9871                // Walk the caret somewhere else in the document, independently
9872                // of where the edit landed.
9873                let want = (step * 29 + 11) % (d.source.len() + 1);
9874                d.caret = (want..=d.source.len())
9875                    .find(|&i| d.source.is_char_boundary(i))
9876                    .unwrap();
9877                d.build_visual_unwrapped();
9878
9879                let want = reference_map_revealing(&d.source, d.reveal_line());
9880                if maps_differ(&d.vmap, &want) {
9881                    panic!(
9882                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
9883                        d.caret, d.source
9884                    );
9885                }
9886            }
9887        }
9888    }
9889
9890    #[test]
9891    fn caret_motion_across_lines_rebuilds_only_under_full() {
9892        // The cache-key change has to earn its keep in both directions: `Full`
9893        // must rebuild when the caret changes line (or the reveal would never
9894        // move), and the hidden modes must *not* (or every arrow key would pay
9895        // for a feature they don't use). The existing `cache_motion` test pins
9896        // the second for the default mode; this pins the pair against a mode
9897        // change alone.
9898        let body = "*one* here\n\n*two* there\n";
9899
9900        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
9901        full.set_markup_mode(MarkupMode::Full);
9902        caret_at(&mut full, "one");
9903        let before = full.revision();
9904        caret_at(&mut full, "two");
9905        assert_eq!(full.revision(), before, "motion is not an edit");
9906        assert!(
9907            drawn_rows(&full).iter().any(|r| r == "*two* there"),
9908            "the map followed the caret: {:?}",
9909            drawn_rows(&full)
9910        );
9911
9912        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
9913        caret_at(&mut hidden, "one");
9914        let key = hidden.vmap_key.clone();
9915        caret_at(&mut hidden, "two");
9916        assert_eq!(
9917            hidden.vmap_key, key,
9918            "a hidden mode rebuilds nothing on motion"
9919        );
9920    }
9921
9922    #[test]
9923    fn wysiwyg_down_crosses_a_paragraph_boundary() {
9924        // Regression: the blank separator row used to share the previous
9925        // paragraph's end offset, so Down got pinned at the boundary (while Up
9926        // still crossed). Both directions must step through it symmetrically.
9927        //
9928        // It's now stepped *over* rather than onto: the blank line between two
9929        // paragraphs is the boundary being drawn, not a line of the document, so
9930        // one press of Down crosses it. The goal column survives the crossing —
9931        // col 3 at the end of "abc" is col 3 at the end of "def".
9932        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
9933        d.caret = 3; // end of "abc" (row 0)
9934        d.move_down(false);
9935        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
9936        assert_eq!(d.caret, 8); // end of "def", col 3 kept
9937        d.move_up(false);
9938        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
9939        assert_eq!(d.caret, 3);
9940    }
9941
9942    #[test]
9943    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
9944        // The second Up and the second Down here run off the ends of the
9945        // document, which is no longer a place a press is swallowed: they carry
9946        // the caret to the start and the end of the text. The claim in the
9947        // middle — that a Down retraces the Up that crossed the paragraph gap —
9948        // is the one this test is for, and it is asserted where it is made.
9949        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
9950        d.caret = 5; // start of "def"
9951        let start = d.caret_pos();
9952        d.move_up(false);
9953        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
9954        d.move_up(false);
9955        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
9956        d.move_down(false);
9957        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
9958        d.move_down(false);
9959        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
9960    }
9961
9962    #[test]
9963    fn wysiwyg_new_paragraph_shows_before_typing() {
9964        // Regression: two Enters at the end of a paragraph produced trailing
9965        // newlines with no AST node, so the caret appeared stuck on the old line
9966        // until a character was typed. It must ride down onto the new line now.
9967        let mut d = doc_with("wys_newpara", "abc\n");
9968        d.view = View::Wysiwyg;
9969        d.caret = 3;
9970        d.insert("\n");
9971        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
9972        assert_eq!(d.source, "abc\n\n\n");
9973        d.build_visual(80);
9974        let (row, _) = d.caret_pos();
9975        assert!(
9976            row >= 2,
9977            "caret should have moved down to the new line, got row {row}"
9978        );
9979        assert!(
9980            d.vmap.num_rows() >= 3,
9981            "the blank lines should render as rows"
9982        );
9983    }
9984
9985    #[test]
9986    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
9987        // The reported bug: Enter at the end of a paragraph that has another
9988        // paragraph below put the caret at the *start of the next paragraph* —
9989        // the empty paragraph it opened had no row, so the caret snapped onto
9990        // "World". It must now sit on its own empty line, with a blank spacer
9991        // above it (the paragraph gap).
9992        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
9993        d.caret = 5; // end of "Hello"
9994        d.newline();
9995        d.build_visual(80);
9996        let (row, col) = d.caret_pos();
9997        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
9998        assert_eq!(
9999            d.vmap.row_width(row),
10000            0,
10001            "caret's row must be empty, not 'World'"
10002        );
10003        assert!(
10004            row >= 2,
10005            "a blank spacer row should sit above the caret, got row {row}"
10006        );
10007        // The row above the caret is a real (empty) gap, and "Hello" stays put.
10008        assert_eq!(
10009            d.vmap.row_width(row - 1),
10010            0,
10011            "the row above the caret is a gap"
10012        );
10013        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
10014        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
10015    }
10016
10017    #[test]
10018    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
10019        // At the document end a single Enter must also show the paragraph gap —
10020        // a blank spacer row above the caret — so the layout already matches how
10021        // it will look once the new paragraph has text.
10022        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
10023        d.caret = 5; // end of "Hello", no trailing newline
10024        d.newline(); // source becomes "Hello\n\n"
10025        d.build_visual(80);
10026        let (row, col) = d.caret_pos();
10027        assert_eq!(col, 0);
10028        assert!(
10029            row >= 2,
10030            "caret should sit below a blank spacer, got row {row}"
10031        );
10032        assert_eq!(
10033            d.vmap.row_width(row - 1),
10034            0,
10035            "the row above the caret is a gap"
10036        );
10037    }
10038
10039    #[test]
10040    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
10041        // The spacer is view-only: typing the new paragraph must not reflow the
10042        // caret onto a different row — the transient view already matched the
10043        // settled one.
10044        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
10045        d.caret = 5;
10046        d.newline();
10047        d.build_visual(80);
10048        let before = d.caret_pos();
10049        d.insert("New");
10050        d.build_visual(80);
10051        let after = d.caret_pos();
10052        assert_eq!(
10053            after.0, before.0,
10054            "typing must not move the caret to another row ({before:?} -> {after:?})"
10055        );
10056    }
10057
10058    #[test]
10059    fn wysiwyg_return_on_the_last_code_line_keeps_the_caret_in_the_block() {
10060        // Return at the end of the block's last line writes an empty line the
10061        // map used to drop, so the caret landed on `after` and the next
10062        // keystroke went into the paragraph below instead of into the code.
10063        let mut d = wysiwyg_doc("code_return", "prose\n\n```\nalpha\nbeta\n```\n\nafter\n");
10064        d.caret = d.source.find("beta").unwrap() + "beta".len();
10065        d.build_visual(80);
10066        let before = d.caret_pos().0;
10067
10068        d.newline();
10069        d.build_visual(80);
10070        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n");
10071
10072        let (row, col) = d.caret_pos();
10073        assert_eq!(row, before + 1, "the caret moves down one row");
10074        assert_eq!(col, 0, "onto the head of the empty line");
10075        let span = d.vmap.code_blocks[0].rows_span.clone();
10076        assert!(
10077            span.contains(&row),
10078            "caret row {row} is outside the block's rows {span:?}"
10079        );
10080
10081        // The whole point: what is typed next is code.
10082        d.insert("gamma");
10083        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\ngamma\n```\n\nafter\n");
10084    }
10085
10086    #[test]
10087    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
10088        let fm = "---\ntitle: hi\n---\n";
10089        let body = format!("{fm}# leaf\n\nbody\n");
10090        let mut d = wysiwyg_doc("wys_fm", &body);
10091        // Opening lifts the caret out of the now-hidden frontmatter.
10092        assert_eq!(
10093            d.caret,
10094            fm.len(),
10095            "caret should start at the first real block"
10096        );
10097        // Left at the content start can't step back into frontmatter.
10098        d.move_left(false);
10099        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
10100        // Doc-start lands on the content floor, not offset 0.
10101        d.move_doc_start(false);
10102        assert_eq!(d.caret, fm.len());
10103        // Select-all + copy never include the frontmatter bytes.
10104        d.select_all();
10105        let sel = d.selected_text().unwrap().to_string();
10106        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
10107        assert!(
10108            sel.starts_with("# leaf"),
10109            "selection should begin at content: {sel:?}"
10110        );
10111    }
10112
10113    #[test]
10114    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
10115        // A fresh note is frontmatter and nothing else. With no rendered block
10116        // to floor the caret it opened at offset 0 — before the opening `---` —
10117        // so the first keystroke wrote itself in front of the metadata and the
10118        // file came out as `This---\ntitle: …`.
10119        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
10120        let mut d = wysiwyg_doc("wys_fm_only", fm);
10121        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
10122        // Nothing is rendered, so the caret draws at the origin of an empty view
10123        // — the same place an empty document puts it.
10124        assert_eq!(d.caret_pos(), (0, 0));
10125        d.insert("This");
10126        assert_eq!(d.source, format!("{fm}This"));
10127    }
10128
10129    /// `select_range` is the verb for a range a host already knows the bytes of,
10130    /// so it must not snap — and must still hold every invariant `place_caret`
10131    /// holds, the frontmatter floor above all.
10132    #[test]
10133    fn select_range_takes_the_range_as_given_but_still_floors_it() {
10134        let fm = "---\ntitle: foo\n---\n\n";
10135        let body = format!("{fm}body foo here\n");
10136        let mut d = wysiwyg_doc("wys_select_range", &body);
10137
10138        // The `foo` in the body: taken exactly, not snapped to a caret stop.
10139        let at = body.rfind("foo").unwrap();
10140        d.select_range(at, at + 3);
10141        assert_eq!(d.selection(), Some((at, at + 3)));
10142        assert_eq!(d.selected_text(), Some("foo"));
10143
10144        // The `foo` in the hidden frontmatter: below the floor, so both ends
10145        // come up to it rather than parking the caret in the metadata, where a
10146        // later keystroke would rewrite `title:`.
10147        let hidden = body.find("foo").unwrap();
10148        assert!(hidden < d.vmap.content_start);
10149        d.select_range(hidden, hidden + 3);
10150        assert!(
10151            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
10152            "a range under the floor must not leave the caret in the frontmatter"
10153        );
10154
10155        // Past the end, and mid-character, are both brought back to something
10156        // sliceable rather than panicking the next reader of the range.
10157        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
10158        let mut d = multi;
10159        d.select_range(2, 9_999);
10160        assert_eq!(d.caret, d.source.len());
10161        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
10162        assert!(d.source.is_char_boundary(d.caret));
10163    }
10164
10165    /// The bug `select_range` exists for: a match butting up against a hidden
10166    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
10167    /// the one before the `**`.
10168    #[test]
10169    fn select_range_does_not_snap_off_a_hidden_delimiter() {
10170        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
10171        let at = d.source.find("needle").unwrap();
10172        d.select_range(at, at + 6);
10173        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
10174    }
10175
10176    #[test]
10177    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
10178        // Backspace deletes `prev_boundary..caret` directly; at the first real
10179        // block that boundary is inside the hidden frontmatter, so it must be a
10180        // no-op rather than eating the closing `---`.
10181        let fm = "---\ntitle: hi\n---\n";
10182        let body = format!("{fm}leaf\n");
10183        let mut d = wysiwyg_doc("wys_fm_bs", &body);
10184        assert_eq!(d.caret, fm.len());
10185        d.backspace();
10186        assert_eq!(d.source, body, "backspace must not touch frontmatter");
10187        d.delete_word_back();
10188        assert_eq!(
10189            d.source, body,
10190            "word-delete must not touch frontmatter either"
10191        );
10192    }
10193
10194    #[test]
10195    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
10196        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
10197        // fenced div, really, since core parses these on for every document
10198        // now (`parse_extensions`). The container is a `directive` node, an
10199        // `is_block_container` kind like `block_quote`, so the caret works
10200        // inside its child paragraph exactly as it would inside a quote: typing
10201        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
10202        // untouched.
10203        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
10204        let mut d = wysiwyg_doc("wys_vis", body);
10205        d.caret = body.find("hello").unwrap() + "hello".len();
10206        d.insert("!");
10207        assert_eq!(
10208            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
10209            "typing inside the block edits its content in place"
10210        );
10211        assert!(
10212            d.source.contains(":::vis{.public .family}"),
10213            "opening fence survives"
10214        );
10215        assert!(d.source.contains(":::\nafter"), "closing fence survives");
10216    }
10217
10218    #[test]
10219    fn source_view_still_reaches_frontmatter() {
10220        // The metadata is only *hidden*, never lost: the source view edits and
10221        // selects it in full, and it's always preserved on save.
10222        let fm = "---\ntitle: hi\n---\n";
10223        let body = format!("{fm}# leaf\n");
10224        let mut d = doc_with("src_fm", &body);
10225        d.select_all();
10226        let sel = d.selected_text().unwrap();
10227        assert!(
10228            sel.contains("title"),
10229            "source view should select everything"
10230        );
10231        d.move_doc_start(false);
10232        assert_eq!(d.caret, 0, "source view can reach offset 0");
10233    }
10234
10235    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
10236
10237    #[test]
10238    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
10239        // The border and padding between two cells all share one source offset,
10240        // so a column-stepping caret would sit on `│` and then stall there
10241        // forever. Right must step: end of "Name" -> start of "Qty".
10242        let mut d = wysiwyg_doc("tbl_right", TABLE);
10243        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
10244        d.move_right(false);
10245        assert_eq!(
10246            d.caret,
10247            TABLE.find("Qty").unwrap(),
10248            "should land in the next cell"
10249        );
10250        let (r, c) = d.caret_pos();
10251        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
10252    }
10253
10254    #[test]
10255    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
10256        let mut d = wysiwyg_doc("tbl_left", TABLE);
10257        d.caret = TABLE.find("Qty").unwrap();
10258        d.move_left(false);
10259        assert_eq!(
10260            d.caret,
10261            TABLE.find("Name").unwrap() + 4,
10262            "end of the previous cell"
10263        );
10264    }
10265
10266    #[test]
10267    fn wysiwyg_down_steps_over_a_table_rule() {
10268        // Between the header and the first body row sits a `├───┼───┤` rule.
10269        // It's drawn but holds no caret, so one Down must reach "Pear".
10270        let mut d = wysiwyg_doc("tbl_down", TABLE);
10271        d.caret = TABLE.find("Name").unwrap();
10272        d.move_down(false);
10273        assert_eq!(
10274            d.caret,
10275            TABLE.find("Pear").unwrap(),
10276            "one Down reaches the body row"
10277        );
10278        d.move_down(false);
10279        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
10280    }
10281
10282    #[test]
10283    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
10284        let mut d = wysiwyg_doc("tbl_tab", TABLE);
10285        d.caret = TABLE.find("Name").unwrap();
10286        // A hop lands with the destination cell's whole content selected, the
10287        // caret at its end — so typing replaces the cell like a form field.
10288        assert!(d.cell_hop(true));
10289        assert_eq!(
10290            d.selected_text(),
10291            Some("Qty"),
10292            "the target cell comes up selected"
10293        );
10294        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
10295        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
10296        assert_eq!(d.selected_text(), Some("Pear"));
10297        assert!(d.cell_hop(false));
10298        assert_eq!(d.selected_text(), Some("Qty"));
10299    }
10300
10301    #[test]
10302    fn tab_outside_a_table_is_not_a_cell_hop() {
10303        // `cell_hop` reports false so the frontend can indent as usual.
10304        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
10305        d.caret = 4;
10306        assert!(!d.cell_hop(true));
10307        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
10308    }
10309
10310    #[test]
10311    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
10312        let mut d = wysiwyg_doc("tbl_edge", TABLE);
10313        d.caret = TABLE.rfind("12").unwrap(); // the final cell
10314        assert!(!d.cell_hop(true), "no cell after the last one");
10315        d.caret = TABLE.find("Name").unwrap();
10316        assert!(!d.cell_hop(false), "no cell before the first one");
10317    }
10318
10319    #[test]
10320    fn wysiwyg_vertical_cell_motion_holds_the_column() {
10321        // Down/Up step to the cell above/below in the *same column*, not back to
10322        // the top-left the way a naive row/col motion over the picture would.
10323        let mut d = wysiwyg_doc("tbl_vert", TABLE);
10324        d.caret = TABLE.find("Qty").unwrap();
10325        // Each vertical hop selects the destination cell, holding the column.
10326        assert!(d.cell_move_vertical(true));
10327        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
10328        assert!(d.cell_move_vertical(true));
10329        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
10330        assert!(!d.cell_move_vertical(true), "no row below the last");
10331        assert!(d.cell_move_vertical(false));
10332        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
10333        assert!(d.cell_move_vertical(false));
10334        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
10335        assert!(!d.cell_move_vertical(false), "no row above the header");
10336    }
10337
10338    #[test]
10339    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
10340        let mut d = wysiwyg_doc("tbl_grow", TABLE);
10341        d.caret = TABLE.rfind("12").unwrap();
10342        let rows_before = d.source.matches('\n').count();
10343        assert!(d.cell_tab(true), "acts as a table key");
10344        assert_eq!(
10345            d.source.matches('\n').count(),
10346            rows_before + 1,
10347            "a fresh row was appended"
10348        );
10349        assert!(d.caret_in_table(), "the caret entered the new row");
10350        // The caret sits in the new row's first cell — past the old last cell.
10351        assert!(d.caret > TABLE.rfind("12").unwrap());
10352    }
10353
10354    #[test]
10355    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
10356        let mut d = wysiwyg_doc("tbl_ret", TABLE);
10357        d.caret = TABLE.find("Name").unwrap();
10358        assert!(d.cell_return(), "acts as a table key");
10359        assert_eq!(
10360            d.selected_text(),
10361            Some("Pear"),
10362            "Return drops one cell, selecting it"
10363        );
10364        // From the last row, Return appends a row and enters it.
10365        d.caret = TABLE.rfind("Fig").unwrap();
10366        let rows_before = d.source.matches('\n').count();
10367        assert!(d.cell_return());
10368        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
10369        assert!(d.caret_in_table());
10370    }
10371
10372    #[test]
10373    fn return_and_tab_outside_a_table_decline() {
10374        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
10375        d.caret = 4;
10376        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
10377        assert!(!d.cell_tab(true), "no table: the frontend indents");
10378        assert!(
10379            !d.cell_line_break(),
10380            "no table: the frontend breaks the line"
10381        );
10382    }
10383
10384    #[test]
10385    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
10386        let mut d = wysiwyg_doc("tbl_break", TABLE);
10387        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
10388        assert!(d.cell_line_break(), "acts as a table key");
10389        assert!(
10390            d.source.contains("Pear<br>"),
10391            "spelled as an inline <br>: {}",
10392            d.source
10393        );
10394        assert!(d.caret_in_table(), "still in the cell, past the break");
10395        // The break renders as a real line: the "Pear" cell now draws two lines,
10396        // so the table's picture is one row taller than a single-line table.
10397        d.build_visual(80);
10398        let table = &d.vmap.tables[0];
10399        let cell = &table.grid[1].cells[0]; // first body row, first column
10400        assert!(
10401            cell.glyphs.iter().any(|g| g.ch == '\n'),
10402            "the cell carries the break as a newline glyph for the frontend to split"
10403        );
10404    }
10405
10406    #[test]
10407    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
10408        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
10409        // back as structure — the whole point of routing through insert_line_break
10410        // instead of splicing raw `<br>` bytes.
10411        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
10412        d.caret = TABLE.find("Pear").unwrap() + 4;
10413        assert!(d.cell_line_break());
10414        let kinds: Vec<Kind> = d
10415            .editor
10416            .nodes()
10417            .unwrap()
10418            .iter()
10419            .map(|n| n.kind.clone())
10420            .collect();
10421        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
10422        assert!(
10423            !kinds.contains(&Kind::RawInline),
10424            "still raw HTML: {kinds:?}"
10425        );
10426    }
10427
10428    #[test]
10429    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
10430        // The `<br>` draws as one newline glyph, so Backspace over it must take
10431        // all four bytes — a one-byte delete would strand a visible `<br` in the
10432        // cell (the reported bug).
10433        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
10434        d.caret = TABLE.find("Pear").unwrap() + 4;
10435        assert!(d.cell_line_break());
10436        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
10437        d.backspace(); // caret sits just past the break
10438        assert!(
10439            !d.source.contains("<br"),
10440            "no half-deleted <br left: {}",
10441            d.source
10442        );
10443        assert!(
10444            d.source.contains("| Pear |"),
10445            "the cell is back to one line: {}",
10446            d.source
10447        );
10448    }
10449
10450    #[test]
10451    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
10452        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
10453        d.caret = TABLE.find("Pear").unwrap() + 4;
10454        assert!(d.cell_line_break());
10455        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
10456        d.delete_forward();
10457        assert!(
10458            !d.source.contains("<br"),
10459            "no half-deleted <br: {}",
10460            d.source
10461        );
10462        assert!(
10463            d.source.contains("| Pear |"),
10464            "cell back to one line: {}",
10465            d.source
10466        );
10467    }
10468
10469    #[test]
10470    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
10471        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
10472        // still consumed (a real newline would split the one-line row), but the
10473        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
10474        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
10475        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10476        d.caret = src.find("Pear").unwrap() + 4;
10477        assert!(d.caret_in_table(), "caret should be inside the djot table");
10478        assert!(
10479            d.cell_line_break(),
10480            "the key is consumed, not passed to the frontend"
10481        );
10482        assert_eq!(d.source, src, "the djot cell is left untouched");
10483        assert!(
10484            !d.source.contains("<br>"),
10485            "no non-idiomatic <br> spliced into djot"
10486        );
10487        assert!(
10488            d.status.is_some(),
10489            "the refusal is surfaced on the status line"
10490        );
10491    }
10492
10493    #[test]
10494    fn typing_in_a_cell_edits_that_cell() {
10495        // Editing comes free once offsets map correctly: the caret is a source
10496        // offset, so a normal splice lands inside the pipe table.
10497        let mut d = wysiwyg_doc("tbl_type", TABLE);
10498        d.caret = TABLE.find("Pear").unwrap() + 4;
10499        d.insert("s");
10500        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
10501    }
10502
10503    #[test]
10504    fn motion_and_delete_treat_an_emoji_as_one_character() {
10505        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
10506        // bytes, several codepoints. Right-arrow must clear it in one step, and
10507        // backspace must remove the whole cluster, not a stray joiner.
10508        let family = "👨‍👩‍👧";
10509        let mut d = doc_with("emoji", &format!("a{family}b\n"));
10510        d.caret = 1; // just after 'a', before the emoji
10511        d.move_right(false);
10512        assert_eq!(
10513            d.caret,
10514            1 + family.len(),
10515            "one step clears the whole cluster"
10516        );
10517        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
10518
10519        d.backspace(); // delete the emoji as a unit
10520        assert_eq!(d.source, "ab\n");
10521        assert_eq!(d.caret, 1);
10522    }
10523
10524    #[test]
10525    fn motion_handles_a_combining_accent_as_one_character() {
10526        // "e" + U+0301 (combining acute) renders as one é.
10527        let mut d = doc_with("combining", "e\u{0301}x\n");
10528        d.caret = 0;
10529        d.move_right(false);
10530        assert_eq!(
10531            d.caret,
10532            "e\u{0301}".len(),
10533            "steps past base + combining mark"
10534        );
10535    }
10536
10537    #[test]
10538    fn undo_then_redo_round_trips_an_edit() {
10539        let mut d = doc_with("undo", "hello\n");
10540        d.caret = 5;
10541        d.insert("!");
10542        assert_eq!(d.source, "hello!\n");
10543        d.undo();
10544        assert_eq!(d.source, "hello\n");
10545        assert_eq!(d.caret, 5, "undo restores the caret");
10546        d.redo();
10547        assert_eq!(d.source, "hello!\n");
10548    }
10549
10550    #[test]
10551    fn a_run_of_typing_undoes_as_one_step() {
10552        let mut d = doc_with("coalesce", "\n");
10553        d.caret = 0;
10554        d.insert("a");
10555        d.insert("b");
10556        d.insert("c");
10557        assert_eq!(d.source, "abc\n");
10558        d.undo(); // the whole typed run, not just "c"
10559        assert_eq!(d.source, "\n");
10560        d.undo(); // nothing left — the run was one step
10561        assert_eq!(d.source, "\n");
10562        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
10563    }
10564
10565    // ── IME composition ──────────────────────────────────────────────────────
10566
10567    #[test]
10568    fn a_composition_run_undoes_as_one_step() {
10569        let mut d = doc_with("compose", "\n");
10570        d.caret = 0;
10571        // What an IME does: each step replaces the last one's provisional bytes.
10572        d.edit_composing(0, 0, "k");
10573        d.edit_composing(0, 1, "か");
10574        d.edit_composing(0, 3, "かん");
10575        d.edit_composing(0, 6, "感"); // the commit
10576        d.end_composition();
10577        assert_eq!(d.source, "感\n");
10578        d.undo(); // the whole composition, not its last keystroke
10579        assert_eq!(d.source, "\n");
10580        assert_eq!(d.status.as_deref(), None, "the run was a single step");
10581    }
10582
10583    #[test]
10584    fn two_compositions_are_two_undo_steps() {
10585        let mut d = doc_with("compose_two", "\n");
10586        d.caret = 0;
10587        d.edit_composing(0, 0, "か");
10588        d.edit_composing(0, 3, "蚊");
10589        d.end_composition();
10590        d.edit_composing(3, 3, "き");
10591        d.edit_composing(3, 6, "木");
10592        d.end_composition();
10593        assert_eq!(d.source, "蚊木\n");
10594        d.undo();
10595        assert_eq!(d.source, "蚊\n", "only the second composition");
10596        d.undo();
10597        assert_eq!(d.source, "\n");
10598    }
10599
10600    #[test]
10601    fn a_composition_does_not_fold_into_the_typing_around_it() {
10602        let mut d = doc_with("compose_typing", "\n");
10603        d.caret = 0;
10604        d.insert("a");
10605        d.insert("b");
10606        d.edit_composing(2, 2, "か");
10607        d.edit_composing(2, 5, "蚊");
10608        d.end_composition();
10609        d.insert("c");
10610        assert_eq!(d.source, "ab蚊c\n");
10611        d.undo();
10612        assert_eq!(d.source, "ab蚊\n");
10613        d.undo();
10614        assert_eq!(d.source, "ab\n");
10615        d.undo();
10616        assert_eq!(d.source, "\n");
10617    }
10618
10619    #[test]
10620    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
10621        let mut d = doc_with("compose_spurious", "\n");
10622        d.caret = 0;
10623        d.insert("a");
10624        d.end_composition(); // an IME unmarking unprompted
10625        d.insert("b");
10626        assert_eq!(d.source, "ab\n");
10627        d.undo();
10628        assert_eq!(d.source, "\n", "still one typed run");
10629    }
10630
10631    // ── the clipboard's rich flavor ──────────────────────────────────────────
10632
10633    #[test]
10634    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
10635        let mut d = doc_with("sel_inline", "a **bold** c\n");
10636        d.anchor = Some(2);
10637        d.caret = 10; // `**bold**`, inside the paragraph
10638        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
10639    }
10640
10641    #[test]
10642    fn a_whole_block_selection_keeps_its_paragraph() {
10643        let mut d = doc_with("sel_block", "a **bold** c\n");
10644        d.anchor = Some(0);
10645        d.caret = 12; // the entire paragraph
10646        assert_eq!(
10647            d.selection_html().as_deref(),
10648            Some("<p>a <strong>bold</strong> c</p>")
10649        );
10650    }
10651
10652    #[test]
10653    fn a_multi_block_selection_keeps_its_structure() {
10654        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
10655        d.select_all();
10656        let html = d.selection_html().expect("renders");
10657        assert!(html.contains("<p>para</p>"), "{html:?}");
10658        assert!(html.contains("<li>one</li>"), "{html:?}");
10659    }
10660
10661    #[test]
10662    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
10663        // The fragment `Head` is a paragraph standalone; the *document* says it
10664        // sits inside one block, so the wrapper is an artifact either way.
10665        let mut d = doc_with("sel_heading", "# Head line\n");
10666        d.anchor = Some(2);
10667        d.caret = 6;
10668        assert_eq!(d.selection_html().as_deref(), Some("Head"));
10669    }
10670
10671    #[test]
10672    fn no_selection_publishes_no_html() {
10673        let mut d = doc_with("sel_none", "a b\n");
10674        d.caret = 1;
10675        assert_eq!(d.selection_html(), None);
10676    }
10677
10678    #[test]
10679    fn pasting_html_converts_it_and_is_one_undo_step() {
10680        let mut d = doc_with("paste_html", "x\n");
10681        d.caret = 1;
10682        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
10683        assert_eq!(d.source, "xa **b** c\n");
10684        d.undo();
10685        assert_eq!(d.source, "x\n", "the whole paste, in one step");
10686    }
10687
10688    #[test]
10689    fn pasting_html_replaces_the_selection() {
10690        let mut d = doc_with("paste_html_sel", "keep drop\n");
10691        d.anchor = Some(5);
10692        d.caret = 9;
10693        assert!(d.paste_html("<em>new</em>"));
10694        assert_eq!(d.source, "keep *new*\n");
10695    }
10696
10697    #[test]
10698    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
10699        let mut d = doc_with("paste_html_bad", "x\n");
10700        d.caret = 1;
10701        // twig builds no table from HTML; raw `<table>` in prose is worse than
10702        // the plain flavor the caller still holds.
10703        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
10704        assert_eq!(d.source, "x\n", "declined edits nothing");
10705    }
10706
10707    #[test]
10708    fn copy_then_paste_round_trips_through_the_html_flavor() {
10709        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
10710        d.select_all();
10711        let html = d.selection_html().expect("renders");
10712        let mut into = doc_with("clip_round_dst", "\n");
10713        into.caret = 0;
10714        assert!(into.paste_html(&html));
10715        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
10716    }
10717
10718    #[test]
10719    fn moving_the_caret_starts_a_new_undo_group() {
10720        let mut d = doc_with("break", "\n");
10721        d.caret = 0;
10722        d.insert("a");
10723        d.insert("b"); // "ab\n", caret at 2
10724        d.move_left(false); // breaks the run
10725        d.insert("X"); // "aXb\n"
10726        assert_eq!(d.source, "aXb\n");
10727        d.undo();
10728        assert_eq!(
10729            d.source, "ab\n",
10730            "first undo removes only the post-move insert"
10731        );
10732        d.undo();
10733        assert_eq!(d.source, "\n", "second undo removes the earlier run");
10734    }
10735
10736    #[test]
10737    fn undo_reverses_a_format_toggle() {
10738        let mut d = doc_with("fmt_undo", "a word b\n");
10739        d.anchor = Some(2);
10740        d.caret = 6;
10741        d.toggle(InlineKind::Strong);
10742        assert_eq!(d.source, "a **word** b\n");
10743        d.undo();
10744        assert_eq!(d.source, "a word b\n");
10745    }
10746
10747    #[test]
10748    fn undo_back_to_the_saved_state_clears_dirty() {
10749        let mut d = doc_with("dirty_undo", "hello\n");
10750        assert!(!d.dirty);
10751        d.caret = 5;
10752        d.insert("!");
10753        assert!(d.dirty);
10754        d.undo();
10755        assert!(
10756            !d.dirty,
10757            "undoing to the saved source is not a modification"
10758        );
10759    }
10760
10761    #[test]
10762    fn a_new_edit_invalidates_redo() {
10763        let mut d = doc_with("redo_inv", "\n");
10764        d.caret = 0;
10765        d.insert("a");
10766        d.undo();
10767        d.insert("b"); // diverges — the redo of "a" is now gone
10768        d.redo();
10769        assert_eq!(d.source, "b\n");
10770    }
10771
10772    #[test]
10773    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
10774        let mut d = doc_with("can_undo", "hello\n");
10775        assert!(
10776            !d.can_undo() && !d.can_redo(),
10777            "a fresh document has no history"
10778        );
10779        d.caret = 5;
10780        d.insert("!");
10781        assert!(
10782            d.can_undo() && !d.can_redo(),
10783            "an edit is a step to take back"
10784        );
10785        d.undo();
10786        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
10787        d.redo();
10788        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
10789        d.undo();
10790        d.insert("?");
10791        assert!(
10792            d.can_undo() && !d.can_redo(),
10793            "a fresh edit ends the redo chain"
10794        );
10795        // A coalesced run over-counts steps — the bound is what a menu needs,
10796        // and it reconciles the moment twig reports the history empty.
10797        d.insert("a");
10798        d.insert("b");
10799        while d.can_undo() {
10800            d.undo();
10801        }
10802        assert_eq!(d.source, "hello\n");
10803        assert!(!d.can_undo());
10804        // A reading surface has nothing to undo, whatever the history holds.
10805        d.redo();
10806        d.set_read_only(true);
10807        assert!(!d.can_undo() && !d.can_redo());
10808    }
10809
10810    #[test]
10811    fn undo_on_empty_history_is_a_no_op() {
10812        let mut d = doc_with("undo_empty", "hi\n");
10813        d.undo();
10814        assert_eq!(d.source, "hi\n");
10815        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
10816    }
10817
10818    #[test]
10819    fn a_one_character_paste_is_its_own_undo_step() {
10820        for view in [View::Source, View::Wysiwyg] {
10821            let mut d = doc_in(view, "paste_step", "ab\n");
10822            d.caret = 0;
10823            d.insert("x");
10824            d.insert("y"); // a run of typing
10825            d.paste("z"); // one character, but pasted — not part of that run
10826            assert_eq!(d.source, "xyzab\n");
10827            d.undo();
10828            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
10829            assert_eq!(d.caret, 2, "and hands back the caret it found");
10830            d.undo();
10831            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
10832        }
10833    }
10834
10835    #[test]
10836    fn the_same_character_typed_still_joins_the_run() {
10837        // The other half of the pair: `z` is a keystroke here and a paste above,
10838        // and the two undo differently. Nothing about the *string* says which —
10839        // which is why provenance has to come from the door the caller uses.
10840        for view in [View::Source, View::Wysiwyg] {
10841            let mut d = doc_in(view, "typed_run", "ab\n");
10842            d.caret = 0;
10843            d.insert("x");
10844            d.insert("y");
10845            d.insert("z");
10846            d.undo();
10847            assert_eq!(d.source, "ab\n", "one run, one step");
10848        }
10849    }
10850
10851    #[test]
10852    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
10853        for view in [View::Source, View::Wysiwyg] {
10854            let mut d = doc_in(view, "undo_caret", "hello world\n");
10855            d.caret = 11; // standing at the end of "world", away from the edit
10856            d.edit(0, 5, "goodbye");
10857            assert_eq!(d.source, "goodbye world\n");
10858            d.undo();
10859            assert_eq!(d.source, "hello world\n");
10860            // The undone edit ends at offset 5; the user was at 11.
10861            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
10862        }
10863    }
10864
10865    #[test]
10866    fn undo_restores_the_selection_the_edit_replaced() {
10867        for view in [View::Source, View::Wysiwyg] {
10868            let mut d = doc_in(view, "undo_sel", "a word b\n");
10869            d.anchor = Some(2);
10870            d.caret = 6; // "word" selected
10871            d.insert("X");
10872            assert_eq!(d.source, "a X b\n");
10873            d.undo();
10874            assert_eq!(d.source, "a word b\n");
10875            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
10876        }
10877    }
10878
10879    #[test]
10880    fn redo_restores_the_caret_the_edit_left_behind() {
10881        for view in [View::Source, View::Wysiwyg] {
10882            let mut d = doc_in(view, "redo_caret", "hello world\n");
10883            d.caret = 11;
10884            d.edit(0, 5, "goodbye");
10885            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
10886            d.undo();
10887            d.redo();
10888            assert_eq!(d.source, "goodbye world\n");
10889            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
10890        }
10891    }
10892
10893    #[test]
10894    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
10895        for view in [View::Source, View::Wysiwyg] {
10896            let mut d = doc_in(view, "run_caret", "hi\n");
10897            d.caret = 2;
10898            d.insert("a");
10899            d.insert("b");
10900            d.insert("c");
10901            assert_eq!(d.source, "hiabc\n");
10902            d.undo();
10903            assert_eq!(d.source, "hi\n");
10904            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
10905            d.redo();
10906            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
10907        }
10908    }
10909
10910    #[test]
10911    fn undo_restores_the_caret_across_a_format_toggle() {
10912        // A toggle reaches twig without going through `splice`, so it has to
10913        // record its own step — miss it and every stack depth below it is off by
10914        // one, and undo starts handing back another edit's caret.
10915        for view in [View::Source, View::Wysiwyg] {
10916            let mut d = doc_in(view, "fmt_caret", "a word b\n");
10917            d.caret = 8;
10918            d.anchor = Some(2);
10919            d.caret = 6;
10920            d.toggle(InlineKind::Strong);
10921            assert_eq!(d.source, "a **word** b\n");
10922            d.undo();
10923            assert_eq!(d.source, "a word b\n");
10924            assert_eq!(
10925                d.selection(),
10926                Some((2, 6)),
10927                "the toggled selection comes back"
10928            );
10929        }
10930    }
10931
10932    #[test]
10933    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
10934        // The drift that would never announce itself: twig drops its redo stack
10935        // on any fresh edit, so a leaf redo entry that outlives it would restore
10936        // a caret from the timeline that edit abandoned.
10937        for view in [View::Source, View::Wysiwyg] {
10938            let mut d = doc_in(view, "redo_trunc", "hello world\n");
10939            d.caret = 11;
10940            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
10941            d.undo();
10942            assert_eq!(d.caret, 11);
10943            d.caret = 0;
10944            d.insert("X"); // diverges: A's redo is gone from twig
10945            assert_eq!(d.source, "Xhello world\n");
10946
10947            d.redo();
10948            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
10949            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
10950            d.undo();
10951            assert_eq!(d.source, "hello world\n");
10952            assert_eq!(
10953                d.caret, 0,
10954                "the surviving step's caret, not the dropped one"
10955            );
10956        }
10957    }
10958
10959    #[test]
10960    fn indent_and_outdent_move_the_caret_line_with_its_text() {
10961        for view in [View::Source, View::Wysiwyg] {
10962            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
10963            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
10964            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
10965            // Indentation the caret is standing *in* collapses to the line start
10966            // rather than dragging the caret into the text.
10967            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
10968            // A line with none to give back is left exactly as it was.
10969            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
10970            // Less than a full level gives back what it has.
10971            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
10972            // A tab is one level however many spaces it isn't.
10973            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
10974        }
10975    }
10976
10977    #[test]
10978    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
10979        // Why the level is two spaces and not the four both frontends type
10980        // today. Four is markdown's indented-code-block marker, so a Tab on a
10981        // paragraph would silently restyle it as code — a width that changes
10982        // what the document *means* isn't an indent. Pinned because the number
10983        // is the kind of thing a later list-aware pass would reach for.
10984        let mut d = doc_with("indent_kind", "hello\n");
10985        d.caret = 2;
10986        d.indent();
10987        assert_eq!(d.source, "  hello\n");
10988        assert!(
10989            d.nodes().iter().any(|n| n.kind == Kind::Para),
10990            "still prose after a Tab"
10991        );
10992        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
10993
10994        // The four-space level this replaces, for contrast: same text, and twig
10995        // reparses the paragraph into a code block.
10996        let mut wide = doc_with("indent_kind_4", "    hello\n");
10997        wide.build_visual(80);
10998        assert!(
10999            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
11000            "four spaces is a code block, not an indented paragraph"
11001        );
11002    }
11003
11004    #[test]
11005    fn indent_nests_a_list_item_under_its_parent() {
11006        // Tab indents a list item by its own marker width, landing its marker at
11007        // the parent's content column so twig reparses it as a nested list.
11008        for view in [View::Source, View::Wysiwyg] {
11009            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
11010            d.caret = 6; // on the second item
11011            d.indent();
11012            assert_eq!(d.source, "- a\n  - b\n");
11013            let lists = d
11014                .nodes()
11015                .iter()
11016                .filter(|n| n.kind == Kind::BulletList)
11017                .count();
11018            assert_eq!(lists, 2, "the indented item is a nested list");
11019        }
11020    }
11021
11022    #[test]
11023    fn indent_nests_an_ordered_item_at_its_marker_width() {
11024        // An ordered marker `1. ` is three columns wide, so a two-space step
11025        // (which nests a bullet) leaves it flat. Regression: Tab must use the
11026        // marker width, three, so the item actually nests — and the source
11027        // renumbers so the sub-list restarts at 1 and the outer list resumes.
11028        for view in [View::Source, View::Wysiwyg] {
11029            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
11030            d.caret = d.source.find('b').unwrap();
11031            d.indent();
11032            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
11033            let lists = d
11034                .nodes()
11035                .iter()
11036                .filter(|n| n.kind == Kind::OrderedList)
11037                .count();
11038            assert_eq!(lists, 2, "the indented item is a nested ordered list");
11039        }
11040    }
11041
11042    #[test]
11043    fn indent_leaves_a_lists_first_item_put() {
11044        // The first item of a list has no sibling above it to nest under, so Tab
11045        // is a no-op there — the marker stays at column zero rather than being
11046        // shoved into indentation twig can't read as a sub-list.
11047        for view in [View::Source, View::Wysiwyg] {
11048            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
11049            d.caret = 1; // on the FIRST item
11050            d.indent();
11051            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
11052            // The sibling below still nests, proving the guard is per-item.
11053            d.caret = d.source.find('b').unwrap();
11054            d.indent();
11055            assert_eq!(d.source, "- a\n  - b\n");
11056        }
11057    }
11058
11059    #[test]
11060    fn hidden_mode_keeps_typed_markup_literal() {
11061        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
11062        // twig escapes what would open markup, so the source is `\*hi\*` and the
11063        // AST is a plain string. Formatting is the commands' job in this mode.
11064        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
11065        d.insert("*hi*");
11066        assert_eq!(d.source, "\\*hi\\*");
11067        assert!(
11068            d.nodes()
11069                .iter()
11070                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
11071        );
11072    }
11073
11074    #[test]
11075    fn hidden_mode_escapes_a_line_start_block_marker() {
11076        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
11077        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
11078        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
11079        d.insert("# hi");
11080        assert_eq!(d.source, "\\# hi");
11081        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
11082    }
11083
11084    #[test]
11085    fn authoring_modes_keep_typed_markup_live() {
11086        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
11087        // (no escape), the same as source view — escaping is `None`'s alone, and
11088        // it's the axis, not the reveal, that decides.
11089        for (view, mode) in [
11090            (View::Wysiwyg, MarkupMode::Shortcuts),
11091            (View::Wysiwyg, MarkupMode::Full),
11092            (View::Source, MarkupMode::None),
11093        ] {
11094            let mut d = doc_in(view, "live_markup", "");
11095            d.set_markup_mode(mode);
11096            d.insert("*hi*");
11097            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
11098        }
11099    }
11100
11101    #[test]
11102    fn hidden_mode_overwrite_undoes_in_one_step() {
11103        // Typing over a selection escapes the replacement *and* stays a single
11104        // undo — the selection-delete and the literal insert fold together, so
11105        // one undo brings the whole selection back, like a plain overwrite.
11106        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
11107        d.anchor = Some(2);
11108        d.caret = 6; // "word"
11109        d.insert("*");
11110        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
11111        d.undo();
11112        assert_eq!(d.source, "a word b\n");
11113        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
11114    }
11115
11116    #[test]
11117    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
11118        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
11119        // the whole visual character, never stranding the hidden `\`.
11120        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
11121        d.insert("*");
11122        assert_eq!(d.source, "\\*");
11123        d.backspace();
11124        assert_eq!(d.source, "", "the escape backslash went with the *");
11125        // A *literal* backslash (source view, no escape) is an ordinary char.
11126        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
11127        s.caret = 3; // after `b`
11128        s.backspace();
11129        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
11130    }
11131
11132    #[test]
11133    fn hidden_mode_leaves_structural_markup_alone() {
11134        // Enter continues a bullet list by writing a real `- ` marker (an
11135        // `insert_raw`, not the typing path), so Hidden mode's escaping never
11136        // touches it — the list keeps working.
11137        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
11138        d.caret = 6;
11139        d.newline();
11140        d.insert("two");
11141        assert_eq!(d.source, "- item\n- two\n");
11142    }
11143
11144    #[test]
11145    fn markup_mode_defaults_to_none_and_round_trips() {
11146        // Diaryx's default is the clean `None` surface; a markup-fluent
11147        // frontend can climb the ladder, and the choice sticks.
11148        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
11149        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
11150        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
11151            d.set_markup_mode(mode);
11152            assert_eq!(d.markup_mode(), mode);
11153        }
11154    }
11155
11156    #[test]
11157    fn full_mode_reveals_only_the_caret_line() {
11158        // The mode's whole claim: the caret's line shows its raw delimiters and
11159        // every other line stays resolved. Two paragraphs with identical markup
11160        // so the only difference between the rows is where the caret is.
11161        let mut d = doc_in(
11162            View::Wysiwyg,
11163            "reveal_caret_line",
11164            "*one* here\n\n*two* there\n",
11165        );
11166        d.set_markup_mode(MarkupMode::Full);
11167
11168        caret_at(&mut d, "one");
11169        let rows = drawn_rows(&d);
11170        assert!(
11171            rows.iter().any(|r| r == "*one* here"),
11172            "caret's line raw: {rows:?}"
11173        );
11174        assert!(
11175            rows.iter().any(|r| r == "two there"),
11176            "other line resolved: {rows:?}"
11177        );
11178
11179        // Move to the other paragraph: the reveal follows, and the line just
11180        // left goes back to being resolved.
11181        caret_at(&mut d, "two");
11182        let rows = drawn_rows(&d);
11183        assert!(
11184            rows.iter().any(|r| r == "*two* there"),
11185            "caret's line raw: {rows:?}"
11186        );
11187        assert!(
11188            rows.iter().any(|r| r == "one here"),
11189            "left line resolved: {rows:?}"
11190        );
11191    }
11192
11193    #[test]
11194    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
11195        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
11196        // the same treatment as an emphasis's `*`: hidden while the caret is
11197        // elsewhere, shown in full where the caret lands. That falls out of
11198        // `delims` reading the bytes between the mark's span and its content
11199        // span, which is exactly `==🔴 ` and `==`, rather than from a table
11200        // of spellings — so the no-space form `==🟢green==` reveals right too.
11201        let mut d = doc_in(
11202            View::Wysiwyg,
11203            "reveal_coloured_mark",
11204            "a ==🔴 red== one\n\nb ==plain== two\n",
11205        );
11206        d.set_markup_mode(MarkupMode::Full);
11207
11208        caret_at(&mut d, "red");
11209        let rows = drawn_rows(&d);
11210        assert!(
11211            rows.iter().any(|r| r == "a ==🔴 red== one"),
11212            "the caret's line shows the colour it was written with: {rows:?}"
11213        );
11214        assert!(
11215            rows.iter().any(|r| r == "b plain two"),
11216            "and every other line stays resolved: {rows:?}"
11217        );
11218
11219        // Away from it, the emoji goes back to being markup — the reader sees
11220        // the words and the wash.
11221        caret_at(&mut d, "two");
11222        let rows = drawn_rows(&d);
11223        assert!(
11224            rows.iter().any(|r| r == "a red one"),
11225            "resolved again: {rows:?}"
11226        );
11227    }
11228
11229    #[test]
11230    fn hidden_modes_never_reveal_wherever_the_caret_is() {
11231        // The two rungs below `Full` share a rendering: delimiters stay hidden
11232        // even under the caret. `Shortcuts` differing from `None` only in what
11233        // typing does is exactly the point of splitting the axes.
11234        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
11235            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
11236            d.set_markup_mode(mode);
11237            caret_at(&mut d, "one");
11238            let rows = drawn_rows(&d);
11239            assert!(
11240                rows.iter().any(|r| r == "one here"),
11241                "{mode:?} hides: {rows:?}"
11242            );
11243            assert!(
11244                !rows.iter().any(|r| r.contains('*')),
11245                "{mode:?} shows no `*`: {rows:?}"
11246            );
11247        }
11248    }
11249
11250    #[test]
11251    fn revealed_delimiters_are_the_authors_own_spelling() {
11252        // Delimiters are re-read from the source rather than synthesized per
11253        // kind, so a line comes back spelled the way it was written: `_em_` does
11254        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
11255        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
11256        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
11257        d.set_markup_mode(MarkupMode::Full);
11258        caret_at(&mut d, "em");
11259        let rows = drawn_rows(&d);
11260        assert!(
11261            rows.iter().any(|r| r == body.trim_end()),
11262            "the revealed line is its own source: {rows:?}"
11263        );
11264    }
11265
11266    #[test]
11267    fn revealed_heading_shows_its_hashes() {
11268        // The `# ` marker is a block-level prefix, not an inline delimiter, so
11269        // it takes its own path — but it reveals on the same rule.
11270        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
11271        d.set_markup_mode(MarkupMode::Full);
11272
11273        caret_at(&mut d, "Title");
11274        assert!(
11275            drawn_rows(&d).iter().any(|r| r == "# Title"),
11276            "{:?}",
11277            drawn_rows(&d)
11278        );
11279
11280        caret_at(&mut d, "body");
11281        let rows = drawn_rows(&d);
11282        assert!(
11283            rows.iter().any(|r| r == "Title"),
11284            "hashes hidden again: {rows:?}"
11285        );
11286    }
11287
11288    #[test]
11289    fn revealed_delimiters_are_caret_stops() {
11290        // A delimiter that is drawn but can't be reached is worse than one
11291        // that's hidden: the mode exists so the markup can be *edited*. Every
11292        // revealed byte must be somewhere the caret can stand.
11293        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
11294        d.set_markup_mode(MarkupMode::Full);
11295        caret_at(&mut d, "em");
11296        let opener = d.source.find('*').unwrap();
11297        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
11298        assert!(
11299            d.vmap.is_stop(opener + 3),
11300            "the closing `*` is a caret stop"
11301        );
11302    }
11303
11304    #[test]
11305    fn setext_heading_reveals_nothing_across_its_newline() {
11306        // A setext heading's underline is on another line, so it is not the
11307        // caret line's to reveal — and emitting it would inject a `\n` glyph
11308        // that splits the row where the author wrote no break.
11309        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
11310        d.set_markup_mode(MarkupMode::Full);
11311        caret_at(&mut d, "Title");
11312        let rows = drawn_rows(&d);
11313        assert!(
11314            rows.iter().any(|r| r == "Title"),
11315            "title renders alone: {rows:?}"
11316        );
11317        assert!(
11318            !rows.iter().any(|r| r.contains('=')),
11319            "no underline leaks in: {rows:?}"
11320        );
11321    }
11322
11323    #[test]
11324    fn markup_mode_axes_split_the_ladder() {
11325        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
11326        // that authors markup but still hides it, and it's the only rung where
11327        // the two axes disagree.
11328        assert!(!MarkupMode::None.authors());
11329        assert!(!MarkupMode::None.reveals_caret_line());
11330        assert!(MarkupMode::Shortcuts.authors());
11331        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
11332        assert!(MarkupMode::Full.authors());
11333        assert!(MarkupMode::Full.reveals_caret_line());
11334    }
11335
11336    #[test]
11337    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
11338        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
11339        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
11340        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
11341        // nested bullet and `hello` stays prose: the file round-trips instead of
11342        // hiding a heading the user never asked for.
11343        for view in [View::Source, View::Wysiwyg] {
11344            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
11345            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
11346            d.indent();
11347            assert_eq!(d.source, "- hello\n  * \n");
11348            assert!(
11349                d.nodes().iter().all(|n| n.kind != Kind::Heading),
11350                "no heading"
11351            );
11352            // And it's genuinely a nested list, not a flat one.
11353            assert_eq!(
11354                d.nodes()
11355                    .iter()
11356                    .filter(|n| n.kind == Kind::BulletList)
11357                    .count(),
11358                2
11359            );
11360        }
11361    }
11362
11363    #[test]
11364    fn indenting_a_dash_item_with_content_keeps_its_dash() {
11365        // With content, `- x` can't be a setext underline, so there's nothing to
11366        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
11367        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
11368        d.caret = d.source.find('x').unwrap();
11369        d.indent();
11370        assert_eq!(d.source, "- hello\n  - x\n");
11371    }
11372
11373    #[test]
11374    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
11375        // The dash→`*` repair coalesces into the Tab, so a single undo restores
11376        // the whole pre-Tab state rather than stranding a half-collapsed doc.
11377        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
11378        d.caret = d.source.find("- \n").unwrap() + 2;
11379        d.indent();
11380        assert_eq!(d.source, "- hello\n  * \n");
11381        d.undo();
11382        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
11383    }
11384
11385    #[test]
11386    fn indent_leaves_a_nested_lists_first_item_put_too() {
11387        // The guard is about siblings, not depth: the first item of an *inner*
11388        // list (already nested under `a`) still has nothing before it at its own
11389        // level, so Tab can't take it deeper.
11390        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
11391        d.caret = d.source.find('b').unwrap();
11392        d.indent();
11393        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
11394        // But `c` (a sibling of `b`) nests under `b`.
11395        d.caret = d.source.find('c').unwrap();
11396        d.indent();
11397        assert_eq!(d.source, "- a\n  - b\n    - c\n");
11398    }
11399
11400    #[test]
11401    fn backspace_at_a_nested_item_start_outdents_it() {
11402        // Backspace with the caret right after a nested item's marker gives back
11403        // one level of nesting, the mirror of Tab — and renumbers the flattened
11404        // ordered list back to a clean run.
11405        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
11406        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
11407        d.backspace();
11408        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
11409    }
11410
11411    #[test]
11412    fn backspace_at_a_top_level_item_start_strips_the_marker() {
11413        // At the outermost level there's no nesting left to give back, so the same
11414        // keystroke drops the bullet and leaves a plain paragraph.
11415        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
11416        d.caret = d.source.find('b').unwrap(); // right after `- `
11417        d.backspace();
11418        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
11419    }
11420
11421    #[test]
11422    fn backspace_mid_item_still_deletes_a_character() {
11423        // The list behaviour is armed only at the item's content start; anywhere
11424        // else Backspace is the ordinary character delete.
11425        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
11426        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
11427        d.backspace();
11428        assert_eq!(d.source, "- b\n");
11429    }
11430
11431    #[test]
11432    fn backspace_at_a_heading_start_strips_the_marker() {
11433        // The `# ` is markup the rich view hides, so Backspace over it takes the
11434        // whole marker and leaves a paragraph. Deleting a byte of it instead left
11435        // `#Title` — no longer a heading, with the hash now literal text the user
11436        // never typed and has to delete again.
11437        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
11438        d.caret = d.source.find('T').unwrap(); // right after `## `
11439        d.backspace();
11440        assert_eq!(d.source, "Title\n");
11441        assert_eq!(
11442            d.caret, 0,
11443            "the caret stays with the text it was in front of"
11444        );
11445    }
11446
11447    #[test]
11448    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
11449        // Only the heading's own marker goes — the quote (or list) it sits in is
11450        // untouched, exactly as un-heading it should be.
11451        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
11452        d.caret = d.source.find('T').unwrap();
11453        d.backspace();
11454        assert_eq!(d.source, "> Title\n");
11455    }
11456
11457    #[test]
11458    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
11459        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
11460        // behind would surface the same stray hash the marker delete just avoided.
11461        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
11462        d.caret = d.source.find('T').unwrap();
11463        d.backspace();
11464        assert_eq!(d.source, "Title\n");
11465        // And it's one edit: a single undo puts the whole heading back.
11466        d.undo();
11467        assert_eq!(d.source, "# Title #\n");
11468    }
11469
11470    #[test]
11471    fn backspace_mid_heading_still_deletes_a_character() {
11472        // The heading behaviour is armed only at the content's start; anywhere
11473        // else Backspace is the ordinary character delete.
11474        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
11475        d.caret = d.source.find('b').unwrap();
11476        d.backspace();
11477        assert_eq!(d.source, "# b\n");
11478    }
11479
11480    #[test]
11481    fn source_view_backspace_still_edits_the_heading_marker_literally() {
11482        // In source view the `# ` is text on the screen the user is deleting a
11483        // byte of, so it keeps its literal meaning — the same split the list
11484        // ladder and Enter draw between the two views.
11485        let mut d = doc_with("bsp_head_src", "# Title\n");
11486        d.caret = d.source.find('T').unwrap();
11487        d.backspace();
11488        assert_eq!(d.source, "#Title\n");
11489    }
11490
11491    #[test]
11492    fn outdent_unnests_an_ordered_item_in_one_press() {
11493        // Shift+Tab gives back exactly the marker width the indent added, so a
11494        // nested ordered item unnests in a single press, and the flattened list
11495        // renumbers back to a clean 1, 2, 3.
11496        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
11497        d.caret = d.source.find('b').unwrap();
11498        d.outdent();
11499        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
11500        let lists = d
11501            .nodes()
11502            .iter()
11503            .filter(|n| n.kind == Kind::OrderedList)
11504            .count();
11505        assert_eq!(lists, 1, "back to one flat list");
11506    }
11507
11508    #[test]
11509    fn table_insert_row_adds_a_row_below_the_caret() {
11510        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
11511        d.caret = d.source.find('1').unwrap(); // in the body row
11512        d.table_insert_row(true);
11513        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
11514    }
11515
11516    #[test]
11517    fn table_insert_and_delete_column_at_the_caret() {
11518        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
11519        d.caret = d.source.find('a').unwrap(); // column 0
11520        d.table_insert_column(true); // add a column to the right of `a`
11521        assert_eq!(
11522            d.source,
11523            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
11524        );
11525        d.caret = d.source.find('b').unwrap(); // now the third column
11526        d.table_delete_column();
11527        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
11528    }
11529
11530    // ── ragged formats ───────────────────────────────────────────────────────
11531    // No format spells every gesture. HTML writes the inline marks as a tag pair
11532    // and no heading, list, quote or link; Markdown spells five of the eight
11533    // marks — the highlight only because leaf parses with `highlight`, which is
11534    // why the question is asked with the extensions; djot spells all eight and
11535    // no in-cell break. leaf asks twig per
11536    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
11537    // op discover the fact on its own — one of them didn't.
11538
11539    /// An HTML document in the rich view, ready for a gesture.
11540    fn html_doc(body: &str) -> Doc {
11541        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
11542        d.view = View::Wysiwyg;
11543        d.build_visual(80);
11544        d
11545    }
11546
11547    #[test]
11548    fn a_table_gesture_leaves_an_html_table_alone() {
11549        // The regression this guard exists for. twig's table editor consults no
11550        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
11551        // HTML `<table>` as a *pipe table* and reported success: the whole
11552        // element replaced by `| a | b |`, silently, on one press of a toolbar
11553        // button. Every grid op went the same way.
11554        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
11555        // A table of named operations, which is what it looks like.
11556        #[allow(clippy::type_complexity)]
11557        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
11558            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
11559            ("delete row", &|d: &mut Doc| d.table_delete_row()),
11560            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
11561            ("delete column", &|d: &mut Doc| d.table_delete_column()),
11562            ("align", &|d: &mut Doc| {
11563                d.table_set_alignment(Alignment::Right)
11564            }),
11565            ("move row", &|d: &mut Doc| d.table_move_row(true)),
11566            ("move column", &|d: &mut Doc| d.table_move_column(true)),
11567        ];
11568        for (name, op) in ops {
11569            let mut d = html_doc(src);
11570            d.caret = d.source.find('a').unwrap();
11571            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
11572            op(&mut d);
11573            assert_eq!(d.source, src, "{name} rewrote an HTML table");
11574            assert!(
11575                !d.dirty,
11576                "{name} marked the document dirty without editing it"
11577            );
11578            assert!(d.status.is_some(), "{name} refused without saying why");
11579        }
11580    }
11581
11582    #[test]
11583    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
11584        // A heading is a wrapping tag pair carrying its level in both ends, a
11585        // quote wraps a range rather than prefixing each line, a link's
11586        // destination lives in an attribute — different *shapes*, not a
11587        // different alphabet, so twig spells none of them and neither does leaf.
11588        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
11589        // A table of named operations, which is what it looks like.
11590        #[allow(clippy::type_complexity)]
11591        let ops: [(&str, &dyn Fn(&mut Doc)); 9] = [
11592            ("heading", &|d: &mut Doc| d.toggle_heading(2)),
11593            ("paragraph", &|d: &mut Doc| {
11594                d.set_block(BlockKind::Paragraph)
11595            }),
11596            ("quote", &|d: &mut Doc| d.toggle_blockquote()),
11597            ("list", &|d: &mut Doc| d.toggle_list(false)),
11598            ("task item", &|d: &mut Doc| d.toggle_task_item()),
11599            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
11600            ("link", &|d: &mut Doc| d.insert_link("https://example.dev")),
11601            ("image", &|d: &mut Doc| d.insert_image("pic.png", "alt")),
11602            ("video", &|d: &mut Doc| {
11603                d.insert_media(MediaKind::Video, "clip.mp4", "")
11604            }),
11605        ];
11606        for (name, op) in ops {
11607            let mut d = html_doc(src);
11608            let at = d.source.find("Hello").unwrap();
11609            d.caret = at;
11610            d.anchor = Some(at + 5); // a selection, for the ops that want one
11611            op(&mut d);
11612            assert_eq!(d.source, src, "{name} edited an HTML document");
11613            assert!(
11614                !d.dirty,
11615                "{name} marked the document dirty without editing it"
11616            );
11617            let status = d.status.as_deref().unwrap_or("");
11618            assert!(
11619                status.contains("html"),
11620                "{name}: the refusal should name the format, got {status:?}"
11621            );
11622        }
11623    }
11624
11625    #[test]
11626    fn html_spells_the_inline_marks_and_the_rule() {
11627        // The other half, and why one per-document flag stopped being enough:
11628        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
11629        // already emits and the parser reads straight back as the same mark —
11630        // and the rule button writes an `<hr>`. Refusing these on the old
11631        // "HTML is parse-only" reading would now be leaf's own limitation.
11632        let mut d = html_doc("<p>Hello world</p>\n");
11633        let at = d.source.find("world").unwrap();
11634        d.caret = at;
11635        d.anchor = Some(at + 5);
11636        d.toggle(InlineKind::Strong);
11637        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
11638        assert!(d.dirty);
11639        assert_eq!(d.status, None, "a supported gesture reports nothing");
11640
11641        // And off again — the toggle reverses, which is the property that makes
11642        // authoring in HTML worth offering rather than a one-way trip.
11643        d.toggle(InlineKind::Strong);
11644        assert_eq!(d.source, "<p>Hello world</p>\n");
11645
11646        let mut d = html_doc("<p>Hello world</p>\n");
11647        d.caret = d.source.find("world").unwrap();
11648        d.insert_thematic_break();
11649        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
11650    }
11651
11652    #[test]
11653    fn a_mark_the_format_cannot_spell_arms_nothing() {
11654        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
11655        // sticky mark for the next text typed. Guarding only the twig call
11656        // leaves that path live, promising a mark the gesture will not write and
11657        // then swallowing the error inside `insert`.
11658        //
11659        // Markdown carries this, on the superscript now rather than on the
11660        // highlight: `^x^` is text there in any configuration, whereas twig
11661        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
11662        // which every leaf document does.
11663        let mut d = doc_with("mark", "Hello world\n");
11664        d.view = View::Wysiwyg;
11665        d.build_visual(80);
11666        d.caret = d.source.find("world").unwrap();
11667        d.toggle(InlineKind::Superscript);
11668        assert!(d.pending_marks.is_empty(), "no mark should be armed");
11669        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
11670        d.insert("X");
11671        assert_eq!(d.source, "Hello Xworld\n");
11672    }
11673
11674    #[test]
11675    fn markdown_authors_a_highlight_and_a_strikethrough() {
11676        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
11677        // write. `==x==` is authorable because leaf's own `parse_extensions`
11678        // turns `highlight` on — twig will only mint bytes this editor's reparse
11679        // reads back — and `~~x~~` because GFM strikethrough is parsed by
11680        // default, so the refusal there was never right for any leaf document.
11681        for (kind, marked) in [
11682            (InlineKind::Mark, "a ==word== b\n"),
11683            (InlineKind::Delete, "a ~~word~~ b\n"),
11684        ] {
11685            let mut d = doc_with("author_mark", "a word b\n");
11686            d.anchor = Some(2);
11687            d.caret = 6;
11688            d.toggle(kind);
11689            assert_eq!(d.source, marked, "{kind:?}");
11690            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
11691            assert!(d.dirty, "{kind:?}");
11692            // The region stays selected, so the second press reverses it — the
11693            // property that separates authoring from a one-way trip.
11694            d.toggle(kind);
11695            assert_eq!(d.source, "a word b\n", "{kind:?}");
11696        }
11697    }
11698
11699    #[test]
11700    fn an_authored_highlight_reads_back_as_a_mark() {
11701        // The round trip the extension gate exists to protect: what the toggle
11702        // writes, the reparse must read back as a `mark` rather than as two
11703        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
11704        // rebuilt map rather than from the source text.
11705        let mut d = doc_with("mark_roundtrip", "a word b\n");
11706        d.view = View::Wysiwyg;
11707        d.build_visual(80);
11708        d.anchor = Some(2);
11709        d.caret = 6;
11710        d.toggle(InlineKind::Mark);
11711        assert_eq!(d.source, "a ==word== b\n");
11712        d.build_visual(80);
11713        let w = d
11714            .vmap
11715            .rows
11716            .iter()
11717            .flat_map(|r| r.glyphs.iter())
11718            .find(|g| g.ch == 'w')
11719            .expect("the highlighted word");
11720        assert_eq!(w.style.role, crate::Role::Mark(None));
11721    }
11722
11723    #[test]
11724    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
11725        // The three states of one gesture, in the order a palette is pressed:
11726        // an uncoloured highlight takes the prefix, a coloured one has it
11727        // replaced, and `None` takes it away with the space that was part of the
11728        // spelling.
11729        let mut d = doc_with("mark_colour", "a ==word== b\n");
11730        d.caret = d.source.find("word").unwrap();
11731        d.set_mark_color(Some(MarkColor::Red));
11732        assert_eq!(d.source, "a ==🔴 word== b\n");
11733        assert_eq!(d.status, None);
11734        assert!(d.dirty);
11735
11736        d.set_mark_color(Some(MarkColor::Blue));
11737        assert_eq!(d.source, "a ==🔵 word== b\n");
11738
11739        d.set_mark_color(None);
11740        assert_eq!(d.source, "a ==word== b\n");
11741    }
11742
11743    #[test]
11744    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
11745        // The prefix is written *before* the word, so an offset in the word has
11746        // to ride its width — a caret that stayed put would be a caret that
11747        // walked backwards through the text it was standing in.
11748        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
11749        let word = d.source.find("word").unwrap();
11750        d.caret = word + 2; // between `wo` and `rd`
11751        d.set_mark_color(Some(MarkColor::Red));
11752        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
11753
11754        // And back the other way when the prefix goes.
11755        d.set_mark_color(None);
11756        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
11757    }
11758
11759    #[test]
11760    fn the_colour_at_the_caret_is_what_the_palette_lights() {
11761        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
11762        d.caret = d.source.find("red").unwrap();
11763        assert!(d.caret_in_mark());
11764        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
11765
11766        d.caret = d.source.find("plain").unwrap();
11767        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
11768        assert_eq!(d.mark_color_at_caret(), None);
11769
11770        d.caret = d.source.find(" and ").unwrap() + 2;
11771        assert!(!d.caret_in_mark());
11772        assert_eq!(d.mark_color_at_caret(), None);
11773    }
11774
11775    #[test]
11776    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
11777        // The gesture colours a highlight that exists; it does not make one.
11778        // Two presses is the price of a coloured highlight from bare text, and
11779        // the reason is undo — one press that spliced twice would take two
11780        // presses to take back.
11781        let mut d = doc_with("mark_colour_none", "a word b\n");
11782        d.caret = d.source.find("word").unwrap();
11783        d.set_mark_color(Some(MarkColor::Red));
11784        assert_eq!(d.source, "a word b\n");
11785        assert!(d.status.is_some(), "it should say why");
11786        assert!(!d.dirty);
11787
11788        // Clearing where there is nothing to clear is the same refusal, not a
11789        // quiet success — the caret is in no highlight either way.
11790        d.status = None;
11791        d.set_mark_color(None);
11792        assert_eq!(d.source, "a word b\n");
11793        assert!(d.status.is_some());
11794    }
11795
11796    #[test]
11797    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
11798        // twig answers this one *successfully* with a `Change` describing some
11799        // earlier edit, so a caller that trusted the change would jump the caret
11800        // to wherever that was. Core answers it before asking.
11801        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
11802        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
11803        d.caret = d.source.find("word").unwrap();
11804        let (source, caret) = (d.source.clone(), d.caret);
11805        d.set_mark_color(None);
11806        assert_eq!(d.source, source);
11807        assert_eq!(
11808            d.caret, caret,
11809            "the caret must not ride a change that isn't one"
11810        );
11811        assert_eq!(d.status, None, "and it is not an error either");
11812    }
11813
11814    #[test]
11815    fn djot_spells_the_highlight_and_not_its_colour() {
11816        // The reason the palette is its own capability rather than the Highlight
11817        // button's: `{=word=}` is a highlight djot writes happily, and there is
11818        // no djot spelling for a colour on it.
11819        assert!(Capabilities::of(Format::Djot).mark);
11820        assert!(!Capabilities::of(Format::Djot).mark_color);
11821        assert!(Capabilities::of(Format::Markdown).mark_color);
11822
11823        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
11824        d.caret = d.source.find("word").unwrap();
11825        assert!(
11826            d.caret_in_mark(),
11827            "the caret is in a highlight all the same"
11828        );
11829        d.set_mark_color(Some(MarkColor::Red));
11830        assert_eq!(d.source, "a {=word=} b\n");
11831        assert!(
11832            d.status.as_deref().unwrap_or("").contains("djot"),
11833            "and the refusal names the document's format: {:?}",
11834            d.status
11835        );
11836    }
11837
11838    #[test]
11839    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
11840        // The round trip that matters for a palette: the bytes twig writes are
11841        // bytes its own reparse reads back as a colour, so the swatch that was
11842        // pressed is the swatch that lights afterwards.
11843        let mut d = doc_with("mark_colour_undo", "a word b\n");
11844        d.anchor = Some(2);
11845        d.caret = 6;
11846        d.toggle(InlineKind::Mark);
11847        d.caret = d.source.find("word").unwrap();
11848        d.set_mark_color(Some(MarkColor::Green));
11849        assert_eq!(d.source, "a ==🟢 word== b\n");
11850        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
11851
11852        // One splice, one step: the colour comes off and the highlight stays.
11853        d.undo();
11854        assert_eq!(d.source, "a ==word== b\n");
11855        d.undo();
11856        assert_eq!(d.source, "a word b\n");
11857    }
11858
11859    #[test]
11860    fn every_colour_leaf_names_is_one_twig_writes() {
11861        // The two enums are one vocabulary, and this is what says so: each of
11862        // leaf's colours writes an emoji twig's reparse reads back as *that*
11863        // colour, so `twig_mark_color`'s table cannot quietly pair red with
11864        // orange.
11865        for color in MarkColor::ALL {
11866            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
11867            d.caret = d.source.find("word").unwrap();
11868            d.set_mark_color(Some(color));
11869            assert_eq!(d.status, None, "{color:?}");
11870            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
11871        }
11872    }
11873
11874    #[test]
11875    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
11876        // The two presses a coloured highlight is made of, in the state the
11877        // first one leaves: `toggle` selects the whole `==word==` and puts the
11878        // caret one past the closing `==`, which is *not* in the mark. Asking at
11879        // the caret alone would refuse to colour the highlight just written —
11880        // the selection's start is what answers.
11881        let mut d = doc_with("mark_colour_fresh", "a word b\n");
11882        d.anchor = Some(2);
11883        d.caret = 6;
11884        d.toggle(InlineKind::Mark);
11885        assert_eq!(d.source, "a ==word== b\n");
11886        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
11887
11888        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
11889        d.set_mark_color(Some(MarkColor::Yellow));
11890        assert_eq!(d.source, "a ==🟡 word== b\n");
11891        assert_eq!(d.status, None);
11892    }
11893
11894    #[test]
11895    fn one_press_highlights_a_selection_and_colours_it() {
11896        // What a toolbar swatch means over a plain selection, and the undo it
11897        // has to have: one press, one step. Two steps would leave an uncoloured
11898        // highlight behind on the way back, which is a state the author never
11899        // asked for and never saw.
11900        let mut d = doc_with("highlight_one", "a word b\n");
11901        d.anchor = Some(2);
11902        d.caret = 6;
11903        d.highlight(Some(MarkColor::Purple));
11904        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
11905        assert_eq!(d.status, None);
11906
11907        d.undo();
11908        assert_eq!(d.source, "a word b\n", "one press, one undo");
11909    }
11910
11911    #[test]
11912    fn one_press_on_an_existing_highlight_only_recolours_it() {
11913        // The other half: inside a highlight there is nothing to make, so the
11914        // compound is the plain gesture and the text is untouched.
11915        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
11916        d.caret = d.source.find("word").unwrap();
11917        d.highlight(Some(MarkColor::Blue));
11918        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
11919        d.undo();
11920        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
11921    }
11922
11923    #[test]
11924    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
11925        // `None` means "no colour", and over bare text that is the Highlight
11926        // button's own job. The fold must not happen here — there is no second
11927        // splice, and folding would take the *previous* edit into this one.
11928        let mut d = doc_with("highlight_none", "a word b and more\n");
11929        d.caret = d.source.find("more").unwrap() + 4; // after "more"
11930        d.insert("!"); // an earlier edit for a wrong fold to swallow
11931        d.anchor = Some(2);
11932        d.caret = 6;
11933        d.highlight(None);
11934        assert_eq!(d.source, "a ==word== b and more!\n");
11935
11936        d.undo();
11937        assert_eq!(
11938            d.source, "a word b and more!\n",
11939            "only the highlight came off"
11940        );
11941        d.undo();
11942        assert_eq!(
11943            d.source, "a word b and more\n",
11944            "and the edit before it survived"
11945        );
11946    }
11947
11948    #[test]
11949    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
11950        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
11951        // a colour cannot be armed with it — so the compound declines rather
11952        // than leaving half a promise.
11953        let mut d = doc_with("highlight_bare", "a word b\n");
11954        d.caret = 4;
11955        d.highlight(Some(MarkColor::Red));
11956        assert_eq!(d.source, "a word b\n");
11957        assert!(d.pending_marks.is_empty(), "and nothing armed");
11958        assert!(d.status.is_some());
11959    }
11960
11961    #[test]
11962    fn a_read_only_document_takes_no_colour() {
11963        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
11964        d.caret = d.source.find("word").unwrap();
11965        d.set_read_only(true);
11966        d.set_mark_color(Some(MarkColor::Red));
11967        assert_eq!(d.source, "a ==word== b\n");
11968    }
11969
11970    #[test]
11971    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
11972        // The other door into `toggle`: no selection, so nothing reaches twig
11973        // until `insert` realises the armed mark. It is armed now — the guard
11974        // above asks `Doc::supports`, which asks with the extensions — and what
11975        // it writes is the same `==…==`.
11976        let mut d = doc_with("sticky_mark", "xy\n");
11977        d.caret = 1;
11978        d.toggle(InlineKind::Mark);
11979        assert!(d.pending_marks.contains(InlineKind::Mark));
11980        d.insert("Z");
11981        assert_eq!(d.source, "x==Z==y\n");
11982    }
11983
11984    #[test]
11985    fn html_documents_still_take_typed_text() {
11986        // The guard covers *markup* gestures and must not touch plain editing:
11987        // twig's splicer is language-neutral, and typing into an HTML document
11988        // is the thing that does work today.
11989        let mut d = html_doc("<p>Hello world</p>\n");
11990        d.caret = d.source.find("world").unwrap();
11991        d.insert("big ");
11992        assert_eq!(d.source, "<p>Hello big world</p>\n");
11993        assert!(d.dirty);
11994        d.backspace();
11995        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
11996        d.undo();
11997        d.undo();
11998        assert_eq!(d.source, "<p>Hello world</p>\n");
11999    }
12000
12001    #[test]
12002    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
12003        // `authorable` only separates "there is a door in" from "there is not",
12004        // and HTML is on the near side of that line — which is exactly why a
12005        // toolbar must not be built from it.
12006        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
12007        assert!(html.authorable());
12008        assert!(
12009            !Doc::from_source("<r>x</r>".into(), Format::Xml)
12010                .unwrap()
12011                .authorable()
12012        );
12013
12014        let caps = html.capabilities();
12015        assert!(caps.bold && caps.italic && caps.code && caps.mark);
12016        assert!(caps.thematic_break && caps.cell_line_break);
12017        assert!(!caps.heading && !caps.blockquote && !caps.bullet_list);
12018        assert!(!caps.task && !caps.link && !caps.image && !caps.code_language);
12019        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
12020        // twig's table editor would happily re-emit as `| a | b |`.
12021        assert!(!caps.table);
12022
12023        // The two lightweight formats spell everything leaf offers — and still
12024        // differ from each other, which is the other half of why one boolean
12025        // can't serve.
12026        for fmt in [Format::Markdown, Format::Djot] {
12027            let caps = Capabilities::of(fmt);
12028            assert!(
12029                caps.heading && caps.blockquote && caps.ordered_list,
12030                "{fmt:?}"
12031            );
12032            assert!(
12033                caps.task && caps.link && caps.image && caps.table,
12034                "{fmt:?}"
12035            );
12036        }
12037        // Both spell the highlight and the strikethrough: djot natively, and
12038        // Markdown because `Capabilities` asks with `parse_extensions` rather
12039        // than with twig's defaults — `==x==` is text under those, and a mark
12040        // under the `highlight` leaf always parses with.
12041        for fmt in [Format::Markdown, Format::Djot] {
12042            let caps = Capabilities::of(fmt);
12043            assert!(caps.mark && caps.strike, "{fmt:?}");
12044        }
12045        // What still separates them, now that the highlight doesn't: djot has
12046        // no in-cell break, and Markdown spells neither of the scripts.
12047        assert!(Capabilities::of(Format::Djot).superscript);
12048        assert!(!Capabilities::of(Format::Markdown).superscript);
12049        assert!(Capabilities::of(Format::Markdown).cell_line_break);
12050        assert!(!Capabilities::of(Format::Djot).cell_line_break);
12051
12052        // A parse-only format answers no to every one of them, so the coarse
12053        // predicate and the record agree there.
12054        let caps = Capabilities::of(Format::Xml);
12055        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
12056    }
12057
12058    #[test]
12059    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
12060        // The guard exists to name the *document's* format rather than twig's
12061        // internals, so the message has to survive being one leaf writes itself.
12062        // Checked against the gesture twig also refuses, since that is the pair
12063        // most at risk of drifting apart.
12064        let mut d = html_doc("<p>Hello</p>\n");
12065        d.caret = d.source.find("Hello").unwrap();
12066        d.set_code_language("zig");
12067        assert_eq!(
12068            d.status.as_deref(),
12069            Some("code language: not supported in html")
12070        );
12071        assert!(!d.dirty);
12072    }
12073
12074    #[test]
12075    fn table_set_alignment_respells_the_delimiter() {
12076        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
12077        d.caret = d.source.find('b').unwrap();
12078        d.table_set_alignment(Alignment::Right);
12079        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
12080    }
12081
12082    #[test]
12083    fn each_empty_table_cell_has_its_own_editable_home() {
12084        // Regression: an empty cell has no twig content_span, so both cells of a
12085        // `|  |  |` row collapsed onto the row's start (before the first `│`).
12086        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
12087        // tell the cells apart. Each empty cell must now have a distinct home
12088        // inside it.
12089        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
12090        let (c0, c1) = {
12091            let cells = &d.vmap.tables[0].grid[1].cells;
12092            (cells[0].start, cells[1].start)
12093        };
12094        assert!(
12095            c0 < c1,
12096            "the two empty cells have distinct homes: {c0} < {c1}"
12097        );
12098        d.caret = c0;
12099        d.insert("x");
12100        assert_eq!(
12101            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
12102            "typed inside the cell"
12103        );
12104    }
12105
12106    #[test]
12107    fn arrows_step_into_each_empty_table_cell() {
12108        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
12109        let (c0, c1) = {
12110            let cells = &d.vmap.tables[0].grid[1].cells;
12111            (cells[0].start, cells[1].start)
12112        };
12113        d.caret = d.source.find('b').unwrap(); // in the header's second cell
12114        let mut seen = std::collections::HashSet::new();
12115        for _ in 0..6 {
12116            d.move_right(false);
12117            seen.insert(d.caret);
12118        }
12119        assert!(
12120            seen.contains(&c0),
12121            "right arrow reaches the first empty cell"
12122        );
12123        assert!(
12124            seen.contains(&c1),
12125            "right arrow reaches the second empty cell"
12126        );
12127    }
12128
12129    #[test]
12130    fn table_op_off_a_table_is_a_no_op_with_a_status() {
12131        let mut d = doc_with("tbl_none", "just text\n");
12132        d.caret = 3;
12133        d.table_insert_row(true);
12134        assert_eq!(d.source, "just text\n", "nothing changed");
12135        assert!(d.status.is_some(), "a status explains why");
12136        assert!(!d.caret_in_table());
12137    }
12138
12139    #[test]
12140    fn enter_in_an_ordered_list_renumbers_the_following_items() {
12141        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
12142        // the renumber pass keeps them sequential, matching what the view draws.
12143        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
12144        d.caret = d.source.find('a').unwrap() + 1; // end of item a
12145        d.newline();
12146        d.insert("x");
12147        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
12148    }
12149
12150    #[test]
12151    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
12152        for view in [View::Source, View::Wysiwyg] {
12153            let mut d = doc_in(view, "outdent_noop", "hello\n");
12154            d.caret = 2;
12155            d.outdent();
12156            assert_eq!(d.source, "hello\n");
12157            assert!(!d.dirty, "a no-op is not a modification");
12158            d.undo();
12159            assert_eq!(
12160                d.status.as_deref(),
12161                Some("nothing to undo"),
12162                "spends no undo step"
12163            );
12164            assert_eq!(d.source, "hello\n");
12165        }
12166    }
12167
12168    #[test]
12169    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
12170        for view in [View::Source, View::Wysiwyg] {
12171            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
12172            d.anchor = Some(0);
12173            d.caret = 7; // through "two"
12174            d.indent();
12175            assert_eq!(
12176                d.source, "  one\n\n  two\n",
12177                "the blank line keeps no trailing pad"
12178            );
12179            // Selected, so a second Tab lands on the same lines rather than on
12180            // whatever the shifted offsets now cover.
12181            assert_eq!(d.selection(), Some((0, 12)));
12182            d.indent();
12183            assert_eq!(d.source, "    one\n\n    two\n");
12184        }
12185    }
12186
12187    #[test]
12188    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
12189        for view in [View::Source, View::Wysiwyg] {
12190            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
12191            d.anchor = Some(0);
12192            d.caret = 15;
12193            d.outdent();
12194            assert_eq!(d.source, "two\none\nnone\n");
12195        }
12196    }
12197
12198    #[test]
12199    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
12200        for view in [View::Source, View::Wysiwyg] {
12201            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
12202            d.anchor = Some(0);
12203            d.caret = 7;
12204            d.indent();
12205            assert_eq!(d.source, "  one\n\n  two\n");
12206            d.undo();
12207            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
12208            assert_eq!(
12209                d.selection(),
12210                Some((0, 7)),
12211                "with the selection it was aimed at"
12212            );
12213            d.redo();
12214            assert_eq!(d.source, "  one\n\n  two\n");
12215            assert_eq!(
12216                d.selection(),
12217                Some((0, 12)),
12218                "redo replays the caret the indent placed, not the one splice left"
12219            );
12220        }
12221    }
12222
12223    #[test]
12224    fn vertical_motion_keeps_the_column() {
12225        let mut d = doc_with("move", "abcd\nef\n");
12226        d.caret = 3; // "abc|d" on row 0, col 3
12227        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
12228        assert_eq!(d.caret, 7); // just after "ef"
12229    }
12230
12231    // ── goal column ──────────────────────────────────────────────────────────
12232
12233    #[test]
12234    fn vertical_motion_goal_column_survives_a_short_line() {
12235        // Regression: re-deriving the column from the clamped position on
12236        // every step permanently forgets it once a short line clamps it.
12237        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
12238        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
12239        assert_eq!(
12240            g("abcd|ef\nxy\nghijkl\n", |d| {
12241                d.move_down(false); // clamps to end of "xy"
12242                d.move_down(false); // restores col 4 on the long line
12243            }),
12244            "abcdef\nxy\nghij|kl\n"
12245        );
12246    }
12247
12248    #[test]
12249    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
12250        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
12251        assert_eq!(d.goal_col, None);
12252        d.caret = 4; // row 0, col 4
12253        d.move_down(false); // clamps into "xy"; goal stays the original col
12254        assert_eq!(d.goal_col, Some(4));
12255        assert_eq!(d.caret_pos(), (1, 2));
12256
12257        // A horizontal motion drops the goal column...
12258        d.move_left(false);
12259        assert_eq!(d.goal_col, None);
12260
12261        // ...so the next vertical motion picks up the *new* column (1), not
12262        // the stale one (4).
12263        d.move_down(false);
12264        assert_eq!(d.goal_col, Some(1));
12265        assert_eq!(d.caret_pos(), (2, 1));
12266    }
12267
12268    #[test]
12269    fn editing_clears_the_goal_column() {
12270        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
12271        d.caret = 4;
12272        d.move_down(false);
12273        assert_eq!(d.goal_col, Some(4));
12274        d.insert("Z");
12275        assert_eq!(d.goal_col, None);
12276    }
12277
12278    #[test]
12279    fn vertical_motion_on_an_empty_document_is_a_no_op() {
12280        let mut d = doc_with("empty_vert", "");
12281        d.move_down(false);
12282        assert_eq!(d.caret, 0);
12283        d.move_up(false);
12284        assert_eq!(d.caret, 0);
12285    }
12286
12287    // ── the document's edges ─────────────────────────────────────────────────
12288
12289    #[test]
12290    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
12291        // The reproduction, and the disagreement: Down on the last line ran to
12292        // the end of the document in the source view — by accident, an
12293        // out-of-range row clamping to the end of the string — and did nothing
12294        // whatever in the view leaf opens in. One rule now, in both.
12295        for (view, tag) in VIEWS {
12296            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
12297            d.caret = 1;
12298            d.move_down(false);
12299            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
12300            d.move_up(false);
12301            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
12302        }
12303    }
12304
12305    #[test]
12306    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
12307        // Down off the bottom is a motion like any other, so it latches a goal
12308        // column — and Up comes back to the column the caret left, not to the
12309        // one the document's end happened to be in.
12310        for (view, tag) in VIEWS {
12311            let gap = if view == View::Source { "\n" } else { "\n\n" };
12312            let src = format!("abcdef{gap}ghijkl");
12313            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
12314            d.caret = 2; // row 0, col 2
12315            d.move_down(false);
12316            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
12317            d.move_down(false);
12318            assert_eq!(
12319                d.caret,
12320                src.len(),
12321                "{tag}: Down off the bottom reaches the end"
12322            );
12323            d.move_up(false);
12324            assert_eq!(
12325                d.caret_pos().1,
12326                2,
12327                "{tag}: Up returns to the column Down left"
12328            );
12329        }
12330    }
12331
12332    #[test]
12333    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
12334        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
12335        // Up that did nothing still armed a goal column, and the next Down aimed
12336        // at a column the caret had never been in.
12337        for (view, tag) in VIEWS {
12338            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
12339            d.caret = 0;
12340            d.move_up(false);
12341            assert_eq!(d.caret, 0, "{tag}: already at the start");
12342            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
12343
12344            d.caret = d.source.len();
12345            d.move_down(false);
12346            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
12347            assert_eq!(
12348                d.goal_col, None,
12349                "{tag}: a no-op Down latched a goal column"
12350            );
12351        }
12352    }
12353
12354    // ── soft wrap ────────────────────────────────────────────────────────────
12355    // Every other test here builds the map at 80 columns, where no fixture is
12356    // long enough to fold. A wrap is where one offset belongs to two rows at
12357    // once, and it broke everything that asks the caret what row it is on.
12358
12359    /// The wrapped fixture these cases share, folded at 12 columns into
12360    /// `one two ` / `three four ` / `five six ` / `seven eight`.
12361    fn wrapped_doc(name: &str) -> Doc {
12362        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
12363        d.build_visual(12);
12364        d
12365    }
12366
12367    #[test]
12368    fn home_and_end_work_from_a_wrapped_row() {
12369        // The reproduction: offset 19 is the `f` of "five", the first character
12370        // of the third row — and also the offset the second row ends at. It
12371        // resolved to the *second* row, so End aimed at a place the caret was
12372        // already in and did nothing, while Home walked backwards onto a row the
12373        // caret had left.
12374        let mut d = wrapped_doc("wrap_home_end");
12375        d.caret = 19;
12376        assert_eq!(
12377            d.caret_pos(),
12378            (2, 0),
12379            "the wrap boundary opens the third row"
12380        );
12381        d.move_end(false);
12382        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
12383        d.move_home(false);
12384        assert_eq!(d.caret, 19, "Home left the row the caret was on");
12385    }
12386
12387    #[test]
12388    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
12389        // The row's end is the last offset that is only ever its own: the offset
12390        // past it opens the row below, and aiming there would send a second
12391        // press on to *that* row's end, and a third to the next — End walking
12392        // down the paragraph rather than sitting where it landed.
12393        let mut d = wrapped_doc("wrap_end_twice");
12394        d.caret = 12; // inside "three", on the second row
12395        d.move_end(false);
12396        assert_eq!(
12397            d.caret, 18,
12398            "the end of `three four`, before the space the wrap ate"
12399        );
12400        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
12401        d.move_end(false);
12402        assert_eq!(d.caret, 18, "a second End moved the caret");
12403        d.move_home(false);
12404        assert_eq!(d.caret, 8, "Home takes the row's own start");
12405    }
12406
12407    #[test]
12408    fn vertical_motion_crosses_a_soft_wrap() {
12409        // Down aimed at the row below's column 0, an offset that resolved *up*
12410        // to the row above's end — so it landed on the offset it already had and
12411        // the caret could never leave a paragraph's first row.
12412        let mut d = wrapped_doc("wrap_down");
12413        d.caret = 0;
12414        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
12415            d.move_down(false);
12416            assert_eq!(d.caret, want, "Down stalled");
12417            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
12418        }
12419        d.move_down(false);
12420        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
12421
12422        // ...and back up, one row per press. The goal column is the end of the
12423        // last row, past every other row's width, so each press clamps to the
12424        // row's own last offset rather than to the one that opens the next.
12425        let mut d = wrapped_doc("wrap_up");
12426        d.caret = 39;
12427        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
12428            d.move_up(false);
12429            assert_eq!(d.caret, want, "Up stalled");
12430            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
12431        }
12432    }
12433
12434    #[test]
12435    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
12436        // The kills take the same line Home and End do, so in WYSIWYG they take
12437        // the visual row — and a soft wrap has no newline in it to delete, so
12438        // nothing is joined by reaching the end of one.
12439        let mut d = wrapped_doc("wrap_kill");
12440        d.caret = 19; // the `f` of "five", opening the third row
12441        d.delete_to_line_end();
12442        // The space the wrap ate goes with the row it was drawn on: sparing it
12443        // would leave "four  seven", two spaces where the row had been.
12444        assert_eq!(d.source, "one two three four seven eight");
12445
12446        // Backwards from the row's last caret position — which is *before* that
12447        // space, so this one survives, being on the far side of the caret.
12448        let mut d = wrapped_doc("wrap_kill_back");
12449        d.caret = 27;
12450        d.delete_to_line_start();
12451        assert_eq!(d.source, "one two three four  seven eight");
12452    }
12453
12454    // ── document start / end ────────────────────────────────────────────────
12455
12456    #[test]
12457    fn move_doc_start_and_end_jump_to_the_edges() {
12458        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
12459        assert_eq!(
12460            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
12461            "|hello\nworld\n"
12462        );
12463        assert_eq!(
12464            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
12465            "hello\nworld\n|"
12466        );
12467        // Already at the edge: a no-op.
12468        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
12469        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
12470    }
12471
12472    #[test]
12473    fn move_doc_start_and_end_extend_the_selection() {
12474        assert_eq!(
12475            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
12476                .move_doc_end(true)),
12477            "hello wor[ld\n|]"
12478        );
12479        assert_eq!(
12480            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
12481                .move_doc_start(true)),
12482            "[|hello wor]ld\n"
12483        );
12484    }
12485
12486    #[test]
12487    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
12488        let mut d = doc_with("empty_edges", "");
12489        d.move_doc_end(false);
12490        assert_eq!(d.caret, 0);
12491        d.move_doc_start(false);
12492        assert_eq!(d.caret, 0);
12493    }
12494
12495    // ── arrow collapses an active selection ─────────────────────────────────
12496
12497    #[test]
12498    fn arrow_collapses_selection_to_its_near_edge() {
12499        let mut d = doc_with("collapse", "hello world\n");
12500
12501        // Forward selection (anchor before caret): Right -> end, Left -> start.
12502        d.anchor = Some(2);
12503        d.caret = 7;
12504        d.move_right(false);
12505        assert_eq!((d.caret, d.anchor), (7, None));
12506
12507        d.anchor = Some(2);
12508        d.caret = 7;
12509        d.move_left(false);
12510        assert_eq!((d.caret, d.anchor), (2, None));
12511
12512        // Backward selection (anchor after caret): edges are the same
12513        // regardless of which end the caret started on.
12514        d.anchor = Some(7);
12515        d.caret = 2;
12516        d.move_right(false);
12517        assert_eq!((d.caret, d.anchor), (7, None));
12518
12519        d.anchor = Some(7);
12520        d.caret = 2;
12521        d.move_left(false);
12522        assert_eq!((d.caret, d.anchor), (2, None));
12523    }
12524
12525    #[test]
12526    fn arrow_with_extend_keeps_growing_the_selection() {
12527        let mut d = doc_with("collapse_extend", "hello world\n");
12528        d.anchor = Some(2);
12529        d.caret = 7;
12530        d.move_right(true); // extend: no collapse, caret steps one further
12531        assert_eq!((d.caret, d.anchor), (8, Some(2)));
12532    }
12533
12534    #[test]
12535    fn arrow_without_a_selection_moves_one_character_as_before() {
12536        let mut d = doc_with("no_collapse", "hello\n");
12537        d.caret = 2;
12538        d.move_right(false);
12539        assert_eq!(d.caret, 3);
12540        d.move_left(false);
12541        assert_eq!(d.caret, 2);
12542    }
12543
12544    /// Press Right until it stops, collecting the offsets walked through. Every
12545    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
12546    /// two stops sharing one source offset can't be moved between, so the caret
12547    /// stalls on the first of them and the walk never reaches the rest.
12548    fn walk_right(d: &mut Doc) -> Vec<usize> {
12549        let mut seen = vec![d.caret];
12550        for _ in 0..2000 {
12551            let before = d.caret;
12552            d.move_right(false);
12553            if d.caret == before {
12554                break;
12555            }
12556            seen.push(d.caret);
12557        }
12558        seen
12559    }
12560
12561    #[test]
12562    fn the_caret_crosses_a_soft_break() {
12563        // A newline inside a paragraph is a `soft_break`, which twig gives no
12564        // span of its own — the space it renders as used to borrow the offset of
12565        // the character before it, and a caret can't move without changing
12566        // offset. Right must walk clean off the end of the first line.
12567        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
12568        d.caret = 0;
12569        let seen = walk_right(&mut d);
12570        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
12571    }
12572
12573    #[test]
12574    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
12575        // The paragraph holds one soft break. Folded (the default) it lays out as
12576        // a single reflowed row; Preserve re-lays it as a row per source line.
12577        // The setter must invalidate the cached map for the change to show, and
12578        // again on the way back — so a round trip returns to the folded layout.
12579        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
12580        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
12581        d.build_visual(80);
12582        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
12583
12584        d.set_line_flow(LineFlow::Preserve);
12585        d.build_visual(80);
12586        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
12587
12588        d.set_line_flow(LineFlow::Fold);
12589        d.build_visual(80);
12590        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
12591    }
12592
12593    #[test]
12594    fn the_caret_still_crosses_a_preserved_soft_break() {
12595        // Preserve renders the soft break as a row boundary rather than a space,
12596        // but the caret must still reach every offset — the break's own offset is
12597        // the first row's end stop, so Right walks clean off the end of line one
12598        // onto line two, exactly as it does when the break is folded.
12599        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
12600        d.set_line_flow(LineFlow::Preserve);
12601        d.build_visual(80);
12602        d.caret = 0;
12603        let seen = walk_right(&mut d);
12604        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
12605    }
12606
12607    #[test]
12608    fn the_caret_walks_a_code_block() {
12609        // Every glyph of a code block used to map to the block's start, so the
12610        // whole block was a single offset and the caret couldn't move inside it.
12611        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
12612        let mut d = wysiwyg_doc("code_walk", src);
12613        d.caret = 0;
12614        let seen = walk_right(&mut d);
12615        // The fences are markup: hidden, and no caret stop. The code between
12616        // them is reached a character at a time.
12617        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
12618        for off in code.clone() {
12619            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
12620        }
12621        assert!(seen.contains(&code.end), "no stop after the last line");
12622    }
12623
12624    #[test]
12625    fn the_caret_walks_an_indented_code_block() {
12626        // An indented block's text has the four-space indent stripped, so it
12627        // isn't a verbatim slice and its lines have to be re-found. The caret
12628        // lands on the code, never in the indent.
12629        let src = "    indented\n    code\n";
12630        let mut d = wysiwyg_doc("indent_code_walk", src);
12631        d.caret = 0;
12632        let seen = walk_right(&mut d);
12633        assert!(seen.contains(&src.find("indented").unwrap()));
12634        assert!(seen.contains(&src.find("code").unwrap()));
12635        assert!(
12636            !seen.contains(&0) || seen[0] == 0,
12637            "the caret starts where it was put"
12638        );
12639        // Nothing in the stripped indent is a stop.
12640        for off in [1, 2, 3] {
12641            assert!(!seen.contains(&off), "landed in the indent at {off}");
12642        }
12643    }
12644
12645    #[test]
12646    fn the_caret_leaves_a_tight_heading() {
12647        // "# H" with text directly under it: the heading row's end and the
12648        // separator row's end are the same offset. Right used to find the
12649        // separator's copy, set the caret to where it already was, and stop.
12650        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
12651        d.caret = 2; // the "H"
12652        let seen = walk_right(&mut d);
12653        assert!(
12654            seen.len() > 2,
12655            "Right stalled at the heading's end: {seen:?}"
12656        );
12657        assert!(
12658            seen.contains(&8),
12659            "never reached the end of \"text\": {seen:?}"
12660        );
12661    }
12662
12663    #[test]
12664    fn the_caret_skips_the_gap_between_two_paragraphs() {
12665        // The blank line between two paragraphs is the boundary itself. The
12666        // caret used to be able to sit on it, and typing there landed in the
12667        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
12668        // soft break, so the text visibly snapped back up.
12669        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
12670        d.caret = 1; // the end of "A"
12671        d.move_right(false);
12672        assert_eq!(d.caret, 3, "Right stopped in the gap");
12673        d.insert("x");
12674        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
12675    }
12676
12677    #[test]
12678    fn down_from_a_paragraph_lands_on_the_next_one() {
12679        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
12680        d.caret = 0;
12681        d.move_down(false);
12682        assert_eq!(d.caret, 3, "Down stopped in the gap");
12683    }
12684
12685    #[test]
12686    fn clicking_the_gap_lands_on_real_text() {
12687        // A click can still *reach* the gap — it's drawn, so it's clickable.
12688        // It has to resolve to somewhere the caret can be.
12689        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
12690        d.click(1, 0, false); // the gap row
12691        assert!(
12692            d.caret == 1 || d.caret == 3,
12693            "click left the caret in the gap at {}",
12694            d.caret
12695        );
12696        d.insert("x");
12697        // Either edge of the boundary is a fair place to land; inside it isn't.
12698        assert!(
12699            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
12700            "click in the gap typed into the boundary: {:?}",
12701            d.source
12702        );
12703    }
12704
12705    #[test]
12706    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
12707        // Enter inserts a paragraph break, which leaves a blank line spare on
12708        // either side of a new one. That middle line is a real empty paragraph:
12709        // the caret lands there, and typing makes a paragraph rather than
12710        // extending a neighbour.
12711        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
12712        d.caret = 1;
12713        d.newline();
12714        assert_eq!(d.source, "A\n\n\n\nB\n");
12715        d.build_visual(80);
12716        let (row, _) = d.caret_pos();
12717        assert!(
12718            d.vmap.row_is_navigable(row),
12719            "the caret landed on a gap row"
12720        );
12721        d.insert("x");
12722        assert_eq!(
12723            d.source, "A\n\nx\n\nB\n",
12724            "the new paragraph merged into a neighbour"
12725        );
12726    }
12727
12728    #[test]
12729    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
12730        let mut d = wysiwyg_doc("gap_eof", "A\n");
12731        d.caret = 1;
12732        d.newline();
12733        d.build_visual(80);
12734        let (row, _) = d.caret_pos();
12735        assert!(
12736            d.vmap.row_is_navigable(row),
12737            "the caret landed on a gap row"
12738        );
12739        d.insert("x");
12740        assert!(
12741            d.source.starts_with("A\n\n") && d.source.contains('x'),
12742            "typing at the end merged into A: {:?}",
12743            d.source
12744        );
12745    }
12746
12747    #[test]
12748    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
12749        // A paragraph broken over two source lines is one paragraph. Selecting
12750        // it must not stop at the newline inside it — that newline is markup the
12751        // rich-text view exists to hide.
12752        let src = "one two\nthree four\n\nnext\n";
12753        let mut d = wysiwyg_doc("triple_para", src);
12754        d.select_block_at(2);
12755        assert_eq!(
12756            d.selected_text(),
12757            Some("one two\nthree four"),
12758            "stopped at the soft break"
12759        );
12760    }
12761
12762    #[test]
12763    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
12764        // The reader scrolls down past the caret's row. Nothing moved the
12765        // caret, so the view must stay where it was put — the old code revealed
12766        // the caret every frame, which dragged the view straight back and made
12767        // the document unscrollable past the caret.
12768        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
12769        d.caret = 0;
12770        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
12771        d.scroll = 4; // the wheel
12772        d.follow_caret(0, 3, 9);
12773        assert_eq!(
12774            d.scroll, 4,
12775            "the wheel was overruled by a caret that never moved"
12776        );
12777    }
12778
12779    #[test]
12780    fn moving_the_caret_brings_the_view_back_to_it() {
12781        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
12782        d.caret = 0;
12783        d.follow_caret(0, 3, 9);
12784        d.scroll = 6; // scrolled away
12785        d.move_right(false); // ...and now the caret moves
12786        let (row, _) = d.caret_pos();
12787        d.follow_caret(row, 3, 9);
12788        assert!(
12789            d.scroll <= row && row < d.scroll + 3,
12790            "caret row {row} off screen at scroll {}",
12791            d.scroll
12792        );
12793    }
12794
12795    #[test]
12796    fn scrolling_stops_at_the_last_row() {
12797        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
12798        d.caret = 0;
12799        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
12800        d.scroll = 999; // the wheel, spun hard
12801        d.follow_caret(0, 3, 3);
12802        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
12803    }
12804
12805    #[test]
12806    fn every_cell_of_a_wide_table_is_reachable() {
12807        // A table whose cells are far wider than the surface: the columns are
12808        // cut to fit and the text wraps inside them, so no cell hangs off the
12809        // right edge where the caret can never go.
12810        let src = "| Ingredient | Notes |\n|---|---|\n\
12811                   | flour milled coarse | sift it twice before folding it in |\n";
12812        let mut d = wysiwyg_doc("wide_table_walk", src);
12813        d.build_visual(30);
12814        d.caret = 0;
12815        let seen = walk_right(&mut d);
12816        for word in ["Ingredient", "Notes", "coarse", "folding"] {
12817            let at = src.find(word).unwrap();
12818            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
12819        }
12820    }
12821
12822    // ── view parity ──────────────────────────────────────────────────────────
12823    // `doc_with` pins the source view, so everything above tests a view users
12824    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
12825    // deletion golden cases through *both*, plus the WYSIWYG cases the two
12826    // can't share: where the source carries markup the rendered text is a
12827    // different string, and the views agreeing would itself be the bug.
12828
12829    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
12830
12831    /// Run `action` in both views on one `|`-marked fixture and assert they
12832    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
12833    /// source verbatim, so the two views are looking at the same text and any
12834    /// disagreement is one of them having lost the plot.
12835    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
12836        let (src, caret) = parse_caret(marked);
12837        let run = |view: View, tag: &str| {
12838            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
12839            d.caret = caret;
12840            action(&mut d);
12841            render_caret(&d)
12842        };
12843        let source = run(VIEWS[0].0, VIEWS[0].1);
12844        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
12845        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
12846        source
12847    }
12848
12849    #[test]
12850    fn word_motion_agrees_across_the_views_on_plain_prose() {
12851        let g = both_views;
12852        assert_eq!(
12853            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
12854            "hello |world"
12855        );
12856        assert_eq!(
12857            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
12858            "|hello world"
12859        );
12860        assert_eq!(
12861            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
12862            "hello| world"
12863        );
12864        assert_eq!(
12865            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
12866            "hello world|"
12867        );
12868        assert_eq!(
12869            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
12870            "foo|.bar"
12871        );
12872        assert_eq!(
12873            g("par_ext", "hello |world", |d| d.move_word_right(true)),
12874            "hello [world|]"
12875        );
12876    }
12877
12878    #[test]
12879    fn word_deletion_agrees_across_the_views_on_plain_prose() {
12880        let g = both_views;
12881        assert_eq!(
12882            g("par_db", "hello world|", |d| d.delete_word_back()),
12883            "hello |"
12884        );
12885        assert_eq!(
12886            g("par_df", "hello |world", |d| d.delete_word_forward()),
12887            "hello |"
12888        );
12889        assert_eq!(
12890            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
12891            "|bar baz"
12892        );
12893        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
12894    }
12895
12896    #[test]
12897    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
12898        let g = both_views;
12899        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
12900        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
12901        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
12902        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
12903    }
12904
12905    #[test]
12906    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
12907        // The reproduction: the stop table was built one stop per `char`, so
12908        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
12909        // source view, which steps by grapheme, can't reach and backspace can't
12910        // survive. The two views must land on the same offset.
12911        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
12912        for (view, tag) in VIEWS {
12913            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
12914            d.caret = 1;
12915            d.move_right(false);
12916            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
12917
12918            // ...and the edit that used to sever a joiner off the front of it.
12919            d.backspace();
12920            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
12921            assert_eq!(d.caret, 1);
12922        }
12923    }
12924
12925    #[test]
12926    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
12927        for (view, tag) in VIEWS {
12928            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
12929            d.caret = 0;
12930            d.move_right(false);
12931            assert_eq!(
12932                d.caret,
12933                "e\u{0301}".len(),
12934                "{tag} stopped on the combining mark"
12935            );
12936        }
12937    }
12938
12939    #[test]
12940    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
12941        // The general form: whatever route the caret takes through a document
12942        // full of clusters, it never lands between the codepoints of one — so no
12943        // motion-then-backspace sequence can leave a dangling joiner behind.
12944        use unicode_segmentation::UnicodeSegmentation;
12945
12946        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
12947        let mut d = wysiwyg_doc("cluster_walk", src);
12948        d.caret = 0;
12949        let boundaries: Vec<usize> = src
12950            .grapheme_indices(true)
12951            .map(|(i, _)| i)
12952            .chain(std::iter::once(src.len()))
12953            .collect();
12954        for off in walk_right(&mut d) {
12955            assert!(
12956                boundaries.contains(&off),
12957                "Right stopped at {off}, inside a grapheme cluster"
12958            );
12959        }
12960    }
12961
12962    #[test]
12963    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
12964        // The reproduction: ⌥→ from inside the opening `**` computed its
12965        // boundary over the raw source and landed on byte 8 — inside the
12966        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
12967        // "bold". The caret drew past the bold word and sat inside it.
12968        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
12969        d.caret = 2;
12970        d.move_word_right(false);
12971        assert!(
12972            d.vmap.is_stop(d.caret),
12973            "landed at {}, not a caret stop",
12974            d.caret
12975        );
12976        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
12977        // The rendered row is "a bold c": column 6 is the space just past "bold",
12978        // and now the caret is really there rather than only drawn there.
12979        assert_eq!(d.caret_pos(), (0, 6));
12980
12981        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
12982        d.move_word_left(false);
12983        assert_eq!(d.caret, 4);
12984        assert_eq!(d.caret_pos(), (0, 2));
12985    }
12986
12987    #[test]
12988    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
12989        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
12990        // inside the closing `**`, and left "a ** c\n" — delimiters with no
12991        // opener. Glyph space covers the word alone, which would leave
12992        // "a **** c": markup wrapped around nothing. The word and the styling
12993        // that was only ever the word's go together.
12994        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
12995        d.caret = 10;
12996        d.delete_word_back();
12997        assert_eq!(d.source, "a  c\n");
12998        assert_eq!(d.caret, 2);
12999
13000        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
13001        d.caret = 4; // the "b"
13002        d.delete_word_forward();
13003        assert_eq!(d.source, "a  c\n");
13004    }
13005
13006    #[test]
13007    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
13008        let src = "a ***bold*** c\n";
13009        let mut d = wysiwyg_doc("wys_word_del_nest", src);
13010        d.caret = src.find(" c").unwrap();
13011        d.delete_word_back();
13012        assert_eq!(
13013            d.source, "a  c\n",
13014            "the emph inside the strong empties it too"
13015        );
13016
13017        let src = "a `code` c\n";
13018        let mut d = wysiwyg_doc("wys_word_del_code", src);
13019        d.caret = src.find(" c").unwrap();
13020        d.delete_word_back();
13021        assert_eq!(d.source, "a  c\n");
13022    }
13023
13024    #[test]
13025    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
13026        // Only an *emptied* node goes. Take one word of two and the `**` still
13027        // has a job to do — over the word that's left, with the space the delete
13028        // pushed against the opening delimiter moved out in front of it, or the
13029        // run would be no run at all (`** words**` is literal asterisks — see
13030        // the mark-edge rule on `splice`).
13031        let src = "a **two words** c\n";
13032        let mut d = wysiwyg_doc("wys_word_del_partial", src);
13033        d.caret = src.find(" words").unwrap();
13034        d.delete_word_back();
13035        assert_eq!(d.source, "a  **words** c\n");
13036    }
13037
13038    #[test]
13039    fn source_view_word_motion_still_walks_the_markup() {
13040        // The other half of the decision: in the source view the `**` are
13041        // characters like any other — they're on the screen, so word motion has
13042        // to stop at them and a word-delete has to leave them behind. Only
13043        // WYSIWYG hides them, so only WYSIWYG steps over them.
13044        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
13045        assert_eq!(
13046            g("src_word_motion", "a |**bold** c\n", |d| d
13047                .move_word_right(false)),
13048            "a **bold|** c\n"
13049        );
13050        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
13051        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
13052        assert_eq!(
13053            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
13054            "a **| c\n"
13055        );
13056    }
13057
13058    #[test]
13059    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
13060        // The single invariant both bugs violated: the caret draws and edits at
13061        // the same place only when it's on a stop. `debug_assert_on_a_stop`
13062        // makes the same claim in-place; this pins it from the outside, over a
13063        // document with every kind of thing the map has to be careful about.
13064        // At two widths: the wide one every other test builds at, where no
13065        // fixture folds, and one narrow enough that they all do. A soft wrap is
13066        // where an offset stops being on exactly one row, and testing only the
13067        // width that never wraps is how the caret came to be pinned at the first
13068        // one Down reached.
13069        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
13070                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
13071        // A table of named operations, which is what it looks like.
13072        #[allow(clippy::type_complexity)]
13073        let motions: [(&str, fn(&mut Doc)); 8] = [
13074            ("right", |d| d.move_right(false)),
13075            ("left", |d| d.move_left(false)),
13076            ("word_right", |d| d.move_word_right(false)),
13077            ("word_left", |d| d.move_word_left(false)),
13078            ("down", |d| d.move_down(false)),
13079            ("up", |d| d.move_up(false)),
13080            ("home", |d| d.move_home(false)),
13081            ("end", |d| d.move_end(false)),
13082        ];
13083        for width in [80, 12] {
13084            let mut d = wysiwyg_doc("stop_invariant", src);
13085            d.build_visual(width);
13086            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
13087            assert!(stops.len() > 20, "fixture should have plenty of stops");
13088            for start in stops {
13089                for (name, motion) in &motions {
13090                    d.caret = start;
13091                    d.anchor = None;
13092                    motion(&mut d);
13093                    assert!(
13094                        d.vmap.is_stop(d.caret),
13095                        "{name} from {start} at width {width} landed at {} — not a caret stop",
13096                        d.caret
13097                    );
13098                }
13099            }
13100        }
13101    }
13102
13103    #[test]
13104    fn no_wysiwyg_motion_is_a_dead_end() {
13105        // Down held to the bottom of a document reaches the bottom, and Up held
13106        // to the top reaches the top — from anywhere, at a width that wraps. The
13107        // invariant above says a motion lands somewhere legal; this one says it
13108        // gets somewhere at all, which is what a caret pinned at a wrap boundary
13109        // was quietly failing to do while every assertion around it held.
13110        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
13111                   - item one two three four five\n\nlast\n";
13112        for width in [80, 12] {
13113            let mut d = wysiwyg_doc("no_dead_end", src);
13114            d.build_visual(width);
13115            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
13116            let (first, last) = (stops[0], stops[stops.len() - 1]);
13117            for &start in &stops {
13118                for (name, motion, want) in [
13119                    (
13120                        "down",
13121                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
13122                        last,
13123                    ),
13124                    ("up", |d: &mut Doc| d.move_up(false), first),
13125                ] {
13126                    d.caret = start;
13127                    d.anchor = None;
13128                    d.goal_col = None;
13129                    // Every row, plus the presses the edges take, plus slack.
13130                    for _ in 0..d.vmap.num_rows() + 4 {
13131                        motion(&mut d);
13132                    }
13133                    assert_eq!(
13134                        d.caret, want,
13135                        "{name} held from {start} at width {width} never arrived"
13136                    );
13137                }
13138            }
13139        }
13140    }
13141    // ── display columns ──────────────────────────────────────────────────────
13142    // A `col` is a terminal cell, not a character. The two are the same number
13143    // for the ASCII the fixtures above are written in, which is how they came
13144    // apart in the first place: `你` is one character drawn in two cells, so a
13145    // column counted in characters names a cell the text isn't in — one earlier
13146    // for every wide character to its left.
13147
13148    #[test]
13149    fn a_wide_character_is_two_columns_wide() {
13150        // The reproduction: `你` is one char and two cells, so the caret just
13151        // past it drew at column 1 — inside the character it had already left.
13152        for (view, tag) in VIEWS {
13153            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
13154            d.caret = "你".len();
13155            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
13156            d.caret = "你好".len();
13157            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
13158        }
13159    }
13160
13161    #[test]
13162    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
13163        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
13164        // two-cell — measuring six cells one at a time, but the character they
13165        // spell is drawn in two. Width belongs to the cluster, not the glyph,
13166        // and the frontends measure it the same way.
13167        let family = "👨‍👩‍👧";
13168        for (view, tag) in VIEWS {
13169            let src = format!("a{family}b\n");
13170            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
13171            d.caret = 1 + family.len();
13172            assert_eq!(
13173                d.caret_pos(),
13174                (0, 3),
13175                "{tag}: 'a' is one cell, the family two"
13176            );
13177        }
13178    }
13179
13180    #[test]
13181    fn both_cells_of_a_wide_character_mean_the_character() {
13182        // Clicking the far half of `好` is still clicking `好`: half a character
13183        // is not a place the caret can be, so it comes to rest at the
13184        // character's start — the column it would have been drawn at anyway.
13185        for (view, tag) in VIEWS {
13186            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
13187            for col in [2, 3] {
13188                d.caret = 0;
13189                d.click(0, col, false);
13190                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
13191                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
13192            }
13193            // Past the last cell is the line's end, as it is for ASCII.
13194            d.click(0, 9, false);
13195            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
13196        }
13197    }
13198
13199    #[test]
13200    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
13201        // The mapping is only a mapping if it inverts: the cell the caret is
13202        // drawn in has to be the cell that brings it back to the same offset.
13203        // Over a fixture where a character may be one cell or two, and one
13204        // codepoint or five.
13205        use unicode_segmentation::UnicodeSegmentation;
13206
13207        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
13208
13209        let mut d = doc_in(View::Source, "roundtrip_source", src);
13210        // Every offset the source view's caret can occupy: it steps by grapheme
13211        // cluster, so those are its boundaries.
13212        for (off, _) in src
13213            .grapheme_indices(true)
13214            .chain(std::iter::once((src.len(), "")))
13215        {
13216            d.caret = off;
13217            let (row, col) = d.caret_pos();
13218            d.click(row, col, false);
13219            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
13220        }
13221
13222        // And in WYSIWYG, where the offsets the caret can occupy are the map's
13223        // stops rather than every boundary.
13224        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
13225        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
13226        assert!(stops.len() > 20, "fixture should have plenty of stops");
13227        for off in stops {
13228            d.caret = off;
13229            let (row, col) = d.caret_pos();
13230            d.click(row, col, false);
13231            assert_eq!(
13232                d.caret, off,
13233                "wysiwyg: {off} → ({row}, {col}) → {}",
13234                d.caret
13235            );
13236        }
13237    }
13238
13239    #[test]
13240    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
13241        // Down from under `世` lands under the glyph in that cell, not two
13242        // characters further along the line. The goal is a column, so a line of
13243        // wide characters and a line of ASCII line up the way they're drawn.
13244        //
13245        // The gap differs by view: a bare newline inside a paragraph is a soft
13246        // break, which WYSIWYG draws as a space on a single row. The views share
13247        // a grid only where the source's lines are the renderer's rows too.
13248        for (view, tag) in VIEWS {
13249            let gap = if view == View::Source { "\n" } else { "\n\n" };
13250            let src = format!("你好世{gap}abcdef\n");
13251            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
13252            d.caret = "你好".len();
13253            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
13254            d.move_down(false);
13255            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
13256            assert!(
13257                d.source[d.caret..].starts_with('e'),
13258                "{tag}: landed on the wrong glyph"
13259            );
13260        }
13261    }
13262
13263    #[test]
13264    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
13265        // Down from column 3 onto `你好`, whose characters start at columns 0
13266        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
13267        // between the cells of one character, so the caret rests on it — and on
13268        // its start, which is the only offset there that is a caret stop.
13269        for (view, tag) in VIEWS {
13270            let gap = if view == View::Source { "\n" } else { "\n\n" };
13271            let src = format!("abcdef{gap}你好\n");
13272            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
13273            let line = src.find('你').unwrap();
13274            d.caret = 3;
13275            d.move_down(false);
13276            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
13277            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
13278        }
13279    }
13280
13281    #[test]
13282    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
13283        // The column the cell's text is laid out in is measured in cells, so the
13284        // caret walking that text has to be too — the two agreeing is the whole
13285        // point of the grid staying square.
13286        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
13287        let at = d.source.find("你").unwrap();
13288        d.caret = at;
13289        let (row, col) = d.caret_pos();
13290        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
13291        // cells further along.
13292        assert_eq!(col, 2, "the cell's first character");
13293        d.move_right(false);
13294        assert_eq!(
13295            d.caret_pos(),
13296            (row, 4),
13297            "`好` is drawn past `你`'s two cells"
13298        );
13299        assert_eq!(d.caret, at + "你".len());
13300    }
13301
13302    // ── active inline marks ───────────────────────────────────────────────────
13303
13304    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
13305    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
13306        let (src, caret) = parse_caret(marked);
13307        let mut d = doc_in(view, name, &src);
13308        d.caret = caret;
13309        d.active_inline_marks().iter().collect()
13310    }
13311
13312    /// The marks over the selection `[start, end)`.
13313    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
13314        let mut d = doc_in(view, name, src);
13315        d.anchor = Some(start);
13316        d.caret = end;
13317        d.active_inline_marks().iter().collect()
13318    }
13319
13320    #[test]
13321    fn a_caret_in_a_mark_reports_it() {
13322        for (view, tag) in VIEWS {
13323            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
13324            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
13325            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
13326            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
13327            // Plain text under no mark lights nothing — the toolbar's resting state.
13328            assert_eq!(m("a| **bold** b"), [], "{tag}");
13329            assert!(m("plain t|ext").is_empty(), "{tag}");
13330        }
13331    }
13332
13333    #[test]
13334    fn nested_marks_all_report() {
13335        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
13336        // the ancestor chain is a chain, and every mark on it is in force.
13337        for (view, tag) in VIEWS {
13338            assert_eq!(
13339                marks(
13340                    view,
13341                    &format!("marks_nested_{tag}"),
13342                    "**bold and *bo|th*** end"
13343                ),
13344                [InlineKind::Strong, InlineKind::Emph],
13345                "{tag}"
13346            );
13347        }
13348    }
13349
13350    #[test]
13351    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
13352        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
13353        // the first byte of its text and the byte after its last — both inside
13354        // the mark's span, both places typing lands inside the bold. The offset
13355        // past the closing delimiter is the next text, and reports nothing.
13356        let src = "a **bold** b";
13357        let inner_start = src.find("bold").unwrap(); // 4
13358        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
13359        for (view, tag) in VIEWS {
13360            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
13361            for off in [2, 3, inner_start, inner_end, 9] {
13362                d.caret = off;
13363                assert!(
13364                    d.active_inline_marks().contains(InlineKind::Strong),
13365                    "{tag}: offset {off} is inside the strong span"
13366                );
13367            }
13368            for off in [0, 1, 10, 11, 12] {
13369                d.caret = off;
13370                assert!(
13371                    !d.active_inline_marks().contains(InlineKind::Strong),
13372                    "{tag}: offset {off} is outside the strong run"
13373                );
13374            }
13375        }
13376    }
13377
13378    #[test]
13379    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
13380        // Regression: twig resolves an offset that is one node's end and the
13381        // next one's start to the node that *starts* there, so `**bold**|\n`
13382        // isn't bold. With nothing following there's no tie to break and the
13383        // chain still ended at the mark, which made a trailing `\n` — not the
13384        // text — decide whether the caret after a bold word reported bold. It's
13385        // the offset past the mark either way, and typing there is plain either
13386        // way. A blank document typed into is exactly this shape.
13387        for (view, tag) in VIEWS {
13388            let m = |name: String, marked| marks(view, &name, marked);
13389            assert_eq!(
13390                m(format!("marks_eob_{tag}"), "**bold**|"),
13391                [],
13392                "{tag}: no trailing newline"
13393            );
13394            assert_eq!(
13395                m(format!("marks_eol_{tag}"), "**bold**|\n"),
13396                [],
13397                "{tag}: with one"
13398            );
13399            // And the last offset that *is* in the mark still is.
13400            assert_eq!(
13401                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
13402                [InlineKind::Strong],
13403                "{tag}"
13404            );
13405        }
13406    }
13407
13408    #[test]
13409    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
13410        let src = "a **bold** b";
13411        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
13412        for (view, tag) in VIEWS {
13413            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
13414            // The whole bold word, and a slice of it.
13415            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
13416            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
13417            // Ending exactly at the closing delimiter's start is still all-bold:
13418            // an exclusive end sits *past* the last selected character, so the
13419            // question is asked of the character, not the boundary.
13420            assert_eq!(
13421                m(b, d_ + 2),
13422                [InlineKind::Strong],
13423                "{tag}: through the close"
13424            );
13425            // Half in, half out: Bold lit here would claim a press turns it off.
13426            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
13427            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
13428        }
13429    }
13430
13431    #[test]
13432    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
13433        // Both ends are bold, but the space between them isn't — two runs are two
13434        // nodes, which is exactly what the node id catches and a kind-only
13435        // comparison would not.
13436        let src = "**one** **two**";
13437        for (view, tag) in VIEWS {
13438            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
13439            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
13440        }
13441    }
13442
13443    #[test]
13444    fn marks_read_the_document_as_it_is_edited() {
13445        // The point of asking twig every frame instead of caching: the answer has
13446        // to follow the toggle that changed it.
13447        let mut d = wysiwyg_doc("marks_live", "one two\n");
13448        d.anchor = Some(0);
13449        d.caret = 3;
13450        assert!(d.active_inline_marks().is_empty(), "plain to start");
13451        d.toggle(InlineKind::Strong);
13452        assert_eq!(d.source, "**one** two\n");
13453        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
13454        assert!(d.active_inline_marks().contains(InlineKind::Strong));
13455        d.toggle(InlineKind::Strong);
13456        assert!(d.active_inline_marks().is_empty(), "and off again");
13457    }
13458
13459    #[test]
13460    fn a_link_is_not_an_inline_mark() {
13461        // `link`/`str` are inline nodes, but nothing on the inline toolbar
13462        // toggles them — a set with a "link mark" in it would have no button.
13463        for (view, tag) in VIEWS {
13464            assert_eq!(
13465                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
13466                [],
13467                "{tag}"
13468            );
13469        }
13470    }
13471
13472    // ── blank documents ───────────────────────────────────────────────────────
13473
13474    #[test]
13475    fn a_blank_document_is_untitled_empty_and_markdown() {
13476        let mut d = Doc::blank().unwrap();
13477        assert!(d.is_untitled());
13478        assert_eq!(d.path, PathBuf::new());
13479        assert_eq!(
13480            d.file_name(),
13481            "untitled",
13482            "the header has to show something"
13483        );
13484        assert_eq!(d.format_name(), "markdown");
13485        assert_eq!(d.source, "");
13486        assert!(!d.dirty, "nothing typed yet is nothing to lose");
13487        assert_eq!(d.disk_state(), DiskState::Untitled);
13488        // And it's a document you can be in: the default view renders it.
13489        d.build_visual(80);
13490        assert_eq!(d.caret, 0);
13491    }
13492
13493    #[test]
13494    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
13495        let mut d = Doc::blank().unwrap();
13496        d.insert("hello");
13497        assert!(d.dirty);
13498        d.save();
13499        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
13500        assert!(d.dirty, "it must not come away believing it saved");
13501        assert!(d.is_untitled(), "and it still has no file");
13502    }
13503
13504    #[test]
13505    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
13506        let p = temp_path("blank_save_as");
13507        let mut d = Doc::blank().unwrap();
13508        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
13509        // be kept literal (`\#`); this test is about save-as, not escaping (which
13510        // has its own test), so it types nothing that escaping would touch.
13511        d.insert("hi");
13512        d.save_as(p.clone());
13513        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
13514        assert!(!d.is_untitled());
13515        assert!(!d.dirty);
13516        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
13517        assert_eq!(
13518            d.disk_state(),
13519            DiskState::Unchanged,
13520            "the watermark is stamped"
13521        );
13522        // And ⌘S is a plain save from here on.
13523        d.insert("!");
13524        d.save();
13525        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
13526        let _ = std::fs::remove_file(&p);
13527    }
13528
13529    // ── a file that isn't there yet ───────────────────────────────────────────
13530
13531    /// A unique path in the temp dir with the given extension, guaranteed not to
13532    /// exist — what `leaf notes.md` is handed when the file has never been made.
13533    fn missing_path(name: &str, ext: &str) -> PathBuf {
13534        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13535        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13536        let mut p = std::env::temp_dir();
13537        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
13538        let _ = std::fs::remove_file(&p);
13539        p
13540    }
13541
13542    #[test]
13543    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
13544        let p = missing_path("named", "md");
13545        let mut d = Doc::open_or_create(p.clone()).unwrap();
13546
13547        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
13548        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
13549        assert!(
13550            !d.is_untitled(),
13551            "it has the name the user asked for — ^S must not detour to Save As"
13552        );
13553        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
13554        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
13555        assert!(!p.exists(), "and opening it wrote nothing");
13556        // And it's a document you can be in.
13557        d.build_visual(80);
13558        assert_eq!(d.caret, 0);
13559    }
13560
13561    #[test]
13562    fn a_new_file_is_created_by_its_first_save() {
13563        let p = missing_path("first_save", "md");
13564        let mut d = Doc::open_or_create(p.clone()).unwrap();
13565        d.insert("hello\n");
13566        assert!(d.dirty);
13567        d.save();
13568
13569        assert_eq!(
13570            std::fs::read_to_string(&p).unwrap(),
13571            "hello\n",
13572            "a plain ^S wrote it — no Save As, no name to invent"
13573        );
13574        assert!(!d.dirty);
13575        assert_eq!(d.disk_state(), DiskState::Unchanged);
13576        let _ = std::fs::remove_file(&p);
13577    }
13578
13579    #[test]
13580    fn a_new_file_takes_its_format_from_the_extension() {
13581        // The one thing `blank` can't do: with no name it has to assume Markdown,
13582        // and typing djot into a Markdown parse is the wrong buffer.
13583        let dj = missing_path("format", "dj");
13584        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
13585        let md = missing_path("format", "md");
13586        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
13587    }
13588
13589    #[test]
13590    fn a_new_file_reports_itself_missing_until_it_is_saved() {
13591        // Not `Untitled` — that's the answer for a document with no path, and it
13592        // would tell a frontend there is nothing a save could collide with. Here
13593        // there is a path, and the file simply isn't at it yet.
13594        let p = missing_path("disk_state", "md");
13595        let mut d = Doc::open_or_create(p.clone()).unwrap();
13596        assert_eq!(d.disk_state(), DiskState::Missing);
13597
13598        // Somebody else creates it while the buffer is open: that's an overwrite
13599        // the frontend has to be able to prompt about, exactly as for an opened
13600        // file. Their bytes, not ours, so `Changed`.
13601        std::fs::write(&p, "theirs\n").unwrap();
13602        assert_eq!(d.disk_state(), DiskState::Changed);
13603
13604        // Saving makes the file ours and re-stamps the watermark.
13605        d.insert("ours\n");
13606        d.save();
13607        assert_eq!(d.disk_state(), DiskState::Unchanged);
13608        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
13609        let _ = std::fs::remove_file(&p);
13610    }
13611
13612    #[test]
13613    fn open_or_create_still_opens_a_file_that_is_there() {
13614        let d = doc_with("open_or_create_existing", "body\n");
13615        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
13616        assert_eq!(reopened.source, "body\n");
13617        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
13618    }
13619
13620    #[test]
13621    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
13622        // A mistyped flag or a stray argument must not become a buffer promising
13623        // to save somewhere — the same refusal `open` gives a real file.
13624        let mut p = std::env::temp_dir();
13625        p.push("leaf_test_new_bad_ext.wat");
13626        assert!(Doc::open_or_create(p).is_err());
13627        let mut none = std::env::temp_dir();
13628        none.push("leaf_test_new_no_ext");
13629        assert!(Doc::open_or_create(none).is_err());
13630    }
13631
13632    #[test]
13633    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
13634        // Opening reads nothing, so there is nothing to fail on yet; the write is
13635        // where it fails, and it says so rather than claiming a save.
13636        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
13637        let mut d = Doc::open_or_create(p).unwrap();
13638        d.insert("x");
13639        d.save();
13640        assert!(
13641            d.status.as_deref().unwrap().starts_with("save failed:"),
13642            "got {:?}",
13643            d.status
13644        );
13645        assert!(d.dirty, "it must not come away believing it saved");
13646    }
13647
13648    // ── save as ───────────────────────────────────────────────────────────────
13649
13650    /// A unique path in the temp dir that no fixture wrote — a Save As target.
13651    fn temp_path(name: &str) -> PathBuf {
13652        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13653        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13654        let mut p = std::env::temp_dir();
13655        p.push(format!("leaf_test_target_{name}_{seq}.md"));
13656        let _ = std::fs::remove_file(&p);
13657        p
13658    }
13659
13660    #[test]
13661    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
13662        let mut d = doc_with("save_as_move", "original\n");
13663        let old = d.path.clone();
13664        let new = temp_path("save_as_move");
13665        d.insert("edited: ");
13666        d.save_as(new.clone());
13667
13668        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
13669        assert_eq!(
13670            std::fs::read_to_string(&old).unwrap(),
13671            "original\n",
13672            "Save As doesn't touch the file it came from"
13673        );
13674        assert_eq!(d.path, new, "the document moved");
13675        assert!(!d.dirty);
13676        assert_eq!(
13677            d.status.as_deref(),
13678            Some(&*format!("saved {}", d.file_name()))
13679        );
13680
13681        // Every later save follows it, which is the whole difference from a copy.
13682        d.caret = 0;
13683        d.insert("re-");
13684        d.save();
13685        assert_eq!(
13686            std::fs::read_to_string(&new).unwrap(),
13687            "re-edited: original\n"
13688        );
13689        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
13690        let _ = std::fs::remove_file(&new);
13691    }
13692
13693    #[test]
13694    fn save_as_overwrites_an_existing_target() {
13695        // The picker already asked; asking again down here is the same question
13696        // twice, and the second one has no way to be answered.
13697        let new = temp_path("save_as_over");
13698        std::fs::write(&new, "theirs\n").unwrap();
13699        let mut d = doc_with("save_as_over", "ours\n");
13700        d.save_as(new.clone());
13701        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
13702        let _ = std::fs::remove_file(&new);
13703    }
13704
13705    #[test]
13706    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
13707        let mut d = doc_with("save_as_fail", "body\n");
13708        let old = d.path.clone();
13709        d.insert("x");
13710        // A directory that doesn't exist: the write can't land.
13711        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
13712        d.save_as(bad);
13713
13714        assert_eq!(
13715            d.path, old,
13716            "the document must not move to a file that isn't there"
13717        );
13718        assert!(d.dirty, "and must not believe it saved");
13719        assert!(
13720            d.status.as_deref().unwrap().starts_with("save failed:"),
13721            "the same failure a plain save reports, got {:?}",
13722            d.status
13723        );
13724        // The original is still the document's file, and still saveable.
13725        d.save();
13726        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
13727        assert!(!d.dirty);
13728    }
13729
13730    #[test]
13731    fn save_as_renames_without_reparsing_the_format() {
13732        // `.dj` on the name doesn't make the buffer djot: it was parsed as
13733        // Markdown and still is, and saying otherwise would be a conversion the
13734        // user never asked for (and an undo history thrown away to do it).
13735        let mut d = doc_with("save_as_format", "**b**\n");
13736        let mut new = temp_path("save_as_format");
13737        new.set_extension("dj");
13738        d.save_as(new.clone());
13739        assert_eq!(d.format_name(), "markdown");
13740        let _ = std::fs::remove_file(&new);
13741    }
13742
13743    // ── external change / reload ──────────────────────────────────────────────
13744
13745    #[test]
13746    fn an_untouched_file_reports_unchanged() {
13747        let mut d = doc_with("disk_clean", "body\n");
13748        assert_eq!(d.disk_state(), DiskState::Unchanged);
13749        // Editing the buffer is not editing the file.
13750        d.insert("x");
13751        assert_eq!(d.disk_state(), DiskState::Unchanged);
13752        assert!(d.dirty);
13753        // Saving re-stamps the watermark rather than reporting our own bytes back.
13754        d.save();
13755        assert_eq!(d.disk_state(), DiskState::Unchanged);
13756    }
13757
13758    #[test]
13759    fn a_file_written_underneath_reports_changed() {
13760        let mut d = doc_with("disk_changed", "body\n");
13761        std::fs::write(&d.path, "someone else\n").unwrap();
13762        assert_eq!(d.disk_state(), DiskState::Changed);
13763        // Dirty *and* changed is the clobber: both halves are readable, and
13764        // leaf-core takes neither side.
13765        d.insert("x");
13766        assert!(d.dirty && d.disk_state() == DiskState::Changed);
13767        // Saving anyway is allowed — the frontend asked, or chose not to.
13768        d.save();
13769        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
13770        assert_eq!(d.disk_state(), DiskState::Unchanged);
13771    }
13772
13773    #[test]
13774    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
13775        // The hash is what makes this honest: the file was written (a fresh
13776        // mtime), and nothing about the document is stale.
13777        let d = doc_with("disk_same_bytes", "body\n");
13778        std::fs::write(&d.path, "body\n").unwrap();
13779        assert_eq!(d.disk_state(), DiskState::Unchanged);
13780    }
13781
13782    #[test]
13783    fn a_deleted_file_reports_missing() {
13784        let mut d = doc_with("disk_missing", "body\n");
13785        std::fs::remove_file(&d.path).unwrap();
13786        assert_eq!(d.disk_state(), DiskState::Missing);
13787        // A save recreates it, and the document is whole again.
13788        d.save();
13789        assert_eq!(d.disk_state(), DiskState::Unchanged);
13790        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
13791    }
13792
13793    #[test]
13794    fn reload_replaces_the_document_with_the_file() {
13795        for (view, tag) in VIEWS {
13796            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
13797            d.insert("edited ");
13798            assert!(d.dirty);
13799            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
13800            d.reload();
13801
13802            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
13803            assert!(!d.dirty, "{tag}: the file is what we have");
13804            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
13805            assert_eq!(
13806                d.status.as_deref(),
13807                Some(&*format!("reloaded {}", d.file_name()))
13808            );
13809            // The reloaded tree is live, not the old parse.
13810            d.caret = d.source.find("three").unwrap();
13811            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
13812        }
13813    }
13814
13815    #[test]
13816    fn reload_clamps_the_caret_and_drops_the_selection() {
13817        let mut d = doc_with("reload_caret", "a long first line\n");
13818        d.caret = 12;
13819        d.anchor = Some(4);
13820        std::fs::write(&d.path, "short\n").unwrap();
13821        d.reload();
13822        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
13823        assert_eq!(
13824            d.anchor, None,
13825            "a selection over bytes that changed is a lie"
13826        );
13827        assert!(d.selection().is_none());
13828
13829        // A caret the file still has room for stays put.
13830        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
13831        d.caret = 2;
13832        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
13833        d.reload();
13834        assert_eq!(d.caret, 2);
13835    }
13836
13837    /// A silent reload is something that happened *to* a reader — a formatter,
13838    /// a `git checkout` — so it has to be undoable like anything else that
13839    /// changes the document, and undoable as one step rather than as however
13840    /// many the file happens to differ by.
13841    #[test]
13842    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
13843        let mut d = doc_with("reload_undo", "body\n");
13844        d.insert("x");
13845        assert_eq!(d.source, "xbody\n");
13846        std::fs::write(&d.path, "replaced\n").unwrap();
13847        d.reload();
13848        assert_eq!(d.source, "replaced\n");
13849        assert!(!d.dirty, "a reload lands clean");
13850
13851        // One ^Z takes the whole swap off, and hands back the unsaved work it
13852        // replaced — which is unsaved again, because the file no longer says it.
13853        d.undo();
13854        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
13855        assert!(d.dirty, "and what it comes back to is unsaved");
13856        // …and the history under it is still there.
13857        d.undo();
13858        assert_eq!(
13859            d.source, "body\n",
13860            "the typing before the reload undoes too"
13861        );
13862        // Redo walks back up through the reload.
13863        d.redo();
13864        d.redo();
13865        assert_eq!(d.source, "replaced\n");
13866    }
13867
13868    /// A file rewritten with the bytes it already had is not an edit, so it
13869    /// must not leave an undo step behind for something nobody did.
13870    #[test]
13871    fn reloading_identical_bytes_pushes_no_undo_step() {
13872        let mut d = doc_with("reload_same", "body\n");
13873        d.insert("x");
13874        std::fs::write(&d.path, "xbody\n").unwrap();
13875        d.reload();
13876        assert_eq!(d.source, "xbody\n");
13877        assert!(!d.dirty, "the file now says what the buffer does");
13878        d.undo();
13879        assert_eq!(
13880            d.source, "body\n",
13881            "one step back is the typing, not a no-op"
13882        );
13883    }
13884
13885    #[test]
13886    fn a_reload_that_cant_read_leaves_the_document_alone() {
13887        let mut d = doc_with("reload_gone", "body\n");
13888        d.insert("x");
13889        std::fs::remove_file(&d.path).unwrap();
13890        d.reload();
13891        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
13892        assert!(d.dirty);
13893        assert!(
13894            d.status.as_deref().unwrap().starts_with("reload failed:"),
13895            "{:?}",
13896            d.status
13897        );
13898
13899        // And an untitled document has nothing to reload from.
13900        let mut d = Doc::blank().unwrap();
13901        d.insert("typed");
13902        d.reload();
13903        assert_eq!(d.source, "typed");
13904        assert_eq!(d.status.as_deref(), Some("no file to reload"));
13905    }
13906
13907    #[test]
13908    fn a_read_only_document_refuses_every_door() {
13909        let mut d = doc_with("readonly", "one two three\n");
13910        d.insert("x");
13911        assert!(d.dirty, "writable first, so the undo step exists");
13912        d.set_read_only(true);
13913        let before = d.source.clone();
13914        d.insert("y");
13915        d.backspace();
13916        d.undo();
13917        d.redo();
13918        assert_eq!(d.source, before, "no door moved a byte");
13919        d.set_read_only(false);
13920        d.undo();
13921        assert_ne!(d.source, before, "off again, the same doors work");
13922    }
13923
13924    /// The doors that go to twig's own verbs rather than through the splice.
13925    /// Typed text in the rendered view under the default markup mode is the
13926    /// everyday one — it is what a keystroke in leaf-web or the Apple views
13927    /// becomes — and it walked straight past the gate.
13928    #[test]
13929    fn a_read_only_document_refuses_the_doors_around_the_splice() {
13930        let mut d = wysiwyg_doc(
13931            "readonly-doors",
13932            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
13933        );
13934        d.set_markup_mode(MarkupMode::None);
13935        d.set_read_only(true);
13936        let before = d.source.clone();
13937        d.place_caret(3, false);
13938        d.insert("y");
13939        d.insert_link("https://example.com");
13940        d.insert_image("a.png", "alt");
13941        d.insert_thematic_break();
13942        d.insert_footnote();
13943        d.place_caret(0, false);
13944        d.place_caret(3, true);
13945        d.toggle(InlineKind::Strong);
13946        d.toggle_heading(2);
13947        d.set_block(BlockKind::Paragraph);
13948        d.toggle_list(false);
13949        d.toggle_blockquote();
13950        d.toggle_task_item();
13951        d.newline();
13952        d.indent();
13953        d.set_code_language("rust");
13954        let in_cell = d.source.find("| c").unwrap() + 2;
13955        d.place_caret(in_cell, false);
13956        assert!(d.caret_in_table(), "the caret is in the grid");
13957        assert!(!d.cell_line_break(), "the cell break reports the refusal");
13958        assert_eq!(d.source, before, "no door moved a byte");
13959        assert!(!d.dirty, "nothing to save");
13960        d.set_read_only(false);
13961        d.place_caret(3, false);
13962        d.insert("y");
13963        assert_ne!(d.source, before, "off again, the same doors work");
13964    }
13965
13966    #[test]
13967    fn a_selection_quote_carries_its_context_on_char_boundaries() {
13968        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
13969        let start = d.source.find("exact").unwrap();
13970        d.place_caret(start, false);
13971        d.place_caret(start + "exact".len(), true);
13972        let q = d.selection_quote(3).unwrap();
13973        assert_eq!(q.exact, "exact");
13974        assert_eq!(
13975            q.prefix, "你好 ",
13976            "chars, not bytes — the multibyte pair counts as two"
13977        );
13978        assert_eq!(q.suffix, " 世界");
13979        assert_eq!(&d.source[q.start..q.end], "exact");
13980        // At the edges the context clips rather than erring.
13981        d.place_caret(0, false);
13982        d.place_caret(6, true);
13983        let q = d.selection_quote(40).unwrap();
13984        assert_eq!(q.prefix, "");
13985        assert_eq!(q.exact, "before");
13986        // No selection is no quote.
13987        d.place_caret(0, false);
13988        assert!(d.selection_quote(3).is_none());
13989    }
13990
13991    #[test]
13992    fn highlights_are_kept_sorted_and_answer_point_queries() {
13993        let mut d = doc_with("hl", "one two three\n");
13994        d.set_highlights(vec![
13995            Highlight {
13996                start: 8,
13997                end: 13,
13998                id: "b".into(),
13999                color: None,
14000                marker: None,
14001            },
14002            Highlight {
14003                start: 0,
14004                end: 3,
14005                id: "a".into(),
14006                color: Some("#ffe066".into()),
14007                marker: None,
14008            },
14009            Highlight {
14010                start: 5,
14011                end: 5,
14012                id: "empty".into(),
14013                color: None,
14014                marker: None,
14015            },
14016        ]);
14017        assert_eq!(
14018            d.highlights()
14019                .iter()
14020                .map(|h| h.id.as_str())
14021                .collect::<Vec<_>>(),
14022            ["a", "b"],
14023            "sorted by start, the empty range dropped"
14024        );
14025        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
14026        assert_eq!(d.highlight_at(3), None, "end is exclusive");
14027        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
14028        d.set_highlights(Vec::new());
14029        assert!(d.highlights().is_empty(), "a replace is a replace");
14030    }
14031
14032    /// `Highlight::covering` and the cursor over it are what both painters ask
14033    /// per glyph, so they have to answer the same as the scan they replaced —
14034    /// including in the gaps, which is where most glyphs are.
14035    #[test]
14036    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
14037        let hl = |start: usize, end: usize, id: &str| Highlight {
14038            start,
14039            end,
14040            id: id.into(),
14041            color: None,
14042            marker: None,
14043        };
14044        // Disjoint, as search hits are: in a range, in a gap, and past the end.
14045        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
14046        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
14047        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
14048        assert_eq!(
14049            Highlight::covering(&hits, 105),
14050            None,
14051            "a gap covers nothing"
14052        );
14053        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
14054        assert_eq!(Highlight::covering(&hits, 9_999), None);
14055        assert_eq!(Highlight::covering(&[], 0), None);
14056
14057        // Nested: first by start, so a hit inside an annotation still resolves
14058        // to the annotation — and the range that stops short doesn't mask it.
14059        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
14060        assert_eq!(
14061            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
14062            Some("outer")
14063        );
14064        assert_eq!(
14065            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
14066            Some("outer")
14067        );
14068    }
14069
14070    /// The cursor is an optimisation, so the only thing worth asserting is that
14071    /// it is not also a change of answer — at every offset, over a list with a
14072    /// nest in it, walked forwards and then backwards.
14073    #[test]
14074    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
14075        let hl = |start: usize, end: usize, id: &str| Highlight {
14076            start,
14077            end,
14078            id: id.into(),
14079            color: None,
14080            marker: None,
14081        };
14082        let mut list = vec![
14083            hl(0, 20, "outer"),
14084            hl(5, 10, "inner"),
14085            hl(30, 33, "hit"),
14086            hl(40, 43, "hit"),
14087        ];
14088        list.sort_by_key(|h| (h.start, h.end));
14089
14090        let mut cursor = HighlightCursor::new(&list);
14091        for offset in 0..50 {
14092            assert_eq!(
14093                cursor.at(offset).map(|h| h.id.as_str()),
14094                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
14095                "cursor disagrees at {offset}"
14096            );
14097        }
14098        // Backwards: the cursor re-seats rather than answering from where it
14099        // had got to, so a painter that revisits a row is still told the truth.
14100        for offset in (0..50).rev() {
14101            assert_eq!(
14102                cursor.at(offset).map(|h| h.id.as_str()),
14103                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
14104                "cursor disagrees walking back at {offset}"
14105            );
14106        }
14107    }
14108}