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::counts::{self, TextCounts};
42use crate::html;
43use crate::source::{self, SourceMap};
44use crate::style::{Align, FontFace, FontSize, LineHeight, MarkColor, TextColor};
45use crate::wysiwyg::{self, MediaKind, MediaStop, VisualMap};
46
47/// Which view the body shows.
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
49pub enum View {
50    /// The raw document with a caret in source bytes.
51    Source,
52    /// Markup resolved to real styles, caret riding the rendered glyphs.
53    Wysiwyg,
54}
55
56/// How much of the source markup the WYSIWYG view exposes — a per-editor
57/// preference, orthogonal to [`View`]. Named for markup rather than for Markdown
58/// because leaf is grammar-agnostic: twig hands it Djot, HTML and XML on the same
59/// terms, and every rung below is about *delimiters*, whatever grammar spells
60/// them. The examples are Markdown only because that is what most documents are.
61///
62/// A single ladder over two underlying axes, because only three of their four
63/// combinations are coherent:
64///
65/// | | authoring off | authoring on |
66/// |---|---|---|
67/// | delimiters hidden | [`None`](Self::None) | [`Shortcuts`](Self::Shortcuts) |
68/// | caret line revealed | *incoherent* | [`Full`](Self::Full) |
69///
70/// The empty quadrant would show delimiters on the caret's line and then escape
71/// the ones you type — a surface that displays a syntax it refuses to accept.
72/// Someone who wants to read raw markup without authoring it has
73/// [`View::Source`], which is the better tool for it.
74///
75/// The two axes are read separately by the code that cares — see
76/// [`reveals_caret_line`](Self::reveals_caret_line) and
77/// [`authors`](Self::authors) — so neither behaviour has to know it's spelled
78/// as a ladder.
79#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
80pub enum MarkupMode {
81    /// Delimiters stay hidden even on the caret's line, and typed syntax stays
82    /// literal — twig escapes anything that would open markup, so formatting
83    /// comes from commands (⌘b, the toolbar) instead of from spelling. The clean
84    /// reading surface for people who don't write markup by hand; the default,
85    /// and what Diaryx ships.
86    #[default]
87    None,
88    /// Delimiters stay hidden, but typing them authors real markup: `*x*`
89    /// becomes italic and the asterisks disappear into the styling
90    /// (Typora/Bear-shaped). For someone who knows the syntax but wants the
91    /// clean surface back once it has been applied.
92    Shortcuts,
93    /// The caret's line shows its raw markup while every other line renders
94    /// resolved (Obsidian live-preview-shaped), and typed syntax authors markup
95    /// — for people fluent in the document's grammar who want to see and edit
96    /// the delimiters they type.
97    Full,
98}
99
100impl MarkupMode {
101    /// Whether the rich view shows raw delimiters on the line holding the caret.
102    /// The rendering axis — read by [`Doc::reveal_line`] and threaded into the
103    /// WYSIWYG builder.
104    pub fn reveals_caret_line(self) -> bool {
105        matches!(self, MarkupMode::Full)
106    }
107
108    /// Whether typed markup characters author real formatting. The editing axis
109    /// — read by [`Doc::insert`], which escapes typed syntax when this is false.
110    pub fn authors(self) -> bool {
111        !matches!(self, MarkupMode::None)
112    }
113}
114
115/// How the WYSIWYG view treats a *soft break* — a bare newline inside a
116/// paragraph. An axis of its own, orthogonal to [`MarkupMode`] (which governs
117/// inline-markup delimiters) and to [`View`]: any reveal preference pairs with
118/// either flow. The renderer consults it when it lays a block's inline content
119/// into visual rows.
120#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
121pub enum LineFlow {
122    /// A soft break folds into a space and the paragraph reflows to the
123    /// viewport width — flowing prose, where the source's line wrapping is
124    /// insignificant. The default, and what Diaryx ships.
125    #[default]
126    Fold,
127    /// A soft break renders as a line break exactly where it was written, so
128    /// the author's source line structure shows on screen unchanged — the mode
129    /// for people who lay out their prose deliberately (one sentence or clause
130    /// per line, semantic line breaks). The break is still a soft break in the
131    /// source; only its rendering changes.
132    Preserve,
133}
134
135/// What the file behind a document looks like right now, against the bytes leaf
136/// last read from it or wrote to it — the question a frontend asks before it
137/// saves (a `Changed` file plus a `dirty` document is an overwrite about to
138/// happen) or when its window regains focus. See [`Doc::disk_state`].
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum DiskState {
141    /// The file holds exactly the bytes leaf last read or wrote.
142    Unchanged,
143    /// Someone else wrote the file since. Saving overwrites their work; see
144    /// [`Doc::reload`] for the other direction.
145    Changed,
146    /// The file is gone — deleted or renamed away. A save recreates it.
147    Missing,
148    /// There is a path, but the file couldn't be read (permissions, a directory
149    /// in the way): leaf can't tell, and won't guess.
150    Unreadable,
151    /// No file behind this document yet — see [`Doc::blank`]. Nothing can have
152    /// changed under a document that was never on disk.
153    Untitled,
154}
155
156/// The inline marks in force at a point in the document — what a toolbar
157/// lights up. A `Copy` bitset rather than a `HashSet`, because
158/// [`Doc::active_inline_marks`] is called on every frame that draws a toolbar
159/// and a set that allocates to answer "is Bold on?" is a set that shouldn't.
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
161pub struct InlineMarks(u8);
162
163impl InlineMarks {
164    /// Every kind, in the order [`InlineMarks::iter`] yields them.
165    const ALL: [InlineKind; 8] = [
166        InlineKind::Strong,
167        InlineKind::Emph,
168        InlineKind::Verbatim,
169        InlineKind::Mark,
170        InlineKind::Superscript,
171        InlineKind::Subscript,
172        InlineKind::Insert,
173        InlineKind::Delete,
174    ];
175
176    pub const fn empty() -> Self {
177        InlineMarks(0)
178    }
179
180    /// Private: the set is an *answer*, and adding a mark to it doesn't mark
181    /// anything ([`Doc::toggle`] does that). `FromIterator` is the way in.
182    fn insert(&mut self, kind: InlineKind) {
183        self.0 |= Self::bit(kind);
184    }
185
186    /// Flip `kind` in the set — the sticky-marks toggle at a collapsed caret.
187    fn flip(&mut self, kind: InlineKind) {
188        self.0 ^= Self::bit(kind);
189    }
190
191    /// The symmetric difference: which marks differ between the two sets. Used
192    /// to resolve the marks already in force at the caret against the pending
193    /// delta — a bit set in the delta flips the base mark for the next keystroke.
194    fn xor(self, other: InlineMarks) -> InlineMarks {
195        InlineMarks(self.0 ^ other.0)
196    }
197
198    /// Whether `kind` is in force — the toolbar's "is Bold active?".
199    pub fn contains(self, kind: InlineKind) -> bool {
200        self.0 & Self::bit(kind) != 0
201    }
202
203    pub fn is_empty(self) -> bool {
204        self.0 == 0
205    }
206
207    /// The marks in force, for a frontend that renders whatever is on rather
208    /// than asking after a fixed list.
209    pub fn iter(self) -> impl Iterator<Item = InlineKind> {
210        Self::ALL.into_iter().filter(move |&k| self.contains(k))
211    }
212
213    fn bit(kind: InlineKind) -> u8 {
214        1 << match kind {
215            InlineKind::Strong => 0,
216            InlineKind::Emph => 1,
217            InlineKind::Verbatim => 2,
218            InlineKind::Mark => 3,
219            InlineKind::Superscript => 4,
220            InlineKind::Subscript => 5,
221            InlineKind::Insert => 6,
222            InlineKind::Delete => 7,
223        }
224    }
225}
226
227impl FromIterator<InlineKind> for InlineMarks {
228    fn from_iter<I: IntoIterator<Item = InlineKind>>(iter: I) -> Self {
229        let mut m = InlineMarks::empty();
230        for k in iter {
231            m.insert(k);
232        }
233        m
234    }
235}
236
237/// What kind of edit produced an undo group. Same-kind edits in a row coalesce
238/// into one undo step (a run of typed characters undoes together); `Other` never
239/// coalesces, so a paste, format toggle, or block change is always its own step.
240#[derive(Clone, Copy, PartialEq, Eq)]
241enum EditKind {
242    Insert,
243    Delete,
244    /// One step of an IME composition — see [`Doc::edit_composing`]. Its own kind
245    /// rather than `Insert`'s because a composition is not typing: each step
246    /// *replaces* the last (`か` → `かん` → `感`), so the run has to coalesce even
247    /// though no two steps insert the same bytes, and it must not fold into the
248    /// typed characters on either side of it.
249    Compose,
250    Other,
251}
252
253/// Which side of the caret a delete looks for an in-cell `<br>` break to swallow
254/// whole — see [`Doc::cell_break_at`]. `Backward` is Backspace (a break ending at
255/// the caret), `Forward` is Delete (one starting at it).
256#[derive(Clone, Copy)]
257enum BreakEdge {
258    Backward,
259    Forward,
260}
261
262/// A re-spelling of one inline mark run, held ready in case the edit about to
263/// happen breaks it — see [`Doc::mark_edge_fix`] and [`Doc::repair_mark_edges`].
264/// Every offset in it is in the coordinates the document will have *after* the
265/// plain edit, since that is when it may be applied.
266struct MarkEdgeFix {
267    /// The run's kind, and an offset inside what was its content: together they
268    /// answer "did the plain edit actually break this mark?" — the question that
269    /// decides whether any of this is applied at all.
270    kind: InlineKind,
271    probe: usize,
272    /// The byte range to re-spell (the run's delimiters included) and its new
273    /// spelling, with the edge whitespace moved outside the delimiters.
274    start: usize,
275    end: usize,
276    text: String,
277    /// Where the caret belongs afterwards — the same place on screen it would
278    /// have had, which is now on the other side of a delimiter.
279    caret: usize,
280    /// The marks in force for text typed at that caret. The caret can land
281    /// outside a run it was inside, and the marks have to survive the move or
282    /// the toolbar goes dark mid-word.
283    want: InlineMarks,
284}
285
286/// The caret and selection at one moment — the part of a history step twig's
287/// `Change` cannot carry, because the caret is leaf's state and twig only knows
288/// about bytes. leaf serializes it into the opaque per-state blob twig now
289/// stores in its own undo history (see `record_caret`), so undo and redo hand
290/// back the caret that matches the source they restore.
291#[derive(Clone, Copy)]
292struct CaretState {
293    caret: usize,
294    anchor: Option<usize>,
295}
296
297impl CaretState {
298    /// Pack into the fixed 17-byte blob leaf hands twig: the caret as a u64,
299    /// then an anchor-present flag and the anchor. twig copies these bytes and
300    /// never reads them.
301    fn to_blob(self) -> [u8; 17] {
302        let mut b = [0u8; 17];
303        b[..8].copy_from_slice(&(self.caret as u64).to_le_bytes());
304        if let Some(a) = self.anchor {
305            b[8] = 1;
306            b[9..].copy_from_slice(&(a as u64).to_le_bytes());
307        }
308        b
309    }
310
311    /// Recover a state from twig's blob, or `None` when it is empty or the wrong
312    /// length — a state twig restored that never had a caret set on it, which
313    /// leaves the caller to fall back to the edit site.
314    fn from_blob(b: &[u8]) -> Option<Self> {
315        let b: &[u8; 17] = b.try_into().ok()?;
316        let caret = u64::from_le_bytes(b[..8].try_into().unwrap()) as usize;
317        let anchor = (b[8] != 0).then(|| u64::from_le_bytes(b[9..].try_into().unwrap()) as usize);
318        Some(CaretState { caret, anchor })
319    }
320}
321
322/// A footnote reference and the note it names — the answer to
323/// [`Doc::footnote_at`].
324///
325/// The two `Option`s move together: a reference whose definition is missing has
326/// neither a body to show nor a place to jump to, and one that resolved has
327/// both.
328#[derive(Clone, PartialEq, Eq, Debug)]
329pub struct FootnoteRef {
330    /// The reference's label — the `1` of `[^1]`, with neither the `^` that
331    /// spells it a footnote nor the brackets around it.
332    pub label: String,
333    /// The note's body as source bytes (see
334    /// [`wysiwyg::footnote_body_span`](crate::wysiwyg)), or `None` when the
335    /// document defines no `[^label]:` to read one from.
336    pub text: Option<String>,
337    /// Where the note's *body* starts, for a "go to note" that moves the caret
338    /// there. `None` alongside a `None` `text`.
339    ///
340    /// The body rather than the definition, because this is an offset to put a
341    /// caret on and the `[^1]:` marker is decoration the caret can't occupy —
342    /// aiming at the definition's first byte snaps to the nearest real stop,
343    /// which is up in the paragraph above the note. It is also simply where a
344    /// reader following a reference wants to land: at the note's first word,
345    /// ready to read or amend it.
346    pub offset: Option<usize>,
347    /// Where the note's body ends, exclusive — so a frontend can ask which
348    /// *rendered rows* the note occupies and draw those instead of [`text`](Self::text).
349    ///
350    /// The rows are the note with its markup resolved: `see *later*` reaches a
351    /// frontend as an italic run, not as asterisks. `text` is the source bytes
352    /// and stays the honest answer for anything that wants the note as written
353    /// (a search index, a copy); this pair of offsets is for anything that wants
354    /// it as *read*. `None` alongside a `None` `offset`.
355    pub end: Option<usize>,
356}
357
358/// A footnote definition and the reference that sends a reader to it — the
359/// answer to [`Doc::footnote_definition_at`], and the other half of the round
360/// trip [`FootnoteRef`] starts.
361///
362/// A note is a place a reader *arrives*, so the useful thing to know while
363/// standing in one is the way back. Without this the jump to a note is a
364/// one-way door: the definitions sit at the foot of the document, so returning
365/// by hand means scrolling back up and finding the sentence again.
366#[derive(Clone, PartialEq, Eq, Debug)]
367pub struct FootnoteDef {
368    /// The definition's label — the `1` of `[^1]: …`, marker and colon stripped,
369    /// spelled exactly as [`FootnoteRef::label`] spells the same footnote's.
370    pub label: String,
371    /// Where the reference's *label* is, for a "back to reference" that moves
372    /// the caret there. `None` for a note nothing refers to — an orphan, which
373    /// is worth being able to say rather than silently doing nothing.
374    ///
375    /// The label rather than the reference's first byte, for
376    /// [`FootnoteRef::offset`]'s reason: a reference's brackets are decoration
377    /// and its label is the only part of it the caret can rest on.
378    ///
379    /// The *first* reference, when a label is cited more than once: a repeated
380    /// citation has no one true home, and the first is both the one a reader
381    /// most likely came from and the only choice that doesn't depend on how
382    /// they got here.
383    pub offset: Option<usize>,
384}
385
386/// Where a locator lands — the answer to [`Doc::locate`].
387///
388/// A locator (the `v2` of a `chapter.dj#v2`) names a *place* rather than a
389/// document, and a place is a span rather than a point: a reader following one
390/// wants the caret at its first byte, and a reader merely *peeking* at one wants
391/// the block it covers drawn. Both are served by carrying the whole span, and
392/// only one of the two can be recovered from an offset alone.
393#[derive(Clone, PartialEq, Eq, Debug)]
394pub struct Landing {
395    /// The first byte of the block the locator names — where a caret goes.
396    pub start: usize,
397    /// One past its last byte, so a frontend can map the pair through
398    /// [`VisualMap::row_range_for`](crate::wysiwyg::VisualMap::row_range_for) to the rendered rows the block occupies and draw
399    /// those, the way a footnote peek draws a note ([`FootnoteRef::end`]).
400    pub end: usize,
401}
402
403/// A selection cited out of the source: the text itself, up to a requested
404/// number of characters either side, and the byte range it came from. See
405/// [`Doc::selection_quote`].
406///
407/// The prefix and suffix are what make the quote *re-findable*: the same text
408/// can occur twice, and a little of what surrounded it is how a later reader —
409/// or the same document after an edit — tells the occurrences apart. The Web
410/// Annotation model calls this a `TextQuoteSelector`; the shape is older than
411/// the name.
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub struct Quote {
414    /// The selected source, verbatim.
415    pub exact: String,
416    /// What immediately preceded it — possibly empty, at the document's start.
417    pub prefix: String,
418    /// What immediately followed it — possibly empty, at the document's end.
419    pub suffix: String,
420    /// Byte offset in the source where the selection begins.
421    pub start: usize,
422    /// Byte offset where it ends (exclusive).
423    pub end: usize,
424}
425
426/// A host-painted range of the source — an annotation's footprint, a search
427/// hit, a reviewer's mark. Leaf renders it (a background wash behind the
428/// glyphs whose source falls inside it) and hands back the `id` when the
429/// reader activates it; what the range *means* is entirely the host's.
430///
431/// Ranges are source bytes, like the caret and the selection, so a host that
432/// anchors quotes against the source ([`Doc::selection_quote`] is the other
433/// half of that loop) can paint what it found without any coordinate
434/// conversion. A range that drifts off the text it meant is the host's to
435/// re-anchor; leaf draws what it is told.
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub struct Highlight {
438    /// Byte offset in the source where the wash begins.
439    pub start: usize,
440    /// Byte offset where it ends (exclusive).
441    pub end: usize,
442    /// The host's name for it, handed back on activation. Opaque to leaf.
443    pub id: String,
444    /// A rendering hint the frontend maps — a `#RRGGBB` hex string, or
445    /// nothing for the theme's default wash.
446    pub color: Option<String>,
447    /// A margin glyph's name, or nothing for wash-only ink. A highlight with
448    /// a marker gets a small glyph in the margin beside its first line, and
449    /// the glyph — not the wash — is what activates it: the wash is ink, the
450    /// marker is the control, which is what lets a reader put a caret in (or
451    /// copy from) annotated text without a card leaping at them. The name is
452    /// opaque to leaf; an Apple frontend reads it as an SF Symbol, a web one
453    /// as a class.
454    pub marker: Option<String>,
455}
456
457impl Highlight {
458    /// The range covering source `offset` in a list [`Doc::set_highlights`]
459    /// sorted, first by start where several overlap — the one place that
460    /// question is answered, for the frontends that paint by asking it as well
461    /// as for [`Doc::highlight_at`].
462    ///
463    /// The list is sorted by `(start, end)`, so the scan can stop at the first
464    /// range starting past `offset` rather than running to the end. A painter
465    /// asking once per glyph wants [`HighlightCursor`] instead; this is the
466    /// one-shot form, for the host asking what the reader just activated.
467    pub fn covering(highlights: &[Highlight], offset: usize) -> Option<&Highlight> {
468        highlights
469            .iter()
470            .take_while(|h| h.start <= offset)
471            .find(|h| offset < h.end)
472    }
473}
474
475/// [`Highlight::covering`] for a caller walking the document in order — which
476/// is every painter, since a frontend draws rows top to bottom and glyphs left
477/// to right.
478///
479/// The one-shot form is a scan from the front of the list per glyph, and a
480/// document with two hundred search hits pays that two hundred times a row. A
481/// range that ends at or before an offset can never cover that offset *or any
482/// later one*, so the cursor retires those permanently and each glyph costs the
483/// ranges that actually reach it. The answer is identical to
484/// [`Highlight::covering`]'s, offset for offset — this is the same scan with
485/// the part that was being redone dropped, not a cheaper approximation.
486///
487/// Offsets are expected to arrive non-decreasing. One that goes backwards is
488/// still answered correctly: the cursor re-seats to the front, since a painter
489/// that revisits a row is asking a question the retired ranges may own again.
490pub struct HighlightCursor<'a> {
491    highlights: &'a [Highlight],
492    /// The first range not yet retired.
493    at: usize,
494    /// The last offset asked about, to notice a caller going backwards.
495    last: usize,
496}
497
498impl<'a> HighlightCursor<'a> {
499    pub fn new(highlights: &'a [Highlight]) -> Self {
500        HighlightCursor {
501            highlights,
502            at: 0,
503            last: 0,
504        }
505    }
506
507    /// The range covering `offset`, advancing the cursor past every range that
508    /// can no longer cover anything.
509    pub fn at(&mut self, offset: usize) -> Option<&'a Highlight> {
510        if offset < self.last {
511            self.at = 0;
512        }
513        self.last = offset;
514        while self
515            .highlights
516            .get(self.at)
517            .is_some_and(|h| h.end <= offset)
518        {
519            self.at += 1;
520        }
521        Highlight::covering(&self.highlights[self.at..], offset)
522    }
523}
524
525/// The identity of a built [`VisualMap`] — see [`Doc::visual_key`]. Opaque on
526/// purpose: the only useful question is whether two of them are the same map,
527/// and what is behind it — which `Doc` built it, and the (revision, wrap,
528/// reveal line) it was built from — is core's business.
529///
530/// The document is part of it because the rest is not unique to one: two
531/// documents opened at the same width are both at revision zero with no reveal
532/// line, and a frontend holding one copy of a map across the two would take
533/// the second's key for the first's and paint the wrong document.
534#[derive(Clone, PartialEq, Eq, Debug)]
535pub struct VisualKey(u64, Option<(u64, Option<usize>, Option<Range<usize>>)>);
536
537pub struct Doc {
538    editor: Editor,
539    pub format: Format,
540    pub path: PathBuf,
541    /// Current source, refreshed from the editor after every successful edit.
542    pub source: String,
543    /// The caret, as a byte offset into `source` (always on a char boundary).
544    pub caret: usize,
545    /// The selection's fixed end, if a selection is active; the moving end is
546    /// the caret. `None` means no selection.
547    pub anchor: Option<usize>,
548    pub dirty: bool,
549    pub status: Option<String>,
550    pub view: View,
551    /// Whether the document refuses to change — a *reading* surface over the
552    /// same rendering, selection, and navigation the editor has.
553    ///
554    /// Enforced here rather than by each frontend hiding its input paths,
555    /// because every mutation funnels through a few doors —
556    /// [`splice_exact`](Self::splice_exact), [`undo`](Self::undo),
557    /// [`redo`](Self::redo), and the handful of inserts that go to twig's own
558    /// verbs directly rather than through the splice (a typed literal, a link,
559    /// an image, a rule, a footnote, a cell's line break) — and guarded doors
560    /// are a guarantee where a frontend's suppressed keyboard is a hope. A
561    /// gated door reports exactly like a rolled-back splice, a path every
562    /// caller already handles. `a_read_only_document_refuses_every_door` is
563    /// the list; a new `self.editor.insert_*` call belongs on it.
564    read_only: bool,
565    /// The host-painted ranges, kept sorted by start — see [`Highlight`].
566    /// State like the selection rather than like the text: no edit history,
567    /// no dirty bit, redrawn from whatever the host last set.
568    highlights: Vec<Highlight>,
569    /// How much of the source markup the rich view exposes — a frontend preference (see
570    /// [`MarkupMode`]). Its two axes are read apart: the rendering one by
571    /// [`reveal_line`](Self::reveal_line), the editing one by
572    /// [`insert`](Self::insert).
573    markup_mode: MarkupMode,
574    /// Whether soft breaks fold into the reflowed paragraph or render where
575    /// they were written (see [`LineFlow`]) — an independent frontend
576    /// preference the WYSIWYG builder consults when it lays out a block.
577    line_flow: LineFlow,
578    /// The kind of the last edit, for coalescing: twig owns the undo *history*
579    /// (see `undo`/`redo`), but "what counts as one undo step" is a frontend-UX
580    /// call, so leaf decides when a run continues and tells twig to coalesce.
581    last_edit_kind: Option<EditKind>,
582    /// The inline marks the user has toggled *at a collapsed caret* with no
583    /// selection — "start typing bold here". Held as the XOR delta from the marks
584    /// already in force at [`pending_at`](Self::pending_at): a set bit means
585    /// "flip this kind for the next typed text", so it both turns a mark on where
586    /// none is (type into bold) and off where one already covers the caret (type
587    /// past the bold you're standing in). [`Doc::insert`] realises it onto the
588    /// freshly typed text and then clears it — a mark once realised is carried by
589    /// the caret sitting inside the run, not by this delta.
590    pending_marks: InlineMarks,
591    /// The caret offset [`pending_marks`](Self::pending_marks) applies to. The
592    /// delta is live only while the caret still stands here with no selection;
593    /// any motion or edit ([`move_to`](Self::move_to), a splice, a click) drops
594    /// it, so a toggled-but-never-typed format doesn't leak onto text elsewhere.
595    pending_at: Option<usize>,
596    /// The source as of the last open/save — `dirty` is `source != clean_source`,
597    /// so undoing back to the saved state correctly clears the modified flag.
598    clean_source: String,
599    /// A hash of the bytes leaf last read from `path` or wrote to it; `None`
600    /// while the document has no file behind it. [`Doc::disk_state`] compares
601    /// the file against this to catch an edit made *outside* leaf before a save
602    /// silently overwrites it — `clean_source` only knows what leaf itself did.
603    ///
604    /// A hash, not an mtime: mtime is the cheap answer and the wrong one — two
605    /// writes inside one filesystem timestamp tick are indistinguishable, a
606    /// clock that steps backwards (or a writer that restores an mtime) hides a
607    /// real change, and a `touch` invents one. The whole point of the watermark
608    /// is to not clobber someone's work, so it reads the bytes and compares what
609    /// is actually there. That costs a file read per question, which is why the
610    /// question is asked on a user event (focus, save) and not every frame.
611    disk_hash: Option<u64>,
612    /// The "sticky" display column vertical motion aims for, in the active
613    /// view's grid. Set on the first `move_up`/`move_down` of a run and
614    /// reused by every subsequent one in that run, so passing through a
615    /// shorter line doesn't permanently forget the original column. Any
616    /// horizontal motion or edit clears it.
617    ///
618    /// A column, not a character index: dropping down a line of `你好` onto one
619    /// of ASCII has to land under the glyph the caret was drawn beneath, which
620    /// is the only thing the user can see to aim by. Where the goal falls inside
621    /// a wide character on the target line, the mapping resolves it to that
622    /// character — the caret lands on it rather than between its cells.
623    goal_col: Option<usize>,
624    /// The rendered map for the WYSIWYG view; empty in the source view. Movement
625    /// and clicks read it to stay in visible space.
626    pub vmap: VisualMap,
627    /// The syntax map for the source view; empty in the WYSIWYG view, which
628    /// styles resolved glyphs instead. Built by [`Doc::build_source`] — a
629    /// frontend that never calls it paints raw source unstyled, which is what
630    /// every frontend did before this map existed.
631    pub smap: SourceMap,
632    /// The revision `smap` was built from, or `None` before the first build.
633    /// The map is a pure function of the text alone — no width, no caret, no
634    /// reveal line — so unlike [`vmap_key`](Self::vmap_key) the revision is the
635    /// whole key.
636    smap_key: Option<u64>,
637    /// Everything the map is built from, as one number: bumped whenever the
638    /// document's text changes, and never by a motion, a selection, or a save.
639    /// A frontend can hold work against it — see [`Doc::revision`].
640    revision: u64,
641    /// How many history steps stand behind the caret, and how many ahead of
642    /// it — the answer to a native Edit menu's "may Undo be enabled?", which
643    /// twig's history does not ask itself. Counted at [`refresh`](Self::refresh),
644    /// the funnel every edit comes through, and moved back and forth by
645    /// [`undo`](Self::undo)/[`redo`](Self::redo). An upper bound rather than
646    /// an exact depth: a coalesced run of typing is one of twig's steps but
647    /// several of these, and twig's own cap on history is not mirrored here.
648    /// Neither error can make `can_undo` false while a step remains, which is
649    /// the only property a menu needs; the one place the bound can be wrong the
650    /// other way — the cap has retired every step — is reconciled the moment
651    /// twig reports nothing to undo.
652    undo_steps: usize,
653    redo_steps: usize,
654    /// What `vmap` was built from, or `None` before the first build. The map is
655    /// a pure function of `(revision, wrap, reveal line)`, so when those haven't
656    /// moved, rebuilding it produces the identical map — see
657    /// [`Doc::build_visual`].
658    ///
659    /// The reveal line ([`Doc::reveal_line`]) is the caret's, and is `None` in
660    /// every mode but [`MarkupMode::Full`] — so outside that mode the key is
661    /// text and width alone, and a caret motion still rebuilds nothing.
662    vmap_key: Option<(u64, Option<usize>, Option<Range<usize>>)>,
663    /// Which `Doc` this is, distinct from every other one built in this
664    /// process. Folded into [`VisualKey`] so that a map stashed by a frontend
665    /// can never be mistaken for another document's — see
666    /// [`Doc::visual_key`]. Nothing else reads it.
667    identity: u64,
668    /// Per-block row cache backing the incremental rebuild: when the text
669    /// changes, only the top-level blocks whose bytes moved are re-rendered and
670    /// the rest are reused shifted (see [`wysiwyg::BlockCache`]). Persists across
671    /// builds; a pure accelerator, so it's never read for correctness.
672    block_cache: wysiwyg::BlockCache,
673    /// How many visual rows each block image reserves, keyed by its destination —
674    /// set by the frontend through [`Doc::set_media_rows`] once it has decoded and
675    /// measured the pictures. Core does no image I/O, so this is the only way it
676    /// learns a picture's height; a destination not in the map reserves the bare
677    /// one-row placeholder. Threaded into the builder so [`wysiwyg::build_cached`]
678    /// sizes each placeholder, and folded into `vmap_key` so a height change
679    /// rebuilds the map.
680    media_rows: HashMap<String, usize>,
681
682    // View geometry the renderer stamps each frame, so mouse events can map a
683    // screen cell back to a byte offset.
684    pub scroll: usize,
685    pub body_origin: (u16, u16),
686    /// Width of the body rectangle last painted by the frontend. Zero means
687    /// unknown (used by tests or a frontend that has not drawn yet).
688    pub body_width: u16,
689    pub body_height: u16,
690    /// The caret as of the last frame drawn, or `None` before the first.
691    ///
692    /// Scrolling is the viewport's business, not the caret's: the view follows
693    /// the caret when the caret *moves*, but a wheel that doesn't touch the
694    /// caret has to be free to scroll away from it — otherwise the view is
695    /// pinned to the caret and stops dead at the edge of the document you can
696    /// see. Comparing against this is what tells the two apart, and it catches a
697    /// caret set by any route, including a frontend assigning the field itself.
698    pub drawn_caret: Option<usize>,
699}
700
701/// The Markdown extensions every leaf document is parsed with — four of them,
702/// each departing from twig's defaults for a reason leaf can state.
703///
704/// `html_elements` promotes embedded raw HTML (`<img>`, `<picture>`,
705/// `<source>`, …) into semantic AST nodes, so a picture becomes a real `image`
706/// node the frontends can frame and rasterize instead of opaque `raw_block`
707/// text. `directives` turns on generic `:::name{.class}` fenced-div containers
708/// (`directive` nodes), which a host app uses for its own semantics (diaryx's
709/// `:::vis{.audience}` visibility blocks) — core renders any directive as a
710/// plain tinted container, agnostic of `name`.
711///
712/// `highlight` and `highlight_colors` are the pair that makes Markdown read
713/// `==text==` as a `mark` node, and `==🔴 text==` as one carrying a
714/// `data-color`. leaf already had somewhere to put both: the
715/// [`Mark`](crate::Role::Mark) role and the ⌘⇧M highlight button predate them,
716/// and until twig 3.3 a Markdown document could only ever *receive* a highlight
717/// from a Djot one it was converted from — the button wrote `==…==` and the
718/// reparse read it straight back as text.
719/// They are on together because a colour is inert without the highlight itself,
720/// and a document that writes `==🔴 x==` means the colour by it.
721///
722/// Every flag is inert for non-Markdown formats, so it's safe to pass them
723/// unconditionally. Threading this through every constructor (not just `open`)
724/// keeps `from_source`, `blank`, and `reload` parsing the same document the same
725/// way — twig reparses with these same flags after each edit.
726pub(crate) fn parse_extensions() -> MarkdownExtensions {
727    MarkdownExtensions {
728        html_elements: true,
729        directives: true,
730        highlight: true,
731        highlight_colors: true,
732        ..Default::default()
733    }
734}
735
736/// Build an editor over `bytes` in `format` with leaf's [`parse_extensions`],
737/// mapping twig's error into the `anyhow` context every constructor shares.
738fn new_editor(bytes: &[u8], format: Format) -> Result<Editor> {
739    Editor::new_ext(bytes, format, parse_extensions()).map_err(|e| anyhow!("twig parse: {e}"))
740}
741
742/// Does `format` spell a table as a **pipe table** — the one grid twig's table
743/// editor knows how to emit?
744///
745/// This is the single capability leaf still has to answer for itself, and the
746/// only hand-maintained format list left in this file. Every other gesture is
747/// [`Format::supports`], which is twig's own answer read across the C ABI — but
748/// twig deliberately leaves the table ops out of that query, because they read
749/// no `Syntax` table at all. They rewrite a grid that is already in the source
750/// and refuse on *position*, never on format. Handed a caret inside an HTML
751/// `<table>`, `table_insert_row` therefore re-emits the whole element as
752/// `| a | b |` and reports success — a real splice, a clean reparse, an honest
753/// `dirty` flag, and nothing downstream able to tell it from a good edit.
754///
755/// So the list is narrow on purpose. `Format` is `#[non_exhaustive]`, and the
756/// wildcard answers "no" for a format leaf has never heard of: a new twig
757/// language that *does* spell pipe tables loses its grid controls until this
758/// line is updated, which shows up as a missing button. The other default hands
759/// it to [`Doc::table_op`], which rewrites documents it cannot spell.
760fn spells_pipe_tables(format: Format) -> bool {
761    matches!(format, Format::Markdown | Format::Djot)
762}
763
764/// Which of leaf's authoring controls this document's format can actually
765/// spell — one flag per toolbar button, resolved once so a frontend can build
766/// its chrome instead of discovering each refusal on a click.
767///
768/// Every field but [`table`](Self::table) is `Format::supports_with` on the
769/// gesture the matching [`Doc`] method calls, so this record cannot drift from
770/// what the ops do; `table` is [`spells_pipe_tables`], the one answer twig
771/// doesn't export.
772///
773/// `supports_with` rather than `supports` because two of these are facts about
774/// the *parse options* as much as about the format. `Format::supports` answers
775/// for twig's defaults, and leaf never parses with those — it parses with
776/// [`parse_extensions`], and a document's toolbar has to describe the document
777/// it is over. A Markdown editor holding `highlight` authors `==text==`; one
778/// without it would mint bytes its own reparse hands back as plain text, which
779/// is why twig asks before it writes.
780///
781/// **The formats are ragged, and that is the point.** A single per-document
782/// boolean was enough while the two authorable formats were Markdown and djot
783/// and everything else spelled nothing. HTML is neither: it writes seven of the
784/// eight inline marks as a tag pair, plus `<code>`, `<hr>`, an in-cell
785/// `<br>`, and — since twig 3.4 — a heading or paragraph rebuilt as its tag
786/// pair, and since 3.5 a quote, a list, a code block, a link and an image
787/// printed as fresh nodes; it spells no task box (a form control there) and
788/// no footnote, and its `<table>` is one twig reads but will not write. So
789/// ⌘B, ⌘1 and the quote button work in an HTML document and the task and
790/// table buttons do not, and no one flag can say that. Markdown and djot
791/// differ from each other too:
792/// `^superscript^` is djot-only, and an in-cell `<br>` is Markdown-only.
793#[derive(Clone, Copy, Debug, Eq, PartialEq)]
794pub struct Capabilities {
795    /// ⌘B — `InlineKind::Strong`.
796    pub bold: bool,
797    /// ⌘I — `InlineKind::Emph`.
798    pub italic: bool,
799    /// Inline code — `InlineKind::Verbatim`.
800    pub code: bool,
801    /// Highlight — `InlineKind::Mark`. Djot spells it, and so does Markdown
802    /// under the `highlight` extension [`parse_extensions`] turns on: the
803    /// button writes `==text==`, which is what the reparse reads back.
804    pub mark: bool,
805    /// ⌘U — `InlineKind::Insert`, which every format that marks at all spells.
806    pub underline: bool,
807    /// Strikethrough — `InlineKind::Delete`. Markdown spells GFM's `~~text~~`
808    /// out of the box, since twig parses it out of the box.
809    pub strike: bool,
810    /// The highlight *palette* — [`Doc::set_mark_color`]. Narrower than
811    /// [`mark`](Self::mark) and deliberately its own flag: Markdown spells a
812    /// colour on a highlight (`==🔴 text==`) and djot spells only the highlight,
813    /// so a toolbar offering the swatches wherever the button lights would offer
814    /// them in a document that cannot write one. Pair with
815    /// [`Doc::caret_in_mark`], which asks the other question — the palette needs
816    /// a highlight to colour as much as a format that spells one.
817    pub mark_color: bool,
818    pub superscript: bool,
819    pub subscript: bool,
820    /// Heading levels and "make this a paragraph" — [`Doc::set_block`].
821    pub heading: bool,
822    pub blockquote: bool,
823    pub bullet_list: bool,
824    pub ordered_list: bool,
825    /// The checkbox controls: giving an item a box, and ticking one.
826    pub task: bool,
827    pub link: bool,
828    /// Covers [`Doc::insert_media`] too — see the note there on why the three
829    /// media kinds stand or fall together.
830    pub image: bool,
831    /// The horizontal-rule button. HTML spells this one (`<hr>`).
832    pub thematic_break: bool,
833    /// The footnote button — [`Doc::insert_footnote`]. Markdown and djot spell
834    /// the pair; HTML has no footnote of its own, so the button goes away rather
835    /// than writing brackets that would render as brackets.
836    pub footnote: bool,
837    /// Setting a fenced block's language — a control only ever offered with the
838    /// caret already in a fence.
839    pub code_language: bool,
840    /// The grid controls: insert/delete/move a row or column, set a column's
841    /// alignment. Pair with [`Doc::caret_in_table`], which asks the other
842    /// question — an HTML `<table>` holds the caret and still can't be edited.
843    pub table: bool,
844    /// Shift+Return inside a cell. Markdown and HTML spell it; djot has no
845    /// idiomatic in-cell break.
846    pub cell_line_break: bool,
847    /// The alignment control — [`Doc::set_alignment`], twig's
848    /// `Gesture::SetBlockAttrs`. Every format leaf opens but XML spells a
849    /// block's attributes, Markdown under the `html_elements`
850    /// [`parse_extensions`] turns on (a `<div>` around the block) and AsciiDoc
851    /// through its `[…]` line.
852    pub alignment: bool,
853    /// The line-spacing menu — [`Doc::set_line_spacing`]. The same gesture as
854    /// [`alignment`](Self::alignment) and so the same answer, and its own flag
855    /// because a toolbar dims controls one at a time and the pair may yet
856    /// diverge.
857    pub line_spacing: bool,
858    /// The size menu — [`Doc::set_font_size`], twig's `Gesture::WrapRangeAttrs`
859    /// over a selection. **Narrower than the block pair**: AsciiDoc's
860    /// `[#id.role]#text#` keeps an id and a role and has no slot for a
861    /// `data-` key, so twig refuses the span there and this is `false` while
862    /// [`alignment`](Self::alignment) is `true`. The block-level form of the
863    /// same property — the caret in a paragraph, no selection — goes through
864    /// `SetBlockAttrs` and still works, which is why the flag describes the
865    /// control rather than the caret.
866    pub font_size: bool,
867    /// The face menu — [`Doc::set_font_family`]. `WrapRangeAttrs`, as
868    /// [`font_size`](Self::font_size) is.
869    pub font_family: bool,
870    /// The text-colour swatches — [`Doc::set_text_color`]. `WrapRangeAttrs`,
871    /// and not to be confused with [`mark_color`](Self::mark_color): that is a
872    /// highlight's background and rides the `mark` node twig already owns,
873    /// this is a run's foreground and rides an attributed span.
874    pub text_color: bool,
875    /// The page-break button — [`Doc::insert_page_break`], twig's
876    /// `Gesture::InsertDirective`. Markdown under the `directives` extension
877    /// [`parse_extensions`] turns on (`::page-break`) and djot, which spells
878    /// it as an empty `::: page-break` fence.
879    ///
880    /// **Those two and no others**, though twig spells the gesture in HTML and
881    /// AsciiDoc as well — see [`Capabilities::of`].
882    pub page_break: bool,
883}
884
885impl Capabilities {
886    /// Resolve every flag for `format`, as leaf parses it. Pure and cheap —
887    /// twig computes each from a static table — but a frontend that wants to
888    /// hold them can.
889    ///
890    /// The extensions are not a parameter because they are not a choice a
891    /// caller makes: every leaf document is parsed with [`parse_extensions`],
892    /// so the format is the whole of what varies.
893    pub fn of(format: Format) -> Self {
894        let exts = parse_extensions();
895        let supports = |g| format.supports_with(exts, g);
896        let inline = |k| supports(Gesture::ToggleInline(k));
897        let container = |k| supports(Gesture::ToggleBlockContainer(k));
898        Self {
899            bold: inline(InlineKind::Strong),
900            italic: inline(InlineKind::Emph),
901            code: inline(InlineKind::Verbatim),
902            mark: inline(InlineKind::Mark),
903            underline: inline(InlineKind::Insert),
904            strike: inline(InlineKind::Delete),
905            mark_color: supports(Gesture::SetMarkColor),
906            superscript: inline(InlineKind::Superscript),
907            subscript: inline(InlineKind::Subscript),
908            heading: supports(Gesture::SetBlock),
909            blockquote: container(BlockContainerKind::BlockQuote),
910            bullet_list: container(BlockContainerKind::BulletList),
911            ordered_list: container(BlockContainerKind::OrderedList),
912            // Both halves of the checkbox story, and leaf offers no control that
913            // needs only one: the item gesture mints the box, the checked one
914            // ticks it, and a format spelling a `task_marker` spells both.
915            task: supports(Gesture::ToggleTaskItem) && supports(Gesture::ToggleTaskChecked),
916            link: supports(Gesture::InsertLink),
917            image: supports(Gesture::InsertImage),
918            thematic_break: supports(Gesture::InsertThematicBreak),
919            footnote: supports(Gesture::InsertFootnote),
920            code_language: supports(Gesture::SetCodeLanguage),
921            table: spells_pipe_tables(format),
922            cell_line_break: supports(Gesture::InsertLineBreak),
923            // The presentation vocabulary, one gesture per level: the two
924            // line-level properties are a block's attributes and the three
925            // run-level ones a span's. They are asked separately because the
926            // formats answer differently — AsciiDoc spells the block and not
927            // the span — and a toolbar that dimmed all five together would dim
928            // three controls that work.
929            alignment: supports(Gesture::SetBlockAttrs),
930            line_spacing: supports(Gesture::SetBlockAttrs),
931            font_size: supports(Gesture::WrapRangeAttrs),
932            font_family: supports(Gesture::WrapRangeAttrs),
933            text_color: supports(Gesture::WrapRangeAttrs),
934            // Narrower than the gesture, on purpose. Twig spells
935            // `InsertDirective` in HTML and AsciiDoc too, and spells it
936            // *differently* there — `<page-break></page-break>` and `<<<` —
937            // and the walker reads only the two spellings above. An HTML page
938            // break draws as nothing at all (no row, no caret home) and an
939            // AsciiDoc one as an empty unlabelled row, so the button would
940            // write a break the author cannot see and cannot get back to.
941            // The proposal claims Markdown and djot, and this is that claim.
942            // Widening it is the walker's work, not this line's — see
943            // `docs/tasks/page-break-in-html-and-asciidoc.md`.
944            page_break: supports(Gesture::InsertDirective)
945                && matches!(format, Format::Markdown | Format::Djot),
946        }
947    }
948}
949
950/// The source of [`Doc::identity`], one per document ever built.
951static NEXT_IDENTITY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
952
953impl Doc {
954    #[cfg(feature = "fs")]
955    pub fn open(path: PathBuf) -> Result<Self> {
956        let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
957        Self::from_disk_bytes(path, bytes)
958    }
959
960    /// An empty document *named* `path`, for a file that isn't there yet — what
961    /// every other terminal editor gives you when you name a file that doesn't
962    /// exist. It is a real named document, not a [`Doc::blank`]: `is_untitled`
963    /// is false, so ⌘S writes straight to `path` with no Save As detour, and
964    /// the header shows the name the user asked for.
965    ///
966    /// The format comes from the extension, exactly as [`Doc::open`] reads it —
967    /// so `leaf notes.dj` starts a djot buffer rather than the Markdown
968    /// [`Doc::blank`] has to assume for want of a name. An extension leaf can't
969    /// parse is still an error: a mistyped flag or a stray argument should say
970    /// so, not open a buffer promising to save somewhere.
971    ///
972    /// The watermark is the hash of *no bytes*, not `None`, and that is the
973    /// whole trick: `None` means untitled, and would leave [`Doc::disk_state`]
974    /// answering [`DiskState::Untitled`] for a document that has a path and
975    /// intends to write to it. Hashing `""` instead makes the answers the true
976    /// ones — [`DiskState::Missing`] while the file still isn't there (a save
977    /// recreates it, which is exactly what this is for), and
978    /// [`DiskState::Changed`] if somebody creates it underneath us between
979    /// launch and save, so the frontend's overwrite prompt guards a new file as
980    /// it guards an opened one.
981    ///
982    /// Nothing is written here. A buffer that is never typed into never touches
983    /// the filesystem, and a `path` whose directory doesn't exist is allowed to
984    /// open — the write is where that fails, and it says so then.
985    #[cfg(feature = "fs")]
986    pub fn create(path: PathBuf) -> Result<Self> {
987        Self::from_disk_bytes(path, Vec::new())
988    }
989
990    /// [`Doc::open`] when the file is there, [`Doc::create`] when it isn't —
991    /// the call a CLI frontend wants for its path argument.
992    ///
993    /// The decision is made from the failed read itself rather than a `exists()`
994    /// check first, so there is no window between the two for the file to appear
995    /// or vanish in. Only `NotFound` opens a new buffer: a permissions error or
996    /// a directory in the way is still an error, because pretending those are
997    /// "no file yet" would offer to save over something leaf couldn't read.
998    #[cfg(feature = "fs")]
999    pub fn open_or_create(path: PathBuf) -> Result<Self> {
1000        match std::fs::read(&path) {
1001            Ok(bytes) => Self::from_disk_bytes(path, bytes),
1002            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::create(path),
1003            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
1004        }
1005    }
1006
1007    /// The shared body of [`Doc::open`] and [`Doc::create`]: bytes that are (or
1008    /// stand in for) the file at `path`, parsed as the format its extension
1009    /// names. Keeping the two on one path is what makes a new file's document
1010    /// identical in every respect to an opened one but its contents.
1011    #[cfg(feature = "fs")]
1012    fn from_disk_bytes(path: PathBuf, bytes: Vec<u8>) -> Result<Self> {
1013        let format = detect_format(&path)?;
1014        let editor = new_editor(&bytes, format)?;
1015        let source = String::from_utf8(bytes).map_err(|_| anyhow!("document is not UTF-8"))?;
1016        let disk_hash = Some(hash_bytes(source.as_bytes()));
1017        // Store the document's *absolute* path. A relative one (`leaf README.md`)
1018        // has an empty parent, so a frontend can't resolve a relative image
1019        // destination (`![](pic.png)`) against the document's directory and the
1020        // picture silently falls back to its text placeholder. `absolute` is
1021        // purely lexical — it prefixes the current directory and normalizes, but
1022        // reads nothing and resolves no symlinks — so `file_name` and save are
1023        // unchanged; it only gives `path.parent()` something to join against.
1024        let path = std::path::absolute(&path).unwrap_or(path);
1025        Ok(Doc::from_parts(editor, format, path, source, disk_hash))
1026    }
1027
1028    /// Build a document from an in-memory string, the format named explicitly —
1029    /// the portable, filesystem-free counterpart to [`Doc::open`] (which reads a
1030    /// path and sniffs the format from its extension). A wasm or FFI host, which
1031    /// has no path to read, uses this: it hands over bytes it fetched however it
1032    /// could, and later persists [`Doc::source`] however it can (a browser
1033    /// download, `localStorage`, a backend `PUT`) and calls [`Doc::mark_saved`].
1034    ///
1035    /// No file backs the result, so it starts untitled ([`Doc::is_untitled`] is
1036    /// true) exactly like a [`Doc::blank`] that has been given content.
1037    pub fn from_source(source: String, format: Format) -> Result<Self> {
1038        let editor = new_editor(source.as_bytes(), format)?;
1039        Ok(Doc::from_parts(
1040            editor,
1041            format,
1042            PathBuf::new(),
1043            source,
1044            None,
1045        ))
1046    }
1047
1048    /// An untitled, empty document — the `+` button and a `leaf` launched with
1049    /// no file argument. Nothing on disk backs it until a [`Doc::save_as`].
1050    ///
1051    /// It is Markdown, because a format has to be chosen before a name exists to
1052    /// read one from: `detect_format` reads the extension and an untitled
1053    /// document has neither. Markdown is what leaf's own files are, what its
1054    /// block markers are already written for (`insert_block_prefix`), and the
1055    /// extension a Save As will overwhelmingly pick — a wrong guess here would
1056    /// mean typing djot into a buffer parsing it as Markdown. Note that Save As
1057    /// *doesn't* revisit this: see [`Doc::save_as`].
1058    pub fn blank() -> Result<Self> {
1059        let format = Format::Markdown;
1060        let editor = new_editor(b"", format)?;
1061        // An empty `path` is the untitled marker (`path` is a public `PathBuf`
1062        // field two frontends already read; making it an `Option` to say this
1063        // would break both). `is_untitled` is the question to ask, not the
1064        // representation to copy.
1065        Ok(Doc::from_parts(
1066            editor,
1067            format,
1068            PathBuf::new(),
1069            String::new(),
1070            None,
1071        ))
1072    }
1073
1074    /// The fields every constructor agrees on, so `open` and `blank` can't drift
1075    /// apart in the ones neither of them has an opinion about.
1076    // `identity` is taken from a counter rather than from the `Doc`'s address,
1077    // which moves — a session that holds one is moved into and out of
1078    // containers freely, and an identity that changed with it would defeat the
1079    // one comparison it exists for.
1080    fn from_parts(
1081        editor: Editor,
1082        format: Format,
1083        path: PathBuf,
1084        source: String,
1085        disk_hash: Option<u64>,
1086    ) -> Self {
1087        Doc {
1088            editor,
1089            format,
1090            path,
1091            disk_hash,
1092            clean_source: source.clone(),
1093            source,
1094            caret: 0,
1095            anchor: None,
1096            dirty: false,
1097            status: None,
1098            read_only: false,
1099            highlights: Vec::new(),
1100            // leaf opens in the rich-text (WYSIWYG) view by default — the
1101            // markup-resolved surface is leaf's differentiator. Frontends can
1102            // still start in source view explicitly (e.g. a CLI flag), and ⌘e/⌥w
1103            // toggles at runtime.
1104            view: View::Wysiwyg,
1105            // `None` by default — the clean surface Diaryx ships, with typed
1106            // syntax kept literal; a markup-fluent frontend can climb the
1107            // ladder to `Shortcuts` or `Full`.
1108            markup_mode: MarkupMode::default(),
1109            // Fold by default — flowing prose that reflows to the viewport, the
1110            // behaviour every frontend had before this preference existed.
1111            line_flow: LineFlow::default(),
1112            last_edit_kind: None,
1113            pending_marks: InlineMarks::empty(),
1114            pending_at: None,
1115            goal_col: None,
1116            vmap: VisualMap::default(),
1117            smap: SourceMap::default(),
1118            // No map yet — the first `build_source` always builds.
1119            smap_key: None,
1120            revision: 0,
1121            undo_steps: 0,
1122            redo_steps: 0,
1123            // No map yet — the first `build_visual` always builds.
1124            vmap_key: None,
1125            identity: NEXT_IDENTITY.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
1126            block_cache: wysiwyg::BlockCache::default(),
1127            media_rows: HashMap::new(),
1128            scroll: 0,
1129            body_origin: (0, 0),
1130            body_width: 0,
1131            body_height: 0,
1132            drawn_caret: None,
1133        }
1134    }
1135
1136    /// Whether this document has no file behind it yet — a [`Doc::blank`] that
1137    /// has never been saved. The question a ⌘S handler asks to know it should
1138    /// open a Save As picker instead ([`Doc::save`] won't guess a name), and the
1139    /// header asks to know the name it shows is a placeholder.
1140    pub fn is_untitled(&self) -> bool {
1141        self.path.as_os_str().is_empty()
1142    }
1143
1144    pub fn toggle_view(&mut self) {
1145        self.view = match self.view {
1146            View::Source => View::Wysiwyg,
1147            View::Wysiwyg => View::Source,
1148        };
1149        self.scroll = 0;
1150        self.status = None;
1151        // Entering WYSIWYG, the caret may be sitting in now-hidden frontmatter;
1152        // lift it to the first rendered offset.
1153        self.clamp_caret();
1154    }
1155
1156    /// The current markup-exposure preference (see [`MarkupMode`]).
1157    pub fn markup_mode(&self) -> MarkupMode {
1158        self.markup_mode
1159    }
1160
1161    /// Set the markup-exposure preference. Both of its axes take effect at
1162    /// once: the editing one on the next [`insert`](Self::insert), and the
1163    /// rendering one on the next build — which is why this drops the cached
1164    /// visual map and the per-block render cache, exactly as
1165    /// [`set_line_flow`](Self::set_line_flow) does.
1166    pub fn set_markup_mode(&mut self, mode: MarkupMode) {
1167        if self.markup_mode == mode {
1168            return;
1169        }
1170        self.markup_mode = mode;
1171        // Neither cache is keyed on the mode, and moving between `Full` and the
1172        // hidden modes changes every row the caret's line renders to — so
1173        // invalidate both explicitly.
1174        self.vmap_key = None;
1175        self.block_cache = wysiwyg::BlockCache::default();
1176    }
1177
1178    /// The source byte range of the line the caret sits on, when that line
1179    /// should render its raw delimiters — `None` in every mode and view that
1180    /// hides them, which is what the builder reads as "reveal nothing".
1181    ///
1182    /// A *source* line (newline to newline), not a visual row: a wrapped
1183    /// paragraph and a `LineFlow::Preserve` soft break both split one source
1184    /// line across several rows, and revealing half a delimiter pair because the
1185    /// other half wrapped would be worse than revealing neither. The range
1186    /// excludes the terminating newline and is empty-but-present on a blank
1187    /// line, which reveals nothing but still keys the caches correctly.
1188    ///
1189    /// Only in [`View::Wysiwyg`]: source view already shows every byte, so
1190    /// there is nothing there to reveal.
1191    pub(crate) fn reveal_line(&self) -> Option<Range<usize>> {
1192        if !self.markup_mode.reveals_caret_line() || self.view != View::Wysiwyg {
1193            return None;
1194        }
1195        Some(source_line_range(&self.source, self.caret))
1196    }
1197
1198    /// The current soft-break flow preference (see [`LineFlow`]).
1199    pub fn line_flow(&self) -> LineFlow {
1200        self.line_flow
1201    }
1202
1203    /// Set the soft-break flow preference. The mode changes how every block lays
1204    /// out, so a change drops the cached visual map and the per-block render
1205    /// cache, forcing the next [`build_visual`] to rebuild under the new flow.
1206    ///
1207    /// [`build_visual`]: Self::build_visual
1208    pub fn set_line_flow(&mut self, mode: LineFlow) {
1209        if self.line_flow == mode {
1210            return;
1211        }
1212        self.line_flow = mode;
1213        // Both caches are keyed on `(revision, wrap)`, neither of which moved —
1214        // so invalidate them explicitly, or the next build would reuse rows laid
1215        // out under the old flow.
1216        self.vmap_key = None;
1217        self.block_cache = wysiwyg::BlockCache::default();
1218    }
1219
1220    pub fn view_name(&self) -> &'static str {
1221        match self.view {
1222            View::Source => "source",
1223            View::Wysiwyg => "wysiwyg",
1224        }
1225    }
1226
1227    /// Rebuild the WYSIWYG visual map for the current tree at `width` columns
1228    /// (called by the renderer each frame it's in the WYSIWYG view).
1229    /// Build the WYSIWYG map, wrapped at `width` display columns.
1230    ///
1231    /// Cheap to call every frame, which is what both frontends do: the map is a
1232    /// pure function of the document and the wrap width, so a call that would
1233    /// rebuild the same map returns the one already built. Only an edit (or a
1234    /// resize) pays.
1235    ///
1236    /// That isn't a micro-optimisation. A frontend repaints for reasons that have
1237    /// nothing to do with the text — a blinking caret, a scroll, a focus change —
1238    /// and rebuilding here is O(document): 23 ms on a 1 MB file, of which 5 ms is
1239    /// marshalling twig's AST across the C ABI. Paid twice a second by the GUI's
1240    /// blink timer, that was 14% of a core spent redrawing an unchanged document.
1241    /// (`cargo run --release -p leaf-core --example bench` for the numbers.)
1242    pub fn build_visual(&mut self, width: usize) {
1243        self.build_map(Some(width));
1244    }
1245
1246    /// Build the WYSIWYG map with each block as a single unwrapped row — for a
1247    /// frontend (the GUI) that wraps at its own proportional pixel width rather
1248    /// than a fixed character column.
1249    pub fn build_visual_unwrapped(&mut self) {
1250        self.build_map(None);
1251    }
1252
1253    /// Build the source view's syntax map ([`Doc::smap`]) — the styling for
1254    /// [`View::Source`], the way [`build_visual`](Self::build_visual) is the
1255    /// styling for [`View::Wysiwyg`].
1256    ///
1257    /// A frontend calls this before painting raw source. One that doesn't gets
1258    /// an empty map and paints unstyled text, so this is additive: nothing
1259    /// breaks by not calling it.
1260    ///
1261    /// Built at most once per revision, and the revision is the whole key — the
1262    /// map has no width and no caret in it, so it survives every resize, every
1263    /// motion, and every selection change.
1264    ///
1265    /// The builds it does do cost a whole-arena marshal, which is precisely what
1266    /// the WYSIWYG path works to avoid, so this has no incremental path where
1267    /// that one has two. From `cargo run --release -p leaf-core --example
1268    /// bench`, per keystroke, against the WYSIWYG build the source view is
1269    /// *not* doing:
1270    ///
1271    /// |  size |  nodes | marshal | `source::build` | (`wysiwyg::build`) |
1272    /// |------:|-------:|--------:|----------------:|-------------------:|
1273    /// |  10 KB|    613 |  0.16 ms|         0.07 ms |            0.28 ms |
1274    /// | 100 KB|  6 097 |  0.84 ms|         0.38 ms |            2.43 ms |
1275    /// |   1 MB| 60 601 |  5.67 ms|         3.12 ms |           23.39 ms |
1276    ///
1277    /// Linear, two thirds of it the marshal, and the build itself five to seven
1278    /// times cheaper than the one it stands in for at every size. Comfortable
1279    /// well past any document a person edits in a terminal — a megabyte is where
1280    /// it would want [`Editor::dirty_range`] and the same splice treatment
1281    /// `build_spliced` gives the other map. The door is open; nothing has needed
1282    /// it yet.
1283    pub fn build_source(&mut self) {
1284        if self.smap_key == Some(self.revision) {
1285            return;
1286        }
1287        let nodes = self.nodes();
1288        self.smap = source::build(&nodes, &self.source);
1289        self.smap_key = Some(self.revision);
1290    }
1291
1292    /// Tell the model how many visual rows each block image should reserve, keyed
1293    /// by the image's destination. A terminal frontend calls this once it has
1294    /// decoded and measured its pictures — core does no image I/O, so this is the
1295    /// only way it learns a height — and the next [`Doc::build_visual`] lays each
1296    /// placeholder out that tall (the label row plus blank filler rows the
1297    /// frontend paints the raster over). A destination left out of the map falls
1298    /// back to the bare one-row placeholder, which is also what a frontend that
1299    /// can't draw pictures (or lays them out in its own units, like the GUI) gets
1300    /// by never calling this.
1301    ///
1302    /// Cheap to call every frame with the same map: only a *change* invalidates
1303    /// the built map (and the block-row cache, since a height isn't part of a
1304    /// block's bytes and so wouldn't otherwise re-render it). Steady state is a
1305    /// no-op, so a frontend can just hand over its current measurements each frame.
1306    pub fn set_media_rows(&mut self, rows: HashMap<String, usize>) {
1307        if self.media_rows == rows {
1308            return;
1309        }
1310        self.media_rows = rows;
1311        // A height lives outside the block's source bytes, so the content-keyed
1312        // block cache would hand back the old-height rows on a hit. Drop it (and
1313        // the splice layout it carries) so the next build re-renders every block
1314        // at the new heights, and force that build by clearing the map key.
1315        self.block_cache = wysiwyg::BlockCache::default();
1316        self.vmap_key = None;
1317    }
1318
1319    /// The revision the document's text is at — bumped by every edit, undo,
1320    /// redo, and reload, and by nothing else. A frontend caches against this to
1321    /// tell a repaint that needs new work from one that doesn't.
1322    ///
1323    /// It counts *edits*, not distinct texts: typing `x` and deleting it again
1324    /// lands on the same text two revisions later. Work is only ever rebuilt
1325    /// needlessly, never wrongly reused.
1326    pub fn revision(&self) -> u64 {
1327        self.revision
1328    }
1329
1330    /// The identity of the map presently in [`vmap`](Self::vmap) — what the last
1331    /// [`build_visual`](Self::build_visual) built it from, or the identity of an
1332    /// unbuilt map before the first one.
1333    ///
1334    /// This is *not* [`revision`](Self::revision). The revision says where the
1335    /// text is; this says where the map is, and the two part company the moment
1336    /// an edit lands, until something rebuilds. A frontend that keeps its own
1337    /// copy of the map — leaf-ratatui stashes core's before splicing filler rows
1338    /// under an oversized heading — compares this against the value it held when
1339    /// it took the copy, and learns whether `vmap` is still the map it stashed
1340    /// or one somebody else has since rebuilt. Restoring a copy over a newer
1341    /// map would paint a stale document; restoring nothing hands core's
1342    /// incremental rebuild a map it never built.
1343    ///
1344    /// "Somebody else" includes another document. The key names the `Doc`
1345    /// as well as the build, so a frontend that draws two documents through
1346    /// one stash — a host with several buffers, or one that opens the next
1347    /// document where the last one stood — never has the copy it took of one
1348    /// accepted by the other, however alike their builds are.
1349    pub fn visual_key(&self) -> VisualKey {
1350        VisualKey(self.identity, self.vmap_key.clone())
1351    }
1352
1353    /// The map, built at most once per `(revision, wrap)`. `clamp_caret` still
1354    /// runs on every call: the caret moves without the document changing, and
1355    /// keeping it on a legal stop is this function's job either way.
1356    fn build_map(&mut self, wrap: Option<usize>) {
1357        // Under `MarkupMode::Full` the map is a function of the caret's *line*
1358        // as well as the text, so the line joins the key: moving within a line
1359        // still reuses the map, and crossing into another one rebuilds it. In
1360        // every other mode `reveal_line` is `None` and the key is what it was,
1361        // so caret motion goes on costing nothing.
1362        let reveal = self.reveal_line();
1363        let key = (self.revision, wrap, reveal.clone());
1364        if self.vmap_key.as_ref() != Some(&key) {
1365            // Enumerate the top-level blocks cheaply — no whole-arena marshal.
1366            // A subtree is pulled only for the block(s) that actually changed, so
1367            // the FFI marshal shrinks from O(document) to O(edited block).
1368            let top = self.top_blocks();
1369
1370            // Fast path: when twig reports a dirty byte range, try to patch the
1371            // previous map in place — a single-block edit moves the prefix,
1372            // shifts the suffix, and re-renders only one block. `build_spliced`
1373            // returns `None` (and we fall back to the always-correct full rebuild)
1374            // whenever the edit reshaped the block structure, hit a table, or
1375            // there's no previous map to patch.
1376            // Preserve soft breaks as written when the flow preference asks for
1377            // it — the builder renders each as its own visual row instead of
1378            // folding it into the reflowed paragraph.
1379            let preserve_soft = self.line_flow == LineFlow::Preserve;
1380            let spliced = match self.editor.dirty_range() {
1381                Some(dirty) => {
1382                    let prev = std::mem::take(&mut self.vmap);
1383                    let source = &self.source;
1384                    let cache = &mut self.block_cache;
1385                    let media_rows = &self.media_rows;
1386                    let editor = &mut self.editor;
1387                    wysiwyg::build_spliced(
1388                        prev,
1389                        source,
1390                        wrap,
1391                        preserve_soft,
1392                        &top,
1393                        dirty,
1394                        media_rows,
1395                        reveal.clone(),
1396                        cache,
1397                        |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1398                    )
1399                }
1400                None => None,
1401            };
1402            self.vmap = spliced.unwrap_or_else(|| {
1403                let source = &self.source;
1404                let cache = &mut self.block_cache;
1405                let media_rows = &self.media_rows;
1406                let editor = &mut self.editor;
1407                wysiwyg::build_cached(
1408                    &top,
1409                    source,
1410                    wrap,
1411                    preserve_soft,
1412                    media_rows,
1413                    reveal,
1414                    cache,
1415                    |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1416                )
1417            });
1418            // Acknowledge the dirty range so the next edit's range starts fresh.
1419            self.editor.clear_dirty();
1420            self.vmap_key = Some(key);
1421        }
1422        self.clamp_caret();
1423    }
1424
1425    fn nodes(&mut self) -> Vec<FlatNode> {
1426        self.editor.nodes().unwrap_or_default()
1427    }
1428
1429    /// The document's top-level blocks for the incremental render. See
1430    /// [`wysiwyg::top_blocks`] for why this isn't simply `child_spans(None)`.
1431    fn top_blocks(&mut self) -> Vec<QueryMatch> {
1432        wysiwyg::top_blocks(&mut self.editor)
1433    }
1434
1435    pub fn format_name(&self) -> &'static str {
1436        // `Format` is `#[non_exhaustive]` as of twig 3.0, so the wildcard is
1437        // required. It also covers `Asciidoc`, which twig parses but cannot
1438        // serialize — leaf never opens a document in it (see `Doc::open`).
1439        match self.format {
1440            Format::Djot => "djot",
1441            Format::Markdown => "markdown",
1442            Format::Xml => "xml",
1443            Format::Html => "html",
1444            _ => "unknown",
1445        }
1446    }
1447
1448    /// Whether this document's format offers *any* door in — `false` only for a
1449    /// wholly parse-only format (XML, AsciiDoc), where every gesture refuses and
1450    /// a frontend may as well open the file read-only.
1451    ///
1452    /// This is a much weaker claim than the name suggests, and driving per-button
1453    /// state from it is exactly the mistake to avoid: HTML answers `true` because
1454    /// it spells the inline marks with a tag pair (`<strong>`, `<em>`, `<code>`)
1455    /// while a heading, a quote, a list, a task box, a link and a code fence all
1456    /// remain unspellable there. Ask [`capabilities`](Self::capabilities) — or
1457    /// [`supports`](Self::supports) — per control.
1458    pub fn authorable(&self) -> bool {
1459        self.format.is_authorable()
1460    }
1461
1462    /// Whether this document can spell `gesture`, which is twig's own answer
1463    /// rather than a copy of it: `Format::supports_with` reads the same
1464    /// `Syntax` table the `Editor` method consults before refusing, chosen by
1465    /// the very [`parse_extensions`] this document's editor reparses with — so
1466    /// what the toolbar offers and what the splice will accept are one table.
1467    ///
1468    /// It is a fact about the *document*, not about the caret. `true` does not
1469    /// promise the gesture succeeds where it is standing — a link over a table
1470    /// border still fails — only that it will not fail with
1471    /// `UnsupportedFormat`. Gray out on `false`; don't read `true` as "this
1472    /// will work here".
1473    pub fn supports(&self, gesture: Gesture) -> bool {
1474        self.format.supports_with(parse_extensions(), gesture)
1475    }
1476
1477    /// Every control's enabled state in one read — what a toolbar builds itself
1478    /// from when a document opens or its format changes. See [`Capabilities`].
1479    pub fn capabilities(&self) -> Capabilities {
1480        Capabilities::of(self.format)
1481    }
1482
1483    /// Refuse a gesture this document's format cannot spell, saying so in the
1484    /// status line. `true` means the caller must return without calling twig.
1485    ///
1486    /// Most of these refusals duplicate one twig would make anyway, and they are
1487    /// made here regardless because a message naming the *document's* format
1488    /// reads better than one naming twig's internals. Two of them are not
1489    /// duplicates and are the reason this is a guard rather than an error
1490    /// translation:
1491    ///
1492    /// - The table family (see [`table_op`](Self::table_op)) consults no
1493    ///   `Syntax` table, so twig does not refuse it at all.
1494    /// - [`toggle`](Self::toggle) at a collapsed caret never reaches twig — it
1495    ///   arms a sticky mark for text not yet typed, which is a promise `insert`
1496    ///   could not keep.
1497    fn refuse_unsupported(&mut self, what: &str, gesture: Gesture) -> bool {
1498        self.refuse_unless(what, self.supports(gesture))
1499    }
1500
1501    /// [`refuse_unsupported`](Self::refuse_unsupported) against a capability leaf
1502    /// answers itself — today only [`spells_pipe_tables`].
1503    fn refuse_unless(&mut self, what: &str, supported: bool) -> bool {
1504        if supported {
1505            return false;
1506        }
1507        self.status = Some(format!("{what}: not supported in {}", self.format_name()));
1508        true
1509    }
1510
1511    /// The name to show for this document. An untitled one has no file to name
1512    /// it, and both frontends put this straight on screen — an empty path
1513    /// renders as an empty header, so it says so instead.
1514    pub fn file_name(&self) -> String {
1515        if self.is_untitled() {
1516            return "untitled".into();
1517        }
1518        self.path
1519            .file_name()
1520            .map(|s| s.to_string_lossy().into_owned())
1521            .unwrap_or_else(|| self.path.display().to_string())
1522    }
1523
1524    /// The selection as an ordered `[start, end)` byte range, or `None` when the
1525    /// caret and anchor coincide (an empty selection is no selection).
1526    pub fn selection(&self) -> Option<(usize, usize)> {
1527        self.anchor
1528            .map(|a| (a.min(self.caret), a.max(self.caret)))
1529            .filter(|(s, e)| s != e)
1530    }
1531
1532    /// The selected text, or `None` when there's no selection — the source
1533    /// slice a copy/cut hands to the system clipboard.
1534    pub fn selected_text(&self) -> Option<&str> {
1535        self.selection().map(|(s, e)| &self.source[s..e])
1536    }
1537
1538    /// The selection as a quote with a little of what surrounds it — the shape
1539    /// a host that cites, annotates, or searches for a passage wants, cut from
1540    /// the **source** rather than from anything rendered, so the quote is
1541    /// findable in the document again by plain string search.
1542    ///
1543    /// `context` is a count of characters (not bytes) on each side, clipped at
1544    /// the document's edges; the slices land on char boundaries by
1545    /// construction. `None` when nothing is selected.
1546    pub fn selection_quote(&self, context: usize) -> Option<Quote> {
1547        let (start, end) = self.selection()?;
1548        let mut before = start;
1549        for _ in 0..context {
1550            match self.source[..before].chars().next_back() {
1551                Some(c) => before -= c.len_utf8(),
1552                None => break,
1553            }
1554        }
1555        let mut after = end;
1556        for _ in 0..context {
1557            match self.source[after..].chars().next() {
1558                Some(c) => after += c.len_utf8(),
1559                None => break,
1560            }
1561        }
1562        Some(Quote {
1563            exact: self.source[start..end].to_string(),
1564            prefix: self.source[before..start].to_string(),
1565            suffix: self.source[end..after].to_string(),
1566            start,
1567            end,
1568        })
1569    }
1570
1571    /// Words, characters, and paragraphs over the whole document — the numbers
1572    /// a status bar or an inspector puts next to a piece of writing.
1573    ///
1574    /// Counted over the text a **reader** sees, not the markup that spells it:
1575    /// `**bold**` is one word and four characters, a link is its label and not
1576    /// its destination, a block picture's `🖼 alt` placeholder is a picture and
1577    /// counts nothing, and leading frontmatter — which the WYSIWYG view does
1578    /// not render at all — is not writing. [`crate::counts`] states the rules
1579    /// in full; [`TextCounts`] states them per field.
1580    ///
1581    /// The same numbers in both views. They have to be: a word count that fell
1582    /// when you pressed ⌘E would be telling you the view had changed, which
1583    /// you knew already. So this reads neither [`Doc::view`] nor the map the
1584    /// frontend last built — it renders the source afresh, unwrapped, with
1585    /// soft breaks folded and no line revealed, and counts that. A narrower
1586    /// window, a different [`MarkupMode`], a different [`LineFlow`], and the
1587    /// source view all give the identical answer, because none of them is an
1588    /// input.
1589    ///
1590    /// That costs a reparse and an unwrapped layout — O(document), about 4 ms
1591    /// on a 45 KB file in release and 36 ms on half a megabyte. Fine on a
1592    /// settle and wrong in a paint loop, so a frontend should ask when the
1593    /// typing stops rather than once a keystroke. Caching it against
1594    /// [`revision`](Self::revision) is the obvious next move if that is ever
1595    /// not enough; nothing has needed it yet.
1596    pub fn counts(&self) -> TextCounts {
1597        self.count_over(None)
1598    }
1599
1600    /// The same statistics over the selection alone — `None` when nothing is
1601    /// selected, since an empty selection is no selection.
1602    ///
1603    /// Same rules, over the same rendering, narrowed to the glyphs whose
1604    /// source byte falls inside [`selection`](Self::selection)'s range. A
1605    /// block the selection only clips still counts as one paragraph, and one
1606    /// it enters without catching a visible character counts as none — a
1607    /// selection that starts on a hidden `**` gains no paragraph from it.
1608    pub fn selection_counts(&self) -> Option<TextCounts> {
1609        let (start, end) = self.selection()?;
1610        Some(self.count_over(Some(start..end)))
1611    }
1612
1613    /// The rendering both counters tally, and the tally itself.
1614    ///
1615    /// A fresh parse rather than `self.editor`, because these take `&self` and
1616    /// twig's arena is reached through `&mut`. A document that will not
1617    /// reparse is a "cannot happen" — the source came out of an editor that
1618    /// had already accepted it — and answers zero rather than panicking in
1619    /// what is very likely a paint path.
1620    fn count_over(&self, range: Option<Range<usize>>) -> TextCounts {
1621        let Ok(mut editor) = new_editor(self.source.as_bytes(), self.format) else {
1622            return TextCounts::default();
1623        };
1624        let Ok(nodes) = editor.nodes() else {
1625            return TextCounts::default();
1626        };
1627        let map = wysiwyg::build(&nodes, &self.source, None, false, &HashMap::new(), None);
1628        counts::tally(&map, range)
1629    }
1630
1631    /// Whether the document refuses to change — see the field.
1632    pub fn read_only(&self) -> bool {
1633        self.read_only
1634    }
1635
1636    /// Turn the read-only gate on or off. A frontend preference like
1637    /// [`set_markup_mode`](Self::set_markup_mode): nothing about the document
1638    /// itself changes, only what may be done to it from here on.
1639    pub fn set_read_only(&mut self, on: bool) {
1640        self.read_only = on;
1641    }
1642
1643    /// The host-painted ranges, sorted by start — see [`Highlight`].
1644    pub fn highlights(&self) -> &[Highlight] {
1645        &self.highlights
1646    }
1647
1648    /// Replace the host-painted ranges wholesale. The whole set each time,
1649    /// rather than add/remove verbs: the host owns the list (it derives it
1650    /// from its own state — annotations, search hits), and a replace can
1651    /// never leave the two disagreeing about what should be on screen.
1652    pub fn set_highlights(&mut self, mut highlights: Vec<Highlight>) {
1653        highlights.retain(|h| h.start < h.end);
1654        highlights.sort_by_key(|h| (h.start, h.end));
1655        self.highlights = highlights;
1656    }
1657
1658    /// The highlight covering source `offset`, if one does — first by start
1659    /// when several overlap, which makes overlapping washes resolvable rather
1660    /// than undefined. What a frontend asks when the reader activates a spot.
1661    ///
1662    /// [`Highlight::covering`] is the whole of it: the frontends paint by
1663    /// asking the same question per glyph, against a slice they were handed
1664    /// rather than against a `Doc`, and one answer for both is what keeps a
1665    /// wash and an activation agreeing about which range a spot is in.
1666    pub fn highlight_at(&self, offset: usize) -> Option<&Highlight> {
1667        Highlight::covering(&self.highlights, offset)
1668    }
1669
1670    /// The AST breadcrumb at the caret (root → deepest), e.g.
1671    /// `doc › para › strong`. Read live from twig via `ancestors_at`.
1672    pub fn breadcrumb(&mut self) -> String {
1673        match self.editor.ancestors_at(self.caret) {
1674            Ok(chain) => chain
1675                .iter()
1676                .map(|m| m.kind.as_str())
1677                .collect::<Vec<_>>()
1678                .join(" › "),
1679            Err(_) => String::new(),
1680        }
1681    }
1682
1683    // ── editing ──────────────────────────────────────────────────────────────
1684
1685    /// Replace the byte range `[start, end)` with `text`, re-anchoring the caret
1686    /// after it. The public form of the internal splice — a pixel frontend that
1687    /// hit-tests to a byte offset (or an IME that hands back an explicit range)
1688    /// edits through this, the same twig `edit_range` the caret ops use.
1689    pub fn edit(&mut self, start: usize, end: usize, text: &str) {
1690        self.splice(start, end, text, EditKind::Other);
1691    }
1692
1693    /// Insert typed `text` at the caret, replacing the selection if there is one.
1694    /// A single typed character coalesces with the run of typing before it; a
1695    /// newline or a multi-character insert is its own undo step.
1696    ///
1697    /// Typed input only — clipboard text goes through [`paste`](Self::paste).
1698    pub fn insert(&mut self, text: &str) {
1699        // The read-only gate, up front: the paths below reach twig by several
1700        // verbs, not all of them through the splice — see the field.
1701        if self.read_only {
1702            return;
1703        }
1704        // Typing against a block picture would dissolve it, and typing past a
1705        // table would grow it a row — see `open_paragraph_at_block_edge`. Give
1706        // the text a paragraph first, so what the caret was standing beside
1707        // stays what it was.
1708        self.open_paragraph_at_block_edge(text);
1709        // Armed sticky marks (⌘b with no selection) turn the next typed text
1710        // bold/italic/… and then retire — see `insert_with_marks`. Whitespace is
1711        // the exception: it takes no mark of its own and keeps the delta armed
1712        // for the character behind it — see `insert_space_with_marks`.
1713        let pending = self.pending_here();
1714        if !pending.is_empty() && self.selection().is_none() && !text.is_empty() {
1715            if text.trim().is_empty() {
1716                self.insert_space_with_marks(self.caret, text, pending);
1717            } else {
1718                self.insert_with_marks(self.caret, text, pending);
1719            }
1720            return;
1721        }
1722        // `MarkupMode::None`: typed syntax stays literal — twig escapes
1723        // anything that would open markup, so a Diaryx user never mints
1724        // formatting by keyboard (it comes from commands instead). The other two
1725        // rungs of the ladder author markup from what you type, which is the
1726        // whole difference between them and this one. Only in the rendered view
1727        // (source view is for typing raw markup) and only where the format has a
1728        // literal spelling at all: escaping is a backslash before a byte from the
1729        // format's own alphabet, and a format with no such alphabet (HTML escapes
1730        // with entities, XML spells nothing) would have `\&` written into it,
1731        // which is two literal characters and not an escape. Marks (⌘b) still
1732        // format — that path returned above; and leaf's own structural inserts go
1733        // through `insert_raw`, never here, so a list marker or quote gutter is
1734        // written as the markup it is.
1735        if !self.markup_mode.authors()
1736            && self.view == View::Wysiwyg
1737            && !text.is_empty()
1738            && self.supports(Gesture::InsertLiteral)
1739        {
1740            self.insert_literal_typed(text);
1741            return;
1742        }
1743        self.insert_raw(text);
1744    }
1745
1746    /// Insert `text` verbatim at the caret (replacing any selection) — the plain
1747    /// path with no Hidden-mode literal escaping. leaf's own structural inserts
1748    /// (a list marker, a quote gutter, an in-cell `<br>`) call this: they ARE
1749    /// markup by design and must not be escaped.
1750    fn insert_raw(&mut self, text: &str) {
1751        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
1752        self.splice(s, e, text, typed_edit_kind(text));
1753    }
1754
1755    /// Open a paragraph for text about to be inserted at one of a block media's
1756    /// two caret stops, or at a table's trailing stop, and leave the caret
1757    /// standing in it.
1758    ///
1759    /// A block image is a paragraph whose entire content is the picture, and the
1760    /// caret's only homes on it are in front of it and just past it (see
1761    /// [`VisualMap::block_media_stop`]). Text inserted at either offset joins
1762    /// *that* paragraph — and a paragraph holding anything besides the image is
1763    /// no longer a block image but a line of text with an inline one in it. The
1764    /// frontend that was painting a photo there paints a text run instead; the
1765    /// picture is still in the file, and nothing said a word. Those two offsets
1766    /// are also exactly where a click on the picture lands, so the whole accident
1767    /// is one tap and one keystroke.
1768    ///
1769    /// So the break goes in first and the text lands in the new empty paragraph —
1770    /// what pressing Return before typing would have done, which is a habit no
1771    /// one should have to learn from losing a photo. A no-op everywhere else, and
1772    /// over a selection (which is replaced, not joined into).
1773    ///
1774    /// A picture inside a quote or a list leaves its container, because `\n\n`
1775    /// ends the block. The alternative is worse: the `\n> ` / next-item
1776    /// continuation [`newline`](Self::newline) writes stays in the same
1777    /// *paragraph*, which is the thing being prevented.
1778    ///
1779    /// A table's trailing stop ([`VisualMap::table_end_stop`]) is the same
1780    /// accident from the other side of a different block: the stop sits at the
1781    /// end of the table's last source line, and a line glued under a table is
1782    /// a row of it — `| 1 | 2 |x` is a three-cell row, not a paragraph. So the
1783    /// break goes in there too, and the text lands under the table.
1784    ///
1785    /// Only in the rendered view. Source view is for typing raw markup, where
1786    /// putting a character against an image is exactly what it looks like.
1787    fn open_paragraph_at_block_edge(&mut self, text: &str) {
1788        if self.view != View::Wysiwyg || text.is_empty() || text == "\n" {
1789            return;
1790        }
1791        if self.selection().is_some() {
1792            return;
1793        }
1794        // The map may be a revision behind (nothing has drawn since the last
1795        // edit), and this asks it about offsets — a stale answer would splice a
1796        // break into the wrong place. Free when it is already current, which it
1797        // is whenever a frontend drew a frame between keystrokes.
1798        self.rebuild_map();
1799        let at = self.caret;
1800        let side = match self.vmap.block_media_stop(at) {
1801            Some((side, _)) => side,
1802            None if self.vmap.table_end_stop(at) => MediaStop::After,
1803            None => return,
1804        };
1805        if !self.splice(at, at, "\n\n", EditKind::Other) {
1806            return;
1807        }
1808        // The break is part of the keystroke, not an edit of its own: leave the
1809        // run marked as typing so the character about to arrive folds into it and
1810        // one undo puts the document back the way it was found. (A paste, or a
1811        // multi-character insert, is `EditKind::Other` and stays its own step —
1812        // as it would have been anywhere else in the document.)
1813        self.last_edit_kind = Some(EditKind::Insert);
1814        if side == MediaStop::Before {
1815            // The break went in above the picture and the caret rode to the end
1816            // of it — which is still hard against the picture. Step back onto the
1817            // blank line it opened, so the text lands above rather than in front.
1818            self.caret = at;
1819        }
1820    }
1821
1822    /// A delete key pressed at one of a block picture's two caret stops, handled
1823    /// as the picture being an *atom* rather than a run of bytes. Returns whether
1824    /// the key was consumed.
1825    ///
1826    /// The caret rests in front of a block image and just past it, never inside
1827    /// its markup — which the rendered view doesn't show. So the byte a delete
1828    /// key nominally takes there is one the writer cannot see, and taking it
1829    /// leaves the picture as broken markup rather than as anything anyone asked
1830    /// for: Backspace at the stop past `![](p.png)` removes the closing paren, and
1831    /// a photo becomes the literal text `![](p.png`. That is how a picture goes
1832    /// missing from a document with nobody having touched it — the same
1833    /// dissolution [`open_paragraph_at_block_edge`](Self::open_paragraph_at_block_edge)
1834    /// prevents from the typing side, and it cost this repository's own test vault
1835    /// a photo before it was found.
1836    ///
1837    /// So the key aimed *at* the picture deletes the picture, whole — Backspace
1838    /// when it is behind the caret, Delete when it is in front — which is what
1839    /// every editor does with an embed, and one undo away. The key aimed *away*
1840    /// from it would otherwise delete the paragraph break and merge a neighbour
1841    /// into the picture's own paragraph, which dissolves it just as surely; it
1842    /// steps the caret over the boundary instead and leaves the
1843    /// next press to delete in the block it has reached — the same "first press
1844    /// steps out of the atom, second press deletes" every delete key here gets,
1845    /// word-deletes included (⌥⌫ in front of a picture is aimed at the prose
1846    /// above, and reaches it on the second press rather than taking the break and
1847    /// the picture with it on the first).
1848    fn delete_around_block_media(&mut self, forward: bool) -> bool {
1849        // The map answers about offsets, so it has to be this revision's — see
1850        // the same call in `open_paragraph_at_block_edge`.
1851        self.rebuild_map();
1852        let Some((side, span)) = self.vmap.block_media_stop(self.caret) else {
1853            return false;
1854        };
1855        let aimed_at_it = side
1856            == if forward {
1857                MediaStop::Before
1858            } else {
1859                MediaStop::After
1860            };
1861        if !aimed_at_it {
1862            let over = if forward {
1863                self.vmap.stop_after(self.caret)
1864            } else {
1865                self.vmap.stop_before(self.caret)
1866            };
1867            if let Some(off) = over.filter(|&o| o >= self.caret_floor()) {
1868                self.caret = off;
1869                self.anchor = None;
1870                self.goal_col = None;
1871            }
1872            return true;
1873        }
1874        // Take the break that held the picture apart from its neighbour with it,
1875        // so the delete doesn't leave a blank paragraph standing where the
1876        // picture was. The last arm is a picture that is the whole document.
1877        let (from, to) = if self.source[..span.start].ends_with("\n\n") {
1878            (span.start - 2, span.end)
1879        } else if self.source[span.end..].starts_with("\n\n") {
1880            (span.start, span.end + 2)
1881        } else {
1882            (span.start, span.end)
1883        };
1884        self.splice(from.max(self.caret_floor()), to, "", EditKind::Other);
1885        true
1886    }
1887
1888    /// The Hidden-mode typing path: replace any selection, then insert `text`
1889    /// escaped so it stays literal. When it replaces a selection the two edits
1890    /// fold into one undo step, so an overwrite undoes atomically (and restores
1891    /// the selection) exactly as a plain one does.
1892    fn insert_literal_typed(&mut self, text: &str) {
1893        let kind = typed_edit_kind(text);
1894        match self.selection() {
1895            Some((s, e)) => {
1896                if !self.splice(s, e, "", EditKind::Other) {
1897                    return;
1898                }
1899                // Typing over a whole marked run takes its delimiters with it
1900                // (the empty content couldn't hold them — see
1901                // `repair_mark_edges`) and leaves its marks armed at the caret.
1902                // The text taking the run's place inherits them, exactly as it
1903                // would have by landing inside a run that survived.
1904                let pending = self.pending_here();
1905                if !pending.is_empty() && !text.trim().is_empty() {
1906                    self.insert_with_marks(self.caret, text, pending);
1907                    return;
1908                }
1909                self.insert_literal_at(self.caret, text, kind, true);
1910            }
1911            None => {
1912                self.insert_literal_at(self.caret, text, kind, false);
1913            }
1914        }
1915    }
1916
1917    /// The sticky-mark delta that is live right now: the marks armed by [`toggle`]
1918    /// at a collapsed caret, but only while the caret still stands where they
1919    /// were armed and nothing is selected. Empty otherwise, so a stale delta
1920    /// never styles text it wasn't meant for.
1921    fn pending_here(&self) -> InlineMarks {
1922        if self.anchor.is_none() && self.pending_at == Some(self.caret) {
1923            self.pending_marks
1924        } else {
1925            InlineMarks::empty()
1926        }
1927    }
1928
1929    /// Drop the armed sticky marks — any caret motion, selection, or edit does
1930    /// this, so "start bold here" only ever applies at the exact spot it was
1931    /// asked for.
1932    fn clear_pending(&mut self) {
1933        self.pending_marks = InlineMarks::empty();
1934        self.pending_at = None;
1935    }
1936
1937    /// Insert `text` at `at` carrying the armed sticky `marks`: a mark not yet in
1938    /// force is wrapped around the freshly typed text; a mark the caret already
1939    /// stands inside is *shed* — the text is inserted past the run's end so it
1940    /// lands unmarked ("type normally again"). The caret comes to rest inside any
1941    /// added runs, so continued typing inherits the marks with no re-wrapping,
1942    /// and the delta is cleared: the marks now live in the document, not here.
1943    fn insert_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
1944        let base = self.mark_spans_at(at);
1945        let base_set: InlineMarks = base.iter().map(|(k, _)| *k).collect();
1946        // Nothing to shed, and a run of exactly these marks standing just behind
1947        // the caret: carry on writing *that* run rather than opening a second
1948        // one beside it.
1949        if base_set.is_empty() && self.rejoin_run(at, text, marks) {
1950            return;
1951        }
1952        // Shed the marks we're turning off: step the insertion point past the
1953        // end of each run the caret sits in, so the new text falls outside it.
1954        let mut ins_at = at;
1955        for (kind, span) in &base {
1956            if marks.contains(*kind) {
1957                ins_at = ins_at.max(span.end);
1958            }
1959        }
1960        if !self.splice_exact(ins_at, ins_at, text, EditKind::Other) {
1961            return;
1962        }
1963        // The plain splice inserted exactly `text` at `ins_at`; that byte range
1964        // is the content every added mark wraps.
1965        let (mut cs, mut ce) = (ins_at, ins_at + text.len());
1966        for kind in marks.iter() {
1967            if !base_set.contains(kind) {
1968                let (ncs, nce) = self.wrap_span(cs, ce, kind);
1969                cs = ncs;
1970                ce = nce;
1971            }
1972        }
1973        self.caret = ce.min(self.source.len());
1974        self.anchor = None;
1975        self.last_edit_kind = None;
1976        // Realised: the marks are in the document now, and the caret sits inside
1977        // them, so there is no delta left to carry. Arm nothing, but remember the
1978        // spot so a *further* toggle before typing starts a clean delta here.
1979        self.pending_marks = InlineMarks::empty();
1980        self.pending_at = Some(self.caret);
1981        self.clamp_caret();
1982        self.record_caret();
1983    }
1984
1985    /// Carry on the marked run just behind `at` — moving its closing delimiters
1986    /// out past the new text — instead of opening a second run of the same marks
1987    /// beside it. Returns whether it did.
1988    ///
1989    /// This is the far half of the mark-edge rule (see [`splice`](Self::splice)).
1990    /// A space typed after a bold word steps the caret out of the run, because
1991    /// `**bold **` is not bold; the next character has to step back *in*, or the
1992    /// writer who typed one bold phrase is left with `**bold** **and**` — two
1993    /// runs that read the same to a reader but spell the file in a way nobody
1994    /// wrote. Only whitespace may stand in the gap (a run doesn't reach across
1995    /// words it isn't marking), and the marks behind it must be exactly the ones
1996    /// armed — a run of *some* other kind is a neighbour, not this phrase.
1997    fn rejoin_run(&mut self, at: usize, text: &str, marks: InlineMarks) -> bool {
1998        if text.is_empty() || text.trim() != text {
1999            return false;
2000        }
2001        let gap_at = self.source[..at].trim_end_matches([' ', '\t']).len();
2002        // Walk in through the delimiters stacked at that point, innermost last:
2003        // `***both*** ` closes two runs with one `***`, and rejoining means
2004        // getting behind all of them.
2005        let (mut cut, mut kinds) = (gap_at, InlineMarks::empty());
2006        while let Some((kind, content_end)) = self
2007            .editor
2008            .ancestors_at(prev_boundary(&self.source, cut))
2009            .unwrap_or_default()
2010            .into_iter()
2011            .filter(|m| m.span.end == cut)
2012            .find_map(|m| Some((inline_kind(&m.kind)?, m.content_span.clone()?.end)))
2013        {
2014            if content_end >= cut {
2015                break; // a mark with no closing delimiter to step behind
2016            }
2017            kinds.insert(kind);
2018            cut = content_end;
2019        }
2020        if cut == gap_at || kinds != marks {
2021            return false;
2022        }
2023        // Re-spell the tail: the gap, then the new text, then the delimiters that
2024        // used to close in front of them — read out of the document rather than
2025        // written from a table, so whatever twig spells them with is what moves.
2026        let tail = format!(
2027            "{}{text}{}",
2028            &self.source[gap_at..at],
2029            &self.source[cut..gap_at]
2030        );
2031        if !self.splice_exact(cut, at, &tail, EditKind::Other) {
2032            return false;
2033        }
2034        self.caret = (cut + (at - gap_at) + text.len()).min(self.source.len());
2035        self.anchor = None;
2036        self.last_edit_kind = None;
2037        self.pending_marks = InlineMarks::empty();
2038        self.pending_at = Some(self.caret);
2039        self.clamp_caret();
2040        self.record_caret();
2041        true
2042    }
2043
2044    /// Insert typed whitespace at a caret with sticky marks armed. Whitespace is
2045    /// never itself wrapped: a mark around a space draws nothing a reader can
2046    /// see, and in Markdown and Djot it draws its own delimiters instead
2047    /// (`** **`). So the space goes in unmarked — outside any run the armed
2048    /// marks are shedding — and the marks stay armed for the character after it,
2049    /// which rejoins the run (see [`rejoin_run`](Self::rejoin_run)).
2050    fn insert_space_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
2051        let base = self.mark_spans_at(at);
2052        // What the *next* character carries: the armed delta resolved against the
2053        // marks in force here, which the space must not quietly drop.
2054        let want = base
2055            .iter()
2056            .map(|(k, _)| *k)
2057            .collect::<InlineMarks>()
2058            .xor(marks);
2059        let mut ins_at = at;
2060        for (kind, span) in &base {
2061            if marks.contains(*kind) {
2062                ins_at = ins_at.max(span.end);
2063            }
2064        }
2065        if !self.splice(ins_at, ins_at, text, typed_edit_kind(text)) {
2066            return;
2067        }
2068        self.rearm(want);
2069        self.record_caret();
2070    }
2071
2072    /// Wrap `[s, e)` in `kind` via twig and return the byte span the *content*
2073    /// (not the delimiters) occupies afterwards. Markdown/Djot inline delimiters
2074    /// are symmetric (`**`…`**`, `_`…`_`, `` ` ``…`` ` ``), so the bytes twig
2075    /// added split evenly around the content — half the growth on each side.
2076    fn wrap_span(&mut self, s: usize, e: usize, kind: InlineKind) -> (usize, usize) {
2077        // The read-only gate — this door reaches twig without the splice.
2078        if self.read_only {
2079            return (s, e);
2080        }
2081        match self.editor.toggle_inline(s, e, kind) {
2082            Ok(change) => {
2083                self.last_edit_kind = None;
2084                self.refresh();
2085                self.dirty = self.source != self.clean_source;
2086                let added = (change.new.end - change.new.start).saturating_sub(e - s);
2087                let half = added / 2;
2088                (change.new.start + half, change.new.end - half)
2089            }
2090            // Unsupported here (e.g. mark on Markdown): leave the text unwrapped
2091            // rather than lose the keystroke.
2092            Err(e2) => {
2093                self.status = Some(format!("{kind:?}: {e2}"));
2094                (s, e)
2095            }
2096        }
2097    }
2098
2099    /// The safe offset to splice a block-level break at, given a caret that may
2100    /// sit exactly between an inline mark's content and its own closing
2101    /// delimiter (`content_span.end == off < span.end` for some enclosing mark
2102    /// — the WYSIWYG caret's natural resting place at the end of `**bold**`
2103    /// with nothing following it on the line: the closing `**` renders no
2104    /// glyph of its own, so the caret's "end of line" offset lands right
2105    /// before it). Splicing a paragraph/list/quote break at `off` itself would
2106    /// sever the delimiter from its content, stranding it alone on the new
2107    /// line. Walks out to the *outermost* such mark's `span.end` instead, so
2108    /// nested marks closing at the same point (`**_x_**`) all clear together.
2109    /// A no-op everywhere else — mid-run, or past real trailing content, no
2110    /// mark's `content_span` ends exactly at `off`.
2111    fn skip_trailing_close_delims(&mut self, off: usize) -> usize {
2112        let off = off.min(self.source.len());
2113        let runs = self.run_span_ids();
2114        self.editor
2115            .ancestors_at(off)
2116            .unwrap_or_default()
2117            .into_iter()
2118            .filter(|m| hides_delims(m, &runs))
2119            .filter(|m| off < m.span.end && m.content_span.as_ref().is_some_and(|c| c.end == off))
2120            .map(|m| m.span.end)
2121            .max()
2122            .unwrap_or(off)
2123    }
2124
2125    /// The offset a *delete* aimed at the character before `off` should stop at,
2126    /// when `off` is the start of a run's text and the bytes behind it are that
2127    /// run's opening delimiter. The rich view draws no glyph for a `**`, so the
2128    /// byte behind the caret at the start of a bold word is not a character the
2129    /// writer can see, let alone one they aimed Backspace at: taking it leaves
2130    /// `a *bold** c` — the styling gone and a literal asterisk in its place. The
2131    /// delete steps over the whole delimiter to the visible character in front of
2132    /// it instead. Walks out to the *outermost* mark opening there, so
2133    /// `**_x_**` clears every delimiter at once, and is a no-op anywhere else.
2134    fn skip_leading_open_delims(&mut self, off: usize) -> usize {
2135        let off = off.min(self.source.len());
2136        let runs = self.run_span_ids();
2137        self.editor
2138            .ancestors_at(off)
2139            .unwrap_or_default()
2140            .into_iter()
2141            .filter(|m| hides_delims(m, &runs))
2142            .filter(|m| {
2143                m.span.start < off && m.content_span.as_ref().is_some_and(|c| c.start == off)
2144            })
2145            .map(|m| m.span.start)
2146            .min()
2147            .unwrap_or(off)
2148    }
2149
2150    /// `off` moved *inside* the run whose closing delimiters end there — the
2151    /// other offset the rich view draws in the same place, since a `**` renders
2152    /// no glyph of its own. `**bold**` has a caret home on each side of its
2153    /// closing delimiter, one column apart on screen and eight bytes and a whole
2154    /// run apart in the file, and a plain ← lands on the outer one whenever a
2155    /// space follows the phrase. The inner one is what the writer is pointing at
2156    /// there: the end of their bold word. Walks in through every mark closing at
2157    /// that point, innermost last, so `***both***` lands inside both. A no-op
2158    /// anywhere else — mid-run, or in prose, no mark's span ends at `off`.
2159    fn step_inside_close_delims(&mut self, off: usize) -> usize {
2160        let mut off = off.min(self.source.len());
2161        let runs = self.run_span_ids();
2162        loop {
2163            let inner = self
2164                .editor
2165                .ancestors_at(prev_boundary(&self.source, off))
2166                .unwrap_or_default()
2167                .into_iter()
2168                .filter(|m| hides_delims(m, &runs) && m.span.end == off)
2169                .filter_map(|m| m.content_span.clone().map(|c| c.end))
2170                .filter(|&end| end < off)
2171                .max();
2172            match inner {
2173                Some(end) => off = end,
2174                None => return off,
2175            }
2176        }
2177    }
2178
2179    /// The mirror at the opening edge: `off` moved inside the run whose
2180    /// delimiters *start* there, onto the first character of its text. See
2181    /// [`step_inside_close_delims`](Self::step_inside_close_delims).
2182    fn step_inside_open_delims(&mut self, off: usize) -> usize {
2183        let mut off = off.min(self.source.len());
2184        let runs = self.run_span_ids();
2185        loop {
2186            let inner = self
2187                .editor
2188                .ancestors_at(off)
2189                .unwrap_or_default()
2190                .into_iter()
2191                .filter(|m| hides_delims(m, &runs) && m.span.start == off)
2192                .filter_map(|m| m.content_span.clone().map(|c| c.start))
2193                .filter(|&start| start > off)
2194                .min();
2195            match inner {
2196                Some(start) => off = start,
2197                None => return off,
2198            }
2199        }
2200    }
2201
2202    /// The ids of the document's attributed run spans — the inline
2203    /// `Container`s [`wysiwyg::is_run_span`] picks out — for [`hides_delims`],
2204    /// which sees an ancestor chain and so only a kind. Read once per gesture,
2205    /// not once per step of a walk.
2206    fn run_span_ids(&mut self) -> Vec<NodeId> {
2207        self.nodes()
2208            .iter()
2209            .filter(|n| wysiwyg::is_run_span(n))
2210            .map(|n| n.id)
2211            .collect()
2212    }
2213
2214    /// The attributed span whose text is exactly `content` — the whole of
2215    /// `<span …>i</span>`'s `i`, or nothing at all when `content` is empty
2216    /// and sits between the tags of `<span …></span>` — as the whole range
2217    /// spelling the span: the node's span, widened to its attribute block
2218    /// where the format writes that outside the node, as djot's
2219    /// `[i]{data-size="large"}` does. `None` for any other range, including
2220    /// part of a span's text.
2221    ///
2222    /// An empty span has an interior of no bytes, or no known interior at
2223    /// all: twig gives Markdown's `<span …></span>` the first and djot's
2224    /// `[]{…}` the second, and the chain already says the offset is inside.
2225    fn run_span_of_content(&mut self, content: Range<usize>) -> Option<Range<usize>> {
2226        let runs = self.run_span_ids();
2227        let m = self
2228            .editor
2229            .ancestors_at(content.start)
2230            .unwrap_or_default()
2231            .into_iter()
2232            .filter(|m| runs.contains(&NodeId(m.node_id)))
2233            .find(|m| match &m.content_span {
2234                Some(c) => *c == content,
2235                None => content.is_empty(),
2236            })?;
2237        let mut range = m.span;
2238        if let Some(attrs) = self
2239            .editor
2240            .document()
2241            .ok()
2242            .and_then(|mut d| d.attrs_span(NodeId(m.node_id)).ok().flatten())
2243        {
2244            range.start = range.start.min(attrs.start);
2245            range.end = range.end.max(attrs.end);
2246        }
2247        Some(range)
2248    }
2249
2250    /// The attributed block whose whole text is exactly `content` — the `T`
2251    /// of Markdown's `<div class="center">\n\nT\n\n</div>` or djot's
2252    /// `{.center}\nT` — as the range a delete that takes that text takes with
2253    /// it: the whole `<div>` when the block is all the div holds, or the
2254    /// `{…}` line down to the end of the text. The block version of
2255    /// [`run_span_of_content`](Self::run_span_of_content), for the same
2256    /// reason: a paragraph with no text is no block, so the div would stand
2257    /// around nothing and the `{…}` line above nothing, and a from-scratch
2258    /// map gives neither a caret home — the `T`'s row is gone with the `T`.
2259    /// `None` for a block with more text, a div holding more, a heading (an
2260    /// empty `# ` is still a heading), and a format whose attributes are the
2261    /// block's own tag (HTML's `<p class="center"></p>` is still a
2262    /// paragraph).
2263    fn attributed_block_of_content(&mut self, content: Range<usize>) -> Option<Range<usize>> {
2264        if content.is_empty() || !matches!(self.format, Format::Markdown | Format::Djot) {
2265            return None;
2266        }
2267        let nodes = self.nodes();
2268        let block = nodes
2269            .iter()
2270            .filter(|n| n.kind == Kind::Para)
2271            .find(|n| n.content_span.as_ref() == Some(&content))?;
2272        match self.format {
2273            Format::Djot => {
2274                let attrs = self
2275                    .editor
2276                    .document()
2277                    .ok()
2278                    .and_then(|mut d| d.attrs_span(block.id).ok().flatten())?;
2279                (attrs.end <= block.span.start).then_some(attrs.start..content.end)
2280            }
2281            _ => {
2282                let div = block
2283                    .parent
2284                    .and_then(|p| nodes.iter().find(|n| n.id == p))
2285                    .filter(|p| wysiwyg::element_tag(p) == Some("div"))?;
2286                let alone = nodes.iter().filter(|n| n.parent == Some(div.id)).count() == 1;
2287                alone.then(|| div.span.clone())
2288            }
2289        }
2290    }
2291
2292    /// The inline mark kinds whose span covers `off`, each with that span — the
2293    /// span-carrying sibling of [`marks_at`](Self::marks_at), which reports node
2294    /// ids instead. Used to shed a mark by stepping past the end of its run.
2295    fn mark_spans_at(&mut self, off: usize) -> Vec<(InlineKind, std::ops::Range<usize>)> {
2296        let off = off.min(self.source.len());
2297        self.editor
2298            .ancestors_at(off)
2299            .unwrap_or_default()
2300            .into_iter()
2301            .filter(|m| off < m.span.end)
2302            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.span.clone())))
2303            .collect()
2304    }
2305
2306    /// Insert clipboard `text` at the caret, replacing the selection if there is
2307    /// one — always its own undo step, whatever its length.
2308    ///
2309    /// Provenance is the whole point, and only the caller has it. `insert` reads
2310    /// a lone character as a keystroke and folds it into the run around it,
2311    /// which is right for typing and wrong for a one-character paste: that paste
2312    /// would vanish mid-run on an undo it was never part of, and the characters
2313    /// the user actually typed would go with it. Length can't tell the two
2314    /// apart — `⌘V` of `x` and typing `x` are the same string — so the door the
2315    /// caller comes through is what says which happened.
2316    pub fn paste(&mut self, text: &str) {
2317        // Pasting against a block picture or a table's end joins the block
2318        // exactly as typing does, and for the same reason — see
2319        // `open_paragraph_at_block_edge`.
2320        self.open_paragraph_at_block_edge(text);
2321        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2322        self.splice(s, e, text, EditKind::Other);
2323    }
2324
2325    /// Replace `[start, end)` with `text` as one step of an IME composition —
2326    /// the same splice as [`edit`](Self::edit), but marked so the run of steps
2327    /// folds into a single undo.
2328    ///
2329    /// A composition is *one* act of writing. Typing `かんじ` and picking 感じ is a
2330    /// dozen calls here, each replacing the last one's provisional bytes, and an
2331    /// undo step per call means undoing a word means pressing ⌘Z until the reading
2332    /// unspools backwards through kana — the intermediate states were never text
2333    /// the user wrote. Only the frontend knows a call is provisional (the bytes
2334    /// look like any other edit), so the door the caller comes through is what
2335    /// says so, exactly as it is for [`paste`](Self::paste) versus
2336    /// [`insert`](Self::insert).
2337    ///
2338    /// Pair with [`end_composition`](Self::end_composition), or the *next*
2339    /// composition folds into this one.
2340    pub fn edit_composing(&mut self, start: usize, end: usize, text: &str) {
2341        self.splice(start, end, text, EditKind::Compose);
2342    }
2343
2344    /// Close the open composition run, so the next one is its own undo step.
2345    /// Call when the IME commits or withdraws a composition.
2346    ///
2347    /// Only clears a *composition* run: a frontend that reports an end it never
2348    /// began (some IMEs unmark unprompted) would otherwise split the run of
2349    /// typing around it into two undo steps for no reason the user can see.
2350    pub fn end_composition(&mut self) {
2351        if self.last_edit_kind == Some(EditKind::Compose) {
2352            self.last_edit_kind = None;
2353        }
2354    }
2355
2356    // ── the clipboard's rich flavor ──────────────────────────────────────────
2357
2358    /// The selection rendered as HTML, for the clipboard's `text/html` flavor —
2359    /// what lets a paste into Docs/Mail/Slack keep its formatting. `None` when
2360    /// nothing is selected, or when the selection doesn't render (the caller
2361    /// still has [`selected_text`](Self::selected_text), which is what to publish
2362    /// as `text/plain` either way).
2363    ///
2364    /// **The fragment is a source substring, and that is the honest limit here.**
2365    /// It's parsed standalone, so a selection whose meaning depends on its
2366    /// surroundings converts as what it literally says rather than what it looks
2367    /// like on screen: half a list item is a paragraph, a row torn out of a table
2368    /// is the text of a row, the `**` of a bold run selected without its closing
2369    /// `**` is two asterisks. Every one of those still *renders* — there's no
2370    /// error to report — it just renders as the fragment and not as the document.
2371    /// Widening the range to whole blocks would publish text the user didn't
2372    /// select, which is a worse lie than a fragment being a fragment; the plain
2373    /// flavor has the same substring, so the two flavors at least agree.
2374    pub fn selection_html(&mut self) -> Option<String> {
2375        let (start, end) = self.selection()?;
2376        let inline = self.selection_is_inline(start, end);
2377        let html = html::render_fragment(&self.source[start..end], self.format)?;
2378        Some(match inline {
2379            true => html::strip_sole_paragraph(html),
2380            false => html,
2381        })
2382    }
2383
2384    /// Paste the clipboard's `text/html` flavor, converting it to this document's
2385    /// format first. Its own undo step, like any [`paste`](Self::paste).
2386    ///
2387    /// Returns whether it landed. `false` means the HTML didn't convert to
2388    /// anything worth pasting — the caller should fall back to the plain flavor
2389    /// rather than treat it as an error. The `html` module has the full list of
2390    /// what that covers: a table twig won't build, markup it doesn't recognise,
2391    /// an empty result.
2392    pub fn paste_html(&mut self, html: &str) -> bool {
2393        match html::parse_fragment(html, self.format) {
2394            Some(source) => {
2395                self.paste(&source);
2396                true
2397            }
2398            None => false,
2399        }
2400    }
2401
2402    /// Does the selection live *inside* a single top-level block?
2403    ///
2404    /// The question [`selection_html`](Self::selection_html) needs and the
2405    /// fragment can't answer: `**bold**` renders as `<p><strong>bold</strong></p>`
2406    /// whether the user selected one word of a sentence or a whole paragraph, and
2407    /// only the document knows which. Selecting a word and pasting into Docs
2408    /// should extend the line you paste into; selecting the paragraph should make
2409    /// a paragraph. So a selection strictly within one block is inline (its `<p>`
2410    /// is an artifact of standalone parsing), and one that covers a whole block —
2411    /// or spans two — keeps its structure.
2412    ///
2413    /// Reads the block from twig rather than guessing from the bytes:
2414    /// `ancestors_at` is `[doc, block, …inline]`, so index 1 is the top-level
2415    /// block containing an offset, and two ends inside the same one cannot have
2416    /// crossed a block boundary.
2417    fn selection_is_inline(&mut self, start: usize, end: usize) -> bool {
2418        // The last *character*, not `end - 1`: the selection's end is exclusive
2419        // and may sit mid-codepoint's-worth of bytes past the last char.
2420        let Some((off, _)) = self.source[start..end].char_indices().next_back() else {
2421            return false;
2422        };
2423        let (Some(head), Some(tail)) =
2424            (self.top_block_span(start), self.top_block_span(start + off))
2425        else {
2426            return false;
2427        };
2428        head == tail && !(start <= head.start && end >= head.end)
2429    }
2430
2431    /// The byte span of the top-level block containing `offset`, or `None` at an
2432    /// offset that belongs to no block (the blank line between two of them).
2433    fn top_block_span(&mut self, offset: usize) -> Option<std::ops::Range<usize>> {
2434        self.editor
2435            .ancestors_at(offset)
2436            .ok()?
2437            .get(1)
2438            .map(|m| m.span.clone())
2439    }
2440
2441    // ── indentation ──────────────────────────────────────────────────────────
2442
2443    /// One indent level.
2444    ///
2445    /// Two spaces, not the four both frontends type for Tab today, because in a
2446    /// markdown document four columns isn't a width — it's a *meaning*. Four
2447    /// spaces at the head of a line is markdown's indented-code-block marker, so
2448    /// one Tab on a paragraph would reparse it into code and style it as such;
2449    /// two cannot, and the line stays the prose it was. Two is also exactly
2450    /// where a `- ` bullet's content starts, so an indented line lands under its
2451    /// parent item's text instead of beside it — the column a list-aware indent
2452    /// has to hit anyway, which keeps this width from being relitigated later.
2453    const INDENT: &'static str = "  ";
2454
2455    /// Indent the selected lines — or the caret's line, with no selection — by
2456    /// one level (Tab).
2457    pub fn indent(&mut self) {
2458        self.reindent(true);
2459        // Nesting changes an ordered list's numbering (the nested item restarts,
2460        // its old siblings resume) — keep the source markers in step.
2461        self.renumber_here();
2462        // Nesting an empty `-` item under a text line reparses that text as a
2463        // setext heading; swap the dash for a `*` before it can (a no-op unless
2464        // the collapse actually happened).
2465        self.avoid_setext_collapse();
2466    }
2467
2468    /// Take one indent level back off the selected lines, or the caret's line
2469    /// (Shift+Tab). A line with no indentation is left exactly as it is.
2470    ///
2471    /// A line with *less* than a full level gives back what it has rather than
2472    /// refusing: outdent's job is to walk a line left, and real documents — hand
2473    /// written, or reflowed by some other editor — are full of indentation that
2474    /// was never a clean multiple of anything. Refusing there would strand the
2475    /// line at a depth Shift+Tab couldn't undo.
2476    pub fn outdent(&mut self) {
2477        self.reindent(false);
2478        self.renumber_here();
2479    }
2480
2481    /// The body of [`indent`](Self::indent) / [`outdent`](Self::outdent).
2482    ///
2483    /// One splice across the whole line range, never one per line: a Tab is one
2484    /// thing the user did, so it has to be one undo step and one reparse. Per
2485    /// line, twig would reparse the document once per line and leave a stack of
2486    /// steps that Shift+⌘Z walks back one line at a time.
2487    fn reindent(&mut self, add: bool) {
2488        let (sel_start, sel_end) = self.selection().unwrap_or((self.caret, self.caret));
2489        let start = source_line_range(&self.source, sel_start).start;
2490        let end = source_line_range(&self.source, sel_end).end;
2491        let region = self.source[start..end].to_string();
2492        let lines: Vec<&str> = region.split('\n').collect();
2493        // A blank line has no text to move, and padding it would leave nothing
2494        // but trailing whitespace — but Tab on a blank line *is* a request for
2495        // indentation to type into, so the skip only applies where the op has
2496        // other lines to do real work on.
2497        let skip_blank = add && lines.len() > 1;
2498
2499        let mut out = String::with_capacity(region.len() + lines.len() * Self::INDENT.len());
2500        let mut deltas: Vec<isize> = Vec::with_capacity(lines.len());
2501        let mut line_off = start;
2502        for (i, full) in lines.iter().enumerate() {
2503            if i > 0 {
2504                out.push('\n');
2505            }
2506            // A list item moves by having its whole leading prefix *replaced*,
2507            // never by having spaces pushed in front of the line. twig spells
2508            // both prefixes, so the quote markers, the parent's indent and an
2509            // ordered marker's extra column all come out right without leaf
2510            // measuring any of them — and a line that only looks like an item
2511            // (a Djot continuation) reports no marker and is left to the plain
2512            // path, where a Tab is just a Tab.
2513            let marker = self.list_marker_on_line(line_off);
2514            let own = marker
2515                .as_ref()
2516                .map(|m| m.marker_start - m.line_start)
2517                .unwrap_or(0);
2518            let delta = if add {
2519                if skip_blank && full.trim().is_empty() {
2520                    out.push_str(full);
2521                    0
2522                } else if marker.is_some() && self.first_item_of_list(line_off) {
2523                    // The first item of a list has no preceding sibling to nest
2524                    // under, so a Tab here can't spell a sub-list — twig would
2525                    // reparse the shoved-over marker as the same list, only
2526                    // indented, which Shift+Tab then can't cleanly undo. Leave the
2527                    // item where it is, the way every list editor refuses to
2528                    // over-indent a list's first line.
2529                    out.push_str(full);
2530                    0
2531                } else if marker.is_some() {
2532                    // Nesting means standing where a *continuation* of this line
2533                    // would stand: past the parent's marker, inside its content
2534                    // column. That is `continuation_prefix`, less a checkbox.
2535                    let new = self.nesting_prefix_at(line_off);
2536                    let delta = new.len() as isize - own as isize;
2537                    out.push_str(&new);
2538                    out.push_str(&full[own..]);
2539                    delta
2540                } else {
2541                    out.push_str(Self::INDENT);
2542                    out.push_str(full);
2543                    Self::INDENT.len() as isize
2544                }
2545            } else if marker.is_some() {
2546                // Unnesting is the mirror: stand where the parent item's own
2547                // line starts, which drops exactly the level it contributed.
2548                let new = self.outdent_prefix_at(line_off);
2549                let delta = new.len() as isize - own as isize;
2550                out.push_str(&new);
2551                out.push_str(&full[own..]);
2552                delta
2553            } else {
2554                // A plain line gives back the ordinary step.
2555                let strip = outdent_width(full, Self::INDENT.len());
2556                out.push_str(&full[strip..]);
2557                -(strip as isize)
2558            };
2559            deltas.push(delta);
2560            line_off += full.len() + 1;
2561        }
2562        // Nothing to give back. Returning before the splice keeps an outdent at
2563        // column zero from spending an undo step on a document it never changed.
2564        if deltas.iter().all(|d| *d == 0) {
2565            return;
2566        }
2567
2568        // Every line's text keeps its offset *within the line*, so the caret is
2569        // remapped by its column, not by its byte offset — which the prefixes on
2570        // the lines above it have already invalidated.
2571        let remap = |off: usize| -> usize {
2572            let (mut old_ls, mut new_ls) = (start, start);
2573            for (line, delta) in lines.iter().zip(&deltas) {
2574                let old_le = old_ls + line.len();
2575                let new_len = (line.len() as isize + delta) as usize;
2576                if off <= old_le {
2577                    let col = (off - old_ls) as isize;
2578                    return new_ls + ((col + delta).max(0) as usize).min(new_len);
2579                }
2580                old_ls = old_le + 1;
2581                new_ls += new_len + 1;
2582            }
2583            start + out.len()
2584        };
2585        let placed = match self.selection() {
2586            // Keep the rewritten region selected, the way a container toggle
2587            // keeps its own: it leaves a second Tab aimed at the same lines
2588            // rather than at whatever the shifted offsets now happen to cover.
2589            Some(_) => (start + out.len(), Some(start)),
2590            None => (remap(self.caret), None),
2591        };
2592
2593        // A rolled-back splice leaves the old source in place, where every offset
2594        // computed above addresses text that was never written.
2595        if !self.splice(start, end, &out, EditKind::Other) {
2596            return;
2597        }
2598        // `splice` re-anchors to the end of the `Change`, which for a whole-region
2599        // rewrite is the last line's end — nowhere the caret was. Place it, then
2600        // re-record the caret so this is the state redo restores, not the one
2601        // `splice` left behind from the `Change`.
2602        self.caret = placed.0.min(self.source.len());
2603        self.anchor = placed.1;
2604        self.clamp_caret();
2605        self.record_caret();
2606    }
2607
2608    /// The Enter key.
2609    ///
2610    /// In source view it's a literal newline. In WYSIWYG it's **AST-aware**: a
2611    /// bare `\n` is only a markdown soft break (same paragraph), so the block the
2612    /// caret is in decides what actually gets written.
2613    ///
2614    ///   - paragraph            → twig's [`Editor::split_block`], which parts the
2615    ///                            block at the caret and reopens its container
2616    ///   - list item            → likewise: the next item, its indent, quote
2617    ///                            prefix and `[ ]` box all reproduced by twig —
2618    ///                            except an *empty* item, which exits the list
2619    ///   - block quote          → likewise: a new paragraph inside the quote
2620    ///   - heading              → a new *paragraph*, not another heading
2621    ///   - code block           → a literal newline (stay in the block)
2622    ///   - blank line           → a literal newline (one Backspace undoes it)
2623    ///   - [`LineFlow::Preserve`] → a single soft break, which renders as a
2624    ///                            visible line
2625    ///
2626    /// Where `split_block` is used it replaces markup leaf used to spell by hand,
2627    /// and it is better at it: it drops the whitespace the caret was sitting in
2628    /// front of instead of stranding it at the head of the second half, and it
2629    /// knows continuations leaf's marker scan never covered — a checklist item
2630    /// continues as an *unchecked* checklist item rather than a plain bullet.
2631    ///
2632    /// The exceptions above are exceptions because `split_block` is either wrong
2633    /// there or refuses: parting a fence yields two fences with the code split
2634    /// between them, parting a heading yields a second heading where every editor
2635    /// gives a paragraph, and a blank line, an empty item, a setext heading and a
2636    /// table all report an error rather than a split.
2637    pub fn newline(&mut self) {
2638        if self.view == View::Source {
2639            self.insert_raw("\n");
2640            return;
2641        }
2642        // Enter over a selection replaces it with a paragraph break.
2643        if let Some((s, e)) = self.selection() {
2644            self.splice(s, e, "\n\n", EditKind::Other);
2645            return;
2646        }
2647        // A caret resting exactly between an inline mark's content and its own
2648        // closing delimiter (`**bold**` with nothing after it on the line —
2649        // the WYSIWYG caret's natural end-of-line position) must not splice a
2650        // block break there: every path below eventually does via
2651        // `insert_raw`/`self.caret`, and splicing before the hidden closing
2652        // delimiter would strand it alone on the new line.
2653        self.caret = self.skip_trailing_close_delims(self.caret);
2654        // The block the caret is in. `block_offset_for_caret` nudges off a line
2655        // end (where the caret sits at the doc level); on a bare line (e.g. an
2656        // empty list item) fall back to the caret so the enclosing list/quote is
2657        // still visible in the ancestors.
2658        let off = self.block_offset_for_caret().unwrap_or(self.caret);
2659        let kinds: Vec<Kind> = self
2660            .editor
2661            .ancestors_at(off)
2662            .map(|c| c.into_iter().map(|m| m.kind).collect())
2663            .unwrap_or_default();
2664        let has = |k: Kind| kinds.contains(&k);
2665
2666        if has(Kind::CodeBlock) {
2667            self.insert_raw("\n");
2668            return;
2669        }
2670        // An *empty* list item exits the list — the standard double-Enter — which
2671        // `split_block` reports as an error rather than a split (there is no
2672        // content to part), so it stays leaf's. `list_marker_on_line` is itself
2673        // the AST gate — it answers from the tree, so a `- ` that reads as a
2674        // marker byte-for-byte but opens no item (a setext underline, a Djot
2675        // continuation line) never reaches here.
2676        if let Some(marker) = self.list_marker_on_line(self.caret)
2677            && self.item_is_empty(&marker)
2678        {
2679            self.exit_list(&marker);
2680            return;
2681        }
2682        // On an *empty* paragraph line, a lone Enter should add a single blank line,
2683        // not another full paragraph break — so it moves down one line and one
2684        // Backspace undoes it, not two. (`split_block` errors here too.)
2685        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
2686        let line_end = self.source[self.caret..]
2687            .find('\n')
2688            .map_or(self.source.len(), |i| self.caret + i);
2689        if self.source[line_start..line_end].trim().is_empty() {
2690            self.insert_raw("\n");
2691            return;
2692        }
2693        // In `Preserve` flow a soft break is a *visible* line the author means to
2694        // make, so Enter writes a single `\n` and typing continues the same
2695        // paragraph on the next line — the behaviour of an ordinary text editor.
2696        // A second Enter then lands on the blank line above and takes the
2697        // empty-line branch, so double-Enter still promotes to a full paragraph
2698        // break; and Backspace, which deletes a lone `\n` over a soft break,
2699        // undoes a single Enter symmetrically. In `Fold` flow a lone `\n` would
2700        // render as an invisible space, so Enter keeps making the paragraph break
2701        // that actually shows.
2702        //
2703        // Only in running prose. A list or a quote has a continuation of its own
2704        // to write, and a `\n` there is not a soft line but a lost container.
2705        let in_container = has(Kind::ListItem) || has(Kind::TaskListItem) || has(Kind::BlockQuote);
2706        if self.line_flow == LineFlow::Preserve && !in_container {
2707            self.insert_raw("\n");
2708            return;
2709        }
2710        // A heading gets a *paragraph*, never a second heading: Enter at the end
2711        // of a title is how every editor is asked for the body under it, and
2712        // `split_block` would repeat the `#` instead. Whitespace at the split
2713        // point goes with the break rather than opening the new paragraph, which
2714        // is what `split_block` does everywhere else.
2715        if has(Kind::Heading) {
2716            let mut end = self.caret;
2717            while self.source.as_bytes().get(end) == Some(&b' ') {
2718                end += 1;
2719            }
2720            self.splice(self.caret, end, "\n\n", EditKind::Other);
2721            return;
2722        }
2723        self.split_block_here();
2724    }
2725
2726    /// Part the block at the caret with twig's [`Editor::split_block`], leaving
2727    /// the caret in the second half.
2728    ///
2729    /// twig reopens whatever the first half was inside of — the bullet with its
2730    /// indent, the quote's `>`, a checklist item's `[ ]` — which is the whole
2731    /// reason this replaced the markup leaf used to spell from the line's bytes.
2732    /// It renumbers nothing, though: a new item mid-list is written with its
2733    /// neighbour's number, so [`renumber_here`](Self::renumber_here) still runs
2734    /// behind it, folded into the same undo step.
2735    ///
2736    /// Falls back to a plain paragraph break if twig declines, so an unhandled
2737    /// shape still moves the caret down rather than swallowing the keystroke.
2738    fn split_block_here(&mut self) {
2739        // The read-only gate — this door reaches twig without the splice.
2740        if self.read_only {
2741            return;
2742        }
2743        match self.editor.split_block(self.caret) {
2744            Ok(change) => {
2745                self.last_edit_kind = None;
2746                self.refresh();
2747                self.anchor = None;
2748                self.caret = change.new.end;
2749                self.dirty = self.source != self.clean_source;
2750                self.status = None;
2751                self.clamp_caret();
2752                self.record_caret();
2753                // Aimed at the new block's *start*: the caret twig leaves is one
2754                // past the marker it wrote, where there is no list in reach.
2755                self.renumber_at(change.new.start);
2756            }
2757            Err(_) => self.insert_raw("\n\n"),
2758        }
2759    }
2760
2761    /// Whether the item on the marker's line carries no content — the shape
2762    /// double-Enter reads as "I'm done with this list."
2763    fn item_is_empty(&self, line: &ListMarker) -> bool {
2764        let content_start = line.content_start().min(self.source.len());
2765        let line_end = self.source[self.caret..]
2766            .find('\n')
2767            .map(|i| self.caret + i)
2768            .unwrap_or(self.source.len());
2769        self.source[content_start..line_end.max(content_start)]
2770            .trim()
2771            .is_empty()
2772    }
2773
2774    /// Leave the list: replace the empty item's marker with a blank line, so the
2775    /// caret lands in a fresh paragraph below it.
2776    ///
2777    /// Inside a quote the blank line has to stay quoted (a bare one would end the
2778    /// quote), and the caret's new line keeps the `> ` it was already behind —
2779    /// leaving the list without also leaving the quote.
2780    fn exit_list(&mut self, line: &ListMarker) {
2781        let prefix = self.quote_prefix_at(line.marker_start);
2782        let blank = prefix.trim_end();
2783        self.splice(
2784            line.line_start,
2785            self.caret,
2786            &format!("{blank}\n{prefix}"),
2787            EditKind::Other,
2788        );
2789    }
2790
2791    /// What a line continuing the containers at `off` has to open with — the
2792    /// quote markers reproduced, each enclosing item's marker as its width in
2793    /// spaces. Also the column a nested item's marker stands in, which is what
2794    /// makes it Tab's answer.
2795    fn continuation_prefix_at(&mut self, off: usize) -> String {
2796        self.editor
2797            .document()
2798            .and_then(|mut d| d.continuation_prefix(off))
2799            .map(|p| p.text)
2800            .unwrap_or_default()
2801    }
2802
2803    /// The column a *nested list* may open at inside the item at `off` — which
2804    /// is not always where the item's own text continues.
2805    ///
2806    /// twig counts a task item's `[ ] ` box as part of its marker, correctly:
2807    /// it is markup a rich view hides, and the item's own wrapped text does
2808    /// stand past it. But a nested list may only open at the *list* marker's
2809    /// column, and four columns further in is an indented continuation of the
2810    /// paragraph instead — `- [ ] a` + `      - [ ] b` is one item, not two.
2811    /// So the box's own width goes back.
2812    ///
2813    /// The one place leaf still reads a checkbox's spelling. It goes when twig
2814    /// reports the list marker's column apart from the box; `checked` is what
2815    /// says a box is there at all, so only its width is being measured here.
2816    fn nesting_prefix_at(&mut self, off: usize) -> String {
2817        let cont = self.continuation_prefix_at(off);
2818        let Some(item) = self.innermost_list_item(off) else {
2819            return cont;
2820        };
2821        if item.checked.is_none() {
2822            return cont;
2823        }
2824        let box_width = item
2825            .marker_span
2826            .and_then(|m| self.source.get(m))
2827            .and_then(|marker| marker.rfind('[').map(|i| marker.len() - i))
2828            .unwrap_or(0);
2829        // The trailing columns are the ones the item's own marker contributed,
2830        // so trimming from the end leaves any quote prefix standing.
2831        cont[..cont.len().saturating_sub(box_width)].to_string()
2832    }
2833
2834    /// Where the line of the item *containing* the item at `off` begins — the
2835    /// prefix Shift+Tab moves back to, which gives up exactly the level the
2836    /// parent contributed. The quote prefix alone for a top-level item, which
2837    /// has no level left to give.
2838    fn outdent_prefix_at(&mut self, off: usize) -> String {
2839        let items: Vec<usize> = self
2840            .editor
2841            .document()
2842            .and_then(|mut d| d.ancestors_at_caret(off))
2843            .map(|c| {
2844                c.into_iter()
2845                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2846                    .map(|m| m.span.start)
2847                    .collect()
2848            })
2849            .unwrap_or_default();
2850        // The second-innermost item is the parent; its own line's indent is the
2851        // target. `list_marker_on_line` gives that line's prefix directly.
2852        let parent = items.len().checked_sub(2).map(|i| items[i]);
2853        match parent.and_then(|p| self.list_marker_on_line(p)) {
2854            Some(m) => self.source[m.line_start..m.marker_start].to_string(),
2855            None => self.quote_prefix_at(off),
2856        }
2857    }
2858
2859    /// The block-quote prefix in force at `off` — `""` outside a quote, `"> "`
2860    /// inside one, `"> > "` inside two.
2861    ///
2862    /// Assembled from each enclosing quote's own [`FlatNode::marker_span`], so
2863    /// the `>` and the space after it are twig's spelling rather than leaf's.
2864    /// The whole line prefix can't answer this: it also carries the indent of
2865    /// whatever the quote holds, which a blank separator line must *not* repeat.
2866    fn quote_prefix_at(&mut self, off: usize) -> String {
2867        let Ok(chain) = self
2868            .editor
2869            .document()
2870            .and_then(|mut d| d.ancestors_at_caret(off))
2871        else {
2872            return String::new();
2873        };
2874        let quotes: Vec<usize> = chain
2875            .iter()
2876            .filter(|m| m.kind == Kind::BlockQuote)
2877            .map(|m| m.node_id as usize)
2878            .collect();
2879        let Ok(nodes) = self.editor.nodes() else {
2880            return String::new();
2881        };
2882        quotes
2883            .iter()
2884            .filter_map(|id| nodes.get(*id)?.marker_span.clone())
2885            .filter_map(|s| self.source.get(s))
2886            .collect()
2887    }
2888
2889    /// Whether the item at `off` sits inside another one — the test Backspace
2890    /// uses to choose between outdenting and dropping the marker.
2891    ///
2892    /// Counted from the AST rather than from the line's leading whitespace,
2893    /// which is indentation in Markdown and, in Djot, may be nothing at all.
2894    fn item_is_nested(&mut self, off: usize) -> bool {
2895        self.editor
2896            .document()
2897            .and_then(|mut d| d.ancestors_at_caret(off))
2898            .map(|c| {
2899                c.into_iter()
2900                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2901                    .count()
2902                    > 1
2903            })
2904            .unwrap_or(false)
2905    }
2906
2907    /// The innermost list item containing `probe`, under twig's **caret**
2908    /// containment rule — a block's end is inside it.
2909    ///
2910    /// Half-open containment can't answer this. An empty item's span is exactly
2911    /// its marker, so the caret sitting after `- ` is one past the end and the
2912    /// item it is plainly in tests as out of reach; that is the shape
2913    /// double-Enter has to recognise to leave the list.
2914    fn innermost_list_item(&mut self, probe: usize) -> Option<FlatNode> {
2915        let chain = self
2916            .editor
2917            .document()
2918            .and_then(|mut d| d.ancestors_at_caret(probe))
2919            .ok()?;
2920        let id = chain
2921            .iter()
2922            .rev()
2923            .find(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)?
2924            .node_id as usize;
2925        self.editor.nodes().ok()?.get(id).cloned()
2926    }
2927
2928    /// The list marker opening `off`'s line, per twig — `None` when that line
2929    /// opens no list item.
2930    ///
2931    /// [`Document::line_prefix`] is the whole hidden run from the line start:
2932    /// `>   1. ` is a quote's marker, an indent, and an item's marker together,
2933    /// and it is `None` on a *continuation* line, which opens nothing. That last
2934    /// case is the one leaf could never get right by reading bytes. `- a\n  - b`
2935    /// is two items in Markdown and one in Djot, where a marker cannot interrupt
2936    /// a paragraph and `  - b` is literal text — identical bytes, and only the
2937    /// parser knows which document it is looking at.
2938    ///
2939    /// The item's own marker is separated out via its
2940    /// [`FlatNode::marker_span`], so `marker_start` splits the prefix into what
2941    /// the containers around it contribute and what the item does.
2942    fn list_marker_on_line(&mut self, off: usize) -> Option<ListMarker> {
2943        let off = off.min(self.source.len());
2944        let prefix = self.editor.document().ok()?.line_prefix(off).ok()??;
2945        // The prefix belongs to a list only when an item's marker closes it —
2946        // a heading's `# ` or a bare quote's `> ` is a prefix too.
2947        let item = self.innermost_list_item(prefix.end.min(self.source.len()))?;
2948        let marker = item.marker_span.clone()?;
2949        if marker.end != prefix.end {
2950            return None;
2951        }
2952        Some(ListMarker {
2953            line_start: prefix.start,
2954            marker_start: marker.start,
2955            text: self.source.get(prefix)?.to_string(),
2956        })
2957    }
2958
2959    /// Whether the list item on `line_start`'s line is the **first item** of its
2960    /// list — the one Tab must not nest, because nesting needs a preceding
2961    /// sibling to become the new parent and a first item has none. `false` for a
2962    /// line that isn't a list item, and for an item with a sibling above it (the
2963    /// one Tab *can* nest). Gated on the AST, not the marker bytes: `- ` reads
2964    /// the same in a setext underline that opens no list at all.
2965    fn first_item_of_list(&mut self, line_start: usize) -> bool {
2966        let Some(marker) = self.list_marker_on_line(line_start) else {
2967            return false;
2968        };
2969        // Probe just inside the marker, where the item's own node is in reach —
2970        // the marker offset itself can resolve to the enclosing list, not the
2971        // `list_item`, whose span starts at the marker.
2972        let probe = marker.content_start().min(self.source.len());
2973        let Some(item) = self.innermost_list_item(probe) else {
2974            return false;
2975        };
2976        let Ok(nodes) = self.editor.nodes() else {
2977            return false;
2978        };
2979        match item.parent {
2980            // First when the parent list opens with this very item.
2981            Some(pid) => nodes
2982                .get(pid.0 as usize)
2983                .is_some_and(|p| p.first_child == Some(item.id)),
2984            // A parentless item is trivially the first (and only) one.
2985            None => true,
2986        }
2987    }
2988
2989    pub fn backspace(&mut self) {
2990        if let Some((s, e)) = self.selection() {
2991            self.splice(s, e, "", EditKind::Other);
2992            return;
2993        }
2994        // WYSIWYG: Backspace at the very start of a list item's content is a
2995        // structural key, not a character delete — it walks the "un-indent, then
2996        // un-list" ladder every list editor gives that keystroke (outdent a
2997        // nested item, strip a top-level one's marker to a paragraph). In source
2998        // view the `- ` is visible text the user is deleting a byte of, so it
2999        // keeps its literal meaning there, like Enter does.
3000        if self.view != View::Source && self.backspace_list_start() {
3001            return;
3002        }
3003        // WYSIWYG: and the same at the start of a heading's content — the `# `
3004        // there is markup the rich view hides, not text the user typed.
3005        if self.view != View::Source && self.backspace_heading_start() {
3006            return;
3007        }
3008        // WYSIWYG: and at the start of a block whose presentation is spelled
3009        // as hidden markup before it — djot's `{.center}` line, Markdown's
3010        // `<div class="center">` — Backspace takes that markup, the way it
3011        // takes a heading's `#`, rather than a byte out of it.
3012        if self.view != View::Source && self.backspace_attributed_block_start() {
3013            return;
3014        }
3015        // WYSIWYG: at a block picture's stops, a byte-at-a-time delete would take
3016        // the markup apart under a caret that cannot see it — see
3017        // `delete_around_block_media`.
3018        if self.view != View::Source && self.delete_around_block_media(false) {
3019            return;
3020        }
3021        // WYSIWYG: Backspace at a table's trailing stop steps back into its last
3022        // cell rather than taking the byte behind the caret — the row's closing
3023        // `|`, which the rich view never drew, so the key would have looked like
3024        // it did nothing. The stop before is the last cell's end.
3025        if self.view != View::Source && self.backspace_at_table_end() {
3026            return;
3027        }
3028        // WYSIWYG: at the start of a block's content, the byte behind the caret
3029        // is a block boundary, and Backspace over one is a join — twig's, so
3030        // that what a join is in each format is not this file's to know. After
3031        // the picture and table cases, which are block starts with their own
3032        // answers.
3033        if self.view != View::Source && self.backspace_joins_block() {
3034            return;
3035        }
3036        // WYSIWYG: Backspace on a *blank line* deletes back to the previous caret
3037        // stop, not a single newline. On a line with no text of its own, the byte
3038        // before the caret is a `\n` that spells part of a block boundary — the gap
3039        // between two blocks, drawn but never a caret home. Removing just it strands
3040        // the caret in that gap and leaves an odd blank line the eye reads as one
3041        // separator but the caret can't land on: the "extra newline" left behind
3042        // after leaving a list (Enter, Enter) or a paragraph and pressing Backspace.
3043        // Deleting to the previous stop instead collapses the whole break at once,
3044        // landing the caret at the end of the block above. Two blank lines in a row
3045        // are one stop apart, so this still removes exactly one — the lone-Enter /
3046        // lone-Backspace symmetry the empty-line case is built on is untouched.
3047        if self.view != View::Source
3048            && self.caret > self.caret_floor()
3049            && self.caret_on_blank_line()
3050            && let Some(stop) = self.vmap.stop_before(self.caret)
3051        {
3052            let stop = stop.max(self.caret_floor());
3053            if stop < self.caret {
3054                if self.source[stop..self.caret].trim().is_empty() {
3055                    self.splice(stop, self.caret, "", EditKind::Delete);
3056                } else {
3057                    // Hidden markup stands between the stop and the caret — a
3058                    // `</div>`, a comment, a link reference definition — and
3059                    // collapsing to the stop would delete it. Take the blank
3060                    // line alone, with the newline that opened it, and land
3061                    // the caret where the collapse would have.
3062                    self.delete_blank_line_to(stop);
3063                }
3064                return;
3065            }
3066        }
3067        if self.caret > self.caret_floor() {
3068            // An in-cell `<br>` draws as one newline glyph, so Backspace over it
3069            // takes the whole tag — a single-byte step would leave a broken `<br`
3070            // showing in the cell. Rich view only (source view edits the literal).
3071            if self.view != View::Source
3072                && let Some((start, end)) = self.cell_break_at(BreakEdge::Backward)
3073            {
3074                let start = start.max(self.caret_floor());
3075                if start < end {
3076                    self.splice(start, end, "", EditKind::Delete);
3077                    return;
3078                }
3079            }
3080            // Aim the delete at the character the writer can *see* behind the
3081            // caret, never at a delimiter the rich view drew nothing for. Two
3082            // steps, and either can apply: from the far side of a run's closing
3083            // `**` step back into the run (the caret is drawn at the end of its
3084            // word), and at the start of a run's text step out past its opening
3085            // `**` to the character in front of it, leaving the run standing.
3086            // Without them a plain Backspace unspells the phrase it is editing
3087            // and leaves a literal asterisk on screen.
3088            let end = if self.view == View::Source {
3089                self.caret
3090            } else {
3091                let inside = self.step_inside_close_delims(self.caret);
3092                // An attributed span with no text — `<span …></span>` as the
3093                // file was written — is hidden markup around nothing, and a
3094                // byte-step here would take its `>`. Backspace takes the span
3095                // whole, with the character before it: the character the key
3096                // looks aimed at, since the span draws nothing.
3097                if let Some(span) = self.run_span_of_content(inside..inside) {
3098                    let from = if self.source[..span.start].ends_with('\n') {
3099                        span.start
3100                    } else {
3101                        prev_boundary(&self.source, span.start)
3102                    };
3103                    let from = from.max(self.caret_floor());
3104                    self.splice(from, span.end, "", EditKind::Delete);
3105                    return;
3106                }
3107                self.skip_leading_open_delims(inside)
3108                    .max(self.caret_floor())
3109            };
3110            // Never delete back across the floor — that would eat hidden
3111            // frontmatter the WYSIWYG caret can't even see.
3112            let mut prev = prev_boundary(&self.source, end).max(self.caret_floor());
3113            // Take a hidden escape backslash with the char it escapes: the rich
3114            // view draws `\*` as a single `*`, so Backspace over it must delete
3115            // both bytes, never strand the `\` as a lone visible backslash (the
3116            // mirror of the Hidden-mode typing that wrote the escape). Source view
3117            // shows the `\`, so there it is an ordinary character.
3118            if self.view != View::Source
3119                && prev > self.caret_floor()
3120                && self.is_hidden_escape(prev - 1)
3121            {
3122                prev -= 1;
3123            }
3124            // The delete that takes the last of a span's text takes the span
3125            // with it, in the same edit: `<span …>i</span>` losing its `i`
3126            // would leave an empty span the map has no stop inside, so the
3127            // caret would draw at the next stop — a line away — until a
3128            // further key removed the span. Landing on the span's start is
3129            // where the letter was.
3130            if self.view != View::Source
3131                && let Some(span) = self.run_span_of_content(prev..end)
3132            {
3133                self.splice(span.start, span.end, "", EditKind::Delete);
3134                return;
3135            }
3136            // And the same for a block: the letter that was all of a centred
3137            // paragraph's text goes with the `<div>` around it, or the `{…}`
3138            // line above it, leaving a plain blank line where the letter was.
3139            // A paragraph with no text is no block, so the markup would stand
3140            // around nothing, the map would give it no caret home, and the
3141            // next key would take the tag apart.
3142            if self.view != View::Source
3143                && let Some(block) = self.attributed_block_of_content(prev..end)
3144            {
3145                self.splice(block.start, block.end, "", EditKind::Delete);
3146                return;
3147            }
3148            if prev < end {
3149                self.splice(prev, end, "", EditKind::Delete);
3150            }
3151        }
3152    }
3153
3154    /// Remove the blank line the caret is on — its own newline and the one
3155    /// that ended the line before it — and put the caret on `stop`, the caret
3156    /// stop before it. The [`backspace`](Self::backspace) blank-line rule for a
3157    /// blank line that hidden markup separates from the block above: the
3158    /// navigable blank row after a `</div>` is always one of at least three
3159    /// newlines under the tag (the drawn separators either side of it), so
3160    /// taking two leaves the blank line the tag needs under it.
3161    fn delete_blank_line_to(&mut self, stop: usize) {
3162        let caret = self.caret;
3163        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
3164        let line_end = self.source[caret..]
3165            .find('\n')
3166            .map_or(self.source.len(), |i| caret + i);
3167        let from = line_start.saturating_sub(1).max(stop);
3168        let to = (line_end + 1).min(self.source.len());
3169        self.splice(from, to, "", EditKind::Delete);
3170        self.caret = stop;
3171        self.anchor = None;
3172        self.goal_col = None;
3173        self.record_caret();
3174    }
3175
3176    /// Move the caret to the stop before it and consume the key — what
3177    /// Backspace does where the byte behind the caret is hidden markup it
3178    /// has no structural answer for, rather than take that markup apart.
3179    fn step_back_to_stop(&mut self) {
3180        // The map answers about offsets, so it has to be this revision's — see
3181        // `open_paragraph_at_block_edge`.
3182        self.rebuild_map();
3183        if let Some(off) = self
3184            .vmap
3185            .stop_before(self.caret)
3186            .filter(|&o| o >= self.caret_floor())
3187        {
3188            self.caret = off;
3189            self.anchor = None;
3190            self.goal_col = None;
3191        }
3192    }
3193
3194    /// Backspace's presentation behaviour: with the caret exactly at the start
3195    /// of a block's content, and that block's attributes spelled as hidden
3196    /// markup before it, strip the attributes. The peer of
3197    /// [`backspace_heading_start`](Self::backspace_heading_start), and the same
3198    /// reasoning: the `{.center}` line above a djot block and the
3199    /// `<div class="center">` around a Markdown one are what the byte behind
3200    /// the caret belongs to, and the rich view draws neither. The ordinary
3201    /// delete took the newline out of `{.center}\nhello` and left
3202    /// `{.center}hello` — the attribute line fused onto the text as prose —
3203    /// and out of `<div …>\n\nhello` it took the blank line the div needs.
3204    ///
3205    /// The whole attribute set goes, the way the whole `#` marker does — the
3206    /// press is over the line that spells it, not over one key of it — and
3207    /// twig's `set_block_attrs` with an empty list is the edit: it removes the
3208    /// djot line and unwraps the Markdown div. Where the block is the first of
3209    /// several in a div, twig has no sole child to unwrap and answers with a
3210    /// no-op, so the caret steps back to the stop before instead, as it does
3211    /// at a table's end. A later child of the div has an ordinary paragraph
3212    /// above it and is not this rule's.
3213    ///
3214    /// Returns whether it acted; `false` leaves Backspace its character delete.
3215    fn backspace_attributed_block_start(&mut self) -> bool {
3216        if !matches!(self.format, Format::Markdown | Format::Djot) {
3217            return false;
3218        }
3219        let caret = self.caret;
3220        let nodes = self.nodes();
3221        let Some(block) = nodes
3222            .iter()
3223            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3224            .find(|n| n.content_span.as_ref().map_or(n.span.start, |c| c.start) == caret)
3225        else {
3226            return false;
3227        };
3228        match self.format {
3229            Format::Djot => {
3230                // twig records where the `{…}` block was written, so this is
3231                // the parser's own answer and not a scan for a `{` above the
3232                // block; `None` (a synthesized or merged set) is not a line
3233                // the caret is standing after.
3234                let spelled = self
3235                    .editor
3236                    .document()
3237                    .ok()
3238                    .and_then(|mut d| d.attrs_span(block.id).ok().flatten())
3239                    .is_some_and(|s| s.end <= caret);
3240                if !spelled {
3241                    return false;
3242                }
3243            }
3244            _ => {
3245                let Some(div) = block
3246                    .parent
3247                    .and_then(|p| nodes.iter().find(|n| n.id == p))
3248                    .filter(|p| wysiwyg::element_tag(p) == Some("div"))
3249                else {
3250                    return false;
3251                };
3252                let mut kids = nodes.iter().filter(|n| n.parent == Some(div.id));
3253                if kids.clone().any(|k| k.span.start < block.span.start) {
3254                    return false;
3255                }
3256                if kids.nth(1).is_some() {
3257                    self.step_back_to_stop();
3258                    return true;
3259                }
3260            }
3261        }
3262        self.write_block_attrs("block attributes", Vec::new());
3263        true
3264    }
3265
3266    /// Backspace at the start of a block's content: join the block into the
3267    /// block before it, as one gesture — twig's `join_blocks`, the inverse of
3268    /// the split Enter makes, spelled the format's way. Two paragraphs join
3269    /// on a soft break; a paragraph under a marker heading joins onto the
3270    /// heading's line; a paragraph after a Markdown `<div>` moves inside it,
3271    /// the hidden `</div>` carried past the joined text; HTML's `</p><p>` is
3272    /// taken as one; a quote's or an item's continuation prefix is written.
3273    /// The joined text takes the block above's presentation and containers,
3274    /// which is the rule every editor with a centred paragraph follows.
3275    ///
3276    /// Leaf used to join by deleting the one newline behind the caret, which
3277    /// is the right bytes for two Markdown paragraphs and nothing else: under
3278    /// a heading it left two blocks, in HTML it took the `>` off a tag, and
3279    /// after a div it took the newline under the hidden `</div>`, which drew
3280    /// nothing different and took the tag apart on the next press. What a
3281    /// join is in each format is twig's to know, and now it does.
3282    ///
3283    /// Where twig refuses — the block above is a code block, a table or a
3284    /// rule with no text to join into, or the caret's block would have to
3285    /// leave a div that holds more after it — the caret steps back to the
3286    /// stop before instead, as it does at a table's end: the key moves the
3287    /// caret and takes no markup apart. Where nothing precedes the block, or
3288    /// the format cannot join at all, Backspace keeps its character delete.
3289    ///
3290    /// Returns whether it acted.
3291    fn backspace_joins_block(&mut self) -> bool {
3292        let caret = self.caret;
3293        if caret <= self.caret_floor() {
3294            return false;
3295        }
3296        let Some(text) = self.text_block_opening_at(caret) else {
3297            return false;
3298        };
3299        match self.join_blocks(caret) {
3300            Ok(change) => {
3301                // The caret keeps its place at the start of the text it stood
3302                // on, wherever the join put that text — after a soft break,
3303                // a space, or a quote's prefix. Found by the bytes, as
3304                // `block_content_in` finds a re-spelled block.
3305                let region = &self.source[change.new.clone()];
3306                let at = region
3307                    .find(&text)
3308                    .map_or(change.new.start, |i| change.new.start + i);
3309                self.land_after_join(at);
3310                true
3311            }
3312            Err(twig::Error::NotEditable) => {
3313                self.step_back_to_stop();
3314                true
3315            }
3316            Err(twig::Error::NotFound | twig::Error::UnsupportedFormat) => false,
3317            Err(e) => {
3318                self.status = Some(format!("join: {e}"));
3319                true
3320            }
3321        }
3322    }
3323
3324    /// Delete at the end of a block's content: join the block after it into
3325    /// this one — [`backspace_joins_block`](Self::backspace_joins_block)'s
3326    /// mirror, and the same twig gesture aimed at the next block. The caret
3327    /// stays where it was, which is where the joined text now begins after
3328    /// the separator. Where twig refuses, the caret steps forward to the next
3329    /// stop instead; where no block follows, Delete keeps its character
3330    /// delete.
3331    fn delete_forward_joins_block(&mut self) -> bool {
3332        let caret = self.caret;
3333        let at_end = self
3334            .nodes()
3335            .iter()
3336            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3337            .any(|n| n.content_span.as_ref().is_some_and(|c| c.end == caret));
3338        if !at_end {
3339            return false;
3340        }
3341        // The next stop, across a line end, in a block: what Delete at a
3342        // block's end points at. On the same line it is a hidden delimiter's
3343        // far side, which the ordinary delete handles; on a blank line it is
3344        // the empty paragraph the byte delete has always closed.
3345        self.rebuild_map();
3346        let Some(stop) = self.vmap.stop_after(caret) else {
3347            return false;
3348        };
3349        if !self.source[caret..stop].contains('\n') || !self.has_block_at(stop) {
3350            return false;
3351        }
3352        match self.join_blocks(stop) {
3353            Ok(change) => {
3354                self.land_after_join(change.old.start);
3355                true
3356            }
3357            Err(twig::Error::NotEditable | twig::Error::NotFound) => {
3358                self.caret = stop;
3359                self.anchor = None;
3360                self.goal_col = None;
3361                true
3362            }
3363            Err(twig::Error::UnsupportedFormat) => false,
3364            Err(e) => {
3365                self.status = Some(format!("join: {e}"));
3366                true
3367            }
3368        }
3369    }
3370
3371    /// The content bytes of the paragraph or heading whose content opens
3372    /// exactly at `off` — the block a Backspace there is at the start of.
3373    fn text_block_opening_at(&mut self, off: usize) -> Option<String> {
3374        self.nodes()
3375            .into_iter()
3376            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3377            .find_map(|n| {
3378                let c = n.content_span?;
3379                (c.start == off).then(|| self.source[c].to_string())
3380            })
3381    }
3382
3383    /// Hand the block at `offset` to twig's `join_blocks`, with the undo
3384    /// plumbing every structural gesture has; the caret is the caller's to
3385    /// place from the change, via [`land_after_join`](Self::land_after_join).
3386    fn join_blocks(&mut self, offset: usize) -> Result<Change, twig::Error> {
3387        if self.read_only {
3388            return Err(twig::Error::NotEditable);
3389        }
3390        self.record_caret();
3391        let change = self.editor.join_blocks(offset)?;
3392        self.last_edit_kind = None; // structural edit is its own undo step
3393        self.refresh();
3394        Ok(change)
3395    }
3396
3397    /// Finish a join: the caret at `at`, no selection, the map this
3398    /// revision's before the clamp — see `write_block_attrs` for why.
3399    fn land_after_join(&mut self, at: usize) {
3400        self.caret = at;
3401        self.anchor = None;
3402        self.goal_col = None;
3403        self.dirty = self.source != self.clean_source;
3404        self.status = None;
3405        self.rebuild_map();
3406        self.clamp_caret();
3407        self.record_caret();
3408    }
3409
3410    /// Backspace at a table's trailing stop: move onto the stop before it (the
3411    /// last cell's end) and consume the key. `false` anywhere else. See
3412    /// [`VisualMap::table_end_stop`] for why the byte behind the caret there is
3413    /// not one to delete.
3414    fn backspace_at_table_end(&mut self) -> bool {
3415        // The map answers about offsets, so it has to be this revision's — see
3416        // `open_paragraph_at_block_edge`.
3417        self.rebuild_map();
3418        if !self.vmap.table_end_stop(self.caret) {
3419            return false;
3420        }
3421        if let Some(off) = self
3422            .vmap
3423            .stop_before(self.caret)
3424            .filter(|&o| o >= self.caret_floor())
3425        {
3426            self.caret = off;
3427            self.anchor = None;
3428            self.goal_col = None;
3429        }
3430        true
3431    }
3432
3433    /// Whether the caret's own source line holds nothing but whitespace — an
3434    /// empty paragraph, or the blank line a block boundary is spelled with. The
3435    /// test for [`backspace`](Self::backspace)'s stop-wise delete: such a line has
3436    /// no text of its own, so the newline before the caret belongs to the gap
3437    /// between blocks rather than to any word the caret is editing.
3438    fn caret_on_blank_line(&self) -> bool {
3439        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
3440        let line_end = self.source[self.caret..]
3441            .find('\n')
3442            .map_or(self.source.len(), |i| self.caret + i);
3443        self.source[line_start..line_end].trim().is_empty()
3444    }
3445
3446    /// The source span of an in-cell hard break (`<br>`) touching the caret on the
3447    /// `edge` side — the byte range to delete whole. A table row is one source
3448    /// line, so its break is spelled `<br>` yet drawn as a single newline glyph
3449    /// (see `wysiwyg.rs`); a delete over it must take every byte, or a one-byte
3450    /// step strands a broken `<br` in the cell. `Backward` matches a break ending
3451    /// at the caret (Backspace), `Forward` one starting at it (Delete). `None`
3452    /// when no such break is adjacent. Only the in-cell break is spelled `<br>`
3453    /// (an ordinary hard break is `  \n`), so the leading `<` alone tells them
3454    /// apart — no ancestor walk needed. Rich view only; source view shows the
3455    /// literal tag and deletes it a byte at a time.
3456    fn cell_break_at(&mut self, edge: BreakEdge) -> Option<(usize, usize)> {
3457        let caret = self.caret;
3458        let nodes = self.nodes();
3459        let src = self.source.as_bytes();
3460        nodes
3461            .iter()
3462            .find(|n| {
3463                n.kind == Kind::HardBreak
3464                    && n.span.start < n.span.end
3465                    && src.get(n.span.start) == Some(&b'<')
3466                    && match edge {
3467                        BreakEdge::Backward => n.span.end == caret,
3468                        BreakEdge::Forward => n.span.start == caret,
3469                    }
3470            })
3471            .map(|n| (n.span.start, n.span.end))
3472    }
3473
3474    /// Whether the source byte at `off` is a backslash twig consumed as an escape
3475    /// (hidden in the rich view), as against a literal backslash (drawn). A
3476    /// backslash escapes exactly an ASCII-punctuation character (the CommonMark /
3477    /// Djot rule twig follows), so `\` + punctuation is the whole test — no AST
3478    /// round-trip needed.
3479    fn is_hidden_escape(&self, off: usize) -> bool {
3480        let b = self.source.as_bytes();
3481        b.get(off) == Some(&b'\\') && b.get(off + 1).is_some_and(u8::is_ascii_punctuation)
3482    }
3483
3484    /// Backspace's list behaviour: when the caret sits exactly at the start of a
3485    /// list item's content (right after its marker), outdent the item if it's
3486    /// nested, else strip the marker so it becomes a paragraph. Returns whether
3487    /// it acted — `false` leaves Backspace its ordinary character delete.
3488    fn backspace_list_start(&mut self) -> bool {
3489        let Some(marker) = self.list_marker_on_line(self.caret) else {
3490            return false;
3491        };
3492        // Only right after the marker. That the line opens a real item is
3493        // already settled: `list_marker_on_line` answers from the tree.
3494        if self.caret != marker.content_start() {
3495            return false;
3496        }
3497        if self.item_is_nested(marker.marker_start) {
3498            // Nested: give back one level, keeping the marker and carrying the
3499            // caret with it.
3500            self.outdent();
3501        } else {
3502            // Top level: drop the marker, leaving a paragraph, then renumber the
3503            // siblings the removed item was counted among. Only the marker goes —
3504            // a quote prefix in front of it still has a quote to hold up.
3505            self.splice(marker.marker_start, self.caret, "", EditKind::Other);
3506            self.renumber_here();
3507        }
3508        true
3509    }
3510
3511    /// Backspace's heading behaviour: with the caret exactly at the start of an
3512    /// ATX heading's content — right after the `#` marker the rich view hides —
3513    /// strip the marker so the line becomes a paragraph. The peer of
3514    /// [`backspace_list_start`](Self::backspace_list_start)'s ladder, and the same
3515    /// reasoning: hidden block markup is structure, so the keystroke over it is
3516    /// structural.
3517    ///
3518    /// Without this the ordinary delete takes the space out of `# Title` and
3519    /// leaves `#Title`, which is no longer a heading at all — the hash the view
3520    /// had been hiding surfaces as literal text the user has to delete a second
3521    /// time, having never typed it. A closing sequence (`# Title #`, hidden at the
3522    /// other end) goes with the marker for the same reason.
3523    ///
3524    /// Returns whether it acted; `false` leaves Backspace its character delete.
3525    fn backspace_heading_start(&mut self) -> bool {
3526        let caret = self.caret;
3527        // The heading whose content opens exactly at the caret. A bare `#` has no
3528        // content span at all — its content starts (and ends) where the line does.
3529        let Some((span, content_end, marker)) = self.nodes().iter().find_map(|n| {
3530            let (start, end) = match &n.content_span {
3531                Some(c) => (c.start, c.end),
3532                None => (n.span.end, n.span.end),
3533            };
3534            (n.kind == Kind::Heading && start == caret)
3535                .then(|| (n.span.clone(), end, n.marker_span.clone()))
3536        }) else {
3537            return false;
3538        };
3539        // twig reports the marker's own extent, so there is nothing to walk back
3540        // over and no `#` in this file. A setext heading has no marker — its
3541        // content opens the line — so it falls through to the ordinary delete,
3542        // as does anything else sitting at a content start.
3543        // `m.end == caret` is what excludes a setext heading, whose marker is the
3544        // underline *after* the content rather than a prefix before it.
3545        let Some(marker) = marker.filter(|m| m.end == caret) else {
3546            return false;
3547        };
3548        let start = marker.start;
3549        // A closing `#` sequence is hidden too, so it can't be left behind. Only
3550        // when the tail really is one: trailing spaces alone are nothing to strip.
3551        let tail = &self.source[content_end..span.end];
3552        if tail.contains('#') && tail.chars().all(|c| c == '#' || c.is_whitespace()) {
3553            let kept = self.source[caret..content_end].to_string();
3554            self.splice(start, span.end, &kept, EditKind::Other);
3555            // The splice leaves the caret past the text it re-wrote; the caret
3556            // belongs where the content now starts, which is where it already was.
3557            self.caret = start;
3558            self.record_caret();
3559        } else {
3560            self.splice(start, caret, "", EditKind::Other);
3561        }
3562        true
3563    }
3564
3565    pub fn delete_forward(&mut self) {
3566        if let Some((s, e)) = self.selection() {
3567            self.splice(s, e, "", EditKind::Other);
3568        } else if self.caret < self.source.len() {
3569            // The mirror of Backspace's: forward-delete in front of a picture
3570            // would eat the `!` off its markup and leave a link where a photo was.
3571            if self.view != View::Source && self.delete_around_block_media(true) {
3572                return;
3573            }
3574            // And of Backspace's join: at the end of a block's content, Delete
3575            // joins the next block into this one.
3576            if self.view != View::Source && self.delete_forward_joins_block() {
3577                return;
3578            }
3579            // Delete forward over an in-cell `<br>` takes the whole tag, the mirror
3580            // of Backspace's swallow (see `cell_break_at`) — else a byte-step
3581            // strands a broken `<br` in the cell.
3582            if self.view != View::Source
3583                && let Some((start, end)) = self.cell_break_at(BreakEdge::Forward)
3584            {
3585                self.splice(start, end, "", EditKind::Delete);
3586                return;
3587            }
3588            // The mirror of Backspace's two steps: from in front of a run's
3589            // opening `**` step into it, onto the first letter of its text, and
3590            // at the end of a run's text step out past its closing `**` to the
3591            // character beyond. Either way Delete takes the character it looks
3592            // like it is pointing at, and never a delimiter drawn as nothing.
3593            // The caret then settles back inside the run it was standing in —
3594            // see `settle_inside_close_delims`.
3595            let from = if self.view == View::Source {
3596                self.caret
3597            } else {
3598                let inside = self.step_inside_open_delims(self.caret);
3599                // The mirror of Backspace's empty-span rule: an attributed
3600                // span with no text goes whole, with the character after it.
3601                if let Some(span) = self.run_span_of_content(inside..inside) {
3602                    let to = if self.source[span.end..].starts_with('\n') {
3603                        span.end
3604                    } else {
3605                        next_boundary(&self.source, span.end)
3606                    };
3607                    self.splice(span.start, to, "", EditKind::Delete);
3608                    return;
3609                }
3610                self.skip_trailing_close_delims(inside)
3611            };
3612            let next = next_boundary(&self.source, from);
3613            // And of its emptying rules: the span goes with its last letter,
3614            // and so does the block's div or `{…}` line.
3615            if self.view != View::Source
3616                && let Some(span) = self.run_span_of_content(from..next)
3617            {
3618                self.splice(span.start, span.end, "", EditKind::Delete);
3619                return;
3620            }
3621            if self.view != View::Source
3622                && let Some(block) = self.attributed_block_of_content(from..next)
3623            {
3624                self.splice(block.start, block.end, "", EditKind::Delete);
3625                return;
3626            }
3627            if from < next {
3628                self.splice(from, next, "", EditKind::Delete);
3629            }
3630        }
3631    }
3632
3633    /// Delete from the caret back to the start of the previous word (⌥⌫ /
3634    /// Ctrl+⌫). Deletes the selection instead when one is active.
3635    pub fn delete_word_back(&mut self) {
3636        if let Some((s, e)) = self.selection() {
3637            self.splice(s, e, "", EditKind::Other);
3638        } else {
3639            // A word back from just past a picture is a word *of its markup*, and
3640            // a word back from in front of one runs through the paragraph break
3641            // into the prose above — dissolving the picture either way. See
3642            // `delete_around_block_media`.
3643            if self.view != View::Source && self.delete_around_block_media(false) {
3644                return;
3645            }
3646            let start = self.word_left_from(self.caret).max(self.caret_floor());
3647            if start < self.caret {
3648                let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3649                self.splice(s, e, "", EditKind::Delete);
3650            }
3651        }
3652    }
3653
3654    /// Delete from the caret forward to the end of the next word (⌥⌦ /
3655    /// Ctrl+Del). Deletes the selection instead when one is active.
3656    pub fn delete_word_forward(&mut self) {
3657        if let Some((s, e)) = self.selection() {
3658            self.splice(s, e, "", EditKind::Other);
3659        } else {
3660            // The mirror: a word forward from in front of a picture is its markup.
3661            if self.view != View::Source && self.delete_around_block_media(true) {
3662                return;
3663            }
3664            let end = self.word_right_from(self.caret);
3665            if end > self.caret {
3666                let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3667                self.splice(s, e, "", EditKind::Delete);
3668            }
3669        }
3670    }
3671
3672    /// Delete from the caret back to the start of its line (⌘⌫). Deletes the
3673    /// selection instead when one is active, as every other delete here does.
3674    ///
3675    /// The line is the view's own — the one Home and End work on, so in WYSIWYG
3676    /// a soft-wrapped row is a line. It is not Home's *target*, though: Home
3677    /// stops at the first character and this takes the indentation with it, the
3678    /// way Cocoa's `deleteToBeginningOfLine:` does. Stopping at the text would
3679    /// leave an indent behind that nothing can then ask to delete, where a caret
3680    /// left at column 0 is one press of Home away from either.
3681    pub fn delete_to_line_start(&mut self) {
3682        if let Some((s, e)) = self.selection() {
3683            self.splice(s, e, "", EditKind::Other);
3684            return;
3685        }
3686        // Never back across the floor: hidden frontmatter isn't on this line, or
3687        // on any line the WYSIWYG caret can see.
3688        let (start, _) = self.line_span();
3689        let start = start.max(self.caret_floor());
3690        if start < self.caret {
3691            let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3692            self.splice(s, e, "", EditKind::Delete);
3693        }
3694    }
3695
3696    /// Kill from the caret to the end of its line (^K). Deletes the selection
3697    /// instead when one is active.
3698    ///
3699    /// At the end of the line it does nothing, rather than pulling the line
3700    /// below up into this one. Joining has no meaning to give it in both views
3701    /// at once: a WYSIWYG line ends at a soft wrap as often as at a newline, and
3702    /// there is nothing there to delete, while the newline a *source* line ends
3703    /// with is only half of the blank line that separates two paragraphs —
3704    /// deleting one leaves a soft break, which is not the join it looks like.
3705    /// The views agreeing is worth more than emacs' second press, and Delete is
3706    /// already the key that joins.
3707    pub fn delete_to_line_end(&mut self) {
3708        if let Some((s, e)) = self.selection() {
3709            self.splice(s, e, "", EditKind::Other);
3710            return;
3711        }
3712        let (_, end) = self.line_span();
3713        if end > self.caret {
3714            let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3715            self.splice(s, e, "", EditKind::Delete);
3716        }
3717    }
3718
3719    /// Grow a WYSIWYG word-delete to swallow any inline node it empties.
3720    ///
3721    /// A glyph-space range covers what the user can see, which for `**bold**` is
3722    /// the word and never the delimiters around it — so deleting the word on its
3723    /// own leaves `a **** c`, markup wrapped around nothing. They asked for the
3724    /// word, and the styling was the word's; the two go together. Only the
3725    /// node's delimiters are taken, and those are hidden here anyway, so nothing
3726    /// visible outside the range is lost.
3727    ///
3728    /// Repeated to a fixed point: emptying `***bold***` empties the emph inside
3729    /// the strong, and only then is the strong empty too.
3730    fn widen_over_emptied_inlines(&mut self, start: usize, end: usize) -> (usize, usize) {
3731        if self.view == View::Source {
3732            return (start, end);
3733        }
3734        let nodes = self.nodes();
3735        let (mut s, mut e) = (start, end);
3736        loop {
3737            let mut grew = false;
3738            for n in nodes.iter().filter(|n| wysiwyg::is_inline(n)) {
3739                let Some(text) = inline_content_span(n, &self.source) else {
3740                    continue;
3741                };
3742                // Some of its text survives, so the node still has a job.
3743                if text.start < s || text.end > e {
3744                    continue;
3745                }
3746                if n.span.start < s || n.span.end > e {
3747                    s = s.min(n.span.start);
3748                    e = e.max(n.span.end);
3749                    grew = true;
3750                }
3751            }
3752            if !grew {
3753                return (s, e);
3754            }
3755        }
3756    }
3757
3758    /// One splice of document text, keeping the **mark-edge rule**: an inline
3759    /// mark's content never begins or ends with whitespace. In Markdown and Djot
3760    /// a delimiter standing against a space is not a delimiter at all — `**bold **`
3761    /// is four literal asterisks around a word, and a rich view drawing the
3762    /// document faithfully has no choice but to show them. That is correct
3763    /// rendering of what the file says, and nobody typing a space after a bold
3764    /// word meant to say it.
3765    ///
3766    /// So the space goes *outside* the run instead — `**bold** ` — which is the
3767    /// same document to a reader and a live one to a parser. The caret follows it
3768    /// out and keeps the marks armed (see [`rearm`](Self::rearm)), so the next
3769    /// character rejoins the run (see [`rejoin_run`](Self::rejoin_run)) and the
3770    /// writer sees one unbroken bold phrase, never a flash of raw syntax.
3771    ///
3772    /// Every ordinary edit — typing, deleting, pasting, an IME step — comes
3773    /// through here, so the rule holds however the whitespace arrives at the
3774    /// edge. The repair is decided *after* the plain edit, by asking whether the
3775    /// mark actually died: a code span's backticks aren't whitespace-sensitive
3776    /// (`` `code ` `` is still code), and nothing is re-spelled when nothing broke.
3777    fn splice(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3778        let fix = self.mark_edge_fix(start, end, text);
3779        if !self.splice_exact(start, end, text, kind) {
3780            return false;
3781        }
3782        if let Some(fix) = fix {
3783            self.repair_mark_edges(fix);
3784        }
3785        if text.is_empty() && end > start {
3786            self.settle_inside_close_delims();
3787        }
3788        true
3789    }
3790
3791    /// After a delete, take a caret left standing past a run's closing delimiters
3792    /// back inside the run.
3793    ///
3794    /// A delete leaves the caret where the deleted bytes began, and when those
3795    /// bytes were the last thing after a marked phrase — the space the mark-edge
3796    /// rule pushed out of `**bold** `, say — that spot is the far side of the
3797    /// closing `**`. The rich view has nothing to draw there: the delimiters are
3798    /// hidden, so the caret shows at the end of the word either way, and the two
3799    /// offsets are one place on screen with two different meanings. Typing at the
3800    /// outer one lands past the run, so the writer who backspaced a space out of
3801    /// their bold phrase watches the next character come out plain, and the
3802    /// toolbar button go dark, with the caret never appearing to move.
3803    ///
3804    /// The end of the run's text is the caret's home there — a delete that took
3805    /// away everything after a phrase leaves the caret at the end of that phrase,
3806    /// which is inside it — so it settles onto that
3807    /// ([`step_inside_close_delims`](Self::step_inside_close_delims) does the
3808    /// walk, through every mark closing at the point): the word stays bold, the
3809    /// button stays lit, and the next character carries on the phrase.
3810    ///
3811    /// Rich view only, and only where a mark really closes at the caret — mid-run
3812    /// or in plain prose no span ends there and the caret stays put. The opening
3813    /// edge is left alone on purpose: a caret in front of a run inherits from the
3814    /// text on its left, which is the plain text outside.
3815    fn settle_inside_close_delims(&mut self) {
3816        if self.view != View::Wysiwyg {
3817            return;
3818        }
3819        let at = self.step_inside_close_delims(self.caret);
3820        if at != self.caret {
3821            self.caret = at;
3822            self.clear_pending();
3823            self.record_caret();
3824        }
3825    }
3826
3827    /// The splice exactly as asked, with no mark-edge repair — for the callers
3828    /// that are *writing* the delimiters themselves ([`insert_with_marks`](Self::insert_with_marks)
3829    /// and [`rejoin_run`](Self::rejoin_run)) and place their own offsets around
3830    /// the bytes they inserted.
3831    ///
3832    /// One `edit_range` through twig, then re-anchor the caret from the returned
3833    /// `Change` and refresh the cached source. A reparse-breaking edit (rare for
3834    /// Markdown/Djot) leaves the document untouched and reports.
3835    ///
3836    /// Returns whether the edit landed — for a caller that has offsets of its
3837    /// own to place afterwards, which a rolled-back splice would leave pointing
3838    /// into text that never came to exist.
3839    fn splice_exact(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3840        // The read-only gate, for every edit at once — see the field.
3841        if self.read_only {
3842            return false;
3843        }
3844        // twig records an undo step for every edit; when this one continues a
3845        // run of the same kind (typing, deleting), tell twig to fold it into the
3846        // step before it so the whole run undoes at once.
3847        let coalesce = kind != EditKind::Other && self.last_edit_kind == Some(kind);
3848        // Hand twig the pre-edit caret before the splice, so the undo step it
3849        // retires carries where the caret was standing.
3850        self.record_caret();
3851        match self.editor.edit_range(start, end, text) {
3852            Ok(change) => {
3853                if coalesce {
3854                    let _ = self.editor.coalesce_last_undo();
3855                }
3856                self.last_edit_kind = Some(kind);
3857                self.refresh();
3858                self.caret = change.new.end;
3859                self.anchor = None;
3860                self.goal_col = None;
3861                self.clear_pending();
3862                self.dirty = self.source != self.clean_source;
3863                self.status = None;
3864                // And the post-edit caret, so a later redo restores it.
3865                self.record_caret();
3866                true
3867            }
3868            // The edit was rolled back, so twig's history did not move and
3869            // neither may ours: pushing here would leave a step with no edit
3870            // under it and shift every later undo onto the wrong caret.
3871            Err(e) => {
3872                self.status = Some(format!("edit: {e}"));
3873                false
3874            }
3875        }
3876    }
3877
3878    /// The re-spelling that would keep the mark-edge rule for the edit
3879    /// `[start, end)` → `text`, or `None` when the edit leaves no whitespace
3880    /// against a delimiter and the plain splice is already right. Computed
3881    /// *before* the edit, while the run's spans and delimiters can still be read
3882    /// off the document; applied afterwards, and only if the mark really died —
3883    /// see [`repair_mark_edges`](Self::repair_mark_edges).
3884    ///
3885    /// Rich view only. Source view is for typing raw markup, where a space put
3886    /// against a `**` is exactly the character it looks like.
3887    fn mark_edge_fix(&mut self, start: usize, end: usize, text: &str) -> Option<MarkEdgeFix> {
3888        if self.view != View::Wysiwyg || start > end || end > self.source.len() {
3889            return None;
3890        }
3891        // Every inline mark standing over the edit, outermost first, with the
3892        // content span that says where its delimiters are.
3893        let chain: Vec<(InlineKind, std::ops::Range<usize>, std::ops::Range<usize>)> = self
3894            .editor
3895            .ancestors_at(start)
3896            .unwrap_or_default()
3897            .into_iter()
3898            .filter_map(|m| {
3899                let kind = inline_kind(&m.kind)?;
3900                let content = m.content_span.clone()?;
3901                Some((kind, m.span.clone(), content))
3902            })
3903            .collect();
3904        // The innermost run whose *content* holds the whole edit: the one whose
3905        // text is being changed, rather than one the edit merely sits under.
3906        let (kind, span, content) = chain
3907            .iter()
3908            .rev()
3909            .find(|(_, _, c)| c.start <= start && end <= c.end)?
3910            .clone();
3911        // What that content becomes. Whitespace at either end of it is what
3912        // would put out the mark.
3913        let body = format!(
3914            "{}{text}{}",
3915            &self.source[content.start..start],
3916            &self.source[end..content.end]
3917        );
3918        let (lead, trail) = if body.trim().is_empty() {
3919            // Nothing but whitespace left: there is no content to mark at all,
3920            // and the delimiters go with it rather than closing on a space.
3921            (body.len(), 0)
3922        } else {
3923            (
3924                body.len() - body.trim_start().len(),
3925                body.len() - body.trim_end().len(),
3926            )
3927        };
3928        // Nothing against a delimiter, and something still between them: the
3929        // plain edit stands. An emptied run is broken just as surely (`**b**`
3930        // with the `b` deleted is the literal `****`) and is re-spelt as the
3931        // nothing it now says.
3932        if lead == 0 && trail == 0 && !body.is_empty() {
3933            return None;
3934        }
3935        // Marks that open or close exactly where this one does — `***both***` is
3936        // two runs sharing an edge — spell their delimiters as one run of bytes,
3937        // so the whitespace has to clear all of them together.
3938        let (mut open_at, mut close_at) = (span.start, span.end);
3939        for _ in 0..chain.len() {
3940            match chain.iter().find(|(_, _, c)| c.start == open_at) {
3941                Some((_, s, _)) => open_at = s.start,
3942                None => break,
3943            }
3944        }
3945        for _ in 0..chain.len() {
3946            match chain.iter().find(|(_, _, c)| c.end == close_at) {
3947                Some((_, s, _)) => close_at = s.end,
3948                None => break,
3949            }
3950        }
3951        let open = &self.source[open_at..content.start];
3952        let close = &self.source[content.end..close_at];
3953        let core = &body[lead..body.len() - trail];
3954        let respelt = if core.is_empty() {
3955            body.clone()
3956        } else {
3957            format!(
3958                "{}{open}{core}{close}{}",
3959                &body[..lead],
3960                &body[body.len() - trail..]
3961            )
3962        };
3963        // The caret sits just past the inserted text within the new content —
3964        // which, when that lands in the whitespace, is now outside the delimiters.
3965        let pos = (start - content.start) + text.len();
3966        let caret = if core.is_empty() || pos <= lead {
3967            open_at + pos
3968        } else if pos >= lead + core.len() {
3969            open_at + lead + open.len() + core.len() + close.len() + (pos - lead - core.len())
3970        } else {
3971            open_at + lead + open.len() + (pos - lead)
3972        };
3973        Some(MarkEdgeFix {
3974            kind,
3975            probe: content.start,
3976            start: open_at,
3977            end: close_at + text.len() - (end - start),
3978            text: respelt,
3979            caret,
3980            // The marks in force here, resolved against any armed sticky delta —
3981            // what the writer is typing in, and so what has to still be true on
3982            // the far side of the delimiter the caret just stepped over.
3983            want: chain
3984                .iter()
3985                .filter(|(_, s, _)| start < s.end)
3986                .map(|(k, _, _)| *k)
3987                .collect::<InlineMarks>()
3988                .xor(self.pending_here()),
3989        })
3990    }
3991
3992    /// Apply a [`MarkEdgeFix`] — but only if the edit it was computed for really
3993    /// did break the mark. Whether whitespace at a delimiter is fatal is the
3994    /// format's business, not leaf's: `**bold **` is no longer strong, while
3995    /// `` `code ` `` is still perfectly good verbatim, and Djot's braced spellings
3996    /// don't care either. Asking the parser afterwards settles it for every kind
3997    /// and format at once, and costs a re-spelling only where one is due.
3998    ///
3999    /// The repair rides along with the edit that caused it — one undo step puts
4000    /// back what the writer typed, not a delimiter shuffle they never saw.
4001    fn repair_mark_edges(&mut self, fix: MarkEdgeFix) {
4002        if fix.end > self.source.len() {
4003            return;
4004        }
4005        if self.marks_at(fix.probe).iter().any(|(k, _)| *k == fix.kind) {
4006            return; // still a mark: these delimiters don't mind the whitespace
4007        }
4008        let resumed = self.last_edit_kind;
4009        if !self.splice_exact(fix.start, fix.end, &fix.text, EditKind::Other) {
4010            return;
4011        }
4012        let _ = self.editor.coalesce_last_undo();
4013        // The keystroke owns the undo step, so the run of typing it belongs to
4014        // keeps coalescing over the repair rather than breaking in two here.
4015        self.last_edit_kind = resumed;
4016        self.caret = fix.caret.min(self.source.len());
4017        self.anchor = None;
4018        self.goal_col = None;
4019        self.rearm(fix.want);
4020        self.clamp_caret();
4021        self.record_caret();
4022    }
4023
4024    /// Arm whatever sticky delta reproduces `want` at the caret — the marks the
4025    /// writer is typing in, carried across an edit that moved the caret out of
4026    /// the run holding them. Arms nothing when the caret already stands in
4027    /// exactly those marks, but still remembers the spot, so a further ⌘b starts
4028    /// a clean delta here (see [`toggle`](Self::toggle)).
4029    fn rearm(&mut self, want: InlineMarks) {
4030        let here: InlineMarks = self
4031            .marks_at(self.caret)
4032            .into_iter()
4033            .map(|(k, _)| k)
4034            .collect();
4035        self.pending_marks = want.xor(here);
4036        self.pending_at = Some(self.caret);
4037    }
4038
4039    /// Insert `text` at `at` as a *literal* run via twig's `insert_literal`,
4040    /// which backslash-escapes any character that would otherwise open markup in
4041    /// this format and position (`*` → `\*`, a line-start `#` → `\#`). The mirror
4042    /// of [`splice`](Self::splice) for the Hidden reveal mode's typing path, with
4043    /// the same caret re-anchor, coalescing, and rollback contract. `at` must be
4044    /// a collapsed point — a selection is deleted by the caller first, since
4045    /// `insert_literal` inserts rather than replaces.
4046    fn insert_literal_at(
4047        &mut self,
4048        at: usize,
4049        text: &str,
4050        kind: EditKind,
4051        force_coalesce: bool,
4052    ) -> bool {
4053        // The read-only gate: this door goes to twig directly, not through
4054        // `splice_exact`, so it guards itself — see the field.
4055        if self.read_only {
4056            return false;
4057        }
4058        // `force_coalesce` folds this into the immediately preceding edit (the
4059        // selection-delete of an overwrite) so the pair is one undo step; else it
4060        // coalesces only when it continues a run of the same-kind typing.
4061        let coalesce =
4062            force_coalesce || (kind != EditKind::Other && self.last_edit_kind == Some(kind));
4063        // The mark-edge rule holds for typed text however it is spelled — see
4064        // `splice`. Only an insert twig passed through unchanged can use it,
4065        // since a fix is measured in the bytes that actually land, and an escape
4066        // adds bytes this couldn't have counted.
4067        let fix = self.mark_edge_fix(at, at, text);
4068        self.record_caret();
4069        match self.editor.insert_literal(at, text) {
4070            Ok(change) => {
4071                if coalesce {
4072                    let _ = self.editor.coalesce_last_undo();
4073                }
4074                self.last_edit_kind = Some(kind);
4075                self.refresh();
4076                self.caret = change.new.end;
4077                self.anchor = None;
4078                self.goal_col = None;
4079                self.clear_pending();
4080                self.dirty = self.source != self.clean_source;
4081                self.status = None;
4082                self.record_caret();
4083                if let Some(fix) = fix.filter(|_| change.new.end - change.new.start == text.len()) {
4084                    self.repair_mark_edges(fix);
4085                }
4086                true
4087            }
4088            Err(e) => {
4089                self.status = Some(format!("edit: {e}"));
4090                false
4091            }
4092        }
4093    }
4094
4095    /// After a structural list edit (a new item, a nest/unnest), renumber the
4096    /// ordered list the caret sits in so its source markers run `1, 2, 3, …`
4097    /// again — a raw splice leaves them stale (`1. 2. 2. 3.`). twig does the
4098    /// renumber as its own edit; fold it into the edit that triggered it so the
4099    /// two undo as one, and only when it actually changed the source (a no-op or
4100    /// a caret outside any ordered list must not coalesce the real edit into the
4101    /// step before it).
4102    fn renumber_here(&mut self) {
4103        self.renumber_at(self.caret);
4104    }
4105
4106    /// [`renumber_here`](Self::renumber_here) aimed somewhere other than the
4107    /// caret — for an edit that leaves the caret one past the item it just wrote,
4108    /// where twig resolves no list to renumber.
4109    fn renumber_at(&mut self, off: usize) {
4110        // The read-only gate — this door reaches twig without the splice.
4111        if self.read_only {
4112            return;
4113        }
4114        let before = self.source.clone();
4115        if self.editor.renumber_ordered_lists(off).is_err() {
4116            return; // not inside an ordered list — nothing to renumber
4117        }
4118        self.refresh();
4119        if self.source != before {
4120            let _ = self.editor.coalesce_last_undo();
4121            self.dirty = self.source != self.clean_source;
4122            self.clamp_caret();
4123            self.record_caret();
4124        }
4125    }
4126
4127    /// Repair the one trap a list edit can spring on itself. An *empty* `-`
4128    /// sub-item written directly beneath a text line reparses that text as a
4129    /// setext heading — `- hello\n  - ` is `<h2>hello</h2>`, because a lone `-`
4130    /// is also a setext-H2 underline (twig is right; pandoc agrees). `*` and `+`
4131    /// bullets can't underline anything, so swap the dash for a `*`: the item
4132    /// stays an empty nested bullet, the parent stays prose, and the source
4133    /// round-trips instead of hiding a heading the user never asked for. Folded
4134    /// into the triggering edit's undo step, the way renumbering is.
4135    ///
4136    /// Gated on the collapse having actually happened (the swapped dash was
4137    /// swallowed into a `heading`), so a real setext heading the author wrote —
4138    /// or a `- x` with content, which can't underline anything — is never
4139    /// touched. This has to live in the *edit*, not the renderer: leaving the
4140    /// hazardous bytes on disk and only painting over them would ship a file
4141    /// every other CommonMark tool reads as a heading.
4142    ///
4143    /// This one keeps its own byte scan, and has to: the hazard is precisely
4144    /// that the dash stopped being a list marker, so [`list_marker_on_line`] —
4145    /// which asks twig which lines open an item — reports nothing here. There is
4146    /// no node to ask about. It is also the last Markdown spelling leaf writes on
4147    /// purpose rather than for want of an answer; once twig spells continuations
4148    /// itself, avoiding the trap becomes twig's, and this goes.
4149    ///
4150    /// [`list_marker_on_line`]: Self::list_marker_on_line
4151    fn avoid_setext_collapse(&mut self) {
4152        let caret = self.caret.min(self.source.len());
4153        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
4154        let bytes = self.source.as_bytes();
4155        let mut dash = line_start;
4156        while matches!(bytes.get(dash), Some(b' ' | b'\t')) {
4157            dash += 1;
4158        }
4159        // A dash bullet is the only marker that doubles as a setext underline.
4160        if bytes.get(dash) != Some(&b'-') {
4161            return;
4162        }
4163        // Only an *empty* item is a bare underline; `- x` carries content and
4164        // can't fold the line above into a heading.
4165        let line_end = self.source[dash..]
4166            .find('\n')
4167            .map_or(self.source.len(), |i| dash + i);
4168        if !self.source[dash + 1..line_end].trim().is_empty() {
4169            return;
4170        }
4171        // The tell: that dash was swallowed into a `heading`. A properly nested
4172        // empty item sits under a `list_item`, with no heading in reach. Probe
4173        // the dash byte itself (well inside the heading), not the caret, whose
4174        // end-of-line offset can fall on the half-open span boundary.
4175        let collapsed = self
4176            .editor
4177            .ancestors_at(dash)
4178            .map(|c| c.into_iter().any(|m| m.kind == Kind::Heading))
4179            .unwrap_or(false);
4180        if !collapsed {
4181            return;
4182        }
4183        let caret = self.caret;
4184        if self.splice(dash, dash + 1, "*", EditKind::Other) {
4185            // Same width, so the caret keeps its column; fold into the edit that
4186            // triggered this so Tab stays one undo step.
4187            let _ = self.editor.coalesce_last_undo();
4188            self.caret = caret.min(self.source.len());
4189            self.clamp_caret();
4190            self.record_caret();
4191        }
4192    }
4193
4194    fn snapshot(&self) -> CaretState {
4195        CaretState {
4196            caret: self.caret,
4197            anchor: self.anchor,
4198        }
4199    }
4200
4201    /// Hand twig the current caret and selection as the blob for the live
4202    /// document state. Called before an edit — so the step twig retires records
4203    /// where the caret was, and undo can restore it — and again once the op has
4204    /// placed the caret, so redo restores where the edit left it.
4205    ///
4206    /// This is the whole of leaf's undo-caret bookkeeping now. twig carries the
4207    /// caret through its own history, so coalescing falls out for free (folding
4208    /// two twig steps into one drops the intermediate blob, keeping the run's
4209    /// first) and the parallel stacks that had to march in lockstep — and could
4210    /// silently drift out of it — are gone.
4211    fn record_caret(&mut self) {
4212        let _ = self.editor.set_caret_blob(&self.snapshot().to_blob());
4213    }
4214
4215    /// Toggle an inline mark over the selection (Bold / Italic / Code / …). Keeps
4216    /// the toggled region selected so a second press cleanly reverses it.
4217    pub fn toggle(&mut self, kind: InlineKind) {
4218        // The read-only gate — this door reaches twig without the splice.
4219        if self.read_only {
4220            return;
4221        }
4222        // Ahead of the no-selection branch below: arming a mark for text not yet
4223        // typed is a promise `insert` cannot keep in a format with no delimiters
4224        // to spell it with. Per *kind*, not per format — Markdown spells five
4225        // of the eight marks (highlight among them, under the `highlight`
4226        // extension leaf parses with), djot all eight, HTML seven.
4227        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleInline(kind)) {
4228            return;
4229        }
4230        let Some((s, e)) = self.selection() else {
4231            // No selection: arm the mark for the next text typed here, the way a
4232            // word processor does. `⌘b`, type, `⌘b` again toggles bold on and off
4233            // in the flow of typing without ever selecting anything — the delta
4234            // is realised onto the freshly typed text by `insert`. A fresh caret
4235            // position starts the delta over from the marks actually in force.
4236            if self.pending_at != Some(self.caret) {
4237                self.pending_marks = InlineMarks::empty();
4238                self.pending_at = Some(self.caret);
4239            }
4240            self.pending_marks.flip(kind);
4241            self.status = None;
4242            return;
4243        };
4244        // Whitespace at the edge of a selection is not part of what was chosen —
4245        // a double-click takes the space after the word with it — and a mark
4246        // cannot close against one anyway: `**word **` is four literal asterisks
4247        // (the mark-edge rule, see `splice`). Mark the words, leave the spaces.
4248        let picked = &self.source[s..e];
4249        let (s, e) = (
4250            s + (picked.len() - picked.trim_start().len()),
4251            e - (picked.len() - picked.trim_end().len()),
4252        );
4253        if s >= e {
4254            self.status = Some(format!("{kind:?}: nothing selected to mark"));
4255            return;
4256        }
4257        // Styling a selection is a one-shot act, not a sticky mode.
4258        self.clear_pending();
4259        self.record_caret();
4260        match self.editor.toggle_inline(s, e, kind) {
4261            Ok(change) => {
4262                self.last_edit_kind = None; // structural edit is its own undo step
4263                self.refresh();
4264                self.anchor = Some(change.new.start);
4265                self.caret = change.new.end;
4266                self.dirty = self.source != self.clean_source;
4267                self.status = None;
4268                self.record_caret();
4269            }
4270            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
4271        }
4272    }
4273
4274    /// Whether the caret stands in a highlight — what a frontend asks to enable
4275    /// or disable its highlight-colour controls, the way
4276    /// [`caret_in_table`](Self::caret_in_table) gates the grid ones.
4277    ///
4278    /// A fact about the *caret*, and the other half of
4279    /// [`Capabilities::mark_color`], which is the fact about the format. A
4280    /// frontend needs both: djot spells a highlight and no colour for it, so a
4281    /// caret standing in `{=word=}` answers `true` here and still has no palette
4282    /// to offer.
4283    ///
4284    /// The rule is [`active_inline_marks`](Self::active_inline_marks)' rule, so
4285    /// the palette appears exactly where the Highlight button is lit — with one
4286    /// deliberate exception: a mark *armed* at a bare caret and not yet typed
4287    /// into lights the button and answers `false` here, because there is no node
4288    /// to colour until the text exists.
4289    pub fn caret_in_mark(&mut self) -> bool {
4290        self.mark_offset().is_some()
4291    }
4292
4293    /// The offset [`set_mark_color`](Self::set_mark_color) speaks for — the one
4294    /// standing in the highlight the gesture means — or `None` when neither end
4295    /// of what is selected is in one.
4296    ///
4297    /// The caret first, and the selection's *start* after it, because of what
4298    /// [`toggle`](Self::toggle) leaves behind: a fresh `==word==` is selected
4299    /// whole, with the caret at its far edge, one past the closing `==` and so
4300    /// (by `marks_at`' half-open rule) not in the mark at all. Highlight a word
4301    /// and colour it — the two presses a coloured highlight is made of — would
4302    /// otherwise refuse on the second, having just written the highlight the
4303    /// author is pointing at.
4304    fn mark_offset(&mut self) -> Option<usize> {
4305        let in_mark = |d: &mut Self, off: usize| {
4306            d.marks_at(off)
4307                .into_iter()
4308                .any(|(k, _)| k == InlineKind::Mark)
4309                .then_some(off)
4310        };
4311        let caret = self.caret.min(self.source.len());
4312        in_mark(self, caret).or_else(|| {
4313            let start = self.selection()?.0;
4314            in_mark(self, start)
4315        })
4316    }
4317
4318    /// The colour of the highlight at the caret — `None` both when the caret is
4319    /// in no highlight and when the highlight it is in names no colour, which
4320    /// are the same answer to "which swatch is lit".
4321    ///
4322    /// The innermost mark, by span, for the same reason
4323    /// [`current_heading_level`](Self::current_heading_level) walks the tree:
4324    /// what the caret is *in* is the deepest node containing it. A `data-color`
4325    /// naming a colour this build has no variant for reads as `None` — the
4326    /// renderer already draws that as a plain highlight rather than guessing,
4327    /// and the toolbar agrees with the renderer.
4328    pub fn mark_color_at_caret(&mut self) -> Option<MarkColor> {
4329        let at = self.mark_offset()?;
4330        self.mark_color_at(at)
4331    }
4332
4333    /// [`mark_color_at_caret`](Self::mark_color_at_caret) at a given offset —
4334    /// the innermost `mark` covering it, and the colour it names.
4335    fn mark_color_at(&mut self, off: usize) -> Option<MarkColor> {
4336        self.nodes()
4337            .into_iter()
4338            .filter(|n| n.kind == Kind::Mark)
4339            .filter(|n| n.span.start <= off && off < n.span.end)
4340            .min_by_key(|n| n.span.end - n.span.start)
4341            .and_then(|n| MarkColor::from_attrs(&n.attrs))
4342    }
4343
4344    /// Colour the highlight at the caret, or clear its colour with `None` — the
4345    /// palette behind a toolbar's Highlight button.
4346    ///
4347    /// Markdown only, and the one gesture whose availability is a fact about the
4348    /// *parse extensions* rather than about the format alone: the colour is
4349    /// spelled `==🔴 text==`, an emoji twig reads back out of the content and
4350    /// records as the mark's `data-color`, and only an editor parsing with
4351    /// `highlight_colors` (which [`parse_extensions`] turns on for every leaf
4352    /// document) reads it back that way. Djot spells the highlight and no colour
4353    /// for it, so this refuses there — see [`Capabilities::mark_color`].
4354    ///
4355    /// **A colour is a property of a highlight that already exists.** There is
4356    /// no "highlight this in red" here, because that is two splices and would be
4357    /// two undo steps under one press; a frontend that wants it calls
4358    /// [`toggle`](Self::toggle) with [`InlineKind::Mark`] first, which is the
4359    /// order the two buttons already sit in. With no highlight at the caret this
4360    /// says so in the status line and writes nothing.
4361    ///
4362    /// The caret keeps its place in the *text*: the splice is entirely in the
4363    /// prefix between the opening `==` and the first word, so an offset past it
4364    /// rides the emoji's width, and one standing on the prefix itself lands
4365    /// where the prefix now ends.
4366    pub fn set_mark_color(&mut self, color: Option<MarkColor>) {
4367        // The read-only gate — this door reaches twig without the splice.
4368        if self.read_only {
4369            return;
4370        }
4371        if self.refuse_unsupported("highlight colour", Gesture::SetMarkColor) {
4372            return;
4373        }
4374        let Some(at) = self.mark_offset() else {
4375            self.status = Some("highlight colour: no highlight at the caret".into());
4376            return;
4377        };
4378        // Clearing a colour a highlight hasn't got is twig's one *successful*
4379        // no-op, and the `Change` it hands back then describes whatever edit came
4380        // before it — a stale span that would drag the caret somewhere it never
4381        // was. Answer it here, where the question is cheap, rather than trusting
4382        // a change that isn't one.
4383        if color.is_none() && self.mark_color_at(at).is_none() {
4384            self.status = None;
4385            return;
4386        }
4387        self.record_caret();
4388        match self.editor.set_mark_color(at, color.map(twig_mark_color)) {
4389            Ok(change) => {
4390                // Re-anchored from the offsets as they were, *before* `refresh`
4391                // sees the new bytes: the caret it clamps is one standing inside
4392                // a prefix that didn't exist a moment ago, and walking it back to
4393                // a char boundary of the emoji loses the place this is restoring.
4394                let caret = reanchor(self.caret, &change);
4395                let anchor = self.anchor.map(|a| reanchor(a, &change));
4396                self.last_edit_kind = None; // structural edit is its own undo step
4397                self.refresh();
4398                self.caret = caret;
4399                self.anchor = anchor;
4400                self.dirty = self.source != self.clean_source;
4401                self.status = None;
4402                self.clamp_caret();
4403                self.record_caret();
4404            }
4405            Err(e) => self.status = Some(format!("highlight colour: {e}")),
4406        }
4407    }
4408
4409    /// One press of a colour swatch: colour the highlight at the caret, or —
4410    /// over a selection that isn't highlighted yet — highlight it and colour it,
4411    /// as **one** undo step.
4412    ///
4413    /// [`set_mark_color`](Self::set_mark_color) is the exact gesture and stays
4414    /// one splice; this is the compound every toolbar actually presses, and it
4415    /// lives here rather than in each frontend because the rule it encodes —
4416    /// what a swatch means when there is no highlight under it yet — is one
4417    /// answer, not one per frontend. The two splices are folded into a single
4418    /// history step, so the press that made a red highlight is taken back by a
4419    /// single undo rather than leaving an uncoloured one behind.
4420    ///
4421    /// `None` clears the colour, and over an unhighlighted selection means
4422    /// simply "highlight this" — the same thing the Highlight button does.
4423    /// A bare caret in no highlight is left alone with a status line, because
4424    /// [`toggle`](Self::toggle) there arms a mark for text not yet typed and a
4425    /// colour cannot be armed with it.
4426    pub fn highlight(&mut self, color: Option<MarkColor>) {
4427        if self.caret_in_mark() || self.selection().is_none() {
4428            self.set_mark_color(color);
4429            return;
4430        }
4431        self.toggle(InlineKind::Mark);
4432        // The format may not spell a highlight at all (`toggle` said so), and
4433        // there is nothing to colour if it doesn't.
4434        if self.status.is_some() {
4435            return;
4436        }
4437        let before = self.revision;
4438        self.set_mark_color(color);
4439        // Only fold when the colour really spliced. `highlight(None)` over a
4440        // fresh highlight is a no-op by design, and coalescing there would eat
4441        // the *previous* edit into the toggle instead.
4442        if self.revision != before {
4443            let _ = self.editor.coalesce_last_undo();
4444        }
4445    }
4446
4447    // ── the presentation vocabulary ─────────────────────────────────────────
4448    //
4449    // Six gestures and five queries over twig's two attribute ops. Each gesture
4450    // edits **one key and keeps the rest**: it reads the node's attributes,
4451    // removes its own key (and, for alignment, its own tokens out of `class`),
4452    // adds the new value or nothing, and passes the list back whole — twig's
4453    // contract is replace-not-merge, so the read is the caller's job. A
4454    // paragraph that came in as `class="lead center" id="intro"
4455    // data-line-height="1.5"` and is right-aligned goes out as `class="lead
4456    // right" id="intro" data-line-height="1.5"`. Nothing leaf did not write is
4457    // touched, which is what lets a document from elsewhere pass through the
4458    // editor unharmed.
4459    //
4460    // Clearing is the same gesture with `None`: the key goes, and an empty list
4461    // at the end unwraps the span or the Markdown div, which twig does.
4462
4463    /// Set — or with `None` clear — the alignment of the block the caret is in.
4464    ///
4465    /// A block property, so the gesture is `set_block_attrs` on the caret's
4466    /// block **whatever is selected**: a line is a block's, and "centre this"
4467    /// with three words selected means the paragraph, not the words. The
4468    /// vocabulary is [`Align`], written as `class` tokens; other tokens on the
4469    /// same `class` are kept.
4470    ///
4471    /// In Markdown the attributes live on a `<div>` around the block — twig has
4472    /// no paragraph attribute syntax to write — and this reads them back off
4473    /// that div when the block is its sole child, so a second press rewrites
4474    /// the div rather than nesting a second one.
4475    pub fn set_alignment(&mut self, align: Option<Align>) {
4476        let attrs = self.block_attrs_at_caret();
4477        if align.is_none()
4478            && self.refuse_clear_from_div("alignment", &attrs, |a| Align::from_attrs(a).is_some())
4479        {
4480            return;
4481        }
4482        let attrs = with_class_token(
4483            &attrs,
4484            |t| Align::from_token(t).is_some(),
4485            align.map(Align::name),
4486        );
4487        self.write_block_attrs("alignment", attrs);
4488    }
4489
4490    /// Set — or with `None` clear — the line spacing of the block the caret is
4491    /// in. [`set_alignment`](Self::set_alignment)'s peer in every respect but
4492    /// the key: [`LineHeight`] under `data-line-height`, one of the menu's
4493    /// three names or an exact ratio, written in its canonical spelling.
4494    pub fn set_line_spacing(&mut self, spacing: Option<LineHeight>) {
4495        let attrs = self.block_attrs_at_caret();
4496        if spacing.is_none()
4497            && self.refuse_clear_from_div("line spacing", &attrs, |a| {
4498                LineHeight::from_attrs(a).is_some()
4499            })
4500        {
4501            return;
4502        }
4503        let spelling = spacing.map(LineHeight::name);
4504        let attrs = with_attr(&attrs, "data-line-height", spelling.as_deref());
4505        self.write_block_attrs("line spacing", attrs);
4506    }
4507
4508    /// Set — or with `None` clear — the size of the selected run, or of the
4509    /// caret's whole block when nothing is selected.
4510    ///
4511    /// Size, face and colour are the *run's*, and the block's when no run is
4512    /// chosen. With a selection the gesture is `wrap_range_attrs`, which wraps
4513    /// the range in an attributed span or re-styles the span it already lies in
4514    /// (never nesting a second, and unwrapping it when the last key goes). With
4515    /// no selection it is `set_block_attrs` on the caret's block, so that "make
4516    /// this paragraph larger" is a click with the caret in it rather than a
4517    /// select-all first.
4518    ///
4519    /// The walker reads the key at both levels with the nearer winning, so a
4520    /// span's `data-size` inside a block carrying its own applies to the span.
4521    ///
4522    /// The vocabulary is [`FontSize`]: one of CSS's seven keywords, which is
4523    /// what a menu offers first because a step reads as a step up under every
4524    /// theme, or the point size an author asked for, which is exact and is all
4525    /// it is. Either is written in its canonical spelling, so a size set twice
4526    /// from the same field writes the same bytes both times.
4527    pub fn set_font_size(&mut self, size: Option<FontSize>) {
4528        let spelling = size.map(FontSize::name);
4529        self.set_run_attr("size", "data-size", spelling.as_deref());
4530    }
4531
4532    /// Set — or with `None` clear — the face of the selected run, or of the
4533    /// caret's whole block. [`set_font_size`](Self::set_font_size)'s peer, with
4534    /// [`FontFace`] under `data-font` — one of the four generics, or the family
4535    /// the author named, which the frontends resolve through the platform's
4536    /// font registry and fall back to the body face without.
4537    pub fn set_font_family(&mut self, font: Option<FontFace>) {
4538        let spelling = font.as_ref().map(FontFace::name);
4539        self.set_run_attr("font", "data-font", spelling.as_deref());
4540    }
4541
4542    /// Set — or with `None` clear — the *text* colour of the selected run, or of
4543    /// the caret's whole block. [`set_font_size`](Self::set_font_size)'s peer,
4544    /// with [`TextColor`] under `data-color` — one of the seven names, whose
4545    /// two inks the theme owns, or the triple the author picked, which is
4546    /// painted as written in both appearances.
4547    ///
4548    /// The same key and the same seven names [`set_mark_color`](Self::set_mark_color)
4549    /// writes, and a different thing: that one colours a highlight's
4550    /// *background* and rides the `mark` node twig owns the spelling of, this
4551    /// one colours the letters and rides an attributed span. The two never
4552    /// collide, because a `mark` is a `mark` and a span is a span — and they
4553    /// share a vocabulary on purpose, so that a frontend with a red for a
4554    /// highlight has a red for text and both are *that* red.
4555    pub fn set_text_color(&mut self, color: Option<TextColor>) {
4556        let spelling = color.map(TextColor::name);
4557        self.set_run_attr("text colour", "data-color", spelling.as_deref());
4558    }
4559
4560    /// Insert a page break at the caret — `::page-break`, a leaf directive with
4561    /// no label and no attributes, which twig spells in every format that names
4562    /// a leaf container (Markdown under the `directives` extension
4563    /// [`parse_extensions`] turns on, and djot, where it is an empty `:::
4564    /// page-break` fence).
4565    ///
4566    /// Placed exactly as [`insert_thematic_break`](Self::insert_thematic_break)
4567    /// places a rule, and for the same reason: a directive is a block, so twig
4568    /// alone has nowhere to put one mid-paragraph and lands it after the
4569    /// caret's whole block. A bare paragraph is therefore parted at the caret
4570    /// first and the break aimed at the *first* half. See that method for the
4571    /// whole of the rule, including why a code block, a list item, a table and
4572    /// a setext heading are left unsplit.
4573    ///
4574    /// The frontends that paginate read the row's
4575    /// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) and open a page there;
4576    /// the ones that do not draw the `⧉ page-break` placeholder every leaf
4577    /// directive gets.
4578    pub fn insert_page_break(&mut self) {
4579        if self.read_only || self.refuse_unsupported("page break", Gesture::InsertDirective) {
4580            return;
4581        }
4582        self.caret = self.skip_trailing_close_delims(self.caret);
4583        // A selection is replaced by the break, as a rule replaces one.
4584        if let Some((s, e)) = self.selection() {
4585            self.splice(s, e, "", EditKind::Other);
4586        }
4587        self.anchor = None;
4588        self.record_caret();
4589        let at = self.caret;
4590        if self.caret_parts_bare_paragraph() {
4591            // A failure here is not fatal: the break still lands after the
4592            // block, which is what this call was trying to improve on.
4593            let _ = self.editor.split_block(at);
4594        }
4595        match self.editor.insert_directive(at, PAGE_BREAK, None, &[]) {
4596            Ok(change) => {
4597                self.last_edit_kind = None;
4598                self.refresh();
4599                self.anchor = None;
4600                self.caret = change.new.end;
4601                self.dirty = self.source != self.clean_source;
4602                self.status = None;
4603                self.clamp_caret();
4604                self.record_caret();
4605            }
4606            Err(e) => self.status = Some(format!("page break: {e}")),
4607        }
4608    }
4609
4610    /// The alignment in force at the caret, or `None` for the theme's default —
4611    /// which swatch of an alignment control is lit.
4612    ///
4613    /// Read off the nearest node that names one: the block the caret is in, and
4614    /// the `div`s around it after that. [`mark_color_at_caret`](Self::mark_color_at_caret)'s
4615    /// shape, one property along.
4616    pub fn alignment_at_caret(&mut self) -> Option<Align> {
4617        self.presentation_chain()
4618            .iter()
4619            .find_map(|attrs| Align::from_attrs(attrs))
4620    }
4621
4622    /// The line spacing in force at the caret, or `None` for the theme's own.
4623    /// [`alignment_at_caret`](Self::alignment_at_caret)'s peer.
4624    pub fn line_spacing_at_caret(&mut self) -> Option<LineHeight> {
4625        self.presentation_chain()
4626            .iter()
4627            .find_map(|attrs| LineHeight::from_attrs(attrs))
4628    }
4629
4630    /// The size in force at the caret, or `None` for the theme's own — the
4631    /// entry a size menu shows ticked.
4632    ///
4633    /// Run-level, so the chain starts one node deeper: the attributed span the
4634    /// caret stands in, then its block, then the `div`s around it. The nearest
4635    /// wins, which is the rule the walker draws by.
4636    ///
4637    /// A name or a value, whichever the nearest node wrote. A `data-size` the
4638    /// grammar does not cover — a `huge` from elsewhere — is not a size this
4639    /// can answer, so the answer is `None` and the menu ticks *Default*, the
4640    /// same thing it did before the vocabulary opened.
4641    pub fn font_size_at_caret(&mut self) -> Option<FontSize> {
4642        self.presentation_chain()
4643            .iter()
4644            .find_map(|attrs| FontSize::from_attrs(attrs))
4645    }
4646
4647    /// The face in force at the caret, or `None` for the theme's body face.
4648    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer.
4649    pub fn font_family_at_caret(&mut self) -> Option<FontFace> {
4650        self.presentation_chain()
4651            .iter()
4652            .find_map(|attrs| FontFace::from_attrs(attrs))
4653    }
4654
4655    /// The *text* colour in force at the caret, or `None` for the theme's.
4656    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer, and not
4657    /// [`mark_color_at_caret`](Self::mark_color_at_caret) — that one reads a
4658    /// highlight's background off a `mark`, and a `mark` is never in this chain.
4659    pub fn text_color_at_caret(&mut self) -> Option<TextColor> {
4660        self.presentation_chain()
4661            .iter()
4662            .find_map(|attrs| TextColor::from_attrs(attrs))
4663    }
4664
4665    /// The selection-or-caret half of the three run-level gestures: a span over
4666    /// a real selection, the caret's block over none.
4667    fn set_run_attr(&mut self, what: &str, key: &str, value: Option<&str>) {
4668        match self.selection() {
4669            Some((start, end)) => {
4670                let attrs = with_attr(&self.run_attrs_over(start, end), key, value);
4671                self.write_run_attrs(what, start, end, attrs);
4672            }
4673            None => {
4674                let own = self.block_attrs_at_caret();
4675                if value.is_none()
4676                    && self.refuse_clear_from_div(what, &own, |a| a.iter().any(|(k, _)| k == key))
4677                {
4678                    return;
4679                }
4680                let attrs = with_attr(&own, key, value);
4681                self.write_block_attrs(what, attrs);
4682            }
4683        }
4684    }
4685
4686    /// A clear this gesture cannot carry out, said out loud instead of written:
4687    /// the node it rewrites — the caret's block, or the `<div>` around it that
4688    /// [`block_attrs_at_caret`](Self::block_attrs_at_caret) folds to in Markdown
4689    /// — does not name the property at all, and a `div` further out does.
4690    ///
4691    /// Handing twig the block's attributes with the key already absent changes
4692    /// no byte, and the query goes on answering `Some` off the div: the menu
4693    /// entry the author pressed stays unticked, and nothing says why. Twig's
4694    /// `set_block_attrs` reaches one node, so leaf cannot clear a key it did not
4695    /// write on a node it is not rewriting — the honest answer is the status
4696    /// line, in the voice the other refusals use.
4697    ///
4698    /// `names` is the property's own reading of an attribute list, because
4699    /// alignment lives in a `class` token rather than a key of its own. Spans
4700    /// are skipped: one inside the block is not what a *block* gesture writes
4701    /// either, but neither is it "the div around the block", and the run-level
4702    /// gestures reach it through a selection.
4703    fn refuse_clear_from_div(
4704        &mut self,
4705        what: &str,
4706        own: &Attrs,
4707        names: impl Fn(&Attrs) -> bool,
4708    ) -> bool {
4709        if names(own) {
4710            return false;
4711        }
4712        let caret = self.caret.min(self.source.len());
4713        if !self
4714            .attr_chain_at(caret)
4715            .iter()
4716            .any(|(span, attrs)| !span && names(attrs))
4717        {
4718            return false;
4719        }
4720        self.status = Some(format!("{what}: set on the div around the block"));
4721        true
4722    }
4723
4724    /// Hand `attrs` to twig as the caret's block's whole attribute set, with the
4725    /// status, undo and caret plumbing [`set_mark_color`](Self::set_mark_color)
4726    /// has.
4727    ///
4728    /// **The caret keeps its place in the text, not its byte offset.** How a
4729    /// format spells a block's attributes is markup written *around* the block
4730    /// — djot's `{…}` line above it, a `<div …>` and two blank lines in front of
4731    /// it in Markdown, a longer opening tag in HTML — and every one of those
4732    /// grows or shrinks above the author's own bytes. Where twig's change
4733    /// rewrites the block whole (Markdown's div is spliced as one region, block
4734    /// included) the plain arithmetic of [`reanchor`] has nothing to shift by
4735    /// and parks the caret at the end of the splice, past the closing `</div>`:
4736    /// the caret is then in no block at all, so a second press of the same menu
4737    /// answers "no block at the caret" and the toolbar's queries read nothing.
4738    /// [`reanchor_in_block`] is what carries it across instead — the block's
4739    /// content span before and after, which is the one thing the respelling
4740    /// leaves alone.
4741    ///
4742    /// Read *before* the splice and applied *after* `refresh`, because both
4743    /// halves of that mapping are facts about a tree twig is between: the
4744    /// block's old bytes are gone once the edit lands, and its new ones are not
4745    /// in `self.source` until the refresh puts them there.
4746    fn write_block_attrs(&mut self, what: &str, attrs: Attrs) {
4747        if self.read_only || self.refuse_unsupported(what, Gesture::SetBlockAttrs) {
4748            return;
4749        }
4750        // A blank line has no block to carry an attribute, and twig answers
4751        // `NotFound` there — say so in leaf's own words instead.
4752        let Some(at) = self.block_offset_for_caret() else {
4753            self.status = Some(format!("{what}: no block at the caret"));
4754            return;
4755        };
4756        self.record_caret();
4757        let pairs = attr_pairs(&attrs);
4758        let was = self.block_content_at(at);
4759        let text = was.clone().map(|s| self.source[s].to_string());
4760        match self.editor.set_block_attrs(at, &pairs) {
4761            Ok(change) => {
4762                let (caret, anchor) = (self.caret, self.anchor);
4763                self.last_edit_kind = None; // structural edit is its own undo step
4764                self.refresh();
4765                let now = self.block_content_in(&change.new, text.as_deref());
4766                // A block the two halves cannot both name — a code block, a
4767                // caret in a list's marker — takes the plain arithmetic, which
4768                // is what it had before.
4769                let block = was.as_ref().zip(now.as_ref());
4770                self.caret = reanchor_in_block(caret, &change, block);
4771                self.anchor = anchor.map(|a| reanchor_in_block(a, &change, block));
4772                self.dirty = self.source != self.clean_source;
4773                self.status = None;
4774                // The clamp reads the caret floor off the map, and this edit
4775                // can move the floor: taking the `{…}` line off a djot
4776                // document's first block moves the first rendered offset to 0,
4777                // and a floor read from the old map stood the caret past the
4778                // block's text. So the map is this revision's before the clamp
4779                // — see `open_paragraph_at_block_edge`.
4780                self.rebuild_map();
4781                self.clamp_caret();
4782                self.record_caret();
4783            }
4784            Err(e) => self.status = Some(format!("{what}: {e}")),
4785        }
4786    }
4787
4788    /// The content span of the innermost paragraph or heading covering `off` —
4789    /// the author's own bytes, without the `# ` or the `<p>` that spells the
4790    /// block around them.
4791    ///
4792    /// The same two kinds [`block_attrs_at_caret`](Self::block_attrs_at_caret)
4793    /// reads, so that what a gesture re-anchors by is the block it wrote to.
4794    fn block_content_at(&mut self, off: usize) -> Option<Range<usize>> {
4795        self.nodes()
4796            .into_iter()
4797            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
4798            .filter(|n| n.span.start <= off && off <= n.span.end)
4799            .min_by_key(|n| n.span.end - n.span.start)
4800            .map(|n| n.content_span.unwrap_or(n.span))
4801    }
4802
4803    /// [`block_content_at`](Self::block_content_at)'s other half: the content
4804    /// span of the block `region` holds now, found by the bytes it held before.
4805    ///
4806    /// Matched on the text rather than taken as the first block in the region,
4807    /// because a rewritten region is markup and all — `<div class="center">`
4808    /// carries words of its own — and because the block this gesture moved is
4809    /// the one whose content the respelling did not touch. `None` where the
4810    /// region holds no block at all, which is djot's every case: the `{…}` line
4811    /// is spliced above the block and the block itself never moves through the
4812    /// change at all, only past it.
4813    fn block_content_in(
4814        &mut self,
4815        region: &Range<usize>,
4816        text: Option<&str>,
4817    ) -> Option<Range<usize>> {
4818        let text = text?;
4819        let spans: Vec<Range<usize>> = self
4820            .nodes()
4821            .into_iter()
4822            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
4823            .filter(|n| region.start <= n.span.start && n.span.end <= region.end)
4824            .map(|n| n.content_span.unwrap_or(n.span))
4825            .collect();
4826        spans
4827            .into_iter()
4828            .find(|s| self.source.get(s.clone()) == Some(text))
4829    }
4830
4831    /// Hand `attrs` to twig as the attribute set of the span over `[start,
4832    /// end)` — wrapping one, or re-styling the one the range already lies in,
4833    /// or unwrapping it when `attrs` is empty.
4834    ///
4835    /// What the splice leaves selected is the span's **content** — the author's
4836    /// words — and not the whole of `change.new`, which is markup and all:
4837    /// `[big]{data-size="large"}` in djot, `<span …>big</span>` in Markdown. A
4838    /// selection reaching past the node's own span lies in no span at all, so a
4839    /// second press of the menu would nest a fresh one instead of re-styling
4840    /// the one just written.
4841    fn write_run_attrs(&mut self, what: &str, start: usize, end: usize, attrs: Attrs) {
4842        if self.read_only || self.refuse_unsupported(what, Gesture::WrapRangeAttrs) {
4843            return;
4844        }
4845        self.record_caret();
4846        let pairs = attr_pairs(&attrs);
4847        match self.editor.wrap_range_attrs(start, end, &pairs) {
4848            Ok(change) => {
4849                self.last_edit_kind = None;
4850                self.refresh();
4851                let content = self.span_content_in(&change.new);
4852                self.anchor = Some(content.start);
4853                self.caret = content.end;
4854                self.dirty = self.source != self.clean_source;
4855                self.status = None;
4856                self.clamp_caret();
4857                self.record_caret();
4858            }
4859            Err(e) => self.status = Some(format!("{what}: {e}")),
4860        }
4861    }
4862
4863    /// The content range of the attributed span `spliced` now holds — the
4864    /// outermost one inside it, since that is the one just written — or
4865    /// `spliced` itself where the splice left no span, which is what an unwrap
4866    /// leaves behind.
4867    fn span_content_in(&mut self, spliced: &Range<usize>) -> Range<usize> {
4868        self.nodes()
4869            .into_iter()
4870            .filter(wysiwyg::is_run_span)
4871            .filter(|n| spliced.start <= n.span.start && n.span.end <= spliced.end)
4872            .max_by_key(|n| n.span.end - n.span.start)
4873            .and_then(|n| n.content_span)
4874            .unwrap_or_else(|| spliced.clone())
4875    }
4876
4877    /// The attribute set `set_block_attrs` is about to **replace** at the caret
4878    /// — which is the block's own, except in Markdown, where twig writes a
4879    /// block's attributes onto a `<div>` around it and rewrites that div when
4880    /// the block is its sole child. Reading the paragraph there would hand back
4881    /// an empty list and quietly drop everything the div said.
4882    ///
4883    /// Empty when the caret is in no block at all, which is the same list a
4884    /// block carrying no attributes gives — and the right one either way, since
4885    /// the gesture then refuses on its own.
4886    fn block_attrs_at_caret(&mut self) -> Attrs {
4887        let Some(off) = self.block_offset_for_caret() else {
4888            return Vec::new();
4889        };
4890        let nodes = self.nodes();
4891        let Some(block) = nodes
4892            .iter()
4893            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
4894            .filter(|n| n.span.start <= off && off <= n.span.end)
4895            .min_by_key(|n| n.span.end - n.span.start)
4896        else {
4897            return Vec::new();
4898        };
4899        if self.format == Format::Markdown
4900            && let Some(parent) = block.parent.and_then(|p| nodes.iter().find(|n| n.id == p))
4901            && wysiwyg::element_tag(parent) == Some("div")
4902            && nodes.iter().filter(|n| n.parent == Some(parent.id)).count() == 1
4903        {
4904            return parent.attrs.clone();
4905        }
4906        block.attrs.clone()
4907    }
4908
4909    /// The attribute set `wrap_range_attrs` is about to **replace** over
4910    /// `[start, end)` — the innermost attributed span the range lies inside,
4911    /// which twig re-styles rather than nesting a second one in. Empty when the
4912    /// range lies in no span, where the gesture mints a fresh one.
4913    fn run_attrs_over(&mut self, start: usize, end: usize) -> Attrs {
4914        self.nodes()
4915            .into_iter()
4916            .filter(wysiwyg::is_run_span)
4917            .filter(|n| n.span.start <= start && end <= n.span.end)
4918            .min_by_key(|n| n.span.end - n.span.start)
4919            .map(|n| n.attrs)
4920            .unwrap_or_default()
4921    }
4922
4923    /// The attribute lists that bear on a presentation query, **nearest first**:
4924    /// the attributed spans the caret stands in (innermost first), then its
4925    /// block, then the `div`s around it. A `find_map` down this is the whole of
4926    /// each query, and the order is the rule the walker draws by.
4927    ///
4928    /// Read at the caret, and at the selection's *start* when the caret stands
4929    /// in no span there. [`write_run_attrs`](Self::write_run_attrs) leaves the
4930    /// caret one past the span it just wrote — `toggle`'s convention — so
4931    /// asking the menu which entry that press just ticked must not answer
4932    /// `None`. Exactly the reason [`mark_offset`](Self::mark_offset) tries both.
4933    fn presentation_chain(&mut self) -> Vec<Attrs> {
4934        let caret = self.caret.min(self.source.len());
4935        let mut chain = self.attr_chain_at(caret);
4936        if !chain.iter().any(|(span, _)| *span)
4937            && let Some((start, _)) = self.selection()
4938        {
4939            let alt = self.attr_chain_at(start);
4940            if alt.iter().any(|(span, _)| *span) {
4941                chain = alt;
4942            }
4943        }
4944        chain.into_iter().map(|(_, attrs)| attrs).collect()
4945    }
4946
4947    /// [`presentation_chain`](Self::presentation_chain) at one offset — every
4948    /// node bearing the vocabulary that covers it, innermost first, each paired
4949    /// with whether it is an attributed span (which is what tells the caller
4950    /// its run-level answer came from a run).
4951    ///
4952    /// Sorted by span length, which *is* the nesting order: a span lies inside
4953    /// its block and a block inside its div, so shortest-first is
4954    /// nearest-first without a second tree walk.
4955    fn attr_chain_at(&mut self, off: usize) -> Vec<(bool, Attrs)> {
4956        let off = off.min(self.source.len());
4957        let mut hits: Vec<(usize, bool, Attrs)> = Vec::new();
4958        for n in self.nodes() {
4959            let span = wysiwyg::is_run_span(&n);
4960            let block = matches!(n.kind, Kind::Para | Kind::Heading);
4961            let div = wysiwyg::element_tag(&n) == Some("div");
4962            if !(span || block || div) {
4963                continue;
4964            }
4965            // A span is half-open, the way a mark is: the offset one past it is
4966            // the text after it. A block and a div claim their end too, so a
4967            // caret resting at the end of a line still reads its paragraph.
4968            let inside = if span {
4969                n.span.start <= off && off < n.span.end
4970            } else {
4971                n.span.start <= off && off <= n.span.end
4972            };
4973            if !inside {
4974                continue;
4975            }
4976            hits.push((n.span.end - n.span.start, span, n.attrs));
4977        }
4978        hits.sort_by_key(|(len, _, _)| *len);
4979        hits.into_iter()
4980            .map(|(_, span, attrs)| (span, attrs))
4981            .collect()
4982    }
4983
4984    /// Convert the block at the caret to a heading level or paragraph.
4985    pub fn set_block(&mut self, kind: BlockKind) {
4986        // The read-only gate — this door reaches twig without the splice.
4987        if self.read_only {
4988            return;
4989        }
4990        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::SetBlock) {
4991            return;
4992        }
4993        self.record_caret();
4994        // A blank line has no node to convert, and twig opens a block there
4995        // rather than declining — so the caret's own offset is the right thing
4996        // to hand it when `block_offset_for_caret` finds nothing.
4997        let offset = self.block_offset_for_caret().unwrap_or(self.caret);
4998        match self.editor.set_block(offset, kind) {
4999            Ok(change) => {
5000                self.last_edit_kind = None;
5001                self.refresh();
5002                // Opening a block on a blank line writes a marker the caret
5003                // belongs *after*; converting an existing one moves nothing.
5004                self.caret = self.caret.max(change.new.end);
5005                self.clamp_caret();
5006                self.anchor = None;
5007                self.dirty = self.source != self.clean_source;
5008                self.status = None;
5009                self.record_caret();
5010            }
5011            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
5012        }
5013    }
5014
5015    /// Whether `off` is inside a text block (paragraph, heading, code block…).
5016    fn has_block_at(&mut self, off: usize) -> bool {
5017        self.editor.ancestors_at(off).ok().is_some_and(|chain| {
5018            chain
5019                .iter()
5020                .any(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
5021        })
5022    }
5023
5024    /// The offset to hand twig's `set_block`: the caret when it is already inside
5025    /// a block, otherwise nudged onto the previous character (a caret at a line
5026    /// end sits at the doc level, outside the block). `None` when the caret is on
5027    /// a blank line — a new paragraph with no block node to convert.
5028    fn block_offset_for_caret(&mut self) -> Option<usize> {
5029        let caret = self.caret.min(self.source.len());
5030        if self.has_block_at(caret) {
5031            return Some(caret);
5032        }
5033        // Nudge to the previous character — but never across a newline: that would
5034        // target the previous block, and a blank line genuinely has no block.
5035        if let Some((i, ch)) = self.source[..caret].char_indices().next_back()
5036            && ch != '\n'
5037            && self.has_block_at(i)
5038        {
5039            return Some(i);
5040        }
5041        None
5042    }
5043
5044    /// The heading level of the text block at the caret, or `None` when that
5045    /// block is not a heading.
5046    pub fn current_heading_level(&mut self) -> Option<u32> {
5047        let caret = self.caret;
5048        self.nodes()
5049            .into_iter()
5050            .filter(|n| n.kind == Kind::Heading)
5051            .find(|n| n.span.start <= caret && caret <= n.span.end)
5052            .and_then(|n| n.level)
5053    }
5054
5055    /// The inline marks in force at the caret (or over the selection) — what a
5056    /// toolbar draws lit, and the block-level [`Doc::current_heading_level`]'s
5057    /// inline counterpart. Cheap enough to call every frame: one twig
5058    /// `ancestors_at` query per caret (two with a selection), each walking root
5059    /// → deepest node at one offset. It never snapshots the tree the way
5060    /// `current_heading_level` does, and the returned set is a `Copy` bitset, so
5061    /// the only allocation is twig's own small ancestor `Vec`.
5062    ///
5063    /// **A selection reports a mark only when the mark covers *all* of it.**
5064    /// That's what every real toolbar means by an active button — Bold lit over
5065    /// a half-bold selection would claim a press turns bold *off*, when
5066    /// [`Doc::toggle`] hands the range to twig and gets the whole thing bolded.
5067    /// Whole-coverage is asked as "is the same mark node standing over both the
5068    /// first and the last character?": inline nodes are contiguous, so one node
5069    /// covering both ends covers every byte between them. Two touching runs
5070    /// (`**a****b**`) are two nodes, and correctly light nothing.
5071    ///
5072    /// At a bare caret a mark is active when the caret stands inside the mark's
5073    /// span — `span.start <= caret < span.end`, delimiters included, which is
5074    /// what makes the boundaries behave. In `a **bold** b` the offsets from the
5075    /// opening `*` (2) through the last byte of the closing `**` (9) are all
5076    /// bold, so the WYSIWYG caret both before `b` and after `d` (the delimiters
5077    /// are hidden, and those offsets are 4 and 8) reports bold — matching where
5078    /// typing would actually land inside the marked run. The offset one past the
5079    /// mark (10) is the text after it and reports nothing, at the end of the
5080    /// buffer exactly as in the middle.
5081    pub fn active_inline_marks(&mut self) -> InlineMarks {
5082        let Some((start, end)) = self.selection() else {
5083            // The marks actually in force at the caret, flipped by any armed
5084            // sticky delta — so `⌘b` at a bare caret lights the Bold button
5085            // immediately, before a single character is typed.
5086            let base: InlineMarks = self
5087                .marks_at(self.caret)
5088                .into_iter()
5089                .map(|(k, _)| k)
5090                .collect();
5091            return base.xor(self.pending_here());
5092        };
5093        // The selection's *last character*, not its exclusive end: `end` is the
5094        // offset one past the selection, which for a selection ending exactly at
5095        // a mark's close is already outside it (`[4,10)` of `a **bold** b` is
5096        // entirely bold, but offset 10 is the space after).
5097        let last = prev_boundary(&self.source, end);
5098        let head = self.marks_at(start);
5099        let tail = self.marks_at(last);
5100        head.into_iter()
5101            .filter(|m| tail.contains(m))
5102            .map(|(k, _)| k)
5103            .collect()
5104    }
5105
5106    /// The inline marks whose span covers `off`, each with the id of the node
5107    /// carrying it — the id is what lets a selection tell one mark node from
5108    /// another of the same kind.
5109    fn marks_at(&mut self, off: usize) -> Vec<(InlineKind, u32)> {
5110        let off = off.min(self.source.len());
5111        self.editor
5112            .ancestors_at(off)
5113            .unwrap_or_default()
5114            .into_iter()
5115            // `span.end` is the offset one *past* the mark, so it isn't in it.
5116            // twig already resolves a boundary to whatever starts there — in
5117            // `**bold** x` offset 8 is the following text, not the strong — but
5118            // when nothing follows, the tie has nobody to break for and the
5119            // chain still ends at the mark. That would make the answer at the
5120            // last offset of the document depend on whether the file happens to
5121            // end in a newline; the rule is `span.start <= off < span.end`, and
5122            // it's the same rule at the end of a buffer as in the middle.
5123            .filter(|m| off < m.span.end)
5124            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.node_id)))
5125            .collect()
5126    }
5127
5128    /// Toggle a heading at the caret: if the block is already this heading level,
5129    /// revert it to a paragraph; otherwise convert it to this heading level.
5130    /// This gives the heading commands the same toggle feel as bold/italic/code —
5131    /// re-applying a heading a line already has turns it back into body text.
5132    pub fn toggle_heading(&mut self, level: u32) {
5133        if self.current_heading_level() == Some(level) {
5134            self.set_block(BlockKind::Paragraph);
5135        } else {
5136            self.set_block(BlockKind::Heading(level));
5137        }
5138    }
5139
5140    /// Toggle a block quote around the selection, or around the block at the
5141    /// caret — the toolbar's Quote button.
5142    pub fn toggle_blockquote(&mut self) {
5143        self.toggle_container(BlockContainerKind::BlockQuote);
5144    }
5145
5146    /// Toggle a numbered (`ordered`) or bulleted list over the selection, or
5147    /// over the block at the caret — one op with the kind as a flag, the way
5148    /// `toggle_heading` takes its level, so a frontend needs no twig type to
5149    /// name the two buttons.
5150    ///
5151    /// Pressing the *other* list's button while in a list converts in place
5152    /// rather than nesting, so the pair reads as one three-state control
5153    /// (bulleted / numbered / neither) rather than two independent wrappers.
5154    pub fn toggle_list(&mut self, ordered: bool) {
5155        self.toggle_container(if ordered {
5156            BlockContainerKind::OrderedList
5157        } else {
5158            BlockContainerKind::BulletList
5159        });
5160    }
5161
5162    // ── Task list items ──────────────────────────────────────────────────────
5163    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
5164    // inline content of the item's first paragraph rather than part of its
5165    // marker, so adding or removing one must leave the item's continuation
5166    // indentation alone, and an item inside a quote is found past the quote
5167    // markers. leaf names the gesture and the offset; the spelling is twig's.
5168
5169    /// Whether the list item at the caret carries a checkbox, and which way it
5170    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
5171    /// item or no item at all. What a toolbar reads to light its checkbox button.
5172    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
5173        self.task_checked_at(self.caret)
5174    }
5175
5176    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
5177    /// offset — what a frontend asks before deciding a click landed on a box.
5178    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
5179        self.innermost_list_item(offset.min(self.source.len()))?
5180            .checked
5181    }
5182
5183    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
5184    /// A no-op with a reported reason when the caret is in no task item — minting
5185    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
5186    pub fn toggle_task_checked(&mut self) {
5187        self.toggle_task_at(self.caret);
5188    }
5189
5190    /// Tick or untick the task item covering `offset` — what a *click* on a
5191    /// rendered checkbox is. Separate from the caret form because a click carries
5192    /// its own offset and must not first move the caret there: ticking a box
5193    /// three paragraphs away should not take the cursor with it.
5194    pub fn toggle_task_at(&mut self, offset: usize) {
5195        // The read-only gate — this door reaches twig without the splice.
5196        if self.read_only {
5197            return;
5198        }
5199        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
5200            return;
5201        }
5202        let offset = offset.min(self.source.len());
5203        self.record_caret();
5204        match self.editor.toggle_task_checked(offset) {
5205            Ok(_) => self.after_task_edit(),
5206            Err(e) => self.status = Some(format!("task: {e}")),
5207        }
5208    }
5209
5210    /// Give the list item at the caret a checkbox, or take its checkbox away —
5211    /// the gesture that converts between a plain bullet and a task. A new box
5212    /// arrives unticked.
5213    pub fn toggle_task_item(&mut self) {
5214        // The read-only gate — this door reaches twig without the splice.
5215        if self.read_only {
5216            return;
5217        }
5218        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
5219            return;
5220        }
5221        let caret = self.caret.min(self.source.len());
5222        self.record_caret();
5223        match self.editor.toggle_task_item(caret) {
5224            Ok(_) => self.after_task_edit(),
5225            Err(e) => self.status = Some(format!("task: {e}")),
5226        }
5227    }
5228
5229    /// Settle after a task gesture. The caret rides its old byte offset and is
5230    /// clamped back in: a box is three or four bytes on the item's first line, so
5231    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
5232    /// real stop either way.
5233    fn after_task_edit(&mut self) {
5234        self.last_edit_kind = None;
5235        self.refresh();
5236        self.anchor = None;
5237        self.dirty = self.source != self.clean_source;
5238        self.status = None;
5239        self.clamp_caret();
5240        self.record_caret();
5241    }
5242
5243    // ── Tables ───────────────────────────────────────────────────────────────
5244    // A table is a grid, and twig edits it as one — add/remove/move a row or
5245    // column, set a column's alignment — re-spelling the whole table in a single
5246    // splice. Every gesture is anchored at the caret's cell. leaf just names the
5247    // gesture and re-reads the result; the whole table's numbering, borders, and
5248    // delimiter are twig's to keep straight.
5249
5250    /// Whether the caret is inside a table — what a frontend asks to enable or
5251    /// disable its table controls.
5252    ///
5253    /// An HTML `<table>` still answers `true`: the caret really is in a table,
5254    /// and the reason the grid controls stay dark there is
5255    /// [`Capabilities::table`], which is a fact about the document's format
5256    /// rather than about the caret. A frontend needs both.
5257    pub fn caret_in_table(&mut self) -> bool {
5258        let caret = self.caret.min(self.source.len());
5259        self.editor
5260            .ancestors_at(caret)
5261            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
5262            .unwrap_or(false)
5263    }
5264
5265    /// One grid op, guarded and settled — the shared body of the seven below.
5266    ///
5267    /// The guard is why this exists rather than seven copies of the same three
5268    /// lines, and it is the one guard leaf cannot delegate to twig. The table
5269    /// editor is the gesture family that consults no `Syntax` table (it spells a
5270    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
5271    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
5272    /// grid as a *pipe table* and reports success, swapping the element out for
5273    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
5274    /// downstream could tell that from a successful edit — the splice is real,
5275    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
5276    /// stopping at the door rather than detecting after the fact. See
5277    /// [`spells_pipe_tables`].
5278    fn table_op(
5279        &mut self,
5280        what: &str,
5281        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
5282    ) {
5283        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
5284            return;
5285        }
5286        self.record_caret();
5287        let at = self.caret;
5288        let r = op(&mut self.editor, at);
5289        self.apply_table(r, what);
5290    }
5291
5292    /// Insert an empty row below (`below`) or above the caret's row.
5293    pub fn table_insert_row(&mut self, below: bool) {
5294        self.table_op("table row", |e, at| e.table_insert_row(at, below));
5295    }
5296
5297    /// Delete the caret's row (not the header, not the last body row).
5298    pub fn table_delete_row(&mut self) {
5299        self.table_op("table row", |e, at| e.table_delete_row(at));
5300    }
5301
5302    /// Insert an empty column right (`right`) or left of the caret's column.
5303    pub fn table_insert_column(&mut self, right: bool) {
5304        self.table_op("table column", |e, at| e.table_insert_column(at, right));
5305    }
5306
5307    /// Delete the caret's column (unless it is the only one).
5308    pub fn table_delete_column(&mut self) {
5309        self.table_op("table column", |e, at| e.table_delete_column(at));
5310    }
5311
5312    /// Set the caret's column to `alignment`.
5313    pub fn table_set_alignment(&mut self, alignment: Alignment) {
5314        self.table_op("table alignment", |e, at| {
5315            e.table_set_alignment(at, alignment)
5316        });
5317    }
5318
5319    /// Move the caret's row one place down (`down`) or up, within the body rows.
5320    pub fn table_move_row(&mut self, down: bool) {
5321        self.table_op("table row", |e, at| e.table_move_row(at, down));
5322    }
5323
5324    /// Move the caret's column one place right (`right`) or left.
5325    pub fn table_move_column(&mut self, right: bool) {
5326        self.table_op("table column", |e, at| e.table_move_column(at, right));
5327    }
5328
5329    /// Settle the caret and document flags after a table op (or report its
5330    /// error). twig re-spells the whole table, so the caret rides its old byte
5331    /// offset and is clamped back into the rebuilt bytes — near enough to where
5332    /// it was, since the op preserves the cells' content and order around it.
5333    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
5334        match result {
5335            Ok(()) => {
5336                self.last_edit_kind = None;
5337                self.refresh();
5338                self.anchor = None;
5339                self.clamp_caret();
5340                self.dirty = self.source != self.clean_source;
5341                self.status = None;
5342                self.record_caret();
5343            }
5344            Err(e) => self.status = Some(format!("{what}: {e}")),
5345        }
5346    }
5347
5348    /// One `toggle_block_container` over the block-level target.
5349    ///
5350    /// leaf says *where*; twig decides everything else — which blocks the range
5351    /// covers, whether that means wrapping, unwrapping, nesting or converting,
5352    /// and how this document's format spells the prefix. The rule that a
5353    /// container only comes off when the range covers every block it holds is
5354    /// what the re-anchoring below is built around.
5355    fn toggle_container(&mut self, kind: BlockContainerKind) {
5356        // The read-only gate — this door reaches twig without the splice.
5357        if self.read_only {
5358            return;
5359        }
5360        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
5361            return;
5362        }
5363        let selected = self.selection();
5364        // A blank line holds no block, and twig opens an *empty* container on one
5365        // — since 3.2.0; it used to decline the range with `NotFound`, which is
5366        // why this used to lend it a scratch paragraph to wrap. Worth knowing
5367        // here because the line-for-line caret mapping below cannot describe it:
5368        // opening one under a paragraph writes the blank line the format needs
5369        // above the marker too, so the rewritten region has a line the old one
5370        // didn't, and "the same line, the same distance from its end" lands on
5371        // that new blank instead of in the container.
5372        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
5373        // Without a selection the target is the caret's own block, resolved the
5374        // way `set_block` resolves it — a caret at a line end sits at the doc
5375        // level and has to be nudged back onto the block it looks like it's in.
5376        // An empty range is enough: twig widens to the whole lines it touches.
5377        let (start, end) = match selected {
5378            Some(range) => range,
5379            None => {
5380                let off = self.block_offset_for_caret().unwrap_or(self.caret);
5381                (off, off)
5382            }
5383        };
5384        self.record_caret();
5385        match self.editor.toggle_block_container(start, end, kind) {
5386            Ok(change) => {
5387                // Read the caret's place out of the *pre-edit* source, before
5388                // `refresh` swaps that source out from under it.
5389                let place = (selected.is_none() && !opened_empty)
5390                    .then(|| self.caret_line_tail(&change.old));
5391                self.last_edit_kind = None; // structural edit is its own undo step
5392                self.refresh();
5393                match place {
5394                    // Both land the caret at the far end of what twig wrote, and
5395                    // differ only in what they leave selected.
5396                    //
5397                    // From a selection: select what the container now holds, the
5398                    // way `toggle` keeps its marked region selected — and for a
5399                    // stronger reason than symmetry: a container comes *off* only
5400                    // a range covering every block it holds, so a selection left
5401                    // on its old bytes (now short by a prefix per line) would nest
5402                    // on the second press instead of reversing the first.
5403                    //
5404                    // From a blank line: nothing to select, and the end of the
5405                    // region is exactly past the bare `> ` / `- ` twig wrote —
5406                    // the caret standing inside the container that was asked for.
5407                    None => {
5408                        self.anchor = (!opened_empty).then_some(change.new.start);
5409                        self.caret = change.new.end;
5410                    }
5411                    Some(place) => {
5412                        self.anchor = None;
5413                        self.caret = self.line_tail_offset(&change.new, place);
5414                    }
5415                }
5416                self.dirty = self.source != self.clean_source;
5417                self.status = None;
5418                self.clamp_caret();
5419                self.record_caret();
5420            }
5421            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
5422        }
5423    }
5424
5425    /// The caret's place inside the region a container toggle is rewriting, in
5426    /// the only terms the rewrite preserves: which of the region's lines it sits
5427    /// on, and how many bytes of that line lie ahead of it.
5428    ///
5429    /// A container's markup goes in at column 0 and never touches what follows
5430    /// on the line, so that pair survives the edit exactly where a byte offset
5431    /// does not — a caret left on its old offset slides back by one prefix per
5432    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
5433    /// `> ` it just asked for.
5434    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
5435        let caret = self.caret.clamp(old.start, old.end);
5436        let line = self.source[old.start..caret].matches('\n').count();
5437        let end = self.source[caret..old.end]
5438            .find('\n')
5439            .map_or(old.end, |i| caret + i);
5440        (line, end - caret)
5441    }
5442
5443    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
5444    /// region: the offset `tail` bytes back from the end of the region's `line`.
5445    ///
5446    /// Both walks are clamped rather than trusted, because the one op that does
5447    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
5448    /// the items back apart with blank lines between them — and a caret landing
5449    /// on the nearest line of the right item beats one landing out of the region
5450    /// entirely.
5451    fn line_tail_offset(
5452        &self,
5453        new: &std::ops::Range<usize>,
5454        (line, tail): (usize, usize),
5455    ) -> usize {
5456        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
5457        let mut start = 0;
5458        for _ in 0..line {
5459            match region[start..].find('\n') {
5460                Some(i) => start += i + 1,
5461                None => break,
5462            }
5463        }
5464        let end = region[start..]
5465            .find('\n')
5466            .map_or(region.len(), |i| start + i);
5467        new.start + end.saturating_sub(tail).max(start)
5468    }
5469
5470    /// Link the selection to `destination` — the toolbar's Link button. With no
5471    /// selection it acts at the caret, which re-points a link the caret is
5472    /// already standing in (twig replaces an existing link's destination and
5473    /// keeps its text) and otherwise spells a link that has no text of its own:
5474    /// an autolink (`<https://x.dev>`) where the destination is one, and
5475    /// `[destination](destination)` where it isn't.
5476    ///
5477    /// `destination` reaches twig raw. Escaping it is format knowledge and the
5478    /// two formats genuinely disagree — Markdown ends a destination at the first
5479    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
5480    /// itself — so the side holding the document is the side that gets to spell
5481    /// it. A destination twig can't carry at all (one with a newline) comes back
5482    /// as an error rather than a quietly rewritten URL.
5483    pub fn insert_link(&mut self, destination: &str) {
5484        if self.read_only || self.refuse_unsupported("link", Gesture::InsertLink) {
5485            return;
5486        }
5487        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
5488        self.record_caret();
5489        match self.editor.insert_link(start, end, destination) {
5490            Ok(change) => {
5491                self.last_edit_kind = None;
5492                self.refresh();
5493                match self.link_text_span(change.new.start) {
5494                    // A link with text of its own: select it, so typing replaces
5495                    // a `[dest](dest)`'s stand-in label and a second press
5496                    // re-points what the first one linked.
5497                    Some(text) => {
5498                        self.anchor = (text.start != text.end).then_some(text.start);
5499                        self.caret = text.end;
5500                    }
5501                    // An autolink is finished the moment it's written — its text
5502                    // *is* the URL. Leaving it selected would aim the next press
5503                    // at the one shape twig still wraps instead of re-points.
5504                    None => {
5505                        self.anchor = None;
5506                        self.caret = change.new.end;
5507                    }
5508                }
5509                self.dirty = self.source != self.clean_source;
5510                self.status = None;
5511                self.clamp_caret();
5512                self.record_caret();
5513            }
5514            Err(e) => self.status = Some(format!("link: {e}")),
5515        }
5516    }
5517
5518    /// Insert a block-level image at the caret: `![alt](destination)`. Any
5519    /// selection becomes the alt text (so "select a caption, insert image" labels
5520    /// it); with no selection, `alt` is used — empty for none. The caret lands
5521    /// just past the inserted image.
5522    ///
5523    /// Both halves go through twig (`insert_literal` for the alt text,
5524    /// `insert_image` for the image), so neither is spelled here. That used to be a
5525    /// `format!`, and it was wrong the first time an app inserted a real filename:
5526    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
5527    /// not an image at all — and the fix is per-format, since moving into the
5528    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
5529    pub fn insert_image(&mut self, destination: &str, alt: &str) {
5530        if self.read_only || self.refuse_unsupported("image", Gesture::InsertImage) {
5531            return;
5532        }
5533        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
5534        self.record_caret();
5535        // With no selection and an explicit `alt`, the alt text has to exist in the
5536        // document before it can be the image's — and it is raw caller input, so
5537        // it goes in through `insert_literal`, which escapes it for the format
5538        // rather than letting a `]` in someone's caption close the image early.
5539        let (start, end) = if start == end && !alt.is_empty() {
5540            match self.editor.insert_literal(start, alt) {
5541                Ok(change) => (change.new.start, change.new.end),
5542                Err(e) => {
5543                    self.status = Some(format!("image: {e}"));
5544                    return;
5545                }
5546            }
5547        } else {
5548            (start, end)
5549        };
5550        match self.editor.insert_image(start, end, destination) {
5551            Ok(change) => {
5552                self.last_edit_kind = None;
5553                self.refresh();
5554                // Just past the image, nothing selected — where a caret belongs
5555                // after inserting one.
5556                self.anchor = None;
5557                self.caret = change.new.end;
5558                self.dirty = self.source != self.clean_source;
5559                self.status = None;
5560                self.clamp_caret();
5561                self.record_caret();
5562            }
5563            Err(e) => self.status = Some(format!("image: {e}")),
5564        }
5565    }
5566
5567    /// Insert a block-level image, video, or audio at the caret. The image case
5568    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
5569    /// HTML elements, which is the only spelling Markdown and Djot have for them:
5570    ///
5571    /// ```text
5572    /// <video src="clip.mp4" controls>alt</video>
5573    /// <audio src="take.mp3" controls>alt</audio>
5574    /// ```
5575    ///
5576    /// HTML rather than a `::video{…}` directive deliberately. A directive means
5577    /// something only to an app that knows the vocabulary, so the document would
5578    /// read as literal punctuation everywhere else; `<video>` is what every other
5579    /// renderer already understands, and what leaf's own reader picks back up
5580    /// through `html_elements` promotion (see [`parse_extensions`]).
5581    ///
5582    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
5583    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
5584    /// `html_elements`. Before that only the multi-line form parsed as a block at
5585    /// all, and this wrote three lines to work around it.
5586    ///
5587    /// `controls` is always written: a player with no transport is a still frame
5588    /// the reader can't do anything with. Any selection becomes the element's
5589    /// fallback text, exactly as it becomes an image's alt.
5590    ///
5591    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
5592    /// applies, and bites harder here: a `"` in `destination` closes the
5593    /// attribute. A frontend taking these from a file picker is fine; one taking
5594    /// them from free text should keep them tame.
5595    ///
5596    /// [`MediaInfo`]: crate::MediaInfo
5597    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
5598        if kind == MediaKind::Image {
5599            return self.insert_image(destination, alt);
5600        }
5601        // Gated on the *image* gesture, not on one of its own — there isn't one,
5602        // since the bytes below are spelled here rather than by twig, and an HTML
5603        // document would in fact parse them. The button is one control with three
5604        // kinds behind it, and two of them working in a format where the third
5605        // cannot is a worse surface than three that agree — especially as
5606        // `insert_image` is the kind anyone reaches for first.
5607        if self.refuse_unsupported("media", Gesture::InsertImage) {
5608            return;
5609        }
5610        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
5611        let alt_text = self
5612            .selected_text()
5613            .map(str::to_string)
5614            .unwrap_or_else(|| alt.to_string());
5615        let tag = match kind {
5616            MediaKind::Audio => "audio",
5617            _ => "video",
5618        };
5619        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
5620        self.edit(start, end, &markup);
5621    }
5622
5623    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
5624    /// button. Spelling and placement are both twig's; leaf used to write `---`
5625    /// itself, which was the Markdown spelling in a djot document too.
5626    ///
5627    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
5628    /// mid-paragraph and lands it after the caret's whole block. To get a rule
5629    /// *at* the caret — the paragraph parted in two around it, which is what a
5630    /// rule button is understood to do — the paragraph is first divided with
5631    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
5632    /// the offset `split_block` returns puts the rule after the *second* half
5633    /// instead, which is a rule in the right document and the wrong place.
5634    ///
5635    /// Only a plain paragraph is split, and only where there is something to
5636    /// part: at the paragraph's end the split has no second half to mint and
5637    /// would write the separator anyway — a blank line and the empty slot Enter
5638    /// leaves for the next paragraph, which the rule then lands above and
5639    /// nothing fills — so there the rule goes straight after the paragraph,
5640    /// which is where the split-and-aim was sending it regardless. At the
5641    /// paragraph's *start* the split is kept, though it parts nothing either:
5642    /// `|para` becomes `\npara` with the caret on the new blank line, and a
5643    /// rule aimed at a blank line is written on it (twig ≥ 3.5.2), which is how
5644    /// "before the paragraph" is said through a gesture that only knows
5645    /// "after" — `---\n\npara`, and `prev\n\n---\n\npara` mid-document. Everywhere
5646    /// else the rule simply lands after the block, which is both twig's own
5647    /// answer and the better one: splitting a fenced code block would leave two
5648    /// fences with a rule between them, and splitting a list item would mint an
5649    /// item nobody asked for on the way to a rule that lands after the list
5650    /// regardless. A table and a setext heading refuse the split outright, so
5651    /// they take the same path by themselves.
5652    pub fn insert_thematic_break(&mut self) {
5653        if self.read_only || self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak)
5654        {
5655            return;
5656        }
5657        self.caret = self.skip_trailing_close_delims(self.caret);
5658        // A selection is replaced by the rule, so collapse it first and let the
5659        // split-and-rule below run from the caret it leaves behind.
5660        if let Some((s, e)) = self.selection() {
5661            self.splice(s, e, "", EditKind::Other);
5662        }
5663        self.anchor = None;
5664        self.record_caret();
5665        let at = self.caret;
5666        if self.caret_parts_bare_paragraph() {
5667            // A failure here is not fatal: the rule still lands after the block,
5668            // which is exactly what this call was trying to improve on.
5669            let _ = self.editor.split_block(at);
5670        }
5671        match self.editor.insert_thematic_break(at) {
5672            Ok(change) => {
5673                self.last_edit_kind = None;
5674                self.refresh();
5675                self.anchor = None;
5676                self.caret = change.new.end;
5677                self.dirty = self.source != self.clean_source;
5678                self.status = None;
5679                self.clamp_caret();
5680                self.record_caret();
5681            }
5682            Err(e) => self.status = Some(format!("thematic break: {e}")),
5683        }
5684    }
5685
5686    /// Insert a fresh table at the caret — the toolbar's Table button. One
5687    /// header row, `rows` empty body rows, `cols` columns, spelled by twig in
5688    /// the document's own dialect and placed the way its thematic break is:
5689    /// after the caret's block, blank-separated. A bare paragraph is parted
5690    /// around the caret first, exactly as
5691    /// [`insert_thematic_break`](Self::insert_thematic_break) parts it, so the
5692    /// table lands *at* the caret rather than after everything the caret's
5693    /// paragraph says.
5694    ///
5695    /// The caret ends in the first header cell, selected the way Tab selects
5696    /// a cell — the natural next act is to type the heading, and Tab then
5697    /// walks the grid. That cell is read back from the rebuilt table map
5698    /// rather than computed from the splice, because twig's blank line and
5699    /// quote prefix put the first bar at an offset only the reparse knows.
5700    ///
5701    /// The shape is the caller's: a menu offers a few, a dialog asks. Zero
5702    /// rows or columns is twig's refusal (a header with nothing under it is
5703    /// what its row delete refuses to leave), reported through `status`.
5704    pub fn insert_table(&mut self, rows: usize, cols: usize) {
5705        if self.read_only || self.refuse_unsupported("table", Gesture::InsertTable) {
5706            return;
5707        }
5708        self.caret = self.skip_trailing_close_delims(self.caret);
5709        if let Some((s, e)) = self.selection() {
5710            self.splice(s, e, "", EditKind::Other);
5711        }
5712        self.anchor = None;
5713        self.record_caret();
5714        let at = self.caret;
5715        if self.caret_parts_bare_paragraph() {
5716            let _ = self.editor.split_block(at);
5717        }
5718        match self.editor.insert_table(at, rows, cols) {
5719            Ok(change) => {
5720                self.last_edit_kind = None;
5721                self.refresh();
5722                self.anchor = None;
5723                self.caret = change.new.end;
5724                self.dirty = self.source != self.clean_source;
5725                self.status = None;
5726                self.clamp_caret();
5727                // Into the first header cell of the table just written: the
5728                // first table whose grid begins inside the splice.
5729                self.rebuild_map();
5730                let first_cell = self
5731                    .vmap
5732                    .tables
5733                    .iter()
5734                    .filter_map(|t| t.grid.first().and_then(|row| row.cells.first()))
5735                    .find(|cell| cell.start >= change.new.start && cell.start < change.new.end)
5736                    .map(|cell| (cell.start, cell.end));
5737                if let Some((start, end)) = first_cell {
5738                    self.select_cell(start, end);
5739                }
5740                self.record_caret();
5741            }
5742            Err(e) => self.status = Some(format!("table: {e}")),
5743        }
5744    }
5745
5746    /// Whether the caret sits in a paragraph and nothing else — no list item, no
5747    /// quote, no fence, no table — with paragraph text still ahead of it. The
5748    /// one shape where parting the block around the caret is unambiguously what
5749    /// a rule button means; see
5750    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
5751    /// container is left to take the rule after itself.
5752    ///
5753    /// The "text ahead" half is what keeps `split_block` from running at the
5754    /// one edge where its output composes badly. At a paragraph's end twig
5755    /// cannot mint the empty second half (no format spells an empty
5756    /// paragraph), so it writes only the separator — a blank line and the
5757    /// slot Enter leaves for the paragraph to come — and a block then aimed at
5758    /// the first half lands above a slot that nothing fills: `para\n` with the
5759    /// caret at 4 came out as `para\n\n* * *\n\n\n`. Trailing whitespace counts
5760    /// as nothing ahead, since the split would shed it as the second half's
5761    /// leading indent and leave the same slot. Which end of the newline a
5762    /// paragraph's span stops at differs between the formats (Markdown before
5763    /// it, djot after), which is why this reads the remaining bytes rather
5764    /// than comparing offsets. The paragraph's
5765    /// start is deliberately not the same case — see
5766    /// [`insert_thematic_break`](Self::insert_thematic_break) for why that
5767    /// split is kept.
5768    fn caret_parts_bare_paragraph(&mut self) -> bool {
5769        let caret = self.caret.min(self.source.len());
5770        let Ok(chain) = self.editor.ancestors_at(caret) else {
5771            return false;
5772        };
5773        let mut para_end = None;
5774        for m in chain {
5775            match m.kind {
5776                Kind::Para => para_end = Some(m.span.end.min(self.source.len())),
5777                Kind::ListItem
5778                | Kind::TaskListItem
5779                | Kind::BlockQuote
5780                | Kind::CodeBlock
5781                | Kind::Table => return false,
5782                _ => {}
5783            }
5784        }
5785        match para_end {
5786            Some(end) if end > caret => !self.source[caret..end].trim().is_empty(),
5787            _ => false,
5788        }
5789    }
5790
5791    /// The destination of the link under the caret — what a Link prompt shows so
5792    /// ⌘K on an existing link edits its URL instead of asking for it again.
5793    /// `None` when the caret stands in no link.
5794    ///
5795    /// An autolink carries no separate destination: its text *is* the URL, so
5796    /// that's what comes back for one.
5797    pub fn link_destination_at_caret(&mut self) -> Option<String> {
5798        self.link_destination_at(self.caret)
5799    }
5800
5801    /// The destination of the link at `off`.
5802    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
5803    /// the caret isn't.
5804    ///
5805    /// The offset form exists for the same reason
5806    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
5807    /// the document somewhere else — a footnote's text in a popover, say — has
5808    /// rows and runs but no caret in them, and still needs to know which of those
5809    /// runs a reader can follow.
5810    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
5811        self.nodes()
5812            .into_iter()
5813            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
5814            .filter(|n| n.span.start <= off && off < n.span.end)
5815            .max_by_key(|n| n.span.start)
5816            .and_then(|n| n.destination.or(n.text))
5817    }
5818
5819    /// Where the locator `id` lands in this document — the `#v2` half of a
5820    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
5821    /// answers to it.
5822    ///
5823    /// The other end of a link, and the reason this exists: without it a
5824    /// destination has only file granularity, so following a citation into a
5825    /// chapter drops the reader at the top of it to hunt for the verse. Which is
5826    /// also why it is a *document* query rather than a caret one — the document
5827    /// being asked is usually not the one the reader is in.
5828    ///
5829    /// Three readings, tried in order, because the same `#some-heading` is
5830    /// written three ways across the formats leaf opens:
5831    ///
5832    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
5833    ///    the auto-ids djot mints for its headings. The only exact answer, so it
5834    ///    goes first — a document that says `{#v1}` has settled the question.
5835    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
5836    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
5837    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
5838    ///    authored anywhere land on a djot heading.
5839    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
5840    ///    none and `{#custom}` is literal text in a Markdown heading — so for
5841    ///    the format most vaults are written in, the heading's own words are the
5842    ///    only thing a fragment can name. This is the rule every Markdown
5843    ///    renderer already follows, which is what makes `#a-heading` mean in
5844    ///    diaryx what it means on the web.
5845    ///
5846    /// Ties go to the earliest match, then to the widest: a duplicated id is the
5847    /// document's mistake and the first one is the answer every anchor
5848    /// implementation gives, while preferring the wider span picks the section
5849    /// over the heading that opens it — more for a peek to show, same place to
5850    /// land.
5851    pub fn locate(&mut self, id: &str) -> Option<Landing> {
5852        let id = id.trim();
5853        if id.is_empty() {
5854            return None;
5855        }
5856        let nodes = self.nodes();
5857
5858        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
5859        // is picking, among nodes that start together, the one that ends last.
5860        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
5861            matches
5862                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
5863                .map(|n| Landing {
5864                    start: n.span.start,
5865                    end: n.span.end,
5866                })
5867        };
5868
5869        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
5870            return Some(landing);
5871        }
5872        let want = slug(id);
5873        if want.is_empty() {
5874            return None;
5875        }
5876        if let Some(landing) = pick(
5877            &mut nodes
5878                .iter()
5879                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
5880        ) {
5881            return Some(landing);
5882        }
5883
5884        // A heading by its words. Its span is one line, so the end comes from
5885        // where the *section* it opens gives out — the next heading that is not
5886        // under it, or the end of the document. A Markdown heading has no
5887        // section node to ask (twig only builds those for djot), and a peek that
5888        // showed the heading alone would answer "what does that say" with the
5889        // title of the thing it says.
5890        let heading = nodes
5891            .iter()
5892            .filter(|n| n.kind == Kind::Heading)
5893            .filter(|n| {
5894                n.content_span
5895                    .clone()
5896                    .and_then(|s| self.source.get(s))
5897                    .is_some_and(|text| slug(text) == want)
5898            })
5899            .min_by_key(|n| n.span.start)?;
5900        let level = heading.level.unwrap_or(u32::MAX);
5901        let end = nodes
5902            .iter()
5903            .filter(|n| n.kind == Kind::Heading)
5904            .filter(|n| n.span.start > heading.span.start)
5905            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
5906            .map(|n| n.span.start)
5907            .min()
5908            .unwrap_or(self.source.len());
5909        Some(Landing {
5910            start: heading.span.start,
5911            end,
5912        })
5913    }
5914
5915    /// Write a footnote at the caret — the toolbar's Footnote button, and the
5916    /// one gesture in the footnote story that *authors* rather than follows.
5917    ///
5918    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
5919    /// the `[^1]:` definition at the end of the document. Half a footnote is not
5920    /// a footnote — a bare reference with nothing defining it renders as literal
5921    /// brackets — so a single button that wrote only the reference would leave
5922    /// the author to hand-spell the other half in a document that had just
5923    /// stopped showing them what the first half meant. One edit also means one
5924    /// undo takes both back.
5925    ///
5926    /// The definition's body is left empty and **the caret lands in it**, which
5927    /// is the whole point of pressing the button: nobody wants a reference to a
5928    /// note they have not written yet. Getting back to where they were writing
5929    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
5930    /// the same return leg a reader following a reference already uses, so the
5931    /// author is left standing on the near end of a round trip that works.
5932    ///
5933    /// A selection collapses to its *end* rather than being replaced: a
5934    /// reference annotates the words before it, so "select the claim, add a
5935    /// footnote" should mark that claim, not consume it.
5936    pub fn insert_footnote(&mut self) {
5937        if self.read_only || self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
5938            return;
5939        }
5940        let at = self.selection().map_or(self.caret, |(_, end)| end);
5941        self.anchor = None;
5942        self.caret = at;
5943        self.record_caret();
5944        let label = self.next_footnote_label();
5945        match self.editor.insert_footnote(at, &label) {
5946            Ok(change) => {
5947                self.last_edit_kind = None;
5948                self.refresh();
5949                self.anchor = None;
5950                // `change.new` runs from the reference to the end of the
5951                // document, so its start is the `[^1]` just written and
5952                // `footnote_at` resolves it to the note the same way a reader's
5953                // tap does — and to the note's *body*, which is already a caret
5954                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
5955                // and has none), so this needs no snap on top. The fallback is
5956                // the reference's own offset: a format that spelled the pair some
5957                // way leaf can't read back should still leave the caret on the
5958                // edit rather than at the far end of a document it just grew.
5959                self.caret = self
5960                    .footnote_at(change.new.start)
5961                    .and_then(|note| note.offset)
5962                    .unwrap_or(change.new.start);
5963                self.dirty = self.source != self.clean_source;
5964                self.status = None;
5965                self.clamp_caret();
5966                self.record_caret();
5967            }
5968            Err(e) => self.status = Some(format!("footnote: {e}")),
5969        }
5970    }
5971
5972    /// The label to give a footnote the author has not named: the lowest counting
5973    /// number no footnote in the document is already wearing.
5974    ///
5975    /// twig takes the label rather than minting one, because it holds no opinion
5976    /// about what a document's footnotes should be called — and it is right not
5977    /// to. Numbering them is what every author of a numbered note expects, and
5978    /// re-using a taken number would silently point the new reference at somebody
5979    /// else's note (twig reuses an existing definition rather than appending a
5980    /// second one, which is the right rule for citing a note twice on purpose and
5981    /// exactly the wrong accident to have by default).
5982    ///
5983    /// *References* are counted alongside definitions, not just definitions: a
5984    /// document carrying a dangling `[^2]` has a 2 that means something to
5985    /// whoever wrote it, and minting a definition for it here would answer a
5986    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
5987    /// count entirely — they take no number, so they block none.
5988    fn next_footnote_label(&mut self) -> String {
5989        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
5990            .into_iter()
5991            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
5992            .filter_map(|label| label.parse().ok())
5993            .collect();
5994        taken.extend(
5995            self.nodes()
5996                .into_iter()
5997                .filter(|n| n.kind == Kind::FootnoteReference)
5998                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
5999                .filter_map(|label| label.parse::<u32>().ok()),
6000        );
6001        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
6002    }
6003
6004    /// The footnote reference under the caret, resolved to the note it names.
6005    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
6006    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
6007        self.footnote_at(self.caret)
6008    }
6009
6010    /// The footnote reference at `off`, resolved to the note it names — what a
6011    /// frontend shows when a reader activates a `[^1]`.
6012    ///
6013    /// A reference is not a link node, so
6014    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
6015    /// (and should not) answer for one: a link names a destination to leave for,
6016    /// a reference names a note that is already in this document. Following one
6017    /// is a move within the page, which is why this hands back an `offset`
6018    /// rather than something to open.
6019    ///
6020    /// Offset-based rather than caret-only because the gesture that wants this
6021    /// most is the one that must not move the caret: a pointer hovering a `[1]`
6022    /// asks what note it names without disturbing where the reader was typing.
6023    /// The caret is just the offset a click already placed —
6024    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
6025    ///
6026    /// `None` when `off` stands in no reference. A reference whose note the
6027    /// document never defines is *not* `None` — it answers with the label it
6028    /// looked for and no text, which is what lets a frontend say so instead of
6029    /// silently doing nothing.
6030    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
6031        // Innermost-wins by latest start, the rule its link sibling uses.
6032        let span = self
6033            .nodes()
6034            .into_iter()
6035            .filter(|n| n.kind == Kind::FootnoteReference)
6036            .filter(|n| n.span.start <= off && off < n.span.end)
6037            .max_by_key(|n| n.span.start)?
6038            .span;
6039        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();
6040
6041        // The note itself. Definitions are roots beside `doc` rather than
6042        // children of it, so they're asked for directly — see
6043        // `wysiwyg::footnote_definitions`.
6044        let note = wysiwyg::footnote_definitions(&mut self.editor)
6045            .into_iter()
6046            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
6047        let Some(note) = note else {
6048            return Some(FootnoteRef {
6049                label,
6050                text: None,
6051                offset: None,
6052                end: None,
6053            });
6054        };
6055        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
6056        Some(FootnoteRef {
6057            label,
6058            text: body
6059                .clone()
6060                .and_then(|b| self.source.get(b))
6061                .map(str::to_string),
6062            // The body's start, not the definition's — see `FootnoteRef::offset`.
6063            offset: body.clone().map(|b| b.start),
6064            end: body.map(|b| b.end),
6065        })
6066    }
6067
6068    /// The footnote *definition* the caret stands in, and where the reference
6069    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
6070    /// at the caret's offset.
6071    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
6072        self.footnote_definition_at(self.caret)
6073    }
6074
6075    /// The footnote definition spanning `off`, and where the reference that
6076    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
6077    ///
6078    /// The mirror image, deliberately: the same gesture that takes a reader from
6079    /// `[1]` down to the note takes them from the note back up to `[1]`, so
6080    /// following a footnote is a round trip rather than a fall. It needs no
6081    /// memory of how the reader arrived — the document says where the reference
6082    /// is — which is what makes it work for a reader who scrolled to the notes
6083    /// themselves, and what keeps it right after an edit moves either end.
6084    ///
6085    /// `None` when `off` stands in no definition. A definition nothing cites is
6086    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
6087    /// its label and no offset, so a frontend can say "nothing refers to this"
6088    /// rather than offer a jump that goes nowhere.
6089    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
6090        // Definitions are roots beside `doc`, so `nodes()` — which walks the
6091        // document body — never reports one. They're asked for directly, the way
6092        // `footnote_at` asks for the note it resolves to.
6093        //
6094        // Closed at the end, unlike the half-open test its neighbours use. A
6095        // definition's span stops at its last content byte — the newline ending
6096        // the line is outside it — so `span.end` is the caret stop at the end of
6097        // the note's own row, not the first byte of anything after. Excluding it
6098        // meant the one caret an author is guaranteed to have, the one left
6099        // sitting at the end of the note they just typed, was in no definition at
6100        // all: writing a note and then asking to go back to its reference
6101        // answered nothing. Two definitions in a row still can't both match —
6102        // there is a blank line between them — and `max_by_key` decides anyway.
6103        let note = wysiwyg::footnote_definitions(&mut self.editor)
6104            .into_iter()
6105            .filter(|m| m.span.start <= off && off <= m.span.end)
6106            .max_by_key(|m| m.span.start)?;
6107        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();
6108
6109        // The earliest reference carrying this label. `min` rather than a `find`,
6110        // because `nodes()` reports a flattened walk whose order is twig's
6111        // business, not document order. Bound first: the walk needs `&mut self`
6112        // and reading the labels back out needs `&self.source`.
6113        let nodes = self.nodes();
6114        let offset = nodes
6115            .into_iter()
6116            .filter(|n| n.kind == Kind::FootnoteReference)
6117            .filter(|n| {
6118                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
6119            })
6120            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
6121            .map(|n| n.span.start + 2)
6122            .min();
6123        Some(FootnoteDef { label, offset })
6124    }
6125
6126    /// The destination of the image under the caret — what an image prompt shows
6127    /// so editing an existing image starts from its current URL instead of blank,
6128    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
6129    /// `None` when the caret stands in no image. A caret resting just after a
6130    /// block image (its trailing stop) is still "in" it — the half-open span test
6131    /// excludes that offset, which is the intended precision: past the image is
6132    /// past it.
6133    pub fn image_destination_at_caret(&mut self) -> Option<String> {
6134        let off = self.caret;
6135        self.nodes()
6136            .into_iter()
6137            .filter(|n| n.kind == Kind::Image)
6138            .filter(|n| n.span.start <= off && off < n.span.end)
6139            .max_by_key(|n| n.span.start)
6140            .and_then(|n| n.destination)
6141    }
6142
6143    /// The language of the fenced code block the caret stands in — what a
6144    /// language prompt shows so editing it starts from the current value rather
6145    /// than blank. `None` when the caret is in no code block, or in one whose
6146    /// fence carries no language (or an indented block, which has no fence).
6147    pub fn code_language_at_caret(&mut self) -> Option<String> {
6148        let start = self.code_block_start_at_caret()?;
6149        wysiwyg::code_language(&self.source, start)
6150    }
6151
6152    /// Whether the caret stands in a fenced code block — the one a language
6153    /// prompt could edit. A frontend gates its "set language" affordance on this
6154    /// (an indented block, which can't carry a language, reports `false`).
6155    pub fn caret_in_fenced_code(&mut self) -> bool {
6156        self.code_block_start_at_caret()
6157            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
6158    }
6159
6160    /// Set (or clear, with `""`) the language of the fenced code block the caret
6161    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
6162    /// block, and a reported error for a language the format's fence cannot
6163    /// carry.
6164    ///
6165    /// twig rewrites the info string, so the fence's own width — measured
6166    /// against a body neither side touches — is kept, and a language holding a
6167    /// space, a line end or the fence character is refused rather than written
6168    /// out to reparse as something else. Leaf used to splice over the info span
6169    /// itself and `trim()` the input, which handled the one bad case it had
6170    /// thought of.
6171    pub fn set_code_language(&mut self, lang: &str) {
6172        // The read-only gate — this door reaches twig without the splice.
6173        if self.read_only {
6174            return;
6175        }
6176        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
6177            return;
6178        }
6179        if self.code_block_start_at_caret().is_none() {
6180            return;
6181        }
6182        let lang = lang.trim();
6183        // `None` clears the info string; `Some("")` asks for an empty one. Both
6184        // write a bare fence, and the prompt's empty value means "clear".
6185        let want = (!lang.is_empty()).then_some(lang);
6186        self.record_caret();
6187        match self.editor.set_code_language(self.caret, want) {
6188            Ok(_) => {
6189                self.last_edit_kind = None;
6190                self.refresh();
6191                self.anchor = None;
6192                self.dirty = self.source != self.clean_source;
6193                self.status = None;
6194                self.clamp_caret();
6195                self.record_caret();
6196            }
6197            Err(e) => self.status = Some(format!("code language: {e}")),
6198        }
6199    }
6200
6201    /// The `span.start` of the code block covering the caret — the anchor
6202    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
6203    /// in none.
6204    fn code_block_start_at_caret(&mut self) -> Option<usize> {
6205        let off = self.caret;
6206        self.nodes()
6207            .into_iter()
6208            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
6209            .max_by_key(|n| n.span.start)
6210            .map(|n| n.span.start)
6211    }
6212
6213    /// The source range of the text inside the link covering `off` — what sits
6214    /// between its `[` and `]`. `None` when twig reports no link there.
6215    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
6216        self.nodes()
6217            .into_iter()
6218            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
6219            // the other's `span.start`; the link that starts latest at or before
6220            // `off` is the one `off` is actually in.
6221            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
6222            .max_by_key(|n| n.span.start)
6223            .and_then(|n| n.content_span)
6224    }
6225
6226    // ── undo / redo ───────────────────────────────────────────────────────────
6227    // twig owns the history of *bytes* (it owns the buffer) and now carries the
6228    // caret through it too: `record_caret` stashes each state's caret in twig's
6229    // opaque per-step blob, and undo/redo hand it back with the source they
6230    // restore. So leaf keeps no history of its own — no parallel stacks to march
6231    // in lockstep and silently drift out of it.
6232
6233    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
6234    /// where they were when that step began.
6235    pub fn undo(&mut self) {
6236        if self.read_only {
6237            return;
6238        }
6239        let (undone, redoable) = (self.undo_steps, self.redo_steps);
6240        match self.editor.undo() {
6241            Ok(Some(change)) => {
6242                self.after_history(change);
6243                // `refresh` counted the restore as an edit; it was a step back.
6244                self.undo_steps = undone.saturating_sub(1);
6245                self.redo_steps = redoable + 1;
6246            }
6247            Ok(None) => {
6248                self.undo_steps = 0;
6249                self.status = Some("nothing to undo".into());
6250            }
6251            Err(e) => self.status = Some(format!("undo: {e}")),
6252        }
6253    }
6254
6255    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
6256    /// selection back where that step originally left them.
6257    pub fn redo(&mut self) {
6258        if self.read_only {
6259            return;
6260        }
6261        let (undone, redoable) = (self.undo_steps, self.redo_steps);
6262        match self.editor.redo() {
6263            Ok(Some(change)) => {
6264                self.after_history(change);
6265                // `refresh` counted the restore as an edit; it was a step forward.
6266                self.undo_steps = undone + 1;
6267                self.redo_steps = redoable.saturating_sub(1);
6268            }
6269            Ok(None) => {
6270                self.redo_steps = 0;
6271                self.status = Some("nothing to redo".into());
6272            }
6273            Err(e) => self.status = Some(format!("redo: {e}")),
6274        }
6275    }
6276
6277    /// Refresh the cached source and put the caret back where the step being
6278    /// undone/redone had it, clearing any active run.
6279    ///
6280    /// The caret comes from twig's blob for the restored state (what
6281    /// `record_caret` stored). `change` is only the fallback for a state with no
6282    /// blob — a caret at the end of the restored text, which is where this always
6283    /// landed before the blobs were kept. It is the edit site, not where the user
6284    /// was standing, so it's a floor and not the behaviour: undoing should hand
6285    /// back the document *and* the place you were working, which for an edit made
6286    /// anywhere but under the caret are two different places.
6287    fn after_history(&mut self, change: Change) {
6288        self.refresh();
6289        match self
6290            .editor
6291            .caret_blob()
6292            .ok()
6293            .and_then(|b| CaretState::from_blob(&b))
6294        {
6295            Some(state) => {
6296                self.caret = state.caret.min(self.source.len());
6297                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
6298            }
6299            None => {
6300                self.caret = change.new.end.min(self.source.len());
6301                self.anchor = None;
6302            }
6303        }
6304        self.goal_col = None;
6305        self.last_edit_kind = None;
6306        self.dirty = self.source != self.clean_source;
6307        self.status = None;
6308        self.clamp_caret();
6309    }
6310
6311    // ── the file ──────────────────────────────────────────────────────────────
6312
6313    #[cfg(feature = "fs")]
6314    pub fn save(&mut self) {
6315        if self.is_untitled() {
6316            // No path to write and no name to invent: ⌘S on an untitled document
6317            // is a Save As, and only a frontend has a picker to ask with. Say so
6318            // rather than failing at the filesystem with an empty path.
6319            self.status = Some("untitled — save as…".into());
6320            return;
6321        }
6322        let path = self.path.clone();
6323        if self.write(&path) {
6324            self.mark_saved();
6325        }
6326    }
6327
6328    /// Save As: write the document to `path` and *move* it there — `self.path`
6329    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
6330    /// what Save As means; a copy would leave the user editing a document whose
6331    /// name is no longer where their keystrokes go.
6332    ///
6333    /// The move only happens if the bytes actually landed. A failed write leaves
6334    /// the path, `dirty`, and the disk watermark exactly as they were, with the
6335    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
6336    /// must never come away believing it was saved.
6337    ///
6338    /// An existing `path` is overwritten, and the caller is the one that knows
6339    /// whether to ask first: a Save As picker has already run that prompt, and a
6340    /// second confirmation from down here would be the same question twice.
6341    ///
6342    /// `format` does **not** follow the new extension. The buffer is parsed as
6343    /// the format it was opened with, and re-reading it as another one is a
6344    /// conversion — a different, lossy operation that would throw away the undo
6345    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
6346    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
6347    /// until it's reopened.
6348    #[cfg(feature = "fs")]
6349    pub fn save_as(&mut self, path: PathBuf) {
6350        if !self.write(&path) {
6351            return;
6352        }
6353        self.path = path;
6354        self.mark_saved();
6355    }
6356
6357    /// Put `source` on disk at `path`, reporting whether it got there. The one
6358    /// place leaf writes a document, so a save and a Save As can't disagree
6359    /// about what a failure looks like.
6360    #[cfg(feature = "fs")]
6361    fn write(&mut self, path: &Path) -> bool {
6362        match std::fs::write(path, self.source.as_bytes()) {
6363            Ok(()) => true,
6364            Err(e) => {
6365                self.status = Some(format!("save failed: {e}"));
6366                false
6367            }
6368        }
6369    }
6370
6371    /// Re-base the document's saved watermark to the current bytes: clears
6372    /// `dirty`, records `source` as the new clean state (so undoing back to here
6373    /// clears the flag again), and re-stamps the on-disk hash.
6374    ///
6375    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
6376    /// the hook a **filesystem-free host** calls itself once it has persisted
6377    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
6378    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
6379    /// are already where that host wants them, and this just tells the model they
6380    /// are safe.
6381    pub fn mark_saved(&mut self) {
6382        self.clean_source = self.source.clone();
6383        self.dirty = false;
6384        // The bytes on disk are now ours, so this is the new watermark: without
6385        // re-stamping it, every save would report its own work as an external
6386        // change forever after.
6387        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
6388        self.status = Some(format!("saved {}", self.file_name()));
6389    }
6390
6391    /// What the file looks like now against the bytes leaf last read or wrote.
6392    ///
6393    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
6394    /// so this is a filesystem round-trip, not a per-frame question — ask it
6395    /// when a window regains focus, on a timer, or before a save.
6396    ///
6397    /// This *only* reports the file. Whether the document also has unsaved edits
6398    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
6399    /// [`DiskState::Changed`] means a save overwrites someone's work and a
6400    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
6401    /// it has no way to ask — so it hands a frontend both halves and lets it put
6402    /// the question to the person who can answer it.
6403    #[cfg(feature = "fs")]
6404    pub fn disk_state(&self) -> DiskState {
6405        let Some(want) = self.disk_hash else {
6406            return DiskState::Untitled;
6407        };
6408        match std::fs::read(&self.path) {
6409            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
6410            Ok(_) => DiskState::Changed,
6411            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
6412            Err(_) => DiskState::Unreadable,
6413        }
6414    }
6415
6416    /// Re-read the file and replace the document with what's there — the other
6417    /// answer to a [`DiskState::Changed`].
6418    ///
6419    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
6420    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
6421    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
6422    /// document shouldn't have to argue with a guard.
6423    ///
6424    /// **The undo history survives, and the reload is one step in it.** The
6425    /// whole buffer is spliced with the file's bytes through the same door every
6426    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
6427    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
6428    /// swapped the document out from under a reader gives them back what they
6429    /// were looking at, marked dirty, and ^Z again carries on into whatever they
6430    /// had done before it. This used to build a fresh parse and drop the stack,
6431    /// on the reasoning that twig's history belongs to the buffer and these are
6432    /// different bytes; that is true of *rebasing* a step onto them and not of
6433    /// recording the swap itself as one, which is all this is. A splice twig
6434    /// won't take falls back to the fresh parse, and only that path still costs
6435    /// the history.
6436    ///
6437    /// The caret keeps its byte offset, clamped to the new length; the selection
6438    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
6439    /// file changed, so it can't know where the caret "still" is. Clamping keeps
6440    /// it where the user left it in the common case (a change further down the
6441    /// file, or none in the text they're sitting in), and never puts it
6442    /// somewhere invalid. A selection has two such offsets and no such excuse —
6443    /// silently reinterpreting one over changed bytes would arm the *next*
6444    /// keystroke to delete something the user never selected.
6445    ///
6446    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
6447    /// document alone with a status.
6448    #[cfg(feature = "fs")]
6449    pub fn reload(&mut self) {
6450        if self.is_untitled() {
6451            self.status = Some("no file to reload".into());
6452            return;
6453        }
6454        let bytes = match std::fs::read(&self.path) {
6455            Ok(b) => b,
6456            Err(e) => {
6457                self.status = Some(format!("reload failed: {e}"));
6458                return;
6459            }
6460        };
6461        let Ok(source) = String::from_utf8(bytes) else {
6462            self.status = Some("reload failed: file is not UTF-8".into());
6463            return;
6464        };
6465        // Already these bytes — someone saved a file back unchanged, or leaf's
6466        // own write is being read back. Re-baseline against it and stop: a
6467        // splice of the text onto itself would put an undo step on the stack for
6468        // something nobody did.
6469        if source == self.source {
6470            self.disk_hash = Some(hash_bytes(source.as_bytes()));
6471            self.clean_source = source;
6472            self.dirty = false;
6473            self.status = Some(format!("reloaded {}", self.file_name()));
6474            return;
6475        }
6476        let caret = self.caret;
6477        // The pre-reload caret, so undoing the swap puts it back where the
6478        // reader was standing — the same bracketing `splice_exact` does.
6479        self.record_caret();
6480        if self
6481            .editor
6482            .edit_range(0, self.source.len(), &source)
6483            .is_ok()
6484        {
6485            self.refresh();
6486        } else {
6487            // twig wouldn't take the splice. Start over from the bytes, which is
6488            // what this always did, and is the one path that still costs the
6489            // history — `format` is the format this document *is*, not what the
6490            // (unchanged) name now says, see `save_as`.
6491            match new_editor(source.as_bytes(), self.format) {
6492                Ok(editor) => {
6493                    self.editor = editor;
6494                    self.source = source.clone();
6495                    // Not going through `refresh`, so the revision has to move
6496                    // here or every frontend keeps painting the old file from
6497                    // cache.
6498                    self.revision += 1;
6499                }
6500                Err(e) => {
6501                    self.status = Some(format!("reload failed: {e}"));
6502                    return;
6503                }
6504            }
6505        }
6506        self.disk_hash = Some(hash_bytes(source.as_bytes()));
6507        self.clean_source = self.source.clone();
6508        self.caret = caret.min(self.source.len());
6509        self.anchor = None;
6510        self.goal_col = None;
6511        self.last_edit_kind = None;
6512        self.dirty = false;
6513        self.status = Some(format!("reloaded {}", self.file_name()));
6514        self.clamp_caret();
6515        // And the post-reload caret, so a redo restores it.
6516        self.record_caret();
6517    }
6518
6519    /// Re-read the source from twig after it has changed the document. The one
6520    /// funnel every edit, undo, and redo comes through — so it's where the
6521    /// revision moves, and anything cached against the text dies here.
6522    fn refresh(&mut self) {
6523        if let Ok(s) = self.editor.source_str() {
6524            self.source = s;
6525        }
6526        self.revision += 1;
6527        // An edit is a step onto the history and the end of anything undone;
6528        // `undo`/`redo` come through here too and correct this after.
6529        self.undo_steps += 1;
6530        self.redo_steps = 0;
6531        self.clamp_caret();
6532    }
6533
6534    /// Whether [`undo`](Self::undo) has a step to take back — for a native
6535    /// Edit menu to enable its item by. See the note on `undo_steps` for what
6536    /// "has" means here.
6537    pub fn can_undo(&self) -> bool {
6538        !self.read_only && self.undo_steps > 0
6539    }
6540
6541    /// Whether [`redo`](Self::redo) has an undone step to restore.
6542    pub fn can_redo(&self) -> bool {
6543        !self.read_only && self.redo_steps > 0
6544    }
6545
6546    // ── caret movement ─────────────────────────────────────────────────────────
6547    // `extend` grows the selection (Shift+motion): it pins the anchor on the
6548    // first extended step and moves only the caret; an un-extended motion drops
6549    // the selection.
6550
6551    /// Place the caret at byte `offset` (clamped to a char boundary), extending
6552    /// the selection when `extend` is set. The public form of `move_to`, for a
6553    /// frontend that hit-tests pixels straight to a source offset.
6554    pub fn place_caret(&mut self, offset: usize, extend: bool) {
6555        self.goal_col = None;
6556        let before = self.caret;
6557        // A pixel hit-test can land between the visible caret stops — in the
6558        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
6559        // Snap to the nearest real stop so the caret can't come to rest where it
6560        // would draw in one place and type in another. The `(row, col)` click
6561        // path (`click`) already snaps this way through `offset_of_pos`; the
6562        // source view reaches every byte, so it snaps to nothing.
6563        let target = match self.view {
6564            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
6565            // The source view reaches every byte, so there is no stop to snap
6566            // to — but "every byte" still means every *character* boundary. A
6567            // caret resting inside a multi-byte character draws nowhere real
6568            // and panics the next time anything slices there.
6569            View::Source => self.char_boundary_at_or_before(offset),
6570        };
6571        self.move_to(target, extend);
6572        self.clamp_caret();
6573        self.debug_assert_on_a_stop(before);
6574    }
6575
6576    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
6577    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
6578    /// grab the metadata) while the source view still selects the literal whole.
6579    pub fn select_all(&mut self) {
6580        self.anchor = Some(self.caret_floor());
6581        self.caret = self.source.len();
6582        self.goal_col = None;
6583        self.last_edit_kind = None;
6584        self.status = None;
6585    }
6586
6587    /// Select the word (or whitespace / punctuation run) at `offset` — the
6588    /// double-click gesture. Anchors on the run's start with the caret at its
6589    /// end so a following Shift-motion extends from the far edge.
6590    pub fn select_word_at(&mut self, offset: usize) {
6591        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
6592        self.anchor = Some(s);
6593        self.caret = e;
6594        self.goal_col = None;
6595        self.last_edit_kind = None;
6596        self.status = None;
6597        self.clamp_caret();
6598    }
6599
6600    /// Select the whole enclosing text block (paragraph, heading, list item's
6601    /// text…) at `offset` — the triple-click gesture. Reads the range straight
6602    /// from the AST (twig's `content_span`), so it selects the entire *logical*
6603    /// paragraph even when that paragraph soft-wraps across several visual rows —
6604    /// where a visual-row-based select breaks down, because one source offset at
6605    /// a wrap boundary belongs to two rows at once.
6606    pub fn select_block_at(&mut self, offset: usize) {
6607        let off = offset.min(self.source.len());
6608        let range = self
6609            .editor
6610            .ancestors_at(off)
6611            .ok()
6612            .and_then(|chain| {
6613                // Ancestors run root → deepest; the deepest node that is neither
6614                // an inline span nor a multi-block container is the text block
6615                // the caret sits in (a paragraph, a heading, a code block…).
6616                chain
6617                    .into_iter()
6618                    .rev()
6619                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
6620                    .map(|m| m.content_span.unwrap_or(m.span))
6621            })
6622            .unwrap_or_else(|| source_line_range(&self.source, off));
6623        self.anchor = Some(range.start.min(self.source.len()));
6624        self.caret = range.end.min(self.source.len());
6625        self.goal_col = None;
6626        self.last_edit_kind = None;
6627        self.status = None;
6628        self.clamp_caret();
6629    }
6630
6631    /// Select the exact source range `[start, end)` — anchor at `start`, caret
6632    /// at `end` — without snapping either end to a visible caret stop.
6633    ///
6634    /// The one caret verb that takes a range it was *handed* rather than one it
6635    /// worked out, for a host that already knows the bytes it means: a search
6636    /// hit, an annotation's footprint, a quote re-anchored through
6637    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
6638    /// wrong tool for that, and not by a little — it snaps to the nearest
6639    /// *visible* stop, and where a range butts up against a hidden delimiter
6640    /// the nearest stop is the one before it, so selecting the "needle" of
6641    /// `**needle**` comes back with "needl" and an edit against it strands the
6642    /// "e".
6643    ///
6644    /// What `place_caret` does that is bookkeeping rather than snapping still
6645    /// happens here, because a host handing in a range is not asking to opt out
6646    /// of the invariants:
6647    ///
6648    /// - both ends are clamped into the document and up to
6649    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
6650    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
6651    ///   types into the metadata;
6652    /// - both land on character boundaries, so nothing slices a `é` in half;
6653    /// - the sticky vertical goal column is dropped, and any armed inline mark
6654    ///   disarmed, since a range from outside inherits neither.
6655    ///
6656    /// An empty range is a caret rather than a selection —
6657    /// [`selection`](Self::selection) reports `None` for it, as it does for any
6658    /// anchor that has met the caret.
6659    pub fn select_range(&mut self, start: usize, end: usize) {
6660        let floor = self.caret_floor();
6661        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
6662        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
6663        self.anchor = Some(anchor);
6664        self.caret = caret;
6665        self.goal_col = None;
6666        self.status = None;
6667        self.last_edit_kind = None;
6668        self.clear_pending();
6669    }
6670
6671    /// `offset` itself if it is a character boundary, else the boundary before
6672    /// it. An offset that isn't one draws nowhere real and panics the next time
6673    /// anything slices there.
6674    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
6675        let mut o = offset.min(self.source.len());
6676        while o > 0 && !self.source.is_char_boundary(o) {
6677            o -= 1;
6678        }
6679        o
6680    }
6681
6682    /// The lowest source offset the caret may occupy in the active view. In
6683    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
6684    /// the first rendered offset; the source view reaches everything, so it's 0.
6685    fn caret_floor(&self) -> usize {
6686        match self.view {
6687            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
6688            View::Source => 0,
6689        }
6690    }
6691
6692    /// Land in a table cell with its whole content selected — the anchor at the
6693    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
6694    /// like tabbing into a form field: the text comes up selected, so typing
6695    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
6696    /// end`) collapses to a plain caret home (an empty selection is no selection).
6697    fn select_cell(&mut self, start: usize, end: usize) {
6698        self.select_range(start, end);
6699    }
6700
6701    fn move_to(&mut self, offset: usize, extend: bool) {
6702        if extend {
6703            if self.anchor.is_none() {
6704                self.anchor = Some(self.caret);
6705            }
6706        } else {
6707            self.anchor = None;
6708        }
6709        self.caret = offset.min(self.source.len()).max(self.caret_floor());
6710        self.status = None;
6711        // A caret move ends the current typing/deletion run, so the next edit
6712        // starts a fresh undo group rather than coalescing across the gap.
6713        self.last_edit_kind = None;
6714        // Moving away disarms any sticky mark — "start bold" applies only where
6715        // it was asked for, not wherever the caret next lands.
6716        self.clear_pending();
6717    }
6718
6719    // In the source view, motion walks source bytes / source lines. In the
6720    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
6721    // what steps the caret cleanly over hidden delimiters.
6722
6723    pub fn move_left(&mut self, extend: bool) {
6724        self.goal_col = None;
6725        if !extend && let Some((s, _e)) = self.selection() {
6726            self.move_to(s, false);
6727            return;
6728        }
6729        let target = match self.view {
6730            View::Source => {
6731                if self.caret > 0 {
6732                    prev_boundary(&self.source, self.caret)
6733                } else {
6734                    0
6735                }
6736            }
6737            // Walks caret *stops*, not columns: decoration (a table border, a
6738            // cell's padding) is stepped over in one press, and a hidden
6739            // delimiter never holds the caret up — though the end of a mark's
6740            // content is a stop of its own (`VisualMap::mark_ends`), so
6741            // leaving `**bold**` from past its `**` is a press onto the end of
6742            // the bold and another onto the `d`.
6743            View::Wysiwyg => self
6744                .vmap
6745                .caret_stop_before(self.caret)
6746                .unwrap_or(self.caret),
6747        };
6748        let before = self.caret;
6749        self.move_to(target, extend);
6750        self.debug_assert_on_a_stop(before);
6751    }
6752
6753    pub fn move_right(&mut self, extend: bool) {
6754        self.goal_col = None;
6755        if !extend && let Some((_s, e)) = self.selection() {
6756            self.move_to(e, false);
6757            return;
6758        }
6759        let target = match self.view {
6760            View::Source => {
6761                if self.caret < self.source.len() {
6762                    next_boundary(&self.source, self.caret)
6763                } else {
6764                    self.caret
6765                }
6766            }
6767            View::Wysiwyg => self.vmap.caret_stop_after(self.caret).unwrap_or(self.caret),
6768        };
6769        let before = self.caret;
6770        self.move_to(target, extend);
6771        self.debug_assert_on_a_stop(before);
6772    }
6773
6774    /// Move to the start of the previous word (⌥← / Ctrl+←).
6775    pub fn move_word_left(&mut self, extend: bool) {
6776        self.goal_col = None;
6777        let before = self.caret;
6778        let target = self.word_left_from(self.caret);
6779        self.move_to(target, extend);
6780        self.debug_assert_on_a_stop(before);
6781    }
6782
6783    /// Move to the end of the next word (⌥→ / Ctrl+→).
6784    pub fn move_word_right(&mut self, extend: bool) {
6785        self.goal_col = None;
6786        let before = self.caret;
6787        let target = self.word_right_from(self.caret);
6788        self.move_to(target, extend);
6789        self.debug_assert_on_a_stop(before);
6790    }
6791
6792    // Word boundaries are found in the space the *view* is in. The source view
6793    // walks the source, because there the source is what's rendered. WYSIWYG
6794    // walks the rendered text instead: `**` is invisible to the user, so it has
6795    // to be invisible to word motion too — a caret parked inside one draws in
6796    // the column after `bold` and types two bytes earlier, and a word-delete
6797    // that stops there shreds the markup into `a ** c`.
6798
6799    /// The word boundary to the left of `off` in the active view's space.
6800    fn word_left_from(&self, off: usize) -> usize {
6801        match self.view {
6802            View::Source => prev_word(&self.source, off),
6803            View::Wysiwyg => self.glyph_word_left(off),
6804        }
6805    }
6806
6807    /// The word boundary to the right of `off` in the active view's space.
6808    fn word_right_from(&self, off: usize) -> usize {
6809        match self.view {
6810            View::Source => next_word(&self.source, off),
6811            View::Wysiwyg => self.glyph_word_right(off),
6812        }
6813    }
6814
6815    /// The character class of the glyph drawn at stop `off`.
6816    ///
6817    /// Read from the source, because a stop points at the source byte its glyph
6818    /// came from — the source *is* where the rendered character is written. What
6819    /// makes the walk glyph space rather than source space is that it only ever
6820    /// visits stops, and the hidden bytes between them have none.
6821    fn class_at(&self, off: usize) -> Class {
6822        self.source
6823            .get(off..)
6824            .and_then(|s| s.chars().next())
6825            .map_or(Class::Space, classify)
6826    }
6827
6828    /// [`next_word`] in glyph space: skip any leading separators, then consume
6829    /// the following word run, with the stop table standing in for the source's
6830    /// characters.
6831    fn glyph_word_right(&self, from: usize) -> usize {
6832        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
6833            return from;
6834        };
6835        let mut in_word = false;
6836        loop {
6837            match self.class_at(off) {
6838                Class::Word => in_word = true,
6839                _ if in_word => return off,
6840                _ => {}
6841            }
6842            match self.vmap.stop_after(off) {
6843                Some(next) => off = next,
6844                None => return off,
6845            }
6846        }
6847    }
6848
6849    /// [`prev_word`] in glyph space: skip separators walking left, then consume
6850    /// the preceding word run.
6851    fn glyph_word_left(&self, from: usize) -> usize {
6852        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
6853            return from;
6854        };
6855        let mut in_word = false;
6856        while let Some(prev) = self.vmap.stop_before(off) {
6857            match self.class_at(prev) {
6858                Class::Word => in_word = true,
6859                _ if in_word => return off,
6860                _ => {}
6861            }
6862            off = prev;
6863        }
6864        off
6865    }
6866
6867    /// After a motion that walks the visual map, the caret must be *on* the map.
6868    /// A stop is the only offset where the caret draws and edits in the same
6869    /// place, and it's the invariant both a caret parked inside an emoji and one
6870    /// parked inside a `**` were quietly breaking.
6871    ///
6872    /// Only when the caret actually moved: a walk with nowhere to go leaves it
6873    /// where it was, which is wherever the floor or a frontend put it rather
6874    /// than somewhere this motion chose.
6875    fn debug_assert_on_a_stop(&self, before: usize) {
6876        debug_assert!(
6877            self.view != View::Wysiwyg
6878                || self.vmap.num_rows() == 0
6879                || self.caret == before
6880                || self.vmap.is_stop(self.caret),
6881            "motion left the caret at {}, which is not a caret stop: it would draw in \
6882             one place and type in another",
6883            self.caret
6884        );
6885    }
6886
6887    // Up and Down run off the ends of the document rather than stopping dead at
6888    // them: Up from the first row lands at the document's start, Down from the
6889    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
6890    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
6891    // reaching the end of the text is what a reader means by it.
6892    //
6893    // The views used to disagree here by accident rather than by decision: the
6894    // source view fell into the edge behaviour through `row_col_to_offset`
6895    // clamping an out-of-range row to the end of the string, while WYSIWYG had
6896    // no row below to walk to and did nothing at all. They share the rule now,
6897    // each in its own space — the source view reaches every byte, WYSIWYG only
6898    // the offsets it draws.
6899
6900    pub fn move_up(&mut self, extend: bool) {
6901        let (row, col) = self.caret_pos();
6902        let goal = self.goal_col.unwrap_or(col);
6903        let target = match self.view {
6904            View::Source => match row.checked_sub(1) {
6905                Some(r) => row_col_to_offset(&self.source, r, goal),
6906                None => self.reachable_start(),
6907            },
6908            // A table's border rules are drawn but hold no caret, so Up steps
6909            // over them to the row that does.
6910            View::Wysiwyg => match self.vmap.navigable_above(row) {
6911                Some(r) => self.row_target(r, goal),
6912                None => self.reachable_start(),
6913            },
6914        };
6915        self.step_vertical(target, goal, extend);
6916    }
6917
6918    pub fn move_down(&mut self, extend: bool) {
6919        let (row, col) = self.caret_pos();
6920        let goal = self.goal_col.unwrap_or(col);
6921        let target = match self.view {
6922            View::Source => match self.source_row_below(row) {
6923                Some(r) => row_col_to_offset(&self.source, r, goal),
6924                None => self.reachable_end(),
6925            },
6926            View::Wysiwyg => match self.vmap.navigable_below(row) {
6927                Some(r) => self.row_target(r, goal),
6928                None => self.reachable_end(),
6929            },
6930        };
6931        self.step_vertical(target, goal, extend);
6932    }
6933
6934    /// Land a vertical motion at `target`, latching the `goal` column it aimed
6935    /// with so the rest of the run keeps aiming there.
6936    ///
6937    /// A motion with nowhere to go changes *nothing*, the goal column included:
6938    /// the latch used to run before the early return at the top of the document,
6939    /// so an Up that did nothing still armed a column, and the next Down aimed
6940    /// at one the caret had never been in.
6941    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
6942        let before = self.caret;
6943        if target == before {
6944            return;
6945        }
6946        self.goal_col = Some(goal);
6947        self.move_to(target, extend);
6948        self.debug_assert_on_a_stop(before);
6949    }
6950
6951    /// The source line below `row`, or `None` when `row` is the last one. Lines
6952    /// are counted by newline, so a trailing one leaves a real, empty last line
6953    /// for the caret to sit on — the document ends below it, not on it.
6954    fn source_row_below(&self, row: usize) -> Option<usize> {
6955        let last = self.source.bytes().filter(|&b| b == b'\n').count();
6956        (row < last).then_some(row + 1)
6957    }
6958
6959    /// Where a vertical motion aiming at the `goal` column lands on visual row
6960    /// `r`: the column clamped to the row, mapped to its offset, then held
6961    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
6962    /// column belongs to the row below, and a gutter's column 0 points at the
6963    /// block rather than at this row.
6964    fn row_target(&self, r: usize, goal: usize) -> usize {
6965        let (start, end) = self.row_bounds(r);
6966        self.vmap
6967            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
6968            .clamp(start, end)
6969    }
6970
6971    /// The first and last offsets the caret can reach in the active view.
6972    ///
6973    /// Not the same span in both: the source view shows every byte, so it can
6974    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
6975    /// sits below the first stop, and a document's trailing newline is drawn
6976    /// nowhere and so sits past the last.
6977    fn reachable_start(&self) -> usize {
6978        match self.view {
6979            View::Source => 0,
6980            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
6981        }
6982    }
6983
6984    fn reachable_end(&self) -> usize {
6985        match self.view {
6986            View::Source => self.source.len(),
6987            View::Wysiwyg => self
6988                .vmap
6989                .stop_at_or_before(self.source.len())
6990                .unwrap_or(self.caret),
6991        }
6992    }
6993
6994    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
6995    /// including the space a soft wrap ate off its end, which is drawn on this
6996    /// row however much the offset past it belongs to the next one.
6997    fn row_span(&self, r: usize) -> (usize, usize) {
6998        let start = self
6999            .vmap
7000            .row_start(r)
7001            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
7002        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
7003        (start.min(end), end)
7004    }
7005
7006    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
7007    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
7008    /// this row's last position is the one before it — the offset before the
7009    /// space the wrap ate, where the caret draws just past the row's last word
7010    /// and types there too.
7011    ///
7012    /// Aiming at the shared offset instead is what stalled End: it is the row's
7013    /// last *column*, so End pressed on the row reached it and then read back as
7014    /// the row below's start, where a second press ran on to that row's end and
7015    /// the next to the one after — End walking down the paragraph a row a press.
7016    fn row_bounds(&self, r: usize) -> (usize, usize) {
7017        let (start, end) = self.row_span(r);
7018        let wraps = self
7019            .vmap
7020            .navigable_below(r)
7021            .and_then(|b| self.vmap.row_start(b))
7022            .is_some_and(|off| off == end);
7023        match wraps {
7024            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
7025            false => (start, end),
7026        }
7027    }
7028
7029    /// The `[start, end]` of the line Home and End aim at: the visual row in
7030    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
7031    ///
7032    /// A soft-wrapped row is a line here, because it is one to the eye and the
7033    /// eye is what these keys are aimed by — a reader pressing End means the end
7034    /// of the line they can see. (`select_block_at` wants the opposite and reads
7035    /// the AST for it: a triple-click grabs the whole paragraph, however many
7036    /// rows it folds into.)
7037    fn line_bounds(&self) -> (usize, usize) {
7038        let (row, _) = self.caret_pos();
7039        match self.view {
7040            View::Source => {
7041                let start = line_start(&self.source, row);
7042                (start, line_end_from(&self.source, start))
7043            }
7044            View::Wysiwyg => self.row_bounds(row),
7045        }
7046    }
7047
7048    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
7049    /// *drawn* — what a kill takes.
7050    ///
7051    /// The two part only at a soft wrap, over the space the wrap ate: the caret
7052    /// can't stand after it (that offset opens the row below, and End stopping
7053    /// there would walk), but it is on this row, and a kill that spared it would
7054    /// leave a double space behind where the row's text had been. Deleting it
7055    /// joins nothing — a wrap is drawn, not written.
7056    fn line_span(&self) -> (usize, usize) {
7057        let (row, _) = self.caret_pos();
7058        match self.view {
7059            View::Source => self.line_bounds(),
7060            View::Wysiwyg => self.row_span(row),
7061        }
7062    }
7063
7064    /// The first offset in `[start, end]` holding something other than
7065    /// whitespace, or `end` when the line holds nothing else — where Home aims.
7066    ///
7067    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
7068    /// so a hidden delimiter is never taken for the line's first character (nor
7069    /// landed on), and the source view steps the source it is showing.
7070    fn first_non_space(&self, start: usize, end: usize) -> usize {
7071        let mut off = start;
7072        while off < end {
7073            if self.class_at(off) != Class::Space {
7074                return off;
7075            }
7076            off = match self.view {
7077                View::Source => next_boundary(&self.source, off),
7078                View::Wysiwyg => match self.vmap.stop_after(off) {
7079                    Some(next) => next,
7080                    None => return end,
7081                },
7082            };
7083        }
7084        end
7085    }
7086
7087    /// Home: to the first character on the line, or to column 0 when the caret
7088    /// is already on it — the two-press toggle every editor spells this way.
7089    /// The indentation is somewhere the caret has to be able to reach and almost
7090    /// never where a reader is headed, so it costs the second press.
7091    pub fn move_home(&mut self, extend: bool) {
7092        self.goal_col = None;
7093        let (start, end) = self.line_bounds();
7094        let text = self.first_non_space(start, end);
7095        let target = if self.caret == text { start } else { text };
7096        let before = self.caret;
7097        self.move_to(target, extend);
7098        self.debug_assert_on_a_stop(before);
7099    }
7100
7101    /// End: to the end of the line.
7102    pub fn move_end(&mut self, extend: bool) {
7103        self.goal_col = None;
7104        let (_, end) = self.line_bounds();
7105        let before = self.caret;
7106        self.move_to(end, extend);
7107        self.debug_assert_on_a_stop(before);
7108    }
7109
7110    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
7111    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
7112    /// when the caret isn't in a table, or is already in the last/first cell — the
7113    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
7114    /// meaning everywhere else.
7115    pub fn cell_hop(&mut self, forward: bool) -> bool {
7116        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
7117            return false;
7118        };
7119        // Flatten to document (row-major) order and step one cell either way.
7120        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
7121        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
7122        let next = if forward {
7123            i.checked_add(1)
7124        } else {
7125            i.checked_sub(1)
7126        };
7127        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
7128            return false; // at the table's edge; leave Tab to the frontend
7129        };
7130        self.select_cell(start, end);
7131        true
7132    }
7133
7134    /// Move the caret to the cell directly above (`down == false`) or below in
7135    /// the same column, landing with the cell's whole content selected (see
7136    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
7137    /// when the caret isn't in a table), so the frontend can fall through — the
7138    /// vertical counterpart of [`Self::cell_hop`].
7139    ///
7140    /// A ragged row that is short a column clamps to its last cell, so Down never
7141    /// falls out of the table over a gap the row above happened to have.
7142    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
7143        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
7144            return false;
7145        };
7146        let target = match down {
7147            true => r + 1,
7148            false if r == 0 => return false,
7149            false => r - 1,
7150        };
7151        let Some(row) = grid.get(target) else {
7152            return false;
7153        };
7154        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
7155            return false;
7156        };
7157        self.select_cell(start, end);
7158        true
7159    }
7160
7161    /// The table containing `off` as a row-major grid of `(start, end)` cell
7162    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
7163    /// isn't in a table. Read straight off the visual map's laid-out grid, so
7164    /// every cell (an empty one included, whose derived home twig gives no
7165    /// `content_span` for) is present and in the order Tab walks them.
7166    // Grid, row, column — three returns that only ever travel together, and a
7167    // named type for the pair of them would be read at one call site.
7168    #[allow(clippy::type_complexity)]
7169    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
7170        for t in &self.vmap.tables {
7171            let mut pos = None;
7172            let grid: Vec<Vec<(usize, usize)>> = t
7173                .grid
7174                .iter()
7175                .enumerate()
7176                .map(|(r, row)| {
7177                    row.cells
7178                        .iter()
7179                        .enumerate()
7180                        .map(|(c, cell)| {
7181                            if pos.is_none() && off >= cell.start && off <= cell.end {
7182                                pos = Some((r, c));
7183                            }
7184                            (cell.start, cell.end)
7185                        })
7186                        .collect()
7187                })
7188                .collect();
7189            if let Some((r, c)) = pos {
7190                return Some((grid, r, c));
7191            }
7192        }
7193        None
7194    }
7195
7196    // ── table key policy ──────────────────────────────────────────────────────
7197    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
7198    // as one policy every frontend shares, rather than each re-deriving it. Each
7199    // reports whether it acted *as a table key*; a `false` hands the key back to
7200    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
7201    // everywhere else.
7202
7203    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
7204    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
7205    /// back and simply stays put at the very first cell. `false` when the caret
7206    /// isn't in a table.
7207    pub fn cell_tab(&mut self, forward: bool) -> bool {
7208        if !self.caret_in_table() {
7209            return false;
7210        }
7211        if self.cell_hop(forward) {
7212            return true;
7213        }
7214        // Off the last cell: grow the table by a row and step into its first
7215        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
7216        if forward {
7217            self.append_row_and_enter(0);
7218        }
7219        true
7220    }
7221
7222    /// Return inside a table: drop to the cell below in the same column,
7223    /// appending a new row when the caret is already in the last one. `false`
7224    /// when the caret isn't in a table, so the frontend inserts a newline.
7225    pub fn cell_return(&mut self) -> bool {
7226        if !self.caret_in_table() {
7227            return false;
7228        }
7229        if self.cell_move_vertical(true) {
7230            return true;
7231        }
7232        // Already on the last row: grow one below and drop into the same column.
7233        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
7234        self.append_row_and_enter(col);
7235        true
7236    }
7237
7238    /// Append a row below the caret's (last) row and land in `col` of it. The
7239    /// caret is in the last row, so twig's "insert below" makes the fresh row the
7240    /// table's new last — but twig re-spells the whole table, moving every byte,
7241    /// so the destination is read back from the rebuilt grid by the table's
7242    /// position (stable across a row insert), not from the pre-edit caret.
7243    fn append_row_and_enter(&mut self, col: usize) {
7244        let table = self.caret_table_index();
7245        self.table_insert_row(true);
7246        self.rebuild_map();
7247        let Some((start, end)) = table
7248            .and_then(|ti| self.vmap.tables.get(ti))
7249            .and_then(|t| t.grid.last())
7250            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
7251            .map(|cell| (cell.start, cell.end))
7252        else {
7253            return;
7254        };
7255        self.select_cell(start, end);
7256    }
7257
7258    /// The index, among the document's tables, of the one the caret sits in —
7259    /// `None` when it's in none. Used to re-find a table after an edit re-spells
7260    /// it (a row insert leaves the table order unchanged).
7261    fn caret_table_index(&self) -> Option<usize> {
7262        let off = self.caret;
7263        self.vmap.tables.iter().position(|t| {
7264            t.grid
7265                .iter()
7266                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
7267        })
7268    }
7269
7270    /// Shift+Return inside a table: insert a hard line break *within* the current
7271    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
7272    /// table, so the frontend inserts an ordinary line break.
7273    ///
7274    /// A table row is a single source line, so the newline-spelled hard break
7275    /// can't live in a cell. twig spells the in-cell break the format's way
7276    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
7277    /// break round-trips as structure the renderer reads back as a line — not the
7278    /// opaque raw HTML the old raw-splice left behind.
7279    ///
7280    /// Djot has no idiomatic in-cell break, so twig refuses it
7281    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
7282    /// would render as the literal text `<br>`. The gesture is still *consumed*
7283    /// there — returning `false` would let the frontend insert a real newline,
7284    /// which splits the one-line row — it just leaves the cell unchanged and says
7285    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
7286    ///
7287    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
7288    /// have to be read together: djot is not the only `false`, and naming it in
7289    /// the message was already a guess that HTML — which spells the break as its
7290    /// own `<br>` — would have made wrong.
7291    pub fn cell_line_break(&mut self) -> bool {
7292        if self.read_only || !self.caret_in_table() {
7293            return false;
7294        }
7295        self.record_caret();
7296        match self.editor.insert_line_break(self.caret) {
7297            Ok(change) => {
7298                self.last_edit_kind = None;
7299                self.refresh();
7300                self.caret = change.new.end;
7301                self.anchor = None;
7302                self.goal_col = None;
7303                self.clamp_caret();
7304                self.dirty = self.source != self.clean_source;
7305                self.status = None;
7306                self.record_caret();
7307            }
7308            Err(twig::Error::UnsupportedFormat) => {
7309                self.status = Some(format!(
7310                    "in-cell line breaks aren't supported in {}",
7311                    self.format_name()
7312                ));
7313            }
7314            Err(_) => {}
7315        }
7316        true
7317    }
7318
7319    /// Rebuild the visual map at the width the last build used. A structural edit
7320    /// bumps the revision and swaps the source in, but leaves the *map* stale;
7321    /// when a single gesture edits and then moves over the result (Tab appending
7322    /// a row, then stepping into it), the move needs the map to already show the
7323    /// edit rather than waiting for the frontend's next frame.
7324    fn rebuild_map(&mut self) {
7325        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
7326        self.build_map(wrap);
7327    }
7328
7329    /// Move the caret to the very start of the document (⌘↑ on macOS,
7330    /// Ctrl+Home on Windows/Linux).
7331    pub fn move_doc_start(&mut self, extend: bool) {
7332        self.goal_col = None;
7333        self.move_to(0, extend);
7334    }
7335
7336    /// Move the caret to the very end of the document (⌘↓ on macOS,
7337    /// Ctrl+End on Windows/Linux).
7338    pub fn move_doc_end(&mut self, extend: bool) {
7339        self.goal_col = None;
7340        let end = self.source.len();
7341        self.move_to(end, extend);
7342    }
7343
7344    /// Point the caret at the body cell `(row, col)` the mouse landed on —
7345    /// `col` being a cell of the terminal grid, which is what a display column
7346    /// is. A click on the far cell of a wide character lands at that
7347    /// character's start; the mapping's own doc-comments carry the rule.
7348    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
7349        self.goal_col = None;
7350        let target = match self.view {
7351            View::Source => row_col_to_offset(&self.source, row, col),
7352            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
7353        };
7354        let before = self.caret;
7355        self.move_to(target, extend);
7356        self.debug_assert_on_a_stop(before);
7357    }
7358
7359    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
7360    /// screen if it has moved since the last frame, and never scroll past the
7361    /// last of `rows`.
7362    ///
7363    /// Only if it has *moved* — that's the whole point. Revealing the caret on
7364    /// every frame ties the viewport to it, and a scroll wheel that fights the
7365    /// caret for the viewport loses: the view snaps back the instant it tries to
7366    /// pass the caret's row, so the document can't be scrolled beyond what's
7367    /// already on screen. A caret move is the frontend's cue to follow; a scroll
7368    /// with the caret sitting still is the reader's cue to leave it alone.
7369    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
7370        if self.drawn_caret != Some(self.caret) {
7371            if caret_row < self.scroll {
7372                self.scroll = caret_row;
7373            } else if height > 0 && caret_row >= self.scroll + height {
7374                self.scroll = caret_row + 1 - height;
7375            }
7376            self.drawn_caret = Some(self.caret);
7377        }
7378        self.scroll = self.scroll.min(rows.saturating_sub(1));
7379    }
7380
7381    /// The caret's screen position `(row, col)` in the active view's grid, with
7382    /// `col` a display column: the cell to draw the caret in, which on a line of
7383    /// `你好` or emoji is not the count of characters before it.
7384    pub fn caret_pos(&self) -> (usize, usize) {
7385        match self.view {
7386            View::Source => offset_to_row_col(&self.source, self.caret),
7387            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
7388        }
7389    }
7390
7391    fn clamp_caret(&mut self) {
7392        if self.caret > self.source.len() {
7393            self.caret = self.source.len();
7394        }
7395        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
7396        // any selection anchor) to the first rendered offset.
7397        let floor = self.caret_floor();
7398        if self.caret < floor {
7399            self.caret = floor;
7400        }
7401        if let Some(a) = self.anchor
7402            && a < floor
7403        {
7404            self.anchor = Some(floor);
7405        }
7406        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
7407            self.caret -= 1;
7408        }
7409    }
7410}
7411
7412// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
7413
7414// Left/right motion and backspace/delete step by *grapheme cluster*, not
7415// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
7416// marks moves and deletes as the single character a user sees. Grapheme
7417// boundaries are a superset of char boundaries, so the caret stays valid for twig.
7418
7419/// How an insert of `text` groups for undo: a single typed character folds into
7420/// the run of typing around it, while a newline or a multi-character insert is a
7421/// step of its own.
7422fn typed_edit_kind(text: &str) -> EditKind {
7423    if text.chars().take(2).count() == 1 && text != "\n" {
7424        EditKind::Insert
7425    } else {
7426        EditKind::Other
7427    }
7428}
7429
7430fn prev_boundary(s: &str, i: usize) -> usize {
7431    let mut cursor = GraphemeCursor::new(i, s.len(), true);
7432    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
7433}
7434
7435fn next_boundary(s: &str, i: usize) -> usize {
7436    let mut cursor = GraphemeCursor::new(i, s.len(), true);
7437    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
7438}
7439
7440// ── word boundaries ──────────────────────────────────────────────────────────
7441// The shared primitive behind word-wise motion, word deletion, and
7442// double-click-to-select-a-word. A "word" is a maximal run of one character
7443// class; whitespace and punctuation are their own classes, so motion skips
7444// cleanly between them the way native text fields do.
7445
7446#[derive(PartialEq, Eq, Clone, Copy)]
7447enum Class {
7448    Word,
7449    Space,
7450    Other,
7451}
7452
7453/// The source range of an inline node's own visible text — the part of it a
7454/// WYSIWYG caret can reach, as against the delimiters that only spell it.
7455/// `None` for a node with no interior to empty (a `str`, a break).
7456///
7457/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
7458/// one delimiter in from the span — the same place the renderer maps it to. A
7459/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
7460/// against the source rather than trusted: a range guessed wrong here is text
7461/// deleted wrong.
7462fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
7463    if let Some(span) = n.content_span.clone() {
7464        return Some(span);
7465    }
7466    match n.kind.as_str() {
7467        "verbatim" | "inline_math" => {
7468            let text = n.text.as_ref()?;
7469            let start = n.span.start + 1;
7470            let range = start..start + text.len();
7471            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
7472        }
7473        _ => None,
7474    }
7475}
7476
7477/// The `id` a node declares, or `None` for one that declares none — the
7478/// attribute djot writes for a `{#v1}` and mints for a heading.
7479///
7480/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
7481/// names nothing, so it reads as absent rather than as the empty string.
7482fn declared_id(n: &FlatNode) -> Option<&str> {
7483    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
7484}
7485
7486/// A heading's words reduced to the form a link fragment spells them in:
7487/// lowercase, runs of anything else collapsed to a single `-`, with none left
7488/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
7489///
7490/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
7491/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
7492/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
7493/// any other language is still a heading someone will link to. Underscores
7494/// survive for the same reason they do on the web: they are word characters
7495/// wherever identifiers are written.
7496fn slug(text: &str) -> String {
7497    let mut out = String::new();
7498    let mut pending = false;
7499    for c in text.chars() {
7500        if c.is_alphanumeric() || c == '_' {
7501            if pending && !out.is_empty() {
7502                out.push('-');
7503            }
7504            pending = false;
7505            out.extend(c.to_lowercase());
7506        } else {
7507            pending = true;
7508        }
7509    }
7510    out
7511}
7512
7513fn is_block_container(kind: &Kind) -> bool {
7514    matches!(
7515        kind,
7516        Kind::Doc
7517            | Kind::Section
7518            | Kind::BlockQuote
7519            | Kind::BulletList
7520            | Kind::OrderedList
7521            | Kind::TaskList
7522            | Kind::ListItem
7523            | Kind::TaskListItem
7524            // Every `container` — a directive in any of its three forms, or a
7525            // promoted HTML element. A *text* directive is really inline, so
7526            // claiming it here is a small overreach, and the deliberate one this
7527            // function's kind-only peer `is_inline_kind` documents: the pair is
7528            // consulted together, and answering "block container" for something
7529            // inline is what keeps an ancestor walk from stopping short of the
7530            // paragraph that actually holds it.
7531            | Kind::Container
7532    )
7533}
7534
7535/// The `[start, end)` byte range of the source line containing `off` (newline
7536/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
7537/// line between paragraphs).
7538fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
7539    let off = off.min(s.len());
7540    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
7541    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
7542    start..end
7543}
7544
7545/// How many leading bytes an outdent takes off `line`: a whole indent level
7546/// where the line has one, and whatever it has where it has less.
7547///
7548/// A leading tab counts as a level on its own. It's indentation some other
7549/// editor wrote, and one tab is one level everywhere it came from — measuring it
7550/// in spaces it doesn't contain would leave it untouchable.
7551fn outdent_width(line: &str, unit: usize) -> usize {
7552    if line.starts_with('\t') {
7553        return 1;
7554    }
7555    line.bytes().take(unit).take_while(|b| *b == b' ').count()
7556}
7557
7558/// A list marker found at the head of a line, together with everything before it
7559/// that a sibling line has to repeat.
7560///
7561/// The three offsets differ only inside a block quote, where `>   - b` opens with
7562/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
7563/// `line_start == marker_start`, and `text` is the plain `"  - "`.
7564#[derive(Clone, Debug)]
7565struct ListMarker {
7566    /// The line's first byte.
7567    line_start: usize,
7568    /// Where the marker proper begins, past any quote prefix. The offset to hand
7569    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
7570    marker_start: usize,
7571    /// `line_start` through the marker's trailing space — quote prefix, indent
7572    /// and bullet together, which is what the next item's line opens with.
7573    text: String,
7574}
7575
7576impl ListMarker {
7577    /// Where the item's content starts — one past the marker's trailing space.
7578    fn content_start(&self) -> usize {
7579        self.line_start + self.text.len()
7580    }
7581}
7582
7583fn classify(c: char) -> Class {
7584    if c == '_' || c.is_alphanumeric() {
7585        Class::Word
7586    } else if c.is_whitespace() {
7587        Class::Space
7588    } else {
7589        Class::Other
7590    }
7591}
7592
7593/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
7594/// skip any leading separators, then consume the following word run.
7595fn next_word(s: &str, i: usize) -> usize {
7596    let mut off = i;
7597    let mut in_word = false;
7598    for c in s[i..].chars() {
7599        if classify(c) == Class::Word {
7600            in_word = true;
7601        } else if in_word {
7602            break;
7603        }
7604        off += c.len_utf8();
7605    }
7606    off
7607}
7608
7609/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
7610/// skip separators walking left, then consume the preceding word run.
7611fn prev_word(s: &str, i: usize) -> usize {
7612    let mut off = i;
7613    let mut in_word = false;
7614    for c in s[..i].chars().rev() {
7615        if classify(c) == Class::Word {
7616            in_word = true;
7617        } else if in_word {
7618            break;
7619        }
7620        off -= c.len_utf8();
7621    }
7622    off
7623}
7624
7625/// The `[start, end)` run of same-class characters surrounding `off` — the
7626/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
7627/// the run ending there is used.
7628fn word_range_at(s: &str, off: usize) -> (usize, usize) {
7629    if s.is_empty() {
7630        return (0, 0);
7631    }
7632    let off = off.min(s.len());
7633    let reference = if off < s.len() {
7634        s[off..].chars().next()
7635    } else {
7636        s[..off].chars().next_back()
7637    };
7638    let Some(rc) = reference else {
7639        return (off, off);
7640    };
7641    let class = classify(rc);
7642
7643    let mut start = off;
7644    for c in s[..start].chars().rev() {
7645        if classify(c) == class {
7646            start -= c.len_utf8();
7647        } else {
7648            break;
7649        }
7650    }
7651    let mut end = off;
7652    for c in s[end..].chars() {
7653        if classify(c) == class {
7654            end += c.len_utf8();
7655        } else {
7656            break;
7657        }
7658    }
7659    (start, end)
7660}
7661
7662/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
7663/// the line's start — terminal cells, not characters, so the column names the
7664/// cell the caret is drawn in even on a line of `你好` or emoji.
7665fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
7666    let off = off.min(s.len());
7667    let mut row = 0;
7668    let mut line_start = 0;
7669    for (i, &b) in s.as_bytes().iter().enumerate() {
7670        if i >= off {
7671            break;
7672        }
7673        if b == b'\n' {
7674            row += 1;
7675            line_start = i + 1;
7676        }
7677    }
7678    (row, wysiwyg::text_width(&s[line_start..off]))
7679}
7680
7681/// The byte offset at display column `col` of `row` (clamped to that line's
7682/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
7683///
7684/// A column landing *inside* a character — the second cell of `你`, or any cell
7685/// but the first of an emoji — resolves to that character's start, which is the
7686/// column the caret would have been drawn at to begin with. So both cells of a
7687/// wide character mean the character, and every offset survives the round trip
7688/// out to a column and back. The walk steps by grapheme cluster for the same
7689/// reason the caret does: a cluster is the character, and the cells belong to it
7690/// rather than to the codepoints spelling it.
7691fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
7692    let start = line_start(s, row);
7693    let end = line_end_from(s, start);
7694    let mut off = start;
7695    let mut at = 0; // the display column `off` sits at
7696    while off < end {
7697        let next = next_boundary(s, off).min(end);
7698        let cells = wysiwyg::text_width(&s[off..next]);
7699        if at + cells > col {
7700            break; // `col` is one of this cluster's own cells
7701        }
7702        at += cells;
7703        off = next;
7704    }
7705    off
7706}
7707
7708fn line_start(s: &str, row: usize) -> usize {
7709    if row == 0 {
7710        return 0;
7711    }
7712    let mut r = 0;
7713    for (i, &b) in s.as_bytes().iter().enumerate() {
7714        if b == b'\n' {
7715            r += 1;
7716            if r == row {
7717                return i + 1;
7718            }
7719        }
7720    }
7721    s.len()
7722}
7723
7724fn line_end_from(s: &str, start: usize) -> usize {
7725    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
7726}
7727
7728/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
7729/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
7730/// twig applies writing the mark out, so the toolbar can light the same button
7731/// that made the node.
7732///
7733/// `None` for every other kind, including the inline nodes that aren't marks at
7734/// all (`str`, `link`, `image`, the math and break kinds): they're things a
7735/// caret stands in, not formatting a button toggles.
7736/// Whether a match from an ancestor chain is an inline run whose delimiters
7737/// the rich view draws nothing for — a mark (`**`, `_`, `==`), or an
7738/// attributed span: `<span data-size="large">…</span>`, djot's `[…]{…}`. The
7739/// span is a [`Kind::Container`], which the kind alone cannot tell from a
7740/// block `<div>`, so the chain's caller passes [`Doc::run_span_ids`] and the
7741/// answer is the node's own. Every delete and caret step that walks over a
7742/// `**` walks over a span's tags by this test; without it Backspace after
7743/// `</span>` took the `>` and left the paragraph unparseable.
7744fn hides_delims(m: &QueryMatch, run_spans: &[NodeId]) -> bool {
7745    inline_kind(&m.kind).is_some() || run_spans.contains(&NodeId(m.node_id))
7746}
7747
7748fn inline_kind(kind: &Kind) -> Option<InlineKind> {
7749    Some(match kind {
7750        Kind::Strong => InlineKind::Strong,
7751        Kind::Emph => InlineKind::Emph,
7752        Kind::Verbatim => InlineKind::Verbatim,
7753        Kind::Mark => InlineKind::Mark,
7754        Kind::Superscript => InlineKind::Superscript,
7755        Kind::Subscript => InlineKind::Subscript,
7756        Kind::Insert => InlineKind::Insert,
7757        Kind::Delete => InlineKind::Delete,
7758        _ => return None,
7759    })
7760}
7761
7762/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
7763/// a highlight's opening `==`.
7764///
7765/// Two enums for one closed vocabulary, and the duplication is the boundary
7766/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
7767/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
7768/// the editor writes. Spelled as a match rather than routed through the two
7769/// crates' name strings so that a colour added on either side is a compile
7770/// error here, where the pairing is decided, rather than a runtime `None` that
7771/// would read as "clear the colour".
7772fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
7773    match color {
7774        MarkColor::Red => twig::MarkColor::Red,
7775        MarkColor::Orange => twig::MarkColor::Orange,
7776        MarkColor::Yellow => twig::MarkColor::Yellow,
7777        MarkColor::Green => twig::MarkColor::Green,
7778        MarkColor::Blue => twig::MarkColor::Blue,
7779        MarkColor::Purple => twig::MarkColor::Purple,
7780        MarkColor::Brown => twig::MarkColor::Brown,
7781    }
7782}
7783
7784/// Where an offset lands after a splice it didn't make — twig's own rule, from
7785/// [`Change`]: shift anything at or past the replaced range's end by the length
7786/// the replacement gained or lost, and leave anything before it alone.
7787///
7788/// An offset *inside* the replaced range has no text of its own to ride any
7789/// more, and lands at the end of what replaced it: for
7790/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
7791/// the prefix is cleared, which then sits where the highlighted text begins.
7792/// One node's attribute list, twig's own `(key, value)` pairs owned — what
7793/// every presentation gesture reads, edits one key of, and passes back whole.
7794type Attrs = Vec<(String, Option<String>)>;
7795
7796/// The name of the leaf directive a page break is — [`Doc::insert_page_break`]
7797/// writes it and the walker draws it, and a frontend that paginates matches a
7798/// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) against it. One spelling,
7799/// stated once.
7800pub const PAGE_BREAK: &str = "page-break";
7801
7802/// `attrs` with `key` set to `value`, or removed when `value` is `None`, and
7803/// every other attribute kept in its place — the read-edit-write half of twig's
7804/// replace-not-merge contract for a `data-` key.
7805///
7806/// **A key that is already there is rewritten where it stands**, and only a key
7807/// the node did not have goes on the end. That is what makes the proposal's
7808/// worked example true: `class="lead center" id="intro"
7809/// data-line-height="1.5"`, right-aligned, is `class="lead right" id="intro"
7810/// data-line-height="1.5"` — the same document with one token changed, and a
7811/// one-line diff. Removing the key and pushing it back would reorder the
7812/// author's attributes on every press, so a document that passed through the
7813/// editor came out shuffled even where nothing about it had changed.
7814///
7815/// A duplicate key — which no format leaf opens can spell, but twig reports
7816/// verbatim — collapses onto the first of its copies, since twig is handed one
7817/// value for one key either way.
7818fn with_attr(attrs: &[(String, Option<String>)], key: &str, value: Option<&str>) -> Attrs {
7819    let mut out: Attrs = Vec::with_capacity(attrs.len() + 1);
7820    let mut written = false;
7821    for (k, v) in attrs {
7822        if k != key {
7823            out.push((k.clone(), v.clone()));
7824            continue;
7825        }
7826        if let Some(new) = value.filter(|_| !written) {
7827            out.push((k.clone(), Some(new.to_string())));
7828            written = true;
7829        }
7830    }
7831    if let Some(new) = value.filter(|_| !written) {
7832        out.push((key.to_string(), Some(new.to_string())));
7833    }
7834    out
7835}
7836
7837/// [`with_attr`] for a `class` token: every token `mine` claims is removed, and
7838/// `token` added, with the rest of the list kept in order.
7839///
7840/// `class` is a space-separated token list, and leaf owns three of the tokens in
7841/// it. A paragraph that arrives as `class="lead center"` and is right-aligned
7842/// goes out as `class="lead right"`; one whose last owned token goes and which
7843/// carried nothing else loses the key, so a block that has lost its whole
7844/// vocabulary is spelled bare again. `class` itself keeps its place among the
7845/// attributes, because [`with_attr`] does the writing.
7846fn with_class_token(
7847    attrs: &[(String, Option<String>)],
7848    mine: impl Fn(&str) -> bool,
7849    token: Option<&str>,
7850) -> Attrs {
7851    let kept: Vec<&str> = attrs
7852        .iter()
7853        .find(|(k, _)| k == "class")
7854        .and_then(|(_, v)| v.as_deref())
7855        .unwrap_or_default()
7856        .split_whitespace()
7857        .filter(|t| !mine(t))
7858        .collect();
7859    let class = kept.into_iter().chain(token).collect::<Vec<_>>().join(" ");
7860    with_attr(
7861        attrs,
7862        "class",
7863        (!class.is_empty()).then_some(class.as_str()),
7864    )
7865}
7866
7867/// An owned attribute list as the borrowed pairs twig's two attribute ops take.
7868///
7869/// A **bare** attribute — one twig reports with no value, such as HTML's `<p
7870/// hidden>` — is passed back as an empty one. Twig refuses a `None` outright
7871/// (djot has no bare attribute, so no format reads one back everywhere), and
7872/// `hidden=""` is the same document where `hidden` is; dropping it instead
7873/// would lose what the author wrote, which is the one thing these gestures
7874/// promise not to do.
7875fn attr_pairs(attrs: &[(String, Option<String>)]) -> Vec<(&str, Option<&str>)> {
7876    attrs
7877        .iter()
7878        .map(|(k, v)| (k.as_str(), Some(v.as_deref().unwrap_or_default())))
7879        .collect()
7880}
7881
7882fn reanchor(off: usize, change: &Change) -> usize {
7883    if off < change.old.start {
7884        return off;
7885    }
7886    if off < change.old.end {
7887        return change.new.end;
7888    }
7889    (off + change.new.end).saturating_sub(change.old.end)
7890}
7891
7892/// [`reanchor`] for an edit that respells the markup *around* a block and
7893/// leaves the block's own bytes alone — which is every attribute gesture.
7894///
7895/// `block` is that block's content span before and after the splice, so an
7896/// offset standing in the text keeps its distance from the text's start and how
7897/// many bytes twig wrote above it never enters the arithmetic. That is the whole
7898/// rule, and it is why nothing here knows how long a `<div …>` is: a second key
7899/// on the same div lengthens the attribute line, clearing the last one takes the
7900/// div away entirely, and both are the same sum. `None` where the splice named
7901/// no block at either end, which is every djot case — the `{…}` line is written
7902/// above the block, and the block itself only shifts past it.
7903///
7904/// Anywhere else it is `reanchor`'s own answer: untouched before the splice,
7905/// shifted by its delta after it, and at the splice's end for an offset that
7906/// stood in markup being rewritten — a caret inside djot's `{…}` line has no
7907/// text to keep.
7908fn reanchor_in_block(
7909    off: usize,
7910    change: &Change,
7911    block: Option<(&Range<usize>, &Range<usize>)>,
7912) -> usize {
7913    if let Some((was, now)) = block
7914        && was.start <= off
7915        && off <= was.end
7916    {
7917        return now.start + (off - was.start).min(now.end - now.start);
7918    }
7919    reanchor(off, change)
7920}
7921
7922/// A watermark for a file's contents (see `Doc::disk_hash`).
7923///
7924/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
7925/// watermark is compared only against one taken by the same process moments
7926/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
7927/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
7928fn hash_bytes(bytes: &[u8]) -> u64 {
7929    use std::hash::{Hash, Hasher};
7930    let mut h = std::collections::hash_map::DefaultHasher::new();
7931    bytes.hash(&mut h);
7932    h.finish()
7933}
7934
7935#[cfg(feature = "fs")]
7936fn detect_format(path: &Path) -> Result<Format> {
7937    let ext = path
7938        .extension()
7939        .and_then(|e| e.to_str())
7940        .unwrap_or("")
7941        .to_ascii_lowercase();
7942    Ok(match ext.as_str() {
7943        "dj" | "djot" => Format::Djot,
7944        "md" | "markdown" => Format::Markdown,
7945        "xml" => Format::Xml,
7946        "html" | "htm" => Format::Html,
7947        other => return Err(anyhow!("unknown document extension: .{other}")),
7948    })
7949}
7950
7951#[cfg(test)]
7952mod tests {
7953    use super::*;
7954    use crate::style::{FontFamily, LineSpacing, SizeStep};
7955
7956    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
7957    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
7958    /// without one is a view no user is ever in.
7959    fn doc_in(view: View, name: &str, body: &str) -> Doc {
7960        // The fixture name doubles as the temp file's, so two tests picking the
7961        // same one raced under the parallel runner and read each other's body —
7962        // a green suite proving the wrong thing. The counter makes that
7963        // unreachable rather than asking every future caller to notice.
7964        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7965        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7966        let mut p = std::env::temp_dir();
7967        p.push(format!("leaf_test_{name}_{seq}.md"));
7968        std::fs::write(&p, body).unwrap();
7969        let mut d = Doc::open(p).unwrap();
7970        d.view = view;
7971        if view == View::Wysiwyg {
7972            d.build_visual(80);
7973        }
7974        d
7975    }
7976
7977    // Source-view document for the source-behaviour tests. `Doc::open` now
7978    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
7979    // `wysiwyg_doc` builds the rich-text variant on top of this.
7980    fn doc_with(name: &str, body: &str) -> Doc {
7981        doc_in(View::Source, name, body)
7982    }
7983
7984    /// Every visual row's drawn text — what the reader actually sees, which is
7985    /// the only thing the reveal preference is supposed to change.
7986    fn drawn_rows(d: &Doc) -> Vec<String> {
7987        d.vmap
7988            .rows
7989            .iter()
7990            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7991            .collect()
7992    }
7993
7994    /// Put the caret at the first byte of `needle` and rebuild, so the row under
7995    /// it becomes the revealed line.
7996    fn caret_at(d: &mut Doc, needle: &str) {
7997        d.caret = d.source.find(needle).expect("needle in source");
7998        d.build_visual(80);
7999    }
8000
8001    #[test]
8002    fn blockquote_after_a_list_is_not_bulleted() {
8003        // twig nests a following top-level block quote under the `bullet_list`
8004        // (a direct child, not a `list_item`). The map must render it de-nested —
8005        // `│ quote`, never `• │ quote` — with a blank separator, like any block
8006        // that follows a list. Regression for the "combined list + blockquote" bug.
8007        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
8008        d.build_visual(80);
8009        let rows: Vec<String> = d
8010            .vmap
8011            .rows
8012            .iter()
8013            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
8014            .collect();
8015        assert!(
8016            rows.iter().any(|r| r == "│ quote"),
8017            "block quote should render on its own gutter, got rows: {rows:?}"
8018        );
8019        assert!(
8020            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
8021            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
8022        );
8023    }
8024
8025    // ── the map is built at most once per (revision, wrap) ───────────────────
8026    //
8027    // A frontend repaints for reasons that have nothing to do with the text — a
8028    // blinking caret, a scroll — and rebuilding the map is O(document). These
8029    // pin *that the cache fires*, which a passing suite can't tell you: a cache
8030    // that never hits is invisible to every other test in this file.
8031    //
8032    // The probe is to wreck the built map and ask for it again. A rebuild
8033    // repairs it; a cache hit hands the wreckage straight back. Nothing else
8034    // can distinguish the two from outside.
8035
8036    #[test]
8037    fn a_rebuild_with_nothing_changed_reuses_the_map() {
8038        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
8039        d.build_visual(80);
8040        assert!(!d.vmap.rows.is_empty());
8041        d.vmap.rows.clear(); // wreck it
8042        d.build_visual(80);
8043        assert!(
8044            d.vmap.rows.is_empty(),
8045            "the map was rebuilt though nothing changed — the cache never fired"
8046        );
8047    }
8048
8049    #[test]
8050    fn an_edit_rebuilds_the_map() {
8051        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
8052        d.build_visual(80);
8053        let before = d.revision();
8054        d.vmap.rows.clear();
8055        d.insert("x");
8056        d.build_visual(80);
8057        assert!(d.revision() > before, "an edit must move the revision");
8058        assert!(
8059            !d.vmap.rows.is_empty(),
8060            "an edited document must not paint from a stale map"
8061        );
8062    }
8063
8064    #[test]
8065    fn a_width_change_rebuilds_the_map() {
8066        // The map is a function of the wrap width too, so a resize is a miss
8067        // even though the text is untouched.
8068        let mut d = doc_in(
8069            View::Wysiwyg,
8070            "cache_width",
8071            "one two three four five six\n",
8072        );
8073        d.build_visual(80);
8074        d.vmap.rows.clear();
8075        d.build_visual(12);
8076        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
8077        // And the unwrapped map is its own key, not the same as any width.
8078        d.vmap.rows.clear();
8079        d.build_visual_unwrapped();
8080        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
8081    }
8082
8083    #[test]
8084    fn a_motion_does_not_rebuild_the_map() {
8085        // The whole point: moving the caret changes nothing the map is built
8086        // from. If a motion bumped the revision, every arrow key would cost a
8087        // full rebuild and the cache would be worthless.
8088        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
8089        d.build_visual(80);
8090        let rev = d.revision();
8091        d.move_right(false);
8092        d.move_right(true);
8093        d.move_down(false);
8094        assert_eq!(d.revision(), rev, "a motion must not move the revision");
8095        d.vmap.rows.clear();
8096        d.build_visual(80);
8097        assert!(
8098            d.vmap.rows.is_empty(),
8099            "a motion should not rebuild the map"
8100        );
8101    }
8102
8103    #[test]
8104    fn saving_does_not_rebuild_the_map() {
8105        // Saving changes `dirty`, not the text.
8106        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
8107        d.insert("x");
8108        d.build_visual(80);
8109        let rev = d.revision();
8110        d.save();
8111        assert_eq!(d.revision(), rev, "a save must not move the revision");
8112        assert!(!d.dirty, "the save should have cleaned the document");
8113    }
8114
8115    #[test]
8116    fn a_reload_rebuilds_the_map() {
8117        // Reload replaces the text without going through `refresh`, so it has to
8118        // move the revision itself — else the editor paints the old file.
8119        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
8120        d.build_visual(80);
8121        let rev = d.revision();
8122        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
8123        d.reload();
8124        assert!(d.revision() > rev, "a reload must move the revision");
8125        d.build_visual(80);
8126        let text: String = d
8127            .vmap
8128            .rows
8129            .iter()
8130            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
8131            .collect();
8132        assert!(
8133            text.contains("wholly new"),
8134            "the reloaded text should be on screen, got {text:?}"
8135        );
8136    }
8137
8138    // ── golden-case harness ──────────────────────────────────────────────────
8139    // The pattern the whole parity suite can reuse: write a fixture with the
8140    // caret marked by `|`, run one action, and compare the rendered result —
8141    // also caret-marked — against the expected string. One readable line per
8142    // behavior, and it exercises the exact `Doc` ops both frontends call.
8143
8144    /// Split a `|`-marked fixture into `(source, caret_offset)`.
8145    fn parse_caret(marked: &str) -> (String, usize) {
8146        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
8147        (marked.replacen('|', "", 1), caret)
8148    }
8149
8150    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
8151    /// selection) so a result reads like the fixtures.
8152    fn render_caret(d: &Doc) -> String {
8153        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
8154        // so the caret always renders inside its own selection.
8155        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
8156        if let Some((s, e)) = d.selection() {
8157            marks.push((s, 0, '['));
8158            marks.push((e, 2, ']'));
8159        }
8160        // Insert right-to-left: descending offset, then descending rank.
8161        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
8162        let mut out = d.source.clone();
8163        for (at, _, ch) in marks {
8164            out.insert(at, ch);
8165        }
8166        out
8167    }
8168
8169    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
8170    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
8171        golden_in(View::Source, name, marked, action)
8172    }
8173
8174    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
8175    /// the same fixture has to read the same way in both.
8176    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
8177        let (src, caret) = parse_caret(marked);
8178        let mut d = doc_in(view, name, &src);
8179        d.caret = caret;
8180        action(&mut d);
8181        render_caret(&d)
8182    }
8183
8184    #[test]
8185    fn word_motion_walks_word_by_word() {
8186        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
8187        assert_eq!(
8188            g("hello wor|ld", |d| d.move_word_left(false)),
8189            "hello |world"
8190        );
8191        assert_eq!(
8192            g("hello| world", |d| d.move_word_left(false)),
8193            "|hello world"
8194        );
8195        assert_eq!(
8196            g("hel|lo world", |d| d.move_word_right(false)),
8197            "hello| world"
8198        );
8199        assert_eq!(
8200            g("hello| world", |d| d.move_word_right(false)),
8201            "hello world|"
8202        );
8203        // Punctuation is its own class, so motion stops at the boundary.
8204        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
8205    }
8206
8207    #[test]
8208    fn word_motion_extends_the_selection_when_asked() {
8209        assert_eq!(
8210            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
8211            "hello [world|]"
8212        );
8213    }
8214
8215    #[test]
8216    fn delete_word_removes_a_whole_word() {
8217        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
8218        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
8219        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
8220        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
8221    }
8222
8223    // ── Home / End ───────────────────────────────────────────────────────────
8224
8225    #[test]
8226    fn home_toggles_between_the_line_s_text_and_its_margin() {
8227        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
8228        // indent to the markup it spells everywhere it means one, so the fixture
8229        // with whitespace left to walk is a code block, which is verbatim.
8230        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
8231        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
8232        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
8233        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
8234        // A line with no indentation has one place to go, so the toggle is a
8235        // no-op rather than a trip to nowhere.
8236        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
8237        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
8238
8239        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
8240        let indent = d.source.find("    indented").unwrap();
8241        d.caret = indent + 6; // inside "indented"
8242        d.move_home(false);
8243        assert_eq!(
8244            d.caret,
8245            indent + 4,
8246            "wysiwyg: Home aims at the code line's text"
8247        );
8248        d.move_home(false);
8249        assert_eq!(
8250            d.caret, indent,
8251            "wysiwyg: the second press takes the indent"
8252        );
8253        d.move_home(false);
8254        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
8255    }
8256
8257    #[test]
8258    fn end_takes_the_line_the_view_is_showing() {
8259        // The line differs by view for the same document, and that is the point:
8260        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
8261        // as a space on one row and the source view as two lines.
8262        let mut d = doc_with("end_src", "one two\nthree\n");
8263        d.caret = 1;
8264        d.move_end(false);
8265        assert_eq!(d.caret, 7, "source: the end of the source line");
8266
8267        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
8268        d.caret = 1;
8269        d.move_end(false);
8270        assert_eq!(
8271            d.caret, 13,
8272            "wysiwyg: the end of the row, soft break and all"
8273        );
8274    }
8275
8276    #[test]
8277    fn home_and_end_extend_the_selection_when_asked() {
8278        for (view, tag) in VIEWS {
8279            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
8280            d.caret = 6;
8281            d.move_end(true);
8282            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
8283            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
8284            d.caret = 6;
8285            d.move_home(true);
8286            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
8287        }
8288    }
8289
8290    // ── kill to the line's start / end ───────────────────────────────────────
8291
8292    #[test]
8293    fn kill_to_the_line_start_and_end_in_both_views() {
8294        for (view, tag) in VIEWS {
8295            // The gap that reads as a paragraph break in each view: the source
8296            // view's lines are the renderer's rows only where the source says so.
8297            let gap = if view == View::Source { "\n" } else { "\n\n" };
8298            let mut d = doc_in(
8299                view,
8300                &format!("kill_end_{tag}"),
8301                &format!("one two{gap}three\n"),
8302            );
8303            d.caret = 3;
8304            d.delete_to_line_end();
8305            assert_eq!(
8306                d.source,
8307                format!("one{gap}three\n"),
8308                "{tag}: ^K to the line's end"
8309            );
8310            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
8311
8312            let mut d = doc_in(
8313                view,
8314                &format!("kill_start_{tag}"),
8315                &format!("one two{gap}three\n"),
8316            );
8317            d.caret = 7; // the end of the first line
8318            d.delete_to_line_start();
8319            assert_eq!(
8320                d.source,
8321                format!("{gap}three\n"),
8322                "{tag}: ⌘⌫ to the line's start"
8323            );
8324            assert_eq!(d.caret, 0, "{tag}");
8325        }
8326    }
8327
8328    #[test]
8329    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
8330        // The decision: at the boundary both kills do nothing, rather than
8331        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
8332        // at a soft wrap as often as at a newline, where there is nothing
8333        // written to delete — and a source newline is only half of the blank
8334        // line between two paragraphs, so taking it leaves a soft break rather
8335        // than the join it looks like. Backspace and Delete are the keys for it.
8336        for (view, tag) in VIEWS {
8337            let gap = if view == View::Source { "\n" } else { "\n\n" };
8338            let src = format!("one{gap}three\n");
8339            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
8340            d.caret = 3; // the end of "one"
8341            d.delete_to_line_end();
8342            assert_eq!(
8343                d.source, src,
8344                "{tag}: ^K at the line's end joined it to the next"
8345            );
8346
8347            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
8348            d.caret = 3 + gap.len(); // the start of "three"
8349            d.delete_to_line_start();
8350            assert_eq!(
8351                d.source, src,
8352                "{tag}: ⌘⌫ at the line's start joined it to the last"
8353            );
8354        }
8355    }
8356
8357    #[test]
8358    fn a_kill_takes_the_selection_when_there_is_one() {
8359        // What every other delete here does with one, so these two as well.
8360        for (view, tag) in VIEWS {
8361            for (name, kill) in [
8362                (
8363                    "end",
8364                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
8365                ),
8366                ("start", |d: &mut Doc| d.delete_to_line_start()),
8367            ] {
8368                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
8369                d.anchor = Some(4);
8370                d.caret = 7; // "two"
8371                kill(&mut d);
8372                assert_eq!(
8373                    d.source, "one  three\n",
8374                    "{tag}: {name} ignored the selection"
8375                );
8376                assert_eq!(d.selection(), None, "{tag}: {name}");
8377            }
8378        }
8379    }
8380
8381    #[test]
8382    fn a_kill_takes_the_markup_it_empties_with_it() {
8383        // The same hazard a word-delete has: a WYSIWYG range covers what the
8384        // user can see, which for `**bold**` is the word and never the
8385        // delimiters, so a kill that stopped at the text would leave `a ****` —
8386        // markup wrapped around nothing.
8387        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
8388        d.caret = d.source.find("bold").unwrap();
8389        d.delete_to_line_end();
8390        assert_eq!(d.source, "a \n");
8391    }
8392
8393    #[test]
8394    fn a_kill_is_undone_in_one_step() {
8395        for (view, tag) in VIEWS {
8396            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
8397            d.caret = 3;
8398            d.delete_to_line_end();
8399            assert_eq!(d.source, "one\n", "{tag}");
8400            d.undo();
8401            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
8402        }
8403    }
8404
8405    #[test]
8406    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
8407        // Regression: triple-click used move_home/move_end over visual rows, so
8408        // it only worked on a paragraph's first row (a wrap-boundary offset maps
8409        // to the earlier row). select_block_at reads the AST, so every offset in
8410        // the paragraph selects the whole thing.
8411        let body = "one two three four five six seven eight\n";
8412        let mut d = doc_with("sel_block", body);
8413        d.view = View::Wysiwyg;
8414        d.build_visual(12); // force the paragraph to wrap into several rows
8415        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
8416        let para = (0, "one two three four five six seven eight".len());
8417        for off in [0usize, 8, 19, 28, 38] {
8418            d.caret = 0;
8419            d.anchor = None;
8420            d.select_block_at(off);
8421            assert_eq!(
8422                d.selection(),
8423                Some(para),
8424                "offset {off} should select the paragraph"
8425            );
8426        }
8427    }
8428
8429    #[test]
8430    fn select_block_uses_content_span_for_a_heading() {
8431        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
8432        d.select_block_at(4); // inside "Title"
8433        // content_span excludes the "# " marker.
8434        assert_eq!(d.selected_text(), Some("Title"));
8435        d.select_block_at(10); // inside "body"
8436        assert_eq!(d.selected_text(), Some("body"));
8437    }
8438
8439    #[test]
8440    fn select_all_spans_the_document() {
8441        let mut d = doc_with("sel_all", "abc\n\ndef\n");
8442        d.select_all();
8443        assert_eq!(d.selection(), Some((0, d.source.len())));
8444    }
8445
8446    #[test]
8447    fn select_word_at_picks_the_surrounding_word() {
8448        let mut d = doc_with("sel_word", "hello world\n");
8449        d.select_word_at(8); // inside "world"
8450        assert_eq!(d.selection(), Some((6, 11)));
8451        // Double-clicking at end-of-word still grabs the word to its left.
8452        d.select_word_at(5); // the space between the words
8453        assert_eq!(d.selection(), Some((5, 6)));
8454    }
8455
8456    #[test]
8457    fn word_helpers_respect_utf8_boundaries() {
8458        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
8459        assert_eq!(
8460            golden("utf8", "|café ok", |d| d.move_word_right(false)),
8461            "café| ok"
8462        );
8463        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
8464    }
8465
8466    #[test]
8467    fn typing_inserts_at_the_caret_and_advances_it() {
8468        let mut d = doc_with("type", "hello\n");
8469        d.insert("Hi ");
8470        assert_eq!(d.source, "Hi hello\n");
8471        assert_eq!(d.caret, 3);
8472        assert!(d.dirty);
8473    }
8474
8475    #[test]
8476    fn backspace_deletes_the_char_before_the_caret() {
8477        let mut d = doc_with("bs", "hello\n");
8478        d.caret = 3; // after "hel"
8479        d.backspace();
8480        assert_eq!(d.source, "helo\n");
8481        assert_eq!(d.caret, 2);
8482    }
8483
8484    #[test]
8485    fn typing_replaces_the_selection() {
8486        let mut d = doc_with("replace", "a word b\n");
8487        d.anchor = Some(2);
8488        d.caret = 6; // "word" selected
8489        d.insert("X");
8490        assert_eq!(d.source, "a X b\n");
8491        assert_eq!(d.caret, 3);
8492        assert_eq!(d.anchor, None);
8493    }
8494
8495    #[test]
8496    fn toggle_bold_wraps_then_unwraps_the_selection() {
8497        let mut d = doc_with("bold", "a word b\n");
8498        d.anchor = Some(2);
8499        d.caret = 6;
8500        d.toggle(InlineKind::Strong);
8501        assert_eq!(d.source, "a **word** b\n");
8502        // The toggled region stays selected, so a second toggle reverses it.
8503        d.toggle(InlineKind::Strong);
8504        assert_eq!(d.source, "a word b\n");
8505        d.toggle(InlineKind::Strong);
8506        assert_eq!(d.source, "a **word** b\n");
8507    }
8508
8509    #[test]
8510    fn toggle_code_wraps_then_unwraps_the_selection() {
8511        let mut d = doc_with("code_rt", "a word b\n");
8512        d.anchor = Some(2);
8513        d.caret = 6;
8514        d.toggle(InlineKind::Verbatim);
8515        assert_eq!(d.source, "a `word` b\n");
8516        d.toggle(InlineKind::Verbatim);
8517        assert_eq!(d.source, "a word b\n");
8518    }
8519
8520    #[test]
8521    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
8522        // ⌘b at a bare caret, then type: the text comes out bold with no
8523        // selection ever made — the word-processor "start bold here" gesture.
8524        let mut d = doc_with("sticky_wrap", "xy\n");
8525        d.caret = 1; // between x and y
8526        d.toggle(InlineKind::Strong);
8527        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
8528        d.insert("A");
8529        assert_eq!(d.source, "x**A**y\n");
8530    }
8531
8532    #[test]
8533    fn sticky_bold_lights_the_toolbar_before_any_typing() {
8534        // The button must light the instant ⌘b is pressed, or the mode is
8535        // invisible until the first character lands.
8536        let mut d = doc_with("sticky_light", "xy\n");
8537        d.caret = 1;
8538        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
8539        d.toggle(InlineKind::Strong);
8540        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8541    }
8542
8543    #[test]
8544    fn sticky_bold_toggled_off_types_normally_again() {
8545        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
8546        // in the flow of typing, the exact sequence the user described.
8547        let mut d = doc_with("sticky_off", "\n");
8548        d.caret = 0;
8549        d.toggle(InlineKind::Strong);
8550        d.insert("a");
8551        d.insert("b"); // continues inside the run, no re-arming
8552        assert_eq!(d.source, "**ab**\n");
8553        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
8554        d.insert("c");
8555        assert_eq!(d.source, "**ab**c\n");
8556    }
8557
8558    #[test]
8559    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
8560        // Once a mark is realised the caret sits inside the run, so plain typing
8561        // extends it rather than starting a second, adjacent bold span.
8562        let mut d = doc_with("sticky_cont", "\n");
8563        d.caret = 0;
8564        d.toggle(InlineKind::Emph);
8565        d.insert("h");
8566        d.insert("i");
8567        assert_eq!(d.source, "*hi*\n");
8568    }
8569
8570    #[test]
8571    fn moving_the_caret_disarms_a_sticky_mark() {
8572        // Arming a mark and then moving away must not style text elsewhere.
8573        let mut d = doc_with("sticky_disarm", "xy\n");
8574        d.caret = 0;
8575        d.toggle(InlineKind::Strong);
8576        d.move_right(false); // caret 0 → 1, disarms
8577        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
8578        d.insert("A");
8579        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
8580    }
8581
8582    #[test]
8583    fn stacked_sticky_marks_apply_together() {
8584        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
8585        let mut d = doc_with("sticky_stack", "\n");
8586        d.caret = 0;
8587        d.toggle(InlineKind::Strong);
8588        d.toggle(InlineKind::Emph);
8589        d.insert("x");
8590        // Land the caret on the styled character and confirm both marks are live.
8591        d.anchor = Some(d.source.find('x').unwrap());
8592        d.caret = d.anchor.unwrap() + 1;
8593        let marks = d.active_inline_marks();
8594        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
8595        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
8596    }
8597
8598    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
8599
8600    #[test]
8601    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
8602        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
8603        // The space inside the run made `**bold **`, which is *not* bold — four
8604        // literal asterisks — so the rich view drew them, correctly and
8605        // uselessly, until the next character happened to close the run again.
8606        let mut d = wysiwyg_doc("edge_typing", "a \n");
8607        d.caret = 2;
8608        d.toggle(InlineKind::Strong);
8609        for c in "bold".chars() {
8610            d.insert(&c.to_string());
8611        }
8612        assert_eq!(d.source, "a **bold**\n");
8613        d.insert(" ");
8614        assert_eq!(
8615            d.source, "a **bold** \n",
8616            "the space belongs outside the run"
8617        );
8618        assert!(
8619            d.active_inline_marks().contains(InlineKind::Strong),
8620            "bold is still what's being typed, so the button stays lit"
8621        );
8622        // What the writer is looking at while all this happens: their words.
8623        d.build_visual(80);
8624        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
8625        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
8626        for c in "hey".chars() {
8627            d.insert(&c.to_string());
8628        }
8629        assert_eq!(
8630            d.source, "a **bold hey**\n",
8631            "one bold phrase, not two runs"
8632        );
8633    }
8634
8635    #[test]
8636    fn typing_past_a_space_can_still_leave_the_bold_behind() {
8637        // The other half: the marks stay armed across the space, so ⌘b turns
8638        // them off again there and the next word is plain — the run isn't
8639        // rejoined by a caret that was told not to.
8640        let mut d = wysiwyg_doc("edge_shed", "\n");
8641        d.caret = 0;
8642        d.toggle(InlineKind::Strong);
8643        for c in "bold ".chars() {
8644            d.insert(&c.to_string());
8645        }
8646        assert_eq!(d.source, "**bold** \n");
8647        d.toggle(InlineKind::Strong);
8648        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
8649        d.insert("x");
8650        assert_eq!(d.source, "**bold** x\n");
8651    }
8652
8653    #[test]
8654    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
8655        // ⌘b and then a space before any word: the space is not marked (nothing
8656        // is), and the word after it is.
8657        let mut d = wysiwyg_doc("edge_space_first", "a\n");
8658        d.caret = 1;
8659        d.toggle(InlineKind::Strong);
8660        d.insert(" ");
8661        assert_eq!(d.source, "a \n");
8662        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8663        d.insert("b");
8664        assert_eq!(d.source, "a **b**\n");
8665    }
8666
8667    #[test]
8668    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
8669        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
8670        d.caret = 8; // the caret's home at the end of the run's text
8671        d.insert(" ");
8672        assert_eq!(
8673            d.source, "x **bold** \n",
8674            "the space lands past the delimiters"
8675        );
8676        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
8677
8678        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
8679        d.caret = 4; // in front of the "b"
8680        d.insert(" ");
8681        assert_eq!(d.source, "x  **bold** y\n");
8682        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
8683    }
8684
8685    #[test]
8686    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
8687        // Backspace over the last letter of a bold phrase.
8688        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
8689        d.caret = 10; // past the "h"
8690        d.backspace();
8691        assert_eq!(d.source, "a **bold** \n");
8692        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
8693        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8694        d.insert("x");
8695        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
8696    }
8697
8698    #[test]
8699    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
8700        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
8701        // mark, which is only text. The marks live on in the caret instead.
8702        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
8703        d.caret = 5;
8704        d.backspace();
8705        assert_eq!(d.source, "a  c\n");
8706        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8707        d.insert("x");
8708        assert_eq!(d.source, "a **x** c\n");
8709    }
8710
8711    #[test]
8712    fn typing_over_a_whole_bold_word_keeps_it_bold() {
8713        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
8714        d.anchor = Some(4);
8715        d.caret = 8; // the word, not its delimiters
8716        d.insert("x");
8717        assert_eq!(d.source, "a **x** c\n");
8718    }
8719
8720    #[test]
8721    fn a_code_span_keeps_the_space_it_is_given() {
8722        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
8723        // is still verbatim, so nothing is re-spelt. The repair asks the parser
8724        // rather than a table of kinds, and this is the answer it gets.
8725        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
8726        d.caret = 7;
8727        d.insert(" ");
8728        assert_eq!(d.source, "a `code ` c\n");
8729    }
8730
8731    #[test]
8732    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
8733        // A run's closing delimiter has a caret home on each side of it, one
8734        // column apart on screen — and a plain ← off the space after a bold word
8735        // lands on the outer one. The character drawn behind the caret there is
8736        // still the last letter of the phrase, so that is what Backspace takes;
8737        // the byte behind it is a `*` nobody can see.
8738        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
8739        d.caret = 9;
8740        d.move_left(false);
8741        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
8742        d.backspace();
8743        assert_eq!(
8744            d.source, "**bol** x\n",
8745            "a letter of the phrase, not its `*`"
8746        );
8747        assert_eq!(d.caret, 5);
8748
8749        // And the mirror in front of the opening delimiter, where Delete's
8750        // character is the first letter of the run.
8751        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
8752        d.caret = 1;
8753        d.delete_forward();
8754        assert_eq!(d.source, "x**old**\n");
8755        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
8756    }
8757
8758    #[test]
8759    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
8760        // The byte beside the caret at either edge of a bold word is a `*` the
8761        // rich view draws nothing for. Taking it is not the character delete the
8762        // key was pressed for — it unspells the run and puts a literal asterisk
8763        // on screen (`a *bold** c`). The visible character is the one that goes.
8764        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
8765        d.caret = 4; // in front of the "b"
8766        d.backspace();
8767        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
8768
8769        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
8770        d.caret = 8; // past the "d"
8771        d.delete_forward();
8772        assert_eq!(d.source, "a **bold**c\n");
8773        assert_eq!(d.caret, 8, "and the caret stays inside the run");
8774        d.insert("x");
8775        assert_eq!(d.source, "a **boldx**c\n");
8776
8777        // A code span's backticks are hidden the same way, so they are covered
8778        // by the same rule and not by a list of kinds.
8779        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
8780        d.caret = 3;
8781        d.backspace();
8782        assert_eq!(d.source, "a`code` c\n");
8783    }
8784
8785    #[test]
8786    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
8787        // The asterisks are on the screen there and the caret can stand between
8788        // them, so a delete takes exactly the byte it is aimed at.
8789        let mut d = doc_with("edge_open_src", "a **bold** c\n");
8790        d.caret = 4;
8791        d.backspace();
8792        assert_eq!(d.source, "a *bold** c\n");
8793
8794        let mut d = doc_with("edge_close_src", "a **bold** c\n");
8795        d.caret = 8;
8796        d.delete_forward();
8797        assert_eq!(d.source, "a **bold* c\n");
8798    }
8799
8800    #[test]
8801    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
8802        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
8803        // The space had stepped outside the run (the mark-edge rule), taking the
8804        // caret with it, so the delete put it back down on the far side of the
8805        // closing `**` — one place on screen, and the wrong side of it. Typing
8806        // came out plain and the toolbar went dark, with nothing to see.
8807        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
8808        d.caret = 0;
8809        d.toggle(InlineKind::Strong);
8810        for c in "bold".chars() {
8811            d.insert(&c.to_string());
8812        }
8813        d.insert(" ");
8814        assert_eq!(d.source, "**bold** \n");
8815        d.backspace();
8816        assert_eq!(
8817            d.source, "**bold**\n",
8818            "the space goes, the delimiters stay"
8819        );
8820        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
8821        assert!(
8822            d.active_inline_marks().contains(InlineKind::Strong),
8823            "so the button is still lit"
8824        );
8825        d.insert("x");
8826        assert_eq!(
8827            d.source, "**boldx**\n",
8828            "and the next character is still bold"
8829        );
8830    }
8831
8832    #[test]
8833    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
8834        // What the stranded caret did next: the byte behind it was the closing
8835        // `*`, so a second press took that instead of a letter — `**bold*`, the
8836        // styling gone and an asterisk on the screen where the word had been.
8837        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
8838        d.caret = 0;
8839        d.toggle(InlineKind::Strong);
8840        for c in "bold ".chars() {
8841            d.insert(&c.to_string());
8842        }
8843        assert_eq!(d.source, "**bold** \n");
8844        d.backspace();
8845        d.backspace();
8846        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
8847        assert_eq!(d.caret, 5);
8848    }
8849
8850    #[test]
8851    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
8852        // `***both***` closes two runs with one stack of asterisks: the caret has
8853        // to walk in through all of them, or it lands between the emph and the
8854        // strong and types half-marked.
8855        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
8856        d.caret = 11;
8857        d.backspace();
8858        assert_eq!(d.source, "***both***\n");
8859        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
8860        d.insert("x");
8861        assert_eq!(d.source, "***bothx***\n");
8862    }
8863
8864    #[test]
8865    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
8866        // The settle only moves a caret a run actually closed over. Ordinary
8867        // deletes — inside a run, or in plain prose — are untouched.
8868        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
8869        d.caret = 8;
8870        d.backspace();
8871        assert_eq!(d.source, "a **bol** c\n");
8872        assert_eq!(d.caret, 7);
8873
8874        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
8875        d.caret = 5;
8876        d.backspace();
8877        assert_eq!(d.source, "plai\n");
8878        assert_eq!(d.caret, 4);
8879    }
8880
8881    #[test]
8882    fn the_source_view_leaves_a_delete_where_it_landed() {
8883        // The delimiters are on the screen there, so the offset past them is a
8884        // place the caret can be seen to be — nothing to settle.
8885        let mut d = doc_with("edge_bksp_src", "**bold** \n");
8886        d.caret = 9;
8887        d.backspace();
8888        assert_eq!(d.source, "**bold**\n");
8889        assert_eq!(d.caret, 8);
8890    }
8891
8892    #[test]
8893    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
8894        // `***both***` closes two runs with one stack of asterisks; a space that
8895        // clears only the inner one lands against the outer's and breaks that
8896        // instead.
8897        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
8898        d.caret = 9;
8899        d.insert(" ");
8900        assert_eq!(d.source, "a ***both*** \n");
8901        assert_eq!(d.caret, 13);
8902        d.insert("x");
8903        assert_eq!(d.source, "a ***both x***\n");
8904    }
8905
8906    #[test]
8907    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
8908        // The delimiter shuffle is not an edit the writer made, so it is not a
8909        // step they have to undo past.
8910        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
8911        d.caret = 8;
8912        d.insert(" ");
8913        assert_eq!(d.source, "a **bold** \n");
8914        d.undo();
8915        assert_eq!(d.source, "a **bold**\n");
8916    }
8917
8918    #[test]
8919    fn the_source_view_types_the_space_where_it_was_asked_to() {
8920        // The rule is a rich-view courtesy. In the source view the delimiters are
8921        // on the screen and the user is editing the bytes they can see.
8922        let mut d = doc_with("edge_src", "a **bold** c\n");
8923        d.caret = 8;
8924        d.insert(" ");
8925        assert_eq!(d.source, "a **bold ** c\n");
8926    }
8927
8928    #[test]
8929    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
8930        // Double-clicking a word takes the space after it; bolding that must not
8931        // spell `**word **`, which is not bold at all.
8932        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
8933        d.anchor = Some(2);
8934        d.caret = 7; // "word "
8935        d.toggle(InlineKind::Strong);
8936        assert_eq!(d.source, "a **word** b\n");
8937        d.toggle(InlineKind::Strong);
8938        assert_eq!(d.source, "a word b\n");
8939        d.toggle(InlineKind::Strong);
8940        assert_eq!(
8941            d.source, "a **word** b\n",
8942            "reapplying the mark must not wrap stale delimiter offsets"
8943        );
8944        // And a selection of nothing but whitespace has no word to mark.
8945        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
8946        d.anchor = Some(6);
8947        d.caret = 7;
8948        d.toggle(InlineKind::Strong);
8949        assert_eq!(d.source, "a word b\n");
8950        assert!(d.status.is_some());
8951    }
8952
8953    #[test]
8954    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
8955        let mut d = doc_with("head_set", "hello\n");
8956        d.caret = 2; // caret inside the paragraph, no selection
8957        d.set_block(BlockKind::Heading(1));
8958        assert_eq!(d.source, "# hello\n");
8959    }
8960
8961    #[test]
8962    fn set_block_heading_works_in_wysiwyg_view() {
8963        // The app defaults to WYSIWYG; the caret is a source offset either way.
8964        let mut d = wysiwyg_doc("head_wys", "hello\n");
8965        d.caret = 2;
8966        d.set_block(BlockKind::Heading(1));
8967        assert_eq!(d.source, "# hello\n");
8968    }
8969
8970    #[test]
8971    fn toggle_heading_applies_switches_and_reverts() {
8972        let mut d = doc_with("head_toggle", "hello\n");
8973        d.caret = 2;
8974        d.toggle_heading(1);
8975        assert_eq!(d.source, "# hello\n"); // paragraph → H1
8976        d.toggle_heading(2);
8977        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
8978        d.toggle_heading(2);
8979        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
8980    }
8981
8982    #[test]
8983    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
8984        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
8985        // the blank line but the caret rendered on the *next* line, because the
8986        // separator was a non-navigable decoration row. In Preserve flow that
8987        // blank line is a real caret home — the caret must resolve onto it, and
8988        // typing there makes the soft break that continues the paragraph.
8989        let src = "line one:\nsecond line\n";
8990        let mut d = wysiwyg_doc("pre_enter_lineend", src);
8991        d.set_line_flow(LineFlow::Preserve);
8992        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
8993        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
8994        d.newline();
8995        d.build_visual_unwrapped();
8996        assert_eq!(d.source, "line one:\n\nsecond line\n");
8997        assert_eq!(
8998            d.caret, 10,
8999            "caret sits on the new blank line, not the next line"
9000        );
9001        // The blank line is row 1, and the caret resolves onto it — not row 2.
9002        assert_eq!(
9003            d.vmap.pos_of_offset(10),
9004            (1, 0),
9005            "caret renders on the blank row"
9006        );
9007        assert!(
9008            !d.vmap.rows[1].decoration,
9009            "the blank line is navigable in Preserve"
9010        );
9011        // Typing there makes a soft break: one paragraph, three lines.
9012        d.insert("new clause,");
9013        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
9014    }
9015
9016    #[test]
9017    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
9018        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
9019        // that keeps it one paragraph — where Fold would open a second paragraph.
9020        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
9021        d.set_line_flow(LineFlow::Preserve);
9022        d.caret = 3;
9023        d.newline();
9024        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
9025
9026        // End-of-paragraph: Enter then typing continues the same paragraph on a
9027        // new line (a soft break), not a fresh paragraph.
9028        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
9029        d.set_line_flow(LineFlow::Preserve);
9030        d.caret = 3;
9031        d.newline();
9032        d.insert("def");
9033        assert_eq!(
9034            d.source, "abc\ndef\n",
9035            "end-of-line Enter + typing is a soft break"
9036        );
9037    }
9038
9039    #[test]
9040    fn preserve_double_enter_still_makes_a_paragraph() {
9041        // Two Enters in a row promote to a real paragraph break: the second lands
9042        // on the blank line the first opened and takes the empty-line branch.
9043        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
9044        d.set_line_flow(LineFlow::Preserve);
9045        d.caret = 3;
9046        d.newline();
9047        d.newline();
9048        d.insert("def");
9049        assert_eq!(
9050            d.source, "abc\n\ndef\n",
9051            "double Enter is a paragraph break"
9052        );
9053    }
9054
9055    #[test]
9056    fn preserve_backspace_joins_across_a_soft_break() {
9057        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
9058        // soft break it deletes the single newline and joins the two lines.
9059        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
9060        d.set_line_flow(LineFlow::Preserve);
9061        d.build_visual(80);
9062        d.caret = 4; // start of "def", just past the soft break
9063        d.backspace();
9064        assert_eq!(
9065            d.source, "abcdef\n",
9066            "Backspace joins across the soft break"
9067        );
9068        assert_eq!(d.caret, 3, "caret lands where the lines meet");
9069    }
9070
9071    #[test]
9072    fn fold_enter_still_starts_a_new_paragraph() {
9073        // The default flow is unchanged: a lone `\n` would render as an invisible
9074        // space, so Enter keeps opening the paragraph break that actually shows.
9075        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
9076        d.caret = 3;
9077        d.newline();
9078        assert_eq!(
9079            d.source, "abc\n\ndef\n",
9080            "Fold mid-line Enter is a paragraph break"
9081        );
9082    }
9083
9084    #[test]
9085    fn wysiwyg_one_enter_starts_a_new_paragraph() {
9086        // Regression: one Enter left the caret between the two newlines, so typing
9087        // made a soft break (one paragraph) and you needed a second Enter.
9088        let mut d = wysiwyg_doc("wys_enter", "abc\n");
9089        d.caret = 3;
9090        d.newline();
9091        d.insert("def");
9092        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
9093    }
9094
9095    #[test]
9096    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
9097        // Regression: Enter at the caret's natural End-of-line resting place
9098        // after a bold run with nothing following it (on screen: right after
9099        // "bold", before the hidden closing "**") spliced the paragraph break
9100        // at that very byte offset — which sits *before* the closing "**" in
9101        // the source, since the delimiter is hidden and emits no glyph of its
9102        // own for `push_row`'s "end of row" fallback to count. That severed the
9103        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
9104        // "**" alone on the new line instead of leaving "**bold**" intact with
9105        // a fresh empty paragraph after it.
9106        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
9107        d.move_end(false); // the WYSIWYG End key, from caret 0
9108        assert_eq!(
9109            d.caret, 6,
9110            "caret rests right after \"bold\", before the hidden \"**\""
9111        );
9112        d.newline();
9113        assert!(
9114            d.source.starts_with("**bold**"),
9115            "the closing ** must stay attached to \"bold\": got {:?}",
9116            d.source
9117        );
9118        assert_eq!(
9119            d.source, "**bold**\n\n\n",
9120            "a fresh empty paragraph follows the still-intact bold run"
9121        );
9122    }
9123
9124    #[test]
9125    fn source_view_enter_is_a_single_newline() {
9126        let mut d = doc_with("src_enter", "abc\n");
9127        d.caret = 3;
9128        d.newline();
9129        assert_eq!(d.source, "abc\n\n");
9130    }
9131
9132    #[test]
9133    fn heading_applies_at_the_end_of_a_paragraph() {
9134        // The caret at a line end sits at the doc level; set_block must still find
9135        // the block on that line.
9136        let mut d = doc_with("head_end", "abc\n");
9137        d.caret = 3; // end of "abc"
9138        d.toggle_heading(1);
9139        assert_eq!(d.source, "# abc\n");
9140    }
9141
9142    #[test]
9143    fn heading_on_an_empty_new_paragraph_creates_one() {
9144        let mut d = wysiwyg_doc("head_empty", "abc\n");
9145        d.caret = 3;
9146        d.newline(); // caret now on a fresh, empty paragraph
9147        d.toggle_heading(1);
9148        d.insert("Title");
9149        assert!(d.source.contains("# Title"), "got {:?}", d.source);
9150    }
9151
9152    #[test]
9153    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
9154        // The reported bug, end to end: click a blank line with another one under
9155        // it, press H1, type. The text landed in the heading and the caret's
9156        // offset was right (the source view drew it there), but the rich view
9157        // drew it two rows lower, on the trailing blank line — the empty `# `
9158        // heading had left every row below it short by the marker's two bytes,
9159        // and the blank line ended up claiming the heading's own end offset.
9160        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
9161        d.build_visual_unwrapped();
9162        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
9163        d.toggle_heading(1);
9164        for c in "title".chars() {
9165            d.insert(&c.to_string());
9166            d.build_visual_unwrapped(); // as a frontend does, one frame per key
9167        }
9168        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
9169        assert_eq!(
9170            d.caret_pos(),
9171            (4, 5),
9172            "the caret draws at the end of the heading"
9173        );
9174    }
9175
9176    #[test]
9177    fn clicking_an_empty_heading_types_after_its_marker() {
9178        // The same anchor from the other side: the empty heading's row is its own
9179        // caret home, so a click on it must land past the hidden `# `. Landing in
9180        // front of the hashes made the first keystroke un-heading the line.
9181        let mut d = wysiwyg_doc("head_click", "# \n");
9182        d.build_visual_unwrapped();
9183        d.caret = d.vmap.offset_of_pos(0, 0);
9184        d.insert("x");
9185        assert_eq!(d.source, "# x\n");
9186    }
9187
9188    #[test]
9189    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
9190        let mut d = wysiwyg_doc("head_enter", "# Title\n");
9191        d.caret = 7; // end of the heading
9192        d.newline();
9193        d.insert("body");
9194        assert_eq!(d.source, "# Title\n\nbody\n");
9195    }
9196
9197    #[test]
9198    fn wysiwyg_enter_continues_a_bullet_list() {
9199        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
9200        d.caret = 6; // end of "item"
9201        d.newline();
9202        d.insert("two");
9203        assert_eq!(d.source, "- item\n- two\n");
9204    }
9205
9206    #[test]
9207    fn wysiwyg_enter_increments_an_ordered_list() {
9208        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
9209        d.caret = 6; // end of "one"
9210        d.newline();
9211        d.insert("two");
9212        assert_eq!(d.source, "1. one\n2. two\n");
9213    }
9214
9215    #[test]
9216    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
9217        // Regression for the "extra newline" left between a list and the paragraph
9218        // below it. Enter, Enter leaves the list on a fresh empty paragraph
9219        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
9220        // Backspace should then take the caret cleanly back to the end of the list
9221        // item, `- item\n\nnext`, not delete a single newline and strand it on the
9222        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
9223        // no caret can land on. The map is rebuilt between keystrokes exactly as a
9224        // frontend does, since Backspace reads the stop table to place the delete.
9225        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
9226        d.caret = 6; // end of "item"
9227        d.newline();
9228        d.build_visual(80);
9229        d.newline(); // leave the list onto a fresh empty paragraph
9230        d.build_visual(80);
9231        assert_eq!(
9232            d.source, "- item\n\n\n\nnext\n",
9233            "double-Enter opens the empty paragraph"
9234        );
9235        d.backspace();
9236        assert_eq!(
9237            d.source, "- item\n\nnext\n",
9238            "one Backspace collapses the whole gap"
9239        );
9240        assert_eq!(
9241            d.caret, 6,
9242            "and lands the caret back at the end of the list item"
9243        );
9244    }
9245
9246    #[test]
9247    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
9248        // The stop-wise delete must not over-reach when there is no block boundary
9249        // to cross: two blank lines in a row are one caret stop apart, so pressing
9250        // Enter on an empty line and then Backspace removes exactly the one newline
9251        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
9252        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
9253        d.caret = 5; // the empty paragraph the first Enter already opened
9254        d.build_visual(80);
9255        d.newline();
9256        d.build_visual(80);
9257        assert_eq!(
9258            d.source, "abc\n\n\n\n",
9259            "Enter on the blank line adds one newline"
9260        );
9261        d.backspace();
9262        assert_eq!(
9263            d.source, "abc\n\n\n",
9264            "Backspace takes back exactly that one newline"
9265        );
9266    }
9267
9268    #[test]
9269    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
9270        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
9271        d.caret = 6; // end of the empty "- " item
9272        d.newline();
9273        d.insert("p");
9274        assert_eq!(d.source, "- a\n\np\n");
9275    }
9276
9277    #[test]
9278    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
9279        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
9280        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
9281        // not take the list-exit path (which would splice the `- ` away as if
9282        // leaving an empty item); the AST guard sends it to a normal break and
9283        // leaves the underline intact.
9284        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
9285        assert!(
9286            d.nodes().iter().any(|n| n.kind == Kind::Heading),
9287            "precondition: twig parses this as a heading, not a list",
9288        );
9289        d.caret = 7; // on the `- ` underline line
9290        d.newline();
9291        assert!(
9292            d.source.contains("- "),
9293            "the setext underline survives, not spliced away as a list item: {:?}",
9294            d.source,
9295        );
9296    }
9297
9298    #[test]
9299    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
9300        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
9301        d.caret = 7; // end of "abc" inside the fence
9302        d.newline();
9303        d.insert("def");
9304        assert_eq!(d.source, "```\nabc\ndef\n```\n");
9305    }
9306
9307    #[test]
9308    fn wysiwyg_enter_continues_a_block_quote() {
9309        // Enter opens a new *paragraph* inside the quote, not a second line of
9310        // the same one. `> quote\n> more` is a soft break, which under
9311        // `LineFlow::Fold` renders as a space — the keystroke would look like it
9312        // did nothing. The quoted blank line is what makes the break visible, and
9313        // it's the same thing Enter does in running prose.
9314        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
9315        d.caret = 7; // end of "quote"
9316        d.newline();
9317        d.insert("more");
9318        assert_eq!(d.source, "> quote\n>\n> more\n");
9319        // Still one quote, now holding two paragraphs — not a quote and a stray
9320        // line that fell out of it.
9321        let quotes = d
9322            .nodes()
9323            .iter()
9324            .filter(|n| n.kind == Kind::BlockQuote)
9325            .count();
9326        assert_eq!(quotes, 1);
9327    }
9328
9329    #[test]
9330    fn set_block_makes_a_heading_at_the_caret() {
9331        let mut d = doc_with("head", "Title\n\nbody\n");
9332        d.caret = 0;
9333        d.set_block(BlockKind::Heading(2));
9334        assert_eq!(d.source, "## Title\n\nbody\n");
9335        d.set_block(BlockKind::Paragraph);
9336        assert_eq!(d.source, "Title\n\nbody\n");
9337    }
9338
9339    // ── block containers (quote / list) ──────────────────────────────────────
9340
9341    #[test]
9342    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
9343        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
9344        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
9345        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
9346        // A caret at a line end sits at the doc level; the block is still found.
9347        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
9348    }
9349
9350    #[test]
9351    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
9352        // Every source line of the paragraph gets its own `> `, so a caret left
9353        // on its old byte offset falls one prefix per line above it too far
9354        // back — inside the markup it just asked for rather than in its word.
9355        assert_eq!(
9356            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
9357            "> aaa\n> b|bb\n> ccc\n"
9358        );
9359    }
9360
9361    #[test]
9362    fn toggle_blockquote_works_in_wysiwyg_view() {
9363        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
9364        assert_eq!(
9365            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
9366            "> hel|lo\n"
9367        );
9368        assert_eq!(
9369            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
9370            "hel|lo\n"
9371        );
9372    }
9373
9374    #[test]
9375    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
9376        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
9377        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
9378        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
9379        // The *other* kind converts in place instead of nesting, which is what
9380        // makes the two buttons one three-state control.
9381        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
9382        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
9383        // Its own kind, over the only item the list holds, takes it off.
9384        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
9385    }
9386
9387    #[test]
9388    fn toggle_list_works_in_wysiwyg_view() {
9389        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
9390        assert_eq!(
9391            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
9392            "1. hel|lo\n"
9393        );
9394        assert_eq!(
9395            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
9396            "- hel|lo\n"
9397        );
9398        assert_eq!(
9399            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
9400            "hel|lo\n"
9401        );
9402    }
9403
9404    #[test]
9405    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
9406        // The selection has to grow with the markup: twig takes a container off
9407        // only a range covering every block it holds, so the second press can
9408        // reverse the first only if the result is what's selected.
9409        let mut d = doc_with("list_sel", "abc\n\ndef\n");
9410        d.select_all();
9411        d.toggle_list(true);
9412        assert_eq!(d.source, "1. abc\n\n2. def\n");
9413        assert_eq!(d.selection(), Some((0, d.source.len())));
9414        d.toggle_list(true);
9415        assert_eq!(d.source, "abc\n\ndef\n");
9416    }
9417
9418    #[test]
9419    fn toggle_blockquote_nests_a_partly_covered_quote() {
9420        // twig's rule: covering only some of a container's blocks nests, because
9421        // taking the quote off would drag its uncovered siblings out with it.
9422        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
9423        d.caret = 2; // in the first quoted paragraph only
9424        d.toggle_blockquote();
9425        assert_eq!(d.source, "> > a\n>\n> b\n");
9426    }
9427
9428    #[test]
9429    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
9430        // A blank line used to be no block for twig to wrap —
9431        // `toggle_block_container` answered `NotFound` — so Quote and the list
9432        // buttons did nothing on the very line the H1 button works on, and leaf
9433        // lent twig a scratch paragraph to wrap and took it back out again.
9434        // twig 3.2.0 opens an empty container there itself, so what is left here
9435        // is where the caret lands: inside the marker that was just written.
9436        let mut d = doc_with("quote_blank", "\nabc\n");
9437        d.caret = 0;
9438        d.toggle_blockquote();
9439        assert_eq!(d.source, "> \nabc\n");
9440        assert_eq!(
9441            d.caret, 2,
9442            "the caret belongs inside the quote it just opened"
9443        );
9444        assert!(d.status.is_none(), "{:?}", d.status);
9445        assert!(d.dirty);
9446
9447        // And the paragraph below is still its own block: an empty container one
9448        // soft break from `abc` would take that paragraph into the quote with it.
9449        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
9450        d.caret = 0;
9451        d.toggle_blockquote();
9452        d.build_visual(80);
9453        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
9454
9455        // The same from the other side: a blank line directly under a paragraph
9456        // earns the blank line an empty block needs, rather than being read as a
9457        // soft break inside that paragraph.
9458        let mut d = doc_with("list_blank_below", "abc\n");
9459        d.caret = 4;
9460        d.toggle_list(false);
9461        assert_eq!(d.source, "abc\n\n- ");
9462        assert_eq!(d.caret, 7);
9463    }
9464
9465    #[test]
9466    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
9467        // The gesture the rendering fix is for. `newline` inside a quote already
9468        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
9469        // spelling — but the two marker lines it adds belonged to no node until
9470        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
9471        // just made drew as plain prose under the quote.
9472        let mut d = wysiwyg_doc("quote_enter", "> a\n");
9473        d.caret = 3; // past `a`, at the end of the quoted line
9474        d.newline();
9475        assert_eq!(d.source, "> a\n>\n> \n");
9476        d.build_visual(80);
9477        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
9478        // And the caret is on the new line, not stranded on the old one.
9479        assert_eq!(d.caret, 8);
9480    }
9481
9482    #[test]
9483    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
9484        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
9485        // now it is twig's single edit. Either way one ⌘z has to put the blank
9486        // line back rather than undoing into a half-built document.
9487        for open in [
9488            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
9489            &|d: &mut Doc| d.toggle_list(false),
9490            &|d: &mut Doc| d.toggle_list(true),
9491        ] {
9492            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
9493            d.caret = 3;
9494            open(&mut d);
9495            assert_ne!(d.source, "a\n\n\n\nb\n");
9496            d.undo();
9497            assert_eq!(d.source, "a\n\n\n\nb\n");
9498        }
9499    }
9500
9501    #[test]
9502    fn a_container_toggle_is_one_undo_step() {
9503        let mut d = doc_with("quote_undo", "hello\n");
9504        d.caret = 3;
9505        d.insert("X"); // a typing run the structural edit must not fold into
9506        d.toggle_blockquote();
9507        assert_eq!(d.source, "> helXlo\n");
9508        d.undo();
9509        assert_eq!(d.source, "helXlo\n");
9510    }
9511
9512    // ── links ────────────────────────────────────────────────────────────────
9513
9514    #[test]
9515    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
9516        let mut d = doc_with("link_sel", "word here\n");
9517        d.anchor = Some(0);
9518        d.caret = 4;
9519        d.insert_link("http://x.dev");
9520        assert_eq!(d.source, "[word](http://x.dev) here\n");
9521        // The text, not the destination — so a second press re-points the link
9522        // the first one made rather than nesting one inside it.
9523        assert_eq!(d.selected_text(), Some("word"));
9524        d.insert_link("http://y.dev");
9525        assert_eq!(d.source, "[word](http://y.dev) here\n");
9526        assert_eq!(d.selected_text(), Some("word"));
9527    }
9528
9529    #[test]
9530    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
9531        let mut d = doc_with("img_caret", "before after\n");
9532        d.caret = 7; // between "before " and "after"
9533        d.insert_image("cat.png", "a cat");
9534        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
9535        // The caret sits just past the inserted image, nothing selected.
9536        assert_eq!(d.selection(), None);
9537        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
9538    }
9539
9540    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
9541    /// destination at the first space, so the `format!` this used to be wrote
9542    /// something that was not an image at all — and the reader saw the markup as
9543    /// text. twig owns the spelling now, and moves it into the angle form.
9544    #[test]
9545    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
9546        let mut d = doc_with("img_space", "x\n");
9547        d.caret = 0;
9548        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
9549        assert_eq!(
9550            d.source,
9551            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
9552        );
9553        // And it reads back as an image pointing at the unescaped path — the angle
9554        // brackets are spelling, not part of the destination.
9555        d.caret = 2;
9556        assert_eq!(
9557            d.image_destination_at_caret(),
9558            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
9559        );
9560    }
9561
9562    /// A `)` in a caption or a filename must not close the image early.
9563    #[test]
9564    fn insert_image_escapes_a_paren_in_either_half() {
9565        let mut d = doc_with("img_paren", "x\n");
9566        d.caret = 0;
9567        d.insert_image("a)b.png", "");
9568        assert_eq!(d.source, "![](a\\)b.png)x\n");
9569        d.caret = 2;
9570        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
9571    }
9572
9573    #[test]
9574    fn insert_image_uses_the_selection_as_alt_text() {
9575        let mut d = doc_with("img_sel", "caption here\n");
9576        d.anchor = Some(0);
9577        d.caret = 7; // "caption"
9578        d.insert_image("p.png", "ignored fallback");
9579        assert_eq!(d.source, "![caption](p.png) here\n");
9580    }
9581
9582    #[test]
9583    fn insert_image_with_no_alt_leaves_empty_brackets() {
9584        let mut d = doc_with("img_noalt", "\n");
9585        d.caret = 0;
9586        d.insert_image("logo.svg", "");
9587        assert_eq!(d.source, "![](logo.svg)\n");
9588    }
9589
9590    #[test]
9591    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
9592        // The round trip is the point: it's no use writing markup the reader
9593        // can't pick up again. This is the pair that only holds from twig 2.5.1
9594        // on — before it, the one-line form went in fine and came back as a
9595        // paragraph of raw tags, publishing no media at all.
9596        let mut d = doc_with("vid_rt", "\n");
9597        d.caret = 0;
9598        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
9599        assert_eq!(
9600            d.source,
9601            "<video src=\"clip.mp4\" controls>a clip</video>\n"
9602        );
9603
9604        d.build_visual(80);
9605        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
9606        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
9607        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
9608        assert_eq!(d.vmap.media[0].alt, "a clip");
9609    }
9610
9611    #[test]
9612    fn insert_media_spells_audio_with_its_own_tag() {
9613        let mut d = doc_with("aud_rt", "\n");
9614        d.caret = 0;
9615        d.insert_media(MediaKind::Audio, "take.mp3", "");
9616        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
9617        d.build_visual(80);
9618        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
9619    }
9620
9621    #[test]
9622    fn insert_media_uses_the_selection_as_fallback_text() {
9623        // The same courtesy `insert_image` does with alt: select a caption,
9624        // insert, and the caption labels the thing rather than being replaced.
9625        let mut d = doc_with("vid_sel", "the talk here\n");
9626        d.anchor = Some(0);
9627        d.caret = 8; // "the talk"
9628        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
9629        assert_eq!(
9630            d.source,
9631            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
9632        );
9633    }
9634
9635    #[test]
9636    fn insert_media_with_an_image_kind_is_just_insert_image() {
9637        let mut d = doc_with("img_via_media", "\n");
9638        d.caret = 0;
9639        d.insert_media(MediaKind::Image, "logo.svg", "x");
9640        assert_eq!(d.source, "![x](logo.svg)\n");
9641    }
9642
9643    // ── thematic breaks ─────────────────────────────────────────────────────
9644
9645    /// The node the source parses as at `caret` — what confirms an inserted
9646    /// `---` actually reads back as a rule, not stray text or a setext heading.
9647    ///
9648    /// The *narrowest* node covering the offset. Every ancestor covers it too,
9649    /// and since twig 2.8 that includes the `doc` root, which now carries a real
9650    /// span (it reported none before, so taking the first match used to land on
9651    /// the block by luck and now always answers `"doc"`).
9652    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
9653        d.nodes()
9654            .into_iter()
9655            .filter(|n| n.span.start <= caret && caret < n.span.end)
9656            .min_by_key(|n| n.span.end - n.span.start)
9657            .map(|n| n.kind)
9658    }
9659
9660    #[test]
9661    fn a_task_box_toggles_at_the_caret_and_reads_back() {
9662        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
9663        d.caret = 8; // inside "todo"
9664        assert_eq!(d.task_checked_at_caret(), Some(false));
9665        d.toggle_task_checked();
9666        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
9667        assert_eq!(d.task_checked_at_caret(), Some(true));
9668        d.toggle_task_checked();
9669        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
9670    }
9671
9672    #[test]
9673    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
9674        // The whole reason `toggle_task_at` exists apart from the caret form:
9675        // ticking a box elsewhere must not move the cursor out of what's being
9676        // typed.
9677        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
9678        d.caret = 8; // inside "first"
9679        let second = d.source.find("second").unwrap();
9680        d.toggle_task_at(second);
9681        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
9682        assert_eq!(d.caret, 8, "the caret stayed in the first item");
9683    }
9684
9685    #[test]
9686    fn a_plain_item_gains_and_loses_a_box() {
9687        let mut d = doc_with("task_mint", "- plain\n");
9688        d.caret = 4;
9689        assert_eq!(d.task_checked_at_caret(), None);
9690        d.toggle_task_item();
9691        assert_eq!(d.source, "- [ ] plain\n");
9692        assert_eq!(
9693            d.task_checked_at_caret(),
9694            Some(false),
9695            "a new box arrives unticked"
9696        );
9697        d.toggle_task_item();
9698        assert_eq!(d.source, "- plain\n");
9699    }
9700
9701    #[test]
9702    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
9703        // `set checked` must not silently convert a bullet into a task — that is
9704        // `toggle_task_item`'s job, and twig refuses it here.
9705        let mut d = doc_with("task_none", "- plain\n");
9706        d.caret = 4;
9707        d.toggle_task_checked();
9708        assert_eq!(d.source, "- plain\n", "nothing written");
9709        assert!(
9710            d.status.is_some(),
9711            "the refusal should reach the status line"
9712        );
9713    }
9714
9715    #[test]
9716    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
9717        let mut d = doc_with("task_quote", "> - [ ] nested\n");
9718        d.caret = d.source.find("nested").unwrap();
9719        assert_eq!(d.task_checked_at_caret(), Some(false));
9720        d.toggle_task_checked();
9721        assert_eq!(d.source, "> - [x] nested\n");
9722    }
9723
9724    #[test]
9725    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
9726        // A rule is a block, so twig's `insert_thematic_break` alone lands it
9727        // after the whole paragraph. `split_block` parts the paragraph first and
9728        // the rule is aimed at the *first* half, which is what a rule button is
9729        // understood to do — and what leaf spelled by hand until twig grew both
9730        // halves of the gesture.
9731        let mut d = doc_with("hr_mid", "before after\n");
9732        d.caret = 7; // between "before " and "after"
9733        d.insert_thematic_break();
9734        assert_eq!(d.source, "before \n\n---\n\nafter\n");
9735        assert_eq!(d.selection(), None);
9736        assert_eq!(
9737            kind_at(&mut d, "before \n\n".len()),
9738            Some(Kind::ThematicBreak)
9739        );
9740    }
9741
9742    #[test]
9743    fn insert_thematic_break_at_a_paragraph_s_end_splits_nothing() {
9744        // At the end there is nothing to part, and a split there writes the
9745        // separator anyway — a blank line and the empty slot the next paragraph
9746        // would fill — which the rule then landed above: `para\n\n* * *\n\n\n`,
9747        // two blank lines nothing fills. Now the rule lands after the paragraph,
9748        // where the split-and-aim was sending it regardless. Both formats, and
9749        // both shapes of a last line — terminated, and still being typed —
9750        // because the two reach the split through different doors: Markdown's
9751        // paragraph span stops before its newline, so `para\n` at 4 never split
9752        // there, but `para` at 4 did.
9753        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
9754            for src in ["para\n", "para"] {
9755                let mut d = Doc::from_source(src.into(), fmt).unwrap();
9756                d.caret = 4;
9757                d.insert_thematic_break();
9758                assert_eq!(d.source, format!("para\n\n{rule}\n"), "{fmt:?} {src:?}");
9759                assert_eq!(d.caret, d.source.len());
9760            }
9761            // Mid-document the slot sat between the rule and the next block.
9762            let mut d = Doc::from_source("para\n\nnext\n".into(), fmt).unwrap();
9763            d.caret = 4;
9764            d.insert_thematic_break();
9765            assert_eq!(d.source, format!("para\n\n{rule}\n\nnext\n"), "{fmt:?}");
9766            // Trailing whitespace is nothing to part either.
9767            let mut d = Doc::from_source("para  \n".into(), fmt).unwrap();
9768            d.caret = 4;
9769            d.insert_thematic_break();
9770            assert_eq!(d.source, format!("para  \n\n{rule}\n"), "{fmt:?}");
9771        }
9772    }
9773
9774    #[test]
9775    fn insert_thematic_break_at_a_paragraph_s_start_lands_before_it() {
9776        // The split at the start parts nothing, but it is kept on purpose:
9777        // `|para` becomes `\npara` with the caret on a blank line, and twig
9778        // (3.5.2) writes a rule aimed at a blank line ON that line — the only
9779        // way "before the paragraph" is reachable through a gesture that only
9780        // places after. Before 3.5.2 this came out as `\n\n---\n\npara`.
9781        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
9782            let mut d = Doc::from_source("para\n".into(), fmt).unwrap();
9783            d.caret = 0;
9784            d.insert_thematic_break();
9785            assert_eq!(d.source, format!("{rule}\n\npara\n"), "{fmt:?}");
9786            let mut d = Doc::from_source("prev\n\npara\n".into(), fmt).unwrap();
9787            d.caret = 6;
9788            d.insert_thematic_break();
9789            assert_eq!(d.source, format!("prev\n\n{rule}\n\npara\n"), "{fmt:?}");
9790        }
9791    }
9792
9793    #[test]
9794    fn insert_thematic_break_on_a_blank_line_takes_that_line() {
9795        // The gap between two blocks is where a click lands the caret; the
9796        // rule goes on the blank, one blank each side.
9797        let mut d = doc_with("hr_gap", "a\n\nb\n");
9798        d.caret = 2;
9799        d.insert_thematic_break();
9800        assert_eq!(d.source, "a\n\n---\n\nb\n");
9801    }
9802
9803    #[test]
9804    fn insert_table_at_a_paragraph_s_end_splits_nothing() {
9805        // The same door as the rule's, through the placement they share.
9806        let mut d = Doc::from_source("para\n".into(), Format::Djot).unwrap();
9807        d.caret = 4;
9808        d.insert_table(1, 1);
9809        assert_eq!(d.source, "para\n\n|  |\n|---|\n|  |\n");
9810        let mut d = doc_with("table_end_typed", "para");
9811        d.caret = 4;
9812        d.insert_table(1, 1);
9813        assert_eq!(d.source, "para\n\n|  |\n| --- |\n|  |\n");
9814        assert!(d.caret_in_table());
9815    }
9816
9817    #[test]
9818    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
9819        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
9820        // and leaf wrote the first into both until twig started spelling it.
9821        let mut md = doc_with("hr_md", "para\n");
9822        md.caret = 2;
9823        md.insert_thematic_break();
9824        assert_eq!(md.source, "pa\n\n---\n\nra\n");
9825
9826        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
9827        dj.caret = 2;
9828        dj.insert_thematic_break();
9829        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
9830    }
9831
9832    #[test]
9833    fn insert_table_parts_the_paragraph_and_lands_in_the_first_header_cell() {
9834        // The table goes *at* the caret the way the rule does: the paragraph is
9835        // parted first, and twig writes the grid after its first half. The
9836        // caret then sits in the first header cell — selected, as Tab would
9837        // leave it — so the next keystroke is the heading.
9838        let mut d = doc_with("table_mid", "before after\n");
9839        d.caret = 7;
9840        d.insert_table(2, 3);
9841        assert_eq!(
9842            d.source,
9843            "before \n\n|  |  |  |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |\n\nafter\n"
9844        );
9845        assert!(d.caret_in_table());
9846        let first_bar = d.source.find('|').unwrap();
9847        assert!(
9848            d.caret > first_bar && d.caret < d.source.find("| ---").unwrap(),
9849            "caret {} is not in the header row",
9850            d.caret
9851        );
9852        d.insert("Name");
9853        assert!(d.source.starts_with("before \n\n| Name |  |  |\n"));
9854        // And the grid the table was written into is one the table keys walk
9855        // (over the map a frontend rebuilds after every edit).
9856        d.build_visual(80);
9857        assert!(d.cell_tab(true));
9858        d.insert("Qty");
9859        assert!(d.source.starts_with("before \n\n| Name | Qty |  |\n"));
9860    }
9861
9862    #[test]
9863    fn insert_table_spells_the_grid_the_format_s_own_way() {
9864        // Djot's delimiter row is unpadded, and leaf never has to know that.
9865        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
9866        dj.caret = 2;
9867        dj.insert_table(1, 2);
9868        assert_eq!(dj.source, "pa\n\n|  |  |\n|---|---|\n|  |  |\n\nra\n");
9869        assert!(dj.caret_in_table());
9870    }
9871
9872    #[test]
9873    fn insert_table_refuses_where_the_format_spells_no_table() {
9874        let mut d = Doc::from_source("<p>ab</p>\n".into(), Format::Html).unwrap();
9875        d.caret = 4;
9876        d.insert_table(1, 1);
9877        assert_eq!(d.source, "<p>ab</p>\n");
9878        assert!(d.status.as_deref().unwrap_or("").contains("not supported"));
9879        assert!(!d.capabilities().table);
9880    }
9881
9882    #[test]
9883    fn insert_table_reports_a_zero_shape_and_writes_nothing() {
9884        let mut d = doc_with("table_zero", "para\n");
9885        d.caret = 2;
9886        d.insert_table(0, 2);
9887        assert_eq!(d.source, "para\n");
9888        assert!(d.status.as_deref().unwrap_or("").starts_with("table:"));
9889    }
9890
9891    #[test]
9892    fn clicking_below_a_final_thematic_break_can_type_after_it() {
9893        let mut d = wysiwyg_doc("hr_final_click", "---\n");
9894        d.build_visual(80);
9895        d.click(d.vmap.num_rows() + 2, 0, false);
9896        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
9897        d.insert("after");
9898        assert_eq!(d.source, "---\nafter");
9899    }
9900
9901    #[test]
9902    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
9903        // The same bytes are two documents. In Markdown `  - b` is a nested item
9904        // and the next one belongs beside it, at its indent. In Djot a list
9905        // marker can't interrupt a paragraph, so those bytes are literal text in
9906        // item `a` and there is only one item — writing `  - ` under it would add
9907        // no item at all, just more text, and the new sibling has to go to
9908        // column zero. Both spellings come out of the *enclosing item's* line.
9909        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
9910        md.caret = "- a\n  - b".len();
9911        md.newline();
9912        assert_eq!(md.source, "- a\n  - b\n  - \n");
9913        assert_eq!(list_items(&mut md), 3);
9914
9915        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
9916        dj.view = View::Wysiwyg;
9917        dj.build_visual(80);
9918        dj.caret = "- a\n  - b".len();
9919        dj.newline();
9920        assert_eq!(dj.source, "- a\n  - b\n- \n");
9921        assert_eq!(list_items(&mut dj), 2);
9922
9923        // Where Djot's nesting is real — opened by a blank line — the indent is
9924        // reproduced there too, and the two formats agree again.
9925        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
9926        dj.view = View::Wysiwyg;
9927        dj.build_visual(80);
9928        dj.caret = "- a\n\n  - b".len();
9929        dj.newline();
9930        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
9931        assert_eq!(list_items(&mut dj), 3);
9932    }
9933
9934    #[test]
9935    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
9936        // Tab replaces the line's whole prefix with the one twig spells, so the
9937        // quote markers, the parent's indent and an ordered marker's extra
9938        // column are all its answer rather than leaf's arithmetic.
9939        for (name, body, caret, want) in [
9940            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
9941            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
9942            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
9943            // A checkbox is markup the item's own text wraps past, but a nested
9944            // list may only open at the *list* marker's column — four in from
9945            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
9946            // parses as one item, not two.
9947            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
9948            (
9949                "quoted task",
9950                "> - [ ] a\n> - [ ] b\n",
9951                18,
9952                "> - [ ] a\n>   - [ ] b\n",
9953            ),
9954        ] {
9955            let mut doc = wysiwyg_doc(name, body);
9956            doc.caret = caret;
9957            doc.indent();
9958            assert_eq!(doc.source, want, "{name}");
9959            // The nesting is real, not just indented text.
9960            assert_eq!(list_items(&mut doc), 2, "{name}");
9961        }
9962    }
9963
9964    #[test]
9965    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
9966        // The same bytes, the two formats disagreeing, and a gesture that used
9967        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
9968        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
9969        // so those bytes are literal text inside item `a` — there is nothing to
9970        // outdent, and treating them as a marker turned one item into two, a
9971        // structural edit from a keystroke that should delete one character.
9972        //
9973        // twig's `line_prefix` is what tells them apart: it reports the marker
9974        // on the Markdown line and nothing on the Djot one, which is a
9975        // continuation. No byte scan can reach that answer.
9976        let src = "- a\n  - b\n";
9977        let at = "- a\n  - ".len();
9978
9979        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
9980        md.view = View::Wysiwyg;
9981        md.build_visual(80);
9982        md.caret = at;
9983        md.backspace();
9984        assert_eq!(md.source, "- a\n- b\n");
9985        assert_eq!(list_items(&mut md), 2);
9986
9987        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
9988        dj.view = View::Wysiwyg;
9989        dj.build_visual(80);
9990        dj.caret = at;
9991        dj.backspace();
9992        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
9993        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
9994    }
9995
9996    #[test]
9997    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
9998        // Leaf used to spell the next item from the marker bytes it scanned, and
9999        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
10000        // and dropped out of the checklist. twig reproduces the whole
10001        // continuation, and a fresh item is always unticked however the one above
10002        // it stands.
10003        for (name, body, want) in [
10004            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
10005            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
10006        ] {
10007            let mut doc = wysiwyg_doc(name, body);
10008            doc.caret = body.trim_end_matches('\n').len();
10009            doc.newline();
10010            assert_eq!(doc.source, want, "{name}");
10011            // Both items are checklist items — the new one is a box, not the
10012            // plain bullet the old marker scan left behind — and it is unticked
10013            // whichever way the one above it faces.
10014            let boxes: Vec<Option<bool>> = doc
10015                .nodes()
10016                .iter()
10017                .filter(|n| n.kind == Kind::TaskListItem)
10018                .map(|n| n.checked)
10019                .collect();
10020            assert_eq!(boxes.len(), 2, "{name}");
10021            assert_eq!(boxes[1], Some(false), "{name}");
10022        }
10023    }
10024
10025    #[test]
10026    fn a_split_takes_the_space_the_caret_was_in_front_of() {
10027        // Splicing a break at the caret strands the space the words were parted
10028        // at on the head of the second block, where it reads as an indent nobody
10029        // typed. twig's split consumes it.
10030        for (name, body, caret, want) in [
10031            ("para", "one two\n", 3, "one\n\ntwo\n"),
10032            ("item", "- one two\n", 5, "- one\n- two\n"),
10033            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
10034            // A heading takes leaf's own path, which has to match.
10035            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
10036        ] {
10037            let mut doc = wysiwyg_doc(name, body);
10038            doc.caret = caret;
10039            doc.newline();
10040            assert_eq!(doc.source, want, "{name}");
10041        }
10042    }
10043
10044    #[test]
10045    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
10046        // The one place leaf keeps its own break: `split_block` repeats the `#`,
10047        // and Enter after a title is how the body under it is asked for.
10048        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
10049        doc.caret = "# Title".len();
10050        doc.newline();
10051        doc.insert("body");
10052        assert_eq!(doc.source, "# Title\n\nbody\n");
10053        assert_eq!(
10054            doc.nodes()
10055                .iter()
10056                .filter(|n| n.kind == Kind::Heading)
10057                .count(),
10058            1
10059        );
10060    }
10061
10062    #[test]
10063    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
10064        // A quoted item's marker doesn't open its line, so a scan that starts at
10065        // column zero finds a `>` where it wanted a bullet, calls the line "not a
10066        // list" and hands Enter to the plain-quote branch — which writes `> ` and
10067        // drops the list. The next item has to carry the whole prefix.
10068        for (name, body, want) in [
10069            ("flat", "> - a\n", "> - a\n> - \n"),
10070            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
10071            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
10072            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
10073            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
10074        ] {
10075            let mut doc = wysiwyg_doc(name, body);
10076            doc.caret = body.trim_end_matches('\n').len();
10077            doc.newline();
10078            assert_eq!(doc.source, want, "{name}");
10079            // The marker isn't just spelled right, it parses as an item.
10080            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
10081        }
10082    }
10083
10084    #[test]
10085    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
10086        // Double-Enter exits the list. Unquoted that means a blank line, but a
10087        // *bare* blank line would end the quote too and drop the caret out of it,
10088        // so the separator keeps its `>` and the caret's line keeps its `> `.
10089        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
10090        doc.caret = "> - a\n> - ".len();
10091        doc.newline();
10092        assert_eq!(doc.source, "> - a\n>\n> \n");
10093        assert_eq!(list_items(&mut doc), 1);
10094        // What "still in the quote" means for the next keystroke: the caret sits
10095        // behind the prefix, and what's typed there lands inside the quote as a
10096        // paragraph of its own — not as more of item `a`.
10097        doc.insert("x");
10098        assert_eq!(doc.source, "> - a\n>\n> x\n");
10099        assert!(
10100            doc.editor
10101                .ancestors_at(doc.caret - 1)
10102                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
10103        );
10104    }
10105
10106    #[test]
10107    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
10108        // The marker is hidden block markup, so Backspace over it is structural —
10109        // but only the marker is the list's. Splicing from the line start would
10110        // take the `>` with it and silently unquote the line.
10111        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
10112        doc.caret = "> - ".len();
10113        doc.backspace();
10114        assert_eq!(doc.source, "> a\n");
10115        assert_eq!(list_items(&mut doc), 0);
10116
10117        // A nested one outdents instead, moving the bullet within the quote
10118        // rather than moving the quote.
10119        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
10120        doc.caret = "> - a\n>   - ".len();
10121        doc.backspace();
10122        assert_eq!(doc.source, "> - a\n> - b\n");
10123        assert_eq!(list_items(&mut doc), 2);
10124    }
10125
10126    #[test]
10127    fn only_a_bare_paragraph_is_parted_around_the_caret() {
10128        // The split is deliberately narrow. Parting a fenced block would leave
10129        // two fences with a rule between them, and parting a list item would
10130        // mint an item nobody asked for on the way to a rule that lands after
10131        // the list either way — so both keep the whole block intact and take the
10132        // rule after it. A caret in a quote is likewise left alone.
10133        for (name, body, caret, want) in [
10134            (
10135                "code",
10136                "```\nfn x() {}\n```\n",
10137                8,
10138                "```\nfn x() {}\n```\n\n---\n",
10139            ),
10140            ("list", "- one two\n", 6, "- one two\n\n---\n"),
10141            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n"),
10142        ] {
10143            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
10144            d.caret = caret;
10145            d.insert_thematic_break();
10146            assert_eq!(d.source, want, "{name}: the block should stay whole");
10147        }
10148    }
10149
10150    #[test]
10151    fn insert_thematic_break_replaces_the_selection() {
10152        // Now that the rule lands *at* the caret again, replacing the selection
10153        // is coherent once more: the text goes, and the rule takes its place.
10154        // The space the deletion left leading the second half is consumed by the
10155        // split rather than opening the new paragraph with it.
10156        let mut d = doc_with("hr_sel", "one two three\n");
10157        d.anchor = Some(4);
10158        d.caret = 7; // "two"
10159        d.insert_thematic_break();
10160        assert_eq!(d.source, "one \n\n---\n\nthree\n");
10161        assert_eq!(d.selection(), None);
10162    }
10163
10164    #[test]
10165    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
10166        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
10167        // because writing `---` into one is code, not a rule — twig now walks out
10168        // to the block that owns the caret's line, so there is nothing to refuse.
10169        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
10170        code.caret = 5; // inside the fenced code
10171        code.insert_thematic_break();
10172        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n");
10173        assert_eq!(code.status, None, "no refusal to report any more");
10174
10175        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
10176        table.caret = 3; // in the header row
10177        table.insert_thematic_break();
10178        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n");
10179    }
10180
10181    #[test]
10182    fn insert_thematic_break_in_a_list_item_ends_the_list() {
10183        // The un-indented rule cannot continue the list, so it closes the list
10184        // and lands at the top level rather than nested inside it.
10185        let mut d = doc_with("hr_list", "- one\n- two\n");
10186        d.caret = "- one\n- tw".len(); // mid "two"
10187        d.insert_thematic_break();
10188        d.build_visual(80);
10189        let rule_at = d.source.find("---").unwrap();
10190        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
10191        assert!(
10192            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
10193                && n.span.start <= rule_at
10194                && rule_at < n.span.end),
10195            "the rule must not be nested inside the list"
10196        );
10197    }
10198
10199    #[test]
10200    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
10201        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
10202        // which is the document the gesture was actually asked for.
10203        let mut d = doc_with("hr_quote", "> hello\n");
10204        d.caret = 4; // inside the quoted text
10205        d.insert_thematic_break();
10206        assert_eq!(d.source, "> hello\n>\n> ---\n");
10207        d.build_visual(80);
10208        let rule_at = d.source.find("---").unwrap();
10209        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
10210        assert!(
10211            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
10212                && n.span.start <= rule_at
10213                && rule_at < n.span.end),
10214            "the rule belongs to the quote it was asked for"
10215        );
10216    }
10217
10218    // ── typing against a block picture ────────────────────────────────────────
10219
10220    /// A rendered-view document with the caret parked on one of the picture's two
10221    /// stops, and the map already built — the state a frontend is in between
10222    /// drawing a frame and the next keystroke.
10223    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
10224        let mut d = doc_in(View::Wysiwyg, name, src);
10225        d.build_visual_unwrapped();
10226        let start = src.find("![").unwrap();
10227        d.caret = match side {
10228            MediaStop::Before => start,
10229            MediaStop::After => start + "![](p.png)".len(),
10230        };
10231        d
10232    }
10233
10234    /// The block media the map publishes, after rebuilding it — "is this still a
10235    /// picture, or has it become a line of text with an image in it?"
10236    fn media_count(d: &mut Doc) -> usize {
10237        d.build_visual_unwrapped();
10238        d.vmap.media.len()
10239    }
10240
10241    #[test]
10242    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
10243        // The accident this prevents: tap the blank page under a photo (which
10244        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
10245        // paragraph with an *inline* image — the photo stops being drawn.
10246        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
10247        d.insert("xy");
10248        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
10249        assert_eq!(media_count(&mut d), 1, "still a picture");
10250    }
10251
10252    #[test]
10253    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
10254        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
10255        d.insert("xy");
10256        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
10257        assert_eq!(media_count(&mut d), 1);
10258    }
10259
10260    #[test]
10261    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
10262        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
10263        d.insert("x");
10264        assert_eq!(d.source, "x\n\n![](p.png)\n");
10265        assert_eq!(media_count(&mut d), 1);
10266    }
10267
10268    #[test]
10269    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
10270        // The opened paragraph is part of the keystroke, not an edit the writer
10271        // made — so it undoes with the character, not a step later.
10272        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
10273        d.insert("x");
10274        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
10275        d.undo();
10276        assert_eq!(d.source, "hi\n\n![](p.png)\n");
10277    }
10278
10279    #[test]
10280    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
10281        // ⌘V dissolves the picture exactly as a keystroke does.
10282        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
10283        d.paste("pasted");
10284        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
10285        assert_eq!(media_count(&mut d), 1);
10286    }
10287
10288    #[test]
10289    fn typing_beside_an_inline_image_is_ordinary_editing() {
10290        // An inline image has no placeholder row and no stops of its own. Opening
10291        // a paragraph mid-sentence would be the bug, not the fix.
10292        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
10293        d.build_visual_unwrapped();
10294        d.caret = "see ![](p.png)".len();
10295        d.insert("!");
10296        assert_eq!(d.source, "see ![](p.png)! here\n");
10297    }
10298
10299    #[test]
10300    fn source_view_types_raw_markup_against_an_image_untouched() {
10301        // Source view is for writing the markup itself; a break inserted behind
10302        // the writer's back there would be the editor arguing with them.
10303        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
10304        d.caret = "![](p.png)".len();
10305        d.insert("x");
10306        assert_eq!(d.source, "![](p.png)x\n");
10307    }
10308
10309    #[test]
10310    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
10311        // A selection is replaced, not joined into, so there is nothing to
10312        // protect: the range takes the picture with it.
10313        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
10314        d.anchor = Some(d.caret);
10315        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
10316        d.insert("x");
10317        assert_eq!(d.source, "hi\n\nx\n");
10318    }
10319
10320    #[test]
10321    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
10322        // What this actually cost: a real vault's photo, to one stray Backspace.
10323        // The caret past `![](p.png)` was deleting the closing paren — invisible
10324        // in the rendered view — and the photo became the text `![](p.png`.
10325        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
10326        d.backspace();
10327        assert_eq!(d.source, "hi\n");
10328        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
10329        d.undo();
10330        assert_eq!(
10331            d.source, "hi\n\n![](p.png)\n",
10332            "and comes back in one piece"
10333        );
10334    }
10335
10336    #[test]
10337    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
10338        // Deleting the break here would join the picture to the paragraph above,
10339        // where it is an *inline* image and stops being drawn. Step over the
10340        // boundary; the next press deletes in the paragraph the caret reached.
10341        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
10342        d.backspace();
10343        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
10344        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
10345        d.backspace();
10346        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
10347        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
10348    }
10349
10350    #[test]
10351    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
10352        // The mirror. A byte-step here eats the `!` and leaves a link.
10353        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
10354        d.delete_forward();
10355        assert_eq!(d.source, "hi\n\nbye\n");
10356        assert_eq!(media_count(&mut d), 0);
10357    }
10358
10359    #[test]
10360    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
10361        let mut d = doc_at_picture(
10362            "pic_del_after",
10363            "hi\n\n![](p.png)\n\nbye\n",
10364            MediaStop::After,
10365        );
10366        d.delete_forward();
10367        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
10368        assert_eq!(
10369            d.caret,
10370            d.source.find("bye").unwrap(),
10371            "the caret stepped down to `bye`"
10372        );
10373    }
10374
10375    #[test]
10376    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
10377        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
10378        d.backspace();
10379        assert_eq!(d.source, "\n");
10380        assert_eq!(media_count(&mut d), 0);
10381    }
10382
10383    #[test]
10384    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
10385        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
10386        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
10387        d.delete_word_back();
10388        assert_eq!(d.source, "hi there\n");
10389
10390        // And in front of one it runs *through* the paragraph break into the
10391        // prose above, which merges the picture inline — so it steps out first,
10392        // and the second press deletes the word it was aimed at.
10393        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
10394        d.delete_word_back();
10395        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
10396        d.delete_word_back();
10397        assert_eq!(
10398            d.source, "hi \n\n![](p.png)\n",
10399            "the word above went, the picture stayed"
10400        );
10401        assert_eq!(media_count(&mut d), 1);
10402    }
10403
10404    #[test]
10405    fn source_view_deletes_raw_markup_against_an_image_untouched() {
10406        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
10407        d.caret = "![](p.png)".len();
10408        d.backspace();
10409        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
10410    }
10411
10412    #[test]
10413    fn image_destination_at_caret_reads_the_image_under_the_caret() {
10414        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
10415        d.caret = 3; // inside the image markup
10416        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
10417        // Past the image, the caret is in no image.
10418        d.caret = "![a cat](cat.png)".len();
10419        assert_eq!(d.image_destination_at_caret(), None);
10420    }
10421
10422    #[test]
10423    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
10424        // The image is one placeholder row by default, and `set_media_rows` grows
10425        // it to the height the frontend measured: the label row plus blank
10426        // `decoration` fillers that hold the vertical space a raster is drawn into.
10427        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
10428        assert_eq!(d.vmap.media.len(), 1);
10429        let img_row = d.vmap.media[0].rows_span.start;
10430        assert_eq!(
10431            d.vmap.media[0].rows_span,
10432            img_row..img_row + 1,
10433            "default is one row"
10434        );
10435
10436        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
10437        d.build_visual(80);
10438        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
10439        let span = d.vmap.media[0].rows_span.clone();
10440        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
10441        // The label row carries the mark and its glyphs; the three below are blank
10442        // decoration — drawn, but no caret and no text.
10443        assert!(
10444            d.vmap.rows[span.start].media.is_some(),
10445            "mark rides the first row"
10446        );
10447        for r in (span.start + 1)..span.end {
10448            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
10449            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
10450            assert!(
10451                d.vmap.rows[r].media.is_none(),
10452                "only the first row is marked"
10453            );
10454        }
10455    }
10456
10457    #[test]
10458    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
10459        // The extra rows are pure spacers: the caret's only homes stay the stop in
10460        // front of the image and the one just past it, so walking the document top
10461        // to bottom visits the same offsets whether the image is 1 row or 5.
10462        let body = "ab\n\n![x](p.png)\n\ncd\n";
10463        let stops_at = |rows: usize| -> Vec<usize> {
10464            let mut d = wysiwyg_doc("img_stops", body);
10465            if rows > 1 {
10466                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
10467                d.build_visual(80);
10468            }
10469            d.caret = 0;
10470            let mut seen = vec![d.caret];
10471            loop {
10472                d.move_right(false);
10473                if *seen.last().unwrap() == d.caret {
10474                    break;
10475                }
10476                seen.push(d.caret);
10477            }
10478            seen
10479        };
10480        assert_eq!(
10481            stops_at(1),
10482            stops_at(5),
10483            "reserving rows must not add stops"
10484        );
10485    }
10486
10487    #[test]
10488    fn insert_link_repoints_the_link_at_a_bare_caret() {
10489        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
10490        d.caret = 3; // in the link's text, nothing selected
10491        d.insert_link("http://y.dev");
10492        assert_eq!(d.source, "[word](http://y.dev)\n");
10493        assert_eq!(d.selected_text(), Some("word"));
10494    }
10495
10496    #[test]
10497    fn insert_link_on_an_empty_range_autolinks_a_url() {
10498        // A link with no text of its own is an autolink, and twig spells it —
10499        // `<…>` is the canonical form and needs no text typed into it, so the
10500        // caret lands after it rather than selecting a finished link.
10501        let mut d = doc_with("link_empty", "\n");
10502        d.caret = 0;
10503        d.insert_link("http://x.dev");
10504        assert_eq!(d.source, "<http://x.dev>\n");
10505        assert_eq!(d.selection(), None);
10506        assert_eq!(d.caret, 14);
10507    }
10508
10509    #[test]
10510    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
10511        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
10512        // in Markdown, so a destination that can't autolink doubles as the text
10513        // instead — which is then selected, ready to be typed over.
10514        let mut d = doc_with("link_rel", "\n");
10515        d.caret = 0;
10516        d.insert_link("./notes.md");
10517        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
10518        assert_eq!(d.selection(), Some((1, 11)));
10519        d.insert("Notes");
10520        assert_eq!(d.source, "[Notes](./notes.md)\n");
10521    }
10522
10523    #[test]
10524    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
10525        // The autolink's text is its URL, so re-pointing replaces the whole
10526        // node — the caret must not splice a second link inside the first.
10527        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
10528        d.caret = 10;
10529        d.insert_link("https://y.dev");
10530        assert_eq!(d.source, "see <https://y.dev> ok\n");
10531    }
10532
10533    #[test]
10534    fn code_language_reads_and_edits_through_the_fence() {
10535        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
10536        d.caret = 10; // inside the code body
10537        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
10538        assert!(d.caret_in_fenced_code());
10539
10540        d.set_code_language("python");
10541        assert!(
10542            d.source.starts_with("```python\n"),
10543            "source: {:?}",
10544            d.source
10545        );
10546        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
10547
10548        // Clearing it leaves a bare fence and no label.
10549        d.set_code_language("");
10550        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
10551        assert_eq!(d.code_language_at_caret(), None);
10552
10553        // A caret outside any code block edits nothing.
10554        let mut p = doc_with("code_lang_none", "just prose\n");
10555        assert!(!p.caret_in_fenced_code());
10556        p.set_code_language("rust");
10557        assert_eq!(p.source, "just prose\n");
10558    }
10559
10560    #[test]
10561    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
10562        // Markdown's info string ends at whitespace, so `two words` would write
10563        // a fence that reads back with a different language than the one asked
10564        // for. twig refuses it; leaf reports that and leaves the source alone.
10565        // The old splice trimmed the ends and wrote whatever was left.
10566        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
10567        d.caret = 10;
10568        d.set_code_language("two words");
10569        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
10570        assert!(d.status.is_some(), "the refusal should be reported");
10571        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
10572    }
10573
10574    #[test]
10575    fn link_destination_at_caret_reads_both_spellings() {
10576        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
10577        d.caret = 5;
10578        assert_eq!(
10579            d.link_destination_at_caret().as_deref(),
10580            Some("https://x.dev")
10581        );
10582        d.caret = 0;
10583        assert_eq!(d.link_destination_at_caret(), None);
10584
10585        // An autolink has no `destination`; its text is the URL.
10586        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
10587        a.caret = 10;
10588        assert_eq!(
10589            a.link_destination_at_caret().as_deref(),
10590            Some("https://x.dev")
10591        );
10592        a.caret = 21;
10593        assert_eq!(a.link_destination_at_caret(), None);
10594    }
10595
10596    #[test]
10597    fn locate_finds_the_block_a_declared_id_names() {
10598        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
10599        // verse. The locator has to land on the *verse*, which is the whole
10600        // reason a link carries one.
10601        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
10602                   {#v2}\nYea, I make a record in the language of my father.\n";
10603        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10604        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
10605        assert_eq!(
10606            d.source[v2.start..v2.end].trim_end(),
10607            "Yea, I make a record in the language of my father."
10608        );
10609        // The attribute line is not part of it: `start` is a place to put a
10610        // caret, and `{#v2}` is markup the caret has no business landing in.
10611        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
10612        assert_eq!(d.locate("v99"), None);
10613    }
10614
10615    #[test]
10616    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
10617        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
10618        // Markdown heading is literal text. So `#the-second-part` can only be
10619        // the heading's own words, which is the rule every Markdown renderer
10620        // already follows and therefore the one a link was authored against.
10621        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
10622        let mut d = doc_with("locate_md", src);
10623        let hit = d.locate("the-second-part").expect("the heading's slug");
10624        assert!(d.source[hit.start..].starts_with("## The Second Part"));
10625        // Bounded by the next heading that isn't under it, so a peek shows the
10626        // section rather than only its title.
10627        assert_eq!(
10628            &d.source[hit.start..hit.end],
10629            "## The Second Part\n\nbody\n\n"
10630        );
10631
10632        // A subsection does not end its parent: `# Title` runs to `## Third`'s
10633        // sibling only because there is no other `#`, so it covers the lot.
10634        let title = d.locate("title").expect("the top heading");
10635        assert_eq!(title.end, d.source.len());
10636    }
10637
10638    #[test]
10639    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
10640        // djot mints `Some-Heading-Here`; a link to it is written
10641        // `#some-heading-here` by nearly everything that writes links. Both
10642        // spellings are one question.
10643        let src = "## Some Heading Here\n\nbody\n";
10644        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10645        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
10646        let slugged = d.locate("some-heading-here").expect("the link's spelling");
10647        assert_eq!(exact, slugged);
10648        // The section, not the heading line — there is more to show than a title.
10649        assert_eq!(&d.source[exact.start..exact.end], src);
10650    }
10651
10652    #[test]
10653    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
10654        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
10655        assert_eq!(d.locate(""), None);
10656        assert_eq!(d.locate("   "), None);
10657        // All punctuation: it names nothing, and must not be read as "match the
10658        // first heading whose slug is also empty".
10659        assert_eq!(d.locate("!!!"), None);
10660    }
10661
10662    #[test]
10663    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
10664        // The document's mistake, and the answer every other anchor
10665        // implementation gives — the alternative is for a link to mean whichever
10666        // of the two a walk happened to reach first.
10667        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
10668        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10669        let hit = d.locate("dup").expect("the first `{#dup}`");
10670        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
10671    }
10672
10673    #[test]
10674    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
10675        // The button's whole job: a reference where the caret was, a definition
10676        // to give it meaning, and the caret waiting in the empty note so the
10677        // next keystroke is the note's first word.
10678        let mut d = doc_with("fn_insert", "A claim and more.\n");
10679        d.caret = 7; // just past "A claim"
10680        d.insert_footnote();
10681        assert!(
10682            d.source.starts_with("A claim[^1] and more."),
10683            "{:?}",
10684            d.source
10685        );
10686        assert!(
10687            d.source.contains("[^1]:"),
10688            "the definition too: {:?}",
10689            d.source
10690        );
10691        assert_eq!(d.status, None);
10692
10693        let reference = d.source.find("[^1]").unwrap();
10694        let note = d
10695            .footnote_at(reference + 2)
10696            .expect("the reference just written");
10697        assert_eq!(note.label, "1");
10698        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
10699        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
10700        // …and typing there is typing into the note, not near it.
10701        d.insert("the note");
10702        assert_eq!(
10703            d.footnote_at(reference + 2).and_then(|f| f.text),
10704            Some("the note".to_string())
10705        );
10706    }
10707
10708    #[test]
10709    fn insert_footnote_numbers_past_the_notes_already_written() {
10710        // A second press must not hand back a label somebody else is using: twig
10711        // reuses a defined label rather than appending a rival definition, so a
10712        // repeat of `1` would quietly point the new reference at the old note.
10713        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
10714        d.caret = 7; // past `[^1]`, before " two."
10715        d.insert_footnote();
10716        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
10717        assert_eq!(d.source.matches("[^2]:").count(), 1);
10718    }
10719
10720    #[test]
10721    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
10722        // `[^2]` with no definition is still a 2 that means something to whoever
10723        // wrote it — stepping over it would mint a note for their reference. A
10724        // word label takes no number, so it blocks none.
10725        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
10726        d.caret = d.source.find(" c").unwrap();
10727        d.insert_footnote();
10728        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
10729        assert!(
10730            d.source.starts_with("a[^2] b[^why][^1] c"),
10731            "{:?}",
10732            d.source
10733        );
10734    }
10735
10736    #[test]
10737    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
10738        // A reference annotates the words before it. Consuming the selection —
10739        // which is what an insert normally does — would delete the very claim
10740        // the author selected in order to footnote.
10741        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
10742        d.anchor = Some(2);
10743        d.caret = 7; // "claim" selected
10744        d.insert_footnote();
10745        assert!(
10746            d.source.starts_with("A claim[^1] and more."),
10747            "{:?}",
10748            d.source
10749        );
10750    }
10751
10752    #[test]
10753    fn a_note_just_written_still_knows_where_its_reference_is() {
10754        // The authoring loop in one test: press the button, type the note, ask to
10755        // go back. The caret ends at the note's last byte — which is the *end* of
10756        // the definition's span, the one offset the query used to exclude — so
10757        // this is where the round trip either works or doesn't.
10758        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
10759        d.caret = 7;
10760        d.insert_footnote();
10761        d.insert("the note");
10762        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
10763        let back = d
10764            .footnote_definition_at_caret()
10765            .expect("still in the note we just typed");
10766        assert_eq!(back.label, "1");
10767        // …and following it lands on the reference's label, where a reader's
10768        // return leg lands.
10769        assert_eq!(back.offset, Some(9));
10770        assert_eq!(&d.source[9..10], "1");
10771    }
10772
10773    #[test]
10774    fn insert_footnote_takes_one_undo_for_both_halves() {
10775        // twig writes the pair as a single edit; the point of that is here.
10776        let before = "A claim and more.\n";
10777        let mut d = doc_with("fn_insert_undo", before);
10778        d.caret = 7;
10779        d.insert_footnote();
10780        assert_ne!(d.source, before);
10781        d.undo();
10782        assert_eq!(d.source, before, "one undo takes back both halves");
10783    }
10784
10785    #[test]
10786    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
10787        // HTML is authorable — it spells the inline marks — and has no footnote.
10788        // The refusal says so rather than writing brackets that would render as
10789        // brackets.
10790        let src = "<p>A claim.</p>\n";
10791        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
10792        assert!(!Capabilities::of(Format::Html).footnote);
10793        d.caret = 5;
10794        d.insert_footnote();
10795        assert_eq!(d.source, src, "nothing written");
10796        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
10797    }
10798
10799    #[test]
10800    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
10801        // The empty body is the one place this could go wrong: the definition
10802        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
10803        // byte early would draw up in the paragraph above the note it belongs to.
10804        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
10805        d.place_caret(7, false);
10806        d.insert_footnote();
10807        d.build_visual(80); // the frame a frontend draws after the edit
10808        assert_eq!(
10809            d.vmap.snap_to_stop(d.caret),
10810            d.caret,
10811            "the caret sits on a stop"
10812        );
10813        let (row, _) = d.caret_pos();
10814        assert!(
10815            drawn_rows(&d)[row].contains("[1]"),
10816            "the caret is on the note's row, not above it: {:?}",
10817            drawn_rows(&d)
10818        );
10819    }
10820
10821    #[test]
10822    fn footnote_at_caret_resolves_a_reference_to_its_note() {
10823        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
10824        // blank line, as one has to.
10825        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
10826        d.caret = 9;
10827        let f = d
10828            .footnote_at_caret()
10829            .expect("the caret stands in a reference");
10830        assert_eq!(f.label, "1");
10831        assert_eq!(f.text.as_deref(), Some("the note"));
10832        // The offset points at the note's first word, not at the definition's
10833        // `[` — the marker is decoration with no caret stop on it.
10834        assert_eq!(f.offset, Some(29));
10835        assert_eq!(&d.source[29..37], "the note");
10836        // …and `end` closes the range, so a frontend can ask which rendered rows
10837        // the note occupies rather than re-deriving them from the text.
10838        assert_eq!(f.end, Some(37));
10839        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
10840    }
10841
10842    /// Two definitions in a row: each is its own note, and neither reaches into
10843    /// the other.
10844    ///
10845    /// A djot definition's span used to run past the blank line into the first
10846    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
10847    /// offsets named the *next* note's rows too, showing a reader two footnotes
10848    /// when they had asked about one. twig 3.1 ends the span after the block's
10849    /// own last line; the test outlives the workaround leaf carried for it.
10850    #[test]
10851    fn footnote_at_stops_a_note_at_the_definition_after_it() {
10852        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
10853        for format in [Format::Markdown, Format::Djot] {
10854            let mut d = Doc::from_source(src.to_string(), format).unwrap();
10855            d.caret = 7;
10856            let f = d.footnote_at_caret().expect("a reference");
10857            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
10858            assert_eq!(
10859                &src[f.offset.unwrap()..f.end.unwrap()],
10860                "first note.",
10861                "in {format:?}"
10862            );
10863        }
10864    }
10865
10866    /// The other side of that boundary: a blank line *inside* a definition is
10867    /// interior to it, and the note keeps its second paragraph.
10868    ///
10869    /// This is what the old body scan cost. It stopped at the first line not
10870    /// indented under the note — a blank line is not — so a two-paragraph note
10871    /// came back as its first paragraph, and "go to note" framed half of it.
10872    /// Reading the span twig gives is both simpler and right.
10873    #[test]
10874    fn footnote_at_keeps_a_notes_second_paragraph() {
10875        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
10876        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10877        d.caret = 7;
10878        let f = d.footnote_at_caret().expect("a reference");
10879        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
10880        // And it stops there — `After.` is the next block, not more note.
10881        assert_eq!(
10882            &src[f.offset.unwrap()..f.end.unwrap()],
10883            f.text.as_deref().unwrap()
10884        );
10885        assert!(!f.text.as_deref().unwrap().contains("After"));
10886    }
10887
10888    #[test]
10889    fn footnote_at_bounds_a_note_whose_body_is_empty() {
10890        // `[^1]:` with nothing after it. The range is empty rather than
10891        // inverted, and still points inside the definition — which is what keeps
10892        // a frontend's row lookup from walking off into the block above.
10893        let src = "A claim[^1].\n\n[^1]:\n";
10894        let mut d = doc_with("fn_empty_body", src);
10895        d.caret = 9;
10896        let f = d.footnote_at_caret().expect("a reference");
10897        assert_eq!(f.text.as_deref(), Some(""));
10898        assert_eq!(f.offset, f.end, "an empty note is an empty range");
10899        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
10900    }
10901
10902    #[test]
10903    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
10904        let mut d = doc_with(
10905            "fn_at_caret_none",
10906            "A claim[^1] and more.\n\n[^1]: the note\n",
10907        );
10908        d.caret = 2; // in the prose
10909        assert_eq!(d.footnote_at_caret(), None);
10910    }
10911
10912    #[test]
10913    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
10914        // The two are deliberately separate: a reference names a note in this
10915        // document, a link names somewhere to leave for, and answering one with
10916        // the other is what made a reference click do nothing at all.
10917        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
10918        d.caret = 3; // the `1` of `[^1]`
10919        assert!(d.footnote_at_caret().is_some());
10920        assert_eq!(
10921            d.link_destination_at_caret(),
10922            None,
10923            "a reference is not a link"
10924        );
10925
10926        d.caret = 10; // inside the link's label
10927        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
10928        assert_eq!(
10929            d.link_destination_at_caret().as_deref(),
10930            Some("https://x.dev")
10931        );
10932    }
10933
10934    #[test]
10935    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
10936        // A `[^99]` the document never defines is a real state — a note deleted
10937        // out from under its reference — and the label is what lets a frontend
10938        // say so. `None` here would be indistinguishable from "not on a
10939        // reference", which is the wrong thing to tell a reader.
10940        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
10941        d.caret = 9;
10942        let f = d
10943            .footnote_at_caret()
10944            .expect("the reference is still a reference");
10945        assert_eq!(f.label, "99");
10946        assert_eq!(f.text, None);
10947        assert_eq!(f.offset, None);
10948    }
10949
10950    #[test]
10951    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
10952        // Labels are not always numbers, and a note's body runs past its first
10953        // line — the indented continuation belongs to the note, so it comes back
10954        // with it (source bytes, verbatim, as documented).
10955        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
10956        let mut d = doc_with("fn_word_label", src);
10957        d.caret = 6;
10958        let f = d
10959            .footnote_at_caret()
10960            .expect("the caret stands in a reference");
10961        assert_eq!(f.label, "note");
10962        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
10963    }
10964
10965    #[test]
10966    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
10967        // The point of the offset form: a pointer hovering a reference asks what
10968        // note it names, and must not drag the caret along to ask.
10969        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
10970        d.caret = 0;
10971        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
10972        assert_eq!(f.label, "1");
10973        assert_eq!(f.text.as_deref(), Some("the note"));
10974        assert_eq!(d.caret, 0, "asking must not move the caret");
10975        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
10976    }
10977
10978    #[test]
10979    fn footnote_definition_at_caret_points_back_at_the_reference() {
10980        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
10981        // the caret can rest on — is at 9.
10982        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
10983        d.caret = 30; // inside the note's body
10984        let f = d
10985            .footnote_definition_at_caret()
10986            .expect("the caret stands in a definition");
10987        assert_eq!(f.label, "1");
10988        assert_eq!(f.offset, Some(9));
10989        assert_eq!(&d.source[7..11], "[^1]");
10990    }
10991
10992    #[test]
10993    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
10994        // The two legs have to meet: wherever `footnote_at` sends the caret, the
10995        // definition query must answer for — otherwise arriving at a note leaves
10996        // the reader somewhere the way back isn't offered.
10997        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
10998        let mut d = doc_with("fn_def_marker", src);
10999        let landed = d.footnote_at(9).unwrap().offset.unwrap();
11000        assert_eq!(
11001            d.footnote_definition_at(landed).and_then(|f| f.offset),
11002            Some(9),
11003            "the note a reference sends you to offers the way back"
11004        );
11005    }
11006
11007    #[test]
11008    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
11009        // The two queries answer for disjoint places, which is what lets one
11010        // gesture mean "down to the note" in one and "back up" in the other
11011        // without either having to remember which way the reader is going.
11012        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
11013        d.caret = 2; // prose
11014        assert_eq!(d.footnote_definition_at_caret(), None);
11015        d.caret = 9; // the reference
11016        assert_eq!(d.footnote_definition_at_caret(), None);
11017        assert!(
11018            d.footnote_at_caret().is_some(),
11019            "which is the reference's own query"
11020        );
11021    }
11022
11023    #[test]
11024    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
11025        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
11026        // note", which is false and leaves a frontend unable to explain why the
11027        // way back is missing.
11028        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
11029        let mut d = doc_with("fn_def_orphan", src);
11030        d.caret = src.find("orphan").unwrap();
11031        let f = d
11032            .footnote_definition_at_caret()
11033            .expect("an orphan is still a definition");
11034        assert_eq!(f.label, "2");
11035        assert_eq!(f.offset, None);
11036    }
11037
11038    #[test]
11039    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
11040        // One label, cited twice. The first is where the reader most likely came
11041        // from, and the only answer that doesn't depend on how they got here.
11042        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
11043        let mut d = doc_with("fn_def_repeat", src);
11044        d.caret = src.find("the note").unwrap();
11045        let f = d.footnote_definition_at_caret().expect("a definition");
11046        assert_eq!(
11047            f.offset,
11048            Some(5),
11049            "the first `[^a]`'s label, not the second's"
11050        );
11051        assert_eq!(&src[3..7], "[^a]");
11052    }
11053
11054    #[test]
11055    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
11056        // Down and back up, each leg found from the document rather than from a
11057        // memory of the other — so it still works for a reader who scrolled to
11058        // the notes instead of jumping there.
11059        //
11060        // `place_caret` rather than assigning `caret`, because that is what a
11061        // frontend calls: it snaps to a real caret stop, and a jump that lands
11062        // on a byte the caret can't rest on would arrive somewhere the return
11063        // leg no longer answers for. `build_map` first, since snapping is a
11064        // no-op until the map exists — which is exactly how this went unnoticed
11065        // when the offsets pointed at the `[^` markers.
11066        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
11067        d.build_map(None);
11068        d.place_caret(9, false);
11069        let down = d
11070            .footnote_at_caret()
11071            .expect("a reference")
11072            .offset
11073            .expect("a note");
11074        d.place_caret(down, false);
11075        let up = d
11076            .footnote_definition_at_caret()
11077            .expect("a definition")
11078            .offset
11079            .expect("a reference");
11080        d.place_caret(up, false);
11081        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
11082        assert_eq!(
11083            d.footnote_at_caret().expect("back on the reference").label,
11084            "1"
11085        );
11086    }
11087
11088    #[test]
11089    fn insert_link_hands_the_destination_to_twig_raw() {
11090        // Escaping is twig's, and format-specific: Markdown ends a destination
11091        // at the first space and needs the `<…>` form, where djot would read
11092        // those angle brackets as part of the URL.
11093        let mut d = doc_with("link_space", "word\n");
11094        d.anchor = Some(0);
11095        d.caret = 4;
11096        d.insert_link("a b");
11097        assert_eq!(d.source, "[word](<a b>)\n");
11098    }
11099
11100    #[test]
11101    fn insert_link_reports_a_destination_no_format_can_carry() {
11102        let mut d = doc_with("link_bad", "word\n");
11103        d.anchor = Some(0);
11104        d.caret = 4;
11105        d.insert_link("a\nb");
11106        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
11107        assert!(
11108            d.status.is_some(),
11109            "InvalidArgument should reach the status line"
11110        );
11111        assert!(!d.dirty);
11112    }
11113
11114    #[test]
11115    fn insert_link_works_in_wysiwyg_view() {
11116        let mut d = wysiwyg_doc("link_wys", "word here\n");
11117        d.anchor = Some(0);
11118        d.caret = 4;
11119        d.insert_link("http://x.dev");
11120        assert_eq!(d.source, "[word](http://x.dev) here\n");
11121        assert_eq!(d.selected_text(), Some("word"));
11122        // The map the caret has to keep riding is rebuilt each frame; motion
11123        // over the fresh one must still land on a real stop (the debug_assert).
11124        d.build_visual(80);
11125        d.move_right(false);
11126        d.move_left(false);
11127    }
11128
11129    #[test]
11130    fn click_maps_a_row_col_to_a_byte_offset() {
11131        let mut d = doc_with("click", "ab\ncd\n");
11132        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
11133        assert_eq!(d.caret, 4);
11134    }
11135
11136    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
11137    // stop just as the `(row, col)` click path does, so the caret can never come
11138    // to rest in the blank gap between two paragraphs — where it would draw in one
11139    // place and type in another.
11140    #[test]
11141    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
11142        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
11143        // caret stop (stops are 0,1,3,4).
11144        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
11145        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
11146        d.place_caret(2, false);
11147        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
11148        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
11149    }
11150
11151    #[test]
11152    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
11153        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
11154        d.place_caret(0, false); // anchor at the start of "A"
11155        d.place_caret(2, true); // drag into the gap
11156        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
11157        let (s, e) = d.selection().expect("a selection");
11158        assert!(
11159            d.vmap.is_stop(s) && d.vmap.is_stop(e),
11160            "selection {s}..{e} off a stop"
11161        );
11162    }
11163
11164    #[test]
11165    fn place_caret_on_a_real_stop_is_left_untouched() {
11166        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
11167        d.place_caret(3, false); // the start of "B" — a genuine stop
11168        assert_eq!(d.caret, 3);
11169    }
11170
11171    // An *empty paragraph* (two blank lines, an intentional blank line the user
11172    // opened) is a real caret stop, unlike the gap — a click into it must stay.
11173    #[test]
11174    fn place_caret_rests_in_an_empty_paragraph() {
11175        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
11176        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
11177        assert!(d.vmap.is_stop(empty));
11178        d.place_caret(empty, false);
11179        assert_eq!(d.caret, empty);
11180    }
11181
11182    // The content end of a hidden mark is a home too (`VisualMap::mark_ends`):
11183    // a drag over the word `bold` ends there, and a caret placed there stays.
11184    #[test]
11185    fn place_caret_rests_at_the_end_of_a_hidden_marks_content() {
11186        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
11187        let mut d = wysiwyg_doc("place_mark_end", src);
11188        let start = src.find("bold").unwrap();
11189        d.place_caret(start, false);
11190        d.place_caret(start + 4, true);
11191        assert_eq!(d.selection(), Some((start, start + 4)), "the whole word");
11192        d.toggle(InlineKind::Strong);
11193        assert_eq!(d.source, src.replace("**bold**", "bold"));
11194    }
11195
11196    #[test]
11197    fn right_steps_onto_the_end_of_a_mark_and_then_past_its_delimiter() {
11198        let mut d = wysiwyg_doc("right_mark_end", "a **bold** b");
11199        d.caret = 7; // before the `d`
11200        d.move_right(false);
11201        assert_eq!(d.caret, 8, "onto the end of the bold");
11202        assert!(d.active_inline_marks().contains(InlineKind::Strong));
11203        d.move_right(false);
11204        assert_eq!(d.caret, 10, "past the closing `**`");
11205        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
11206        d.move_left(false);
11207        assert_eq!(d.caret, 8);
11208        d.move_left(false);
11209        assert_eq!(d.caret, 7);
11210        // Typing at the inner home extends the bold.
11211        d.caret = 8;
11212        d.insert("!");
11213        assert_eq!(d.source, "a **bold!** b");
11214    }
11215
11216    #[test]
11217    fn a_marks_end_home_follows_an_edit_through_the_incremental_map() {
11218        // The splice path shifts the home with the block it is in, and the
11219        // re-rendered block finds its own again.
11220        let mut d = wysiwyg_doc("mark_end_splice", "x\n\na **bold** b\n\ny\n");
11221        d.build_visual_unwrapped();
11222        d.edit(0, 0, "zz");
11223        d.build_visual_unwrapped();
11224        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a shift");
11225        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
11226        let at = d.source.find("bold").unwrap();
11227        d.edit(at, at, "very ");
11228        d.build_visual_unwrapped();
11229        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a re-render");
11230        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
11231    }
11232
11233    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
11234        doc_in(View::Wysiwyg, name, body)
11235    }
11236
11237    /// How many list items the source actually parses into — the check that a
11238    /// marker Leaf wrote is a marker the format agrees is one.
11239    fn list_items(doc: &mut Doc) -> usize {
11240        doc.editor
11241            .nodes()
11242            .unwrap()
11243            .iter()
11244            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
11245            .count()
11246    }
11247
11248    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
11249    /// incremental (`build_spliced` / `build_cached`) path must always match.
11250    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
11251        reference_map_revealing(source, None)
11252    }
11253
11254    /// [`reference_map`] with a reveal line — the ground truth for the
11255    /// `MarkupMode::Full` builds, where the map is a function of the caret's
11256    /// line as well as the text.
11257    fn reference_map_revealing(
11258        source: &str,
11259        reveal: Option<Range<usize>>,
11260    ) -> crate::wysiwyg::VisualMap {
11261        // The same parse `Doc` uses. With twig's plain defaults instead, the two
11262        // sides disagree on what the *document* is before the renderer is even
11263        // reached — a bare `:word` is a text directive to one and prose to the
11264        // other — and the mismatch reads as a splice bug that isn't one.
11265        let mut ed =
11266            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
11267        let nodes = ed.nodes().unwrap();
11268        crate::wysiwyg::build(
11269            &nodes,
11270            source,
11271            None,
11272            false,
11273            &std::collections::HashMap::new(),
11274            reveal,
11275        )
11276    }
11277
11278    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
11279        if a.rows.len() != b.rows.len() {
11280            return true;
11281        }
11282        for (ra, rb) in a.rows.iter().zip(&b.rows) {
11283            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
11284                return true;
11285            }
11286            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
11287                if ga.ch != gb.ch || ga.src != gb.src {
11288                    return true;
11289                }
11290            }
11291        }
11292        false
11293    }
11294
11295    #[test]
11296    fn incremental_build_matches_a_fresh_build_across_edits() {
11297        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
11298        // fast path, gated on twig's `dirty_range`) or falls back to
11299        // `build_cached`. After each edit the map must be byte-identical to a
11300        // from-scratch build — this is the correctness net under the splice.
11301        let docs = [
11302            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
11303            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
11304            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
11305            // A footnote definition is a root beside `doc`, merged back into the
11306            // top-level list by `wysiwyg::top_blocks`. The random edits below
11307            // make and unmake definitions as they go (a deleted `:` turns one
11308            // back into a paragraph, and vice versa), which is exactly the
11309            // structural churn the splice path has to notice and bail out of.
11310            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
11311            // A comment is a top-level block that draws no rows — a layout entry
11312            // at zero rows either side of blocks that do. The edits below type
11313            // into the blocks around it (a splice past a hidden block), and
11314            // break the comment open into prose and back (a structural change).
11315            "intro\n\n<!-- exec -->\n```\ncode\n```\n\nafter the comment\n\n<!-- trail -->\n",
11316            // Link reference definitions: a hidden block that an edit can turn
11317            // into a paragraph (a deleted `:`) and back, and whose own bytes an
11318            // edit can land in.
11319            "see [a] and [b]\n\n[a]: /a\n\nmid text\n\n[b]: /b\n",
11320        ];
11321        // A deterministic mix: mostly single characters (which stay inside one
11322        // block → splice), plus edits that reshape structure (a paragraph break,
11323        // a heading marker, a code fence → fallback), so both paths are exercised.
11324        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
11325        for src in docs {
11326            let mut d = wysiwyg_doc("diff", src);
11327            d.build_visual_unwrapped();
11328            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
11329
11330            for step in 0..60usize {
11331                let len = d.source.len();
11332                let raw = (step * 13 + 5) % (len + 1);
11333                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
11334                let pre = d.source.clone();
11335                let action;
11336                if step % 3 == 0 && pos < len {
11337                    let end = (pos + 1..=len)
11338                        .find(|&i| d.source.is_char_boundary(i))
11339                        .unwrap();
11340                    action = format!("delete [{pos},{end})");
11341                    d.edit(pos, end, "");
11342                } else {
11343                    let ins = inserts[step % inserts.len()];
11344                    action = format!("insert {ins:?} @ {pos}");
11345                    d.edit(pos, pos, ins);
11346                }
11347                d.build_visual_unwrapped();
11348                if maps_differ(&d.vmap, &reference_map(&d.source)) {
11349                    panic!(
11350                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
11351                        d.source
11352                    );
11353                }
11354            }
11355        }
11356    }
11357
11358    /// A frontend is handed [`Doc::vmap`] and may present it differently:
11359    /// leaf-ratatui splices blank filler rows under an oversized heading so the
11360    /// raster it paints there has somewhere to stand, and leaves them in the map
11361    /// because the caret and the mouse both read it between frames. The splice
11362    /// path addresses that map by *row index*, against the block layout the last
11363    /// build recorded — so handed a map with rows in it that no block owns, it
11364    /// laid the re-rendered block over one of the fillers and carried the rows
11365    /// the block really occupied into the suffix. One stranded copy of the
11366    /// edited line, and everything below it a row further down, per keystroke.
11367    ///
11368    /// A map that isn't the one the layout describes is a map this path can't
11369    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
11370    #[test]
11371    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
11372        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
11373        d.build_visual_unwrapped();
11374
11375        // Stand in for the heading filler rows: two blank rows past the heading
11376        // that no block accounts for. Cloning a real row keeps every field
11377        // plausible — it is the row *count* the splice can't survive.
11378        let filler = d.vmap.rows[0].clone();
11379        d.vmap.rows.insert(1, filler.clone());
11380        d.vmap.rows.insert(1, filler);
11381
11382        // An edit inside the last block: the single-block case the splice path
11383        // is for, and the one the frontend hits on every keystroke.
11384        let at = d.source.len() - 1;
11385        d.edit(at, at, "!");
11386        d.build_visual_unwrapped();
11387
11388        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
11389    }
11390
11391    /// A glyph's [`FaceId`] has to mean the same thing however its row was
11392    /// built. A row comes three ways — a fresh walk, a [`BlockCache`] hit
11393    /// cloned at a shifted offset, and a previous map's rows a splice kept
11394    /// untouched — and only the first of those walks a `data-font` at all. An
11395    /// index into a per-build table would have had the same glyph naming two
11396    /// families the moment a second one appeared; the id is the name's own
11397    /// hash, so nothing is remapped and the table is merged rather than rebuilt.
11398    ///
11399    /// Two families, because one cannot tell a wrong id from a right one.
11400    ///
11401    /// [`FaceId`]: crate::style::FaceId
11402    /// [`BlockCache`]: crate::wysiwyg::BlockCache
11403    #[test]
11404    fn a_spliced_rebuild_still_says_which_family_each_glyph_is_set_in() {
11405        use crate::style::{FaceId, FaceRef};
11406        let garamond = FaceId::of("Garamond");
11407        let futura = FaceId::of("Futura");
11408        let mut d = wysiwyg_doc(
11409            "two_faces",
11410            "x <span data-font=\"Garamond\">alpha</span>\n\ny <span data-font=\"Futura\">beta</span>\n",
11411        );
11412        d.build_visual_unwrapped();
11413
11414        // What the map has to keep saying, whichever path built it.
11415        let check = |d: &Doc, ctx: &str| {
11416            let face_of = |ch: char| {
11417                d.vmap
11418                    .rows
11419                    .iter()
11420                    .flat_map(|r| r.glyphs.iter())
11421                    .find(|g| g.ch == ch)
11422                    .map(|g| g.style.font)
11423            };
11424            assert_eq!(face_of('a'), Some(Some(FaceRef::Named(garamond))), "{ctx}");
11425            assert_eq!(face_of('b'), Some(Some(FaceRef::Named(futura))), "{ctx}");
11426            assert_eq!(d.vmap.face_name(garamond), Some("Garamond"), "{ctx}");
11427            assert_eq!(d.vmap.face_name(futura), Some("Futura"), "{ctx}");
11428            assert_eq!(d.vmap.face_name(FaceId::of("Bodoni")), None, "{ctx}");
11429        };
11430        check(&d, "fresh");
11431
11432        // An edit inside the second block: the single-block case the splice
11433        // path is for. The first block's rows are carried over untouched, so
11434        // its glyphs' ids are the previous build's and the table has to be too.
11435        let at = d.source.find("beta").unwrap();
11436        d.edit(at, at, "z");
11437        d.build_visual_unwrapped();
11438        check(&d, "after an edit in the second block");
11439        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced");
11440
11441        // And the other way round, so the block that was kept is the one that
11442        // is now re-rendered.
11443        let at = d.source.find("alpha").unwrap();
11444        d.edit(at, at, "z");
11445        d.build_visual_unwrapped();
11446        check(&d, "after an edit in the first block");
11447        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced again");
11448
11449        // A structural edit is one the splice bails out of, so the map is
11450        // reassembled by `build_cached` — where an untouched block is a *cache
11451        // hit* and its rows are cloned without a `data-font` being walked
11452        // again. The names the entry stored are what keeps the table honest
11453        // there.
11454        let at = d.source.find("\n\ny ").unwrap();
11455        d.edit(at, at, "\n\nmiddle");
11456        d.build_visual_unwrapped();
11457        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached");
11458        // Twice, because that first `build_cached` is what stores the entries:
11459        // this one is the build where the Garamond block is a *hit*, its rows
11460        // cloned with their ids and no attribute walked to explain them.
11461        let at = d.source.len() - 1;
11462        d.edit(at, at, "\n\ntail");
11463        d.build_visual_unwrapped();
11464        check(&d, "after a structural edit, through the block cache");
11465        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached again");
11466
11467        // A family the edit took the last glyph of leaves the glyphs with no
11468        // face and the table with a name nothing asks for — harmless, and the
11469        // price of not walking the rows the splice exists to avoid walking.
11470        let span = d.source.find("<span data-font=\"Futura\">").unwrap();
11471        let end = d.source.rfind("</span>").unwrap() + "</span>".len();
11472        d.edit(span, end, "beta");
11473        d.build_visual_unwrapped();
11474        assert!(!d.source.contains("Futura"), "{:?}", d.source);
11475        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "the face removed");
11476    }
11477
11478    #[test]
11479    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
11480        // The same correctness net as `incremental_build_matches_a_fresh_build_
11481        // across_edits`, under `MarkupMode::Full` — where the map depends on
11482        // the caret's *line* as well as the text, so the two caches have a new
11483        // way to be wrong. Both are exercised: the block cache can hand back
11484        // rows built for a line that is no longer the revealed one, and the
11485        // splice path can reuse a suffix that still has yesterday's line raw.
11486        //
11487        // Caret motion is interleaved with the edits deliberately, because a
11488        // caret that only ever moved with the edit would never cross a line
11489        // without also dirtying it — the case where a stale reveal survives.
11490        let docs = [
11491            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
11492            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
11493        ];
11494        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
11495        for src in docs {
11496            let mut d = wysiwyg_doc("reveal_diff", src);
11497            d.set_markup_mode(MarkupMode::Full);
11498
11499            for step in 0..60usize {
11500                let len = d.source.len();
11501                let raw = (step * 13 + 5) % (len + 1);
11502                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
11503                let pre = d.source.clone();
11504                let action;
11505                if step % 3 == 0 && pos < len {
11506                    let end = (pos + 1..=len)
11507                        .find(|&i| d.source.is_char_boundary(i))
11508                        .unwrap();
11509                    action = format!("delete [{pos},{end})");
11510                    d.edit(pos, end, "");
11511                } else {
11512                    let ins = inserts[step % inserts.len()];
11513                    action = format!("insert {ins:?} @ {pos}");
11514                    d.edit(pos, pos, ins);
11515                }
11516                // Walk the caret somewhere else in the document, independently
11517                // of where the edit landed.
11518                let want = (step * 29 + 11) % (d.source.len() + 1);
11519                d.caret = (want..=d.source.len())
11520                    .find(|&i| d.source.is_char_boundary(i))
11521                    .unwrap();
11522                d.build_visual_unwrapped();
11523
11524                let want = reference_map_revealing(&d.source, d.reveal_line());
11525                if maps_differ(&d.vmap, &want) {
11526                    panic!(
11527                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
11528                        d.caret, d.source
11529                    );
11530                }
11531            }
11532        }
11533    }
11534
11535    #[test]
11536    fn caret_motion_across_lines_rebuilds_only_under_full() {
11537        // The cache-key change has to earn its keep in both directions: `Full`
11538        // must rebuild when the caret changes line (or the reveal would never
11539        // move), and the hidden modes must *not* (or every arrow key would pay
11540        // for a feature they don't use). The existing `cache_motion` test pins
11541        // the second for the default mode; this pins the pair against a mode
11542        // change alone.
11543        let body = "*one* here\n\n*two* there\n";
11544
11545        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
11546        full.set_markup_mode(MarkupMode::Full);
11547        caret_at(&mut full, "one");
11548        let before = full.revision();
11549        caret_at(&mut full, "two");
11550        assert_eq!(full.revision(), before, "motion is not an edit");
11551        assert!(
11552            drawn_rows(&full).iter().any(|r| r == "*two* there"),
11553            "the map followed the caret: {:?}",
11554            drawn_rows(&full)
11555        );
11556
11557        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
11558        caret_at(&mut hidden, "one");
11559        let key = hidden.vmap_key.clone();
11560        caret_at(&mut hidden, "two");
11561        assert_eq!(
11562            hidden.vmap_key, key,
11563            "a hidden mode rebuilds nothing on motion"
11564        );
11565    }
11566
11567    #[test]
11568    fn wysiwyg_down_crosses_a_paragraph_boundary() {
11569        // Regression: the blank separator row used to share the previous
11570        // paragraph's end offset, so Down got pinned at the boundary (while Up
11571        // still crossed). Both directions must step through it symmetrically.
11572        //
11573        // It's now stepped *over* rather than onto: the blank line between two
11574        // paragraphs is the boundary being drawn, not a line of the document, so
11575        // one press of Down crosses it. The goal column survives the crossing —
11576        // col 3 at the end of "abc" is col 3 at the end of "def".
11577        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
11578        d.caret = 3; // end of "abc" (row 0)
11579        d.move_down(false);
11580        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
11581        assert_eq!(d.caret, 8); // end of "def", col 3 kept
11582        d.move_up(false);
11583        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
11584        assert_eq!(d.caret, 3);
11585    }
11586
11587    #[test]
11588    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
11589        // The second Up and the second Down here run off the ends of the
11590        // document, which is no longer a place a press is swallowed: they carry
11591        // the caret to the start and the end of the text. The claim in the
11592        // middle — that a Down retraces the Up that crossed the paragraph gap —
11593        // is the one this test is for, and it is asserted where it is made.
11594        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
11595        d.caret = 5; // start of "def"
11596        let start = d.caret_pos();
11597        d.move_up(false);
11598        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
11599        d.move_up(false);
11600        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
11601        d.move_down(false);
11602        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
11603        d.move_down(false);
11604        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
11605    }
11606
11607    #[test]
11608    fn wysiwyg_new_paragraph_shows_before_typing() {
11609        // Regression: two Enters at the end of a paragraph produced trailing
11610        // newlines with no AST node, so the caret appeared stuck on the old line
11611        // until a character was typed. It must ride down onto the new line now.
11612        let mut d = doc_with("wys_newpara", "abc\n");
11613        d.view = View::Wysiwyg;
11614        d.caret = 3;
11615        d.insert("\n");
11616        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
11617        assert_eq!(d.source, "abc\n\n\n");
11618        d.build_visual(80);
11619        let (row, _) = d.caret_pos();
11620        assert!(
11621            row >= 2,
11622            "caret should have moved down to the new line, got row {row}"
11623        );
11624        assert!(
11625            d.vmap.num_rows() >= 3,
11626            "the blank lines should render as rows"
11627        );
11628    }
11629
11630    #[test]
11631    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
11632        // The reported bug: Enter at the end of a paragraph that has another
11633        // paragraph below put the caret at the *start of the next paragraph* —
11634        // the empty paragraph it opened had no row, so the caret snapped onto
11635        // "World". It must now sit on its own empty line, with a blank spacer
11636        // above it (the paragraph gap).
11637        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
11638        d.caret = 5; // end of "Hello"
11639        d.newline();
11640        d.build_visual(80);
11641        let (row, col) = d.caret_pos();
11642        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
11643        assert_eq!(
11644            d.vmap.row_width(row),
11645            0,
11646            "caret's row must be empty, not 'World'"
11647        );
11648        assert!(
11649            row >= 2,
11650            "a blank spacer row should sit above the caret, got row {row}"
11651        );
11652        // The row above the caret is a real (empty) gap, and "Hello" stays put.
11653        assert_eq!(
11654            d.vmap.row_width(row - 1),
11655            0,
11656            "the row above the caret is a gap"
11657        );
11658        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
11659        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
11660    }
11661
11662    #[test]
11663    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
11664        // At the document end a single Enter must also show the paragraph gap —
11665        // a blank spacer row above the caret — so the layout already matches how
11666        // it will look once the new paragraph has text.
11667        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
11668        d.caret = 5; // end of "Hello", no trailing newline
11669        d.newline(); // source becomes "Hello\n\n"
11670        d.build_visual(80);
11671        let (row, col) = d.caret_pos();
11672        assert_eq!(col, 0);
11673        assert!(
11674            row >= 2,
11675            "caret should sit below a blank spacer, got row {row}"
11676        );
11677        assert_eq!(
11678            d.vmap.row_width(row - 1),
11679            0,
11680            "the row above the caret is a gap"
11681        );
11682    }
11683
11684    #[test]
11685    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
11686        // The spacer is view-only: typing the new paragraph must not reflow the
11687        // caret onto a different row — the transient view already matched the
11688        // settled one.
11689        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
11690        d.caret = 5;
11691        d.newline();
11692        d.build_visual(80);
11693        let before = d.caret_pos();
11694        d.insert("New");
11695        d.build_visual(80);
11696        let after = d.caret_pos();
11697        assert_eq!(
11698            after.0, before.0,
11699            "typing must not move the caret to another row ({before:?} -> {after:?})"
11700        );
11701    }
11702
11703    #[test]
11704    fn wysiwyg_return_on_the_last_code_line_keeps_the_caret_in_the_block() {
11705        // Return at the end of the block's last line writes an empty line the
11706        // map used to drop, so the caret landed on `after` and the next
11707        // keystroke went into the paragraph below instead of into the code.
11708        let mut d = wysiwyg_doc("code_return", "prose\n\n```\nalpha\nbeta\n```\n\nafter\n");
11709        d.caret = d.source.find("beta").unwrap() + "beta".len();
11710        d.build_visual(80);
11711        let before = d.caret_pos().0;
11712
11713        d.newline();
11714        d.build_visual(80);
11715        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n");
11716
11717        let (row, col) = d.caret_pos();
11718        assert_eq!(row, before + 1, "the caret moves down one row");
11719        assert_eq!(col, 0, "onto the head of the empty line");
11720        let span = d.vmap.code_blocks[0].rows_span.clone();
11721        assert!(
11722            span.contains(&row),
11723            "caret row {row} is outside the block's rows {span:?}"
11724        );
11725
11726        // The whole point: what is typed next is code.
11727        d.insert("gamma");
11728        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\ngamma\n```\n\nafter\n");
11729    }
11730
11731    #[test]
11732    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
11733        let fm = "---\ntitle: hi\n---\n";
11734        let body = format!("{fm}# leaf\n\nbody\n");
11735        let mut d = wysiwyg_doc("wys_fm", &body);
11736        // Opening lifts the caret out of the now-hidden frontmatter.
11737        assert_eq!(
11738            d.caret,
11739            fm.len(),
11740            "caret should start at the first real block"
11741        );
11742        // Left at the content start can't step back into frontmatter.
11743        d.move_left(false);
11744        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
11745        // Doc-start lands on the content floor, not offset 0.
11746        d.move_doc_start(false);
11747        assert_eq!(d.caret, fm.len());
11748        // Select-all + copy never include the frontmatter bytes.
11749        d.select_all();
11750        let sel = d.selected_text().unwrap().to_string();
11751        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
11752        assert!(
11753            sel.starts_with("# leaf"),
11754            "selection should begin at content: {sel:?}"
11755        );
11756    }
11757
11758    #[test]
11759    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
11760        // A fresh note is frontmatter and nothing else. With no rendered block
11761        // to floor the caret it opened at offset 0 — before the opening `---` —
11762        // so the first keystroke wrote itself in front of the metadata and the
11763        // file came out as `This---\ntitle: …`.
11764        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
11765        let mut d = wysiwyg_doc("wys_fm_only", fm);
11766        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
11767        // Nothing is rendered, so the caret draws at the origin of an empty view
11768        // — the same place an empty document puts it.
11769        assert_eq!(d.caret_pos(), (0, 0));
11770        d.insert("This");
11771        assert_eq!(d.source, format!("{fm}This"));
11772    }
11773
11774    /// `select_range` is the verb for a range a host already knows the bytes of,
11775    /// so it must not snap — and must still hold every invariant `place_caret`
11776    /// holds, the frontmatter floor above all.
11777    #[test]
11778    fn select_range_takes_the_range_as_given_but_still_floors_it() {
11779        let fm = "---\ntitle: foo\n---\n\n";
11780        let body = format!("{fm}body foo here\n");
11781        let mut d = wysiwyg_doc("wys_select_range", &body);
11782
11783        // The `foo` in the body: taken exactly, not snapped to a caret stop.
11784        let at = body.rfind("foo").unwrap();
11785        d.select_range(at, at + 3);
11786        assert_eq!(d.selection(), Some((at, at + 3)));
11787        assert_eq!(d.selected_text(), Some("foo"));
11788
11789        // The `foo` in the hidden frontmatter: below the floor, so both ends
11790        // come up to it rather than parking the caret in the metadata, where a
11791        // later keystroke would rewrite `title:`.
11792        let hidden = body.find("foo").unwrap();
11793        assert!(hidden < d.vmap.content_start);
11794        d.select_range(hidden, hidden + 3);
11795        assert!(
11796            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
11797            "a range under the floor must not leave the caret in the frontmatter"
11798        );
11799
11800        // Past the end, and mid-character, are both brought back to something
11801        // sliceable rather than panicking the next reader of the range.
11802        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
11803        let mut d = multi;
11804        d.select_range(2, 9_999);
11805        assert_eq!(d.caret, d.source.len());
11806        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
11807        assert!(d.source.is_char_boundary(d.caret));
11808    }
11809
11810    /// The bug `select_range` exists for: a match butting up against a hidden
11811    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
11812    /// the one before the `**`.
11813    #[test]
11814    fn select_range_does_not_snap_off_a_hidden_delimiter() {
11815        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
11816        let at = d.source.find("needle").unwrap();
11817        d.select_range(at, at + 6);
11818        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
11819    }
11820
11821    #[test]
11822    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
11823        // Backspace deletes `prev_boundary..caret` directly; at the first real
11824        // block that boundary is inside the hidden frontmatter, so it must be a
11825        // no-op rather than eating the closing `---`.
11826        let fm = "---\ntitle: hi\n---\n";
11827        let body = format!("{fm}leaf\n");
11828        let mut d = wysiwyg_doc("wys_fm_bs", &body);
11829        assert_eq!(d.caret, fm.len());
11830        d.backspace();
11831        assert_eq!(d.source, body, "backspace must not touch frontmatter");
11832        d.delete_word_back();
11833        assert_eq!(
11834            d.source, body,
11835            "word-delete must not touch frontmatter either"
11836        );
11837    }
11838
11839    #[test]
11840    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
11841        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
11842        // fenced div, really, since core parses these on for every document
11843        // now (`parse_extensions`). The container is a `directive` node, an
11844        // `is_block_container` kind like `block_quote`, so the caret works
11845        // inside its child paragraph exactly as it would inside a quote: typing
11846        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
11847        // untouched.
11848        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
11849        let mut d = wysiwyg_doc("wys_vis", body);
11850        d.caret = body.find("hello").unwrap() + "hello".len();
11851        d.insert("!");
11852        assert_eq!(
11853            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
11854            "typing inside the block edits its content in place"
11855        );
11856        assert!(
11857            d.source.contains(":::vis{.public .family}"),
11858            "opening fence survives"
11859        );
11860        assert!(d.source.contains(":::\nafter"), "closing fence survives");
11861    }
11862
11863    #[test]
11864    fn source_view_still_reaches_frontmatter() {
11865        // The metadata is only *hidden*, never lost: the source view edits and
11866        // selects it in full, and it's always preserved on save.
11867        let fm = "---\ntitle: hi\n---\n";
11868        let body = format!("{fm}# leaf\n");
11869        let mut d = doc_with("src_fm", &body);
11870        d.select_all();
11871        let sel = d.selected_text().unwrap();
11872        assert!(
11873            sel.contains("title"),
11874            "source view should select everything"
11875        );
11876        d.move_doc_start(false);
11877        assert_eq!(d.caret, 0, "source view can reach offset 0");
11878    }
11879
11880    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
11881
11882    #[test]
11883    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
11884        // The border and padding between two cells all share one source offset,
11885        // so a column-stepping caret would sit on `│` and then stall there
11886        // forever. Right must step: end of "Name" -> start of "Qty".
11887        let mut d = wysiwyg_doc("tbl_right", TABLE);
11888        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
11889        d.move_right(false);
11890        assert_eq!(
11891            d.caret,
11892            TABLE.find("Qty").unwrap(),
11893            "should land in the next cell"
11894        );
11895        let (r, c) = d.caret_pos();
11896        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
11897    }
11898
11899    #[test]
11900    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
11901        let mut d = wysiwyg_doc("tbl_left", TABLE);
11902        d.caret = TABLE.find("Qty").unwrap();
11903        d.move_left(false);
11904        assert_eq!(
11905            d.caret,
11906            TABLE.find("Name").unwrap() + 4,
11907            "end of the previous cell"
11908        );
11909    }
11910
11911    #[test]
11912    fn wysiwyg_down_steps_over_a_table_rule() {
11913        // Between the header and the first body row sits a `├───┼───┤` rule.
11914        // It's drawn but holds no caret, so one Down must reach "Pear".
11915        let mut d = wysiwyg_doc("tbl_down", TABLE);
11916        d.caret = TABLE.find("Name").unwrap();
11917        d.move_down(false);
11918        assert_eq!(
11919            d.caret,
11920            TABLE.find("Pear").unwrap(),
11921            "one Down reaches the body row"
11922        );
11923        d.move_down(false);
11924        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
11925    }
11926
11927    #[test]
11928    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
11929        let mut d = wysiwyg_doc("tbl_tab", TABLE);
11930        d.caret = TABLE.find("Name").unwrap();
11931        // A hop lands with the destination cell's whole content selected, the
11932        // caret at its end — so typing replaces the cell like a form field.
11933        assert!(d.cell_hop(true));
11934        assert_eq!(
11935            d.selected_text(),
11936            Some("Qty"),
11937            "the target cell comes up selected"
11938        );
11939        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
11940        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
11941        assert_eq!(d.selected_text(), Some("Pear"));
11942        assert!(d.cell_hop(false));
11943        assert_eq!(d.selected_text(), Some("Qty"));
11944    }
11945
11946    #[test]
11947    fn tab_outside_a_table_is_not_a_cell_hop() {
11948        // `cell_hop` reports false so the frontend can indent as usual.
11949        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
11950        d.caret = 4;
11951        assert!(!d.cell_hop(true));
11952        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
11953    }
11954
11955    #[test]
11956    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
11957        let mut d = wysiwyg_doc("tbl_edge", TABLE);
11958        d.caret = TABLE.rfind("12").unwrap(); // the final cell
11959        assert!(!d.cell_hop(true), "no cell after the last one");
11960        d.caret = TABLE.find("Name").unwrap();
11961        assert!(!d.cell_hop(false), "no cell before the first one");
11962    }
11963
11964    #[test]
11965    fn wysiwyg_vertical_cell_motion_holds_the_column() {
11966        // Down/Up step to the cell above/below in the *same column*, not back to
11967        // the top-left the way a naive row/col motion over the picture would.
11968        let mut d = wysiwyg_doc("tbl_vert", TABLE);
11969        d.caret = TABLE.find("Qty").unwrap();
11970        // Each vertical hop selects the destination cell, holding the column.
11971        assert!(d.cell_move_vertical(true));
11972        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
11973        assert!(d.cell_move_vertical(true));
11974        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
11975        assert!(!d.cell_move_vertical(true), "no row below the last");
11976        assert!(d.cell_move_vertical(false));
11977        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
11978        assert!(d.cell_move_vertical(false));
11979        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
11980        assert!(!d.cell_move_vertical(false), "no row above the header");
11981    }
11982
11983    #[test]
11984    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
11985        let mut d = wysiwyg_doc("tbl_grow", TABLE);
11986        d.caret = TABLE.rfind("12").unwrap();
11987        let rows_before = d.source.matches('\n').count();
11988        assert!(d.cell_tab(true), "acts as a table key");
11989        assert_eq!(
11990            d.source.matches('\n').count(),
11991            rows_before + 1,
11992            "a fresh row was appended"
11993        );
11994        assert!(d.caret_in_table(), "the caret entered the new row");
11995        // The caret sits in the new row's first cell — past the old last cell.
11996        assert!(d.caret > TABLE.rfind("12").unwrap());
11997    }
11998
11999    #[test]
12000    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
12001        let mut d = wysiwyg_doc("tbl_ret", TABLE);
12002        d.caret = TABLE.find("Name").unwrap();
12003        assert!(d.cell_return(), "acts as a table key");
12004        assert_eq!(
12005            d.selected_text(),
12006            Some("Pear"),
12007            "Return drops one cell, selecting it"
12008        );
12009        // From the last row, Return appends a row and enters it.
12010        d.caret = TABLE.rfind("Fig").unwrap();
12011        let rows_before = d.source.matches('\n').count();
12012        assert!(d.cell_return());
12013        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
12014        assert!(d.caret_in_table());
12015    }
12016
12017    #[test]
12018    fn return_and_tab_outside_a_table_decline() {
12019        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
12020        d.caret = 4;
12021        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
12022        assert!(!d.cell_tab(true), "no table: the frontend indents");
12023        assert!(
12024            !d.cell_line_break(),
12025            "no table: the frontend breaks the line"
12026        );
12027    }
12028
12029    #[test]
12030    fn a_click_under_a_trailing_table_lands_past_it_and_enter_opens_a_line() {
12031        // A document that ends in a table used to end *inside* it: nothing
12032        // past the last cell was a caret stop, so a click in the blank space
12033        // under the grid snapped back into the table and there was no way to
12034        // write a line after it. The bottom border's end is that stop now.
12035        let mut d = wysiwyg_doc("tbl_trail", TABLE);
12036        let rows = d.vmap.num_rows();
12037        d.click(rows + 3, 0, false);
12038        let end = TABLE.trim_end_matches('\n').len();
12039        assert_eq!(d.caret, end, "the caret stands just past the table");
12040        assert!(!d.caret_in_table(), "past the table is outside it");
12041        assert!(!d.cell_return(), "Return there is the frontend's newline");
12042        d.newline();
12043        d.insert("after");
12044        assert_eq!(
12045            d.source,
12046            format!("{TABLE}\nafter\n"),
12047            "Enter opens a paragraph under the table"
12048        );
12049    }
12050
12051    #[test]
12052    fn typing_at_a_table_s_trailing_stop_opens_a_paragraph_first() {
12053        // The stop sits at the end of the table's last source line, and a
12054        // line glued under a table is a row of it — `| Fig | 12 |x` would be a
12055        // three-cell row. So the text gets a paragraph of its own, as it does
12056        // beside a block picture.
12057        let mut d = wysiwyg_doc("tbl_type", TABLE);
12058        d.caret = TABLE.trim_end_matches('\n').len();
12059        d.insert("x");
12060        assert_eq!(d.source, format!("{TABLE}\nx\n"));
12061        assert_eq!(d.caret, TABLE.len() + 2, "the caret follows the text");
12062        // And a paste, which joins the block exactly as typing would.
12063        let mut d = wysiwyg_doc("tbl_paste", TABLE);
12064        d.caret = TABLE.trim_end_matches('\n').len();
12065        d.paste("pasted");
12066        assert_eq!(d.source, format!("{TABLE}\npasted\n"));
12067    }
12068
12069    #[test]
12070    fn right_leaves_a_table_by_its_trailing_stop_and_backspace_steps_back_in() {
12071        let mut d = wysiwyg_doc("tbl_edge", TABLE);
12072        let last_cell_end = TABLE.rfind("12").unwrap() + 2;
12073        let end = TABLE.trim_end_matches('\n').len();
12074        d.caret = last_cell_end;
12075        d.move_right(false);
12076        assert_eq!(d.caret, end, "Right from the last cell leaves the table");
12077        // Backspace there takes no byte: the one behind the caret is the row's
12078        // closing `|`, which the rich view never drew. It steps back instead.
12079        d.backspace();
12080        assert_eq!(d.source, TABLE, "nothing deleted");
12081        assert_eq!(d.caret, last_cell_end, "back into the last cell");
12082        // Down from the last row lands on the same stop, and Up returns.
12083        d.move_down(false);
12084        assert_eq!(d.caret, end, "Down from the last row leaves the table");
12085        d.move_up(false);
12086        assert_eq!(d.caret, last_cell_end);
12087    }
12088
12089    #[test]
12090    fn a_table_s_trailing_stop_sits_between_it_and_the_text_below() {
12091        // With prose under the table, the stop is one hop between the last
12092        // cell and the paragraph — the shape a block picture's second stop has.
12093        let src = format!("{TABLE}\nafter\n");
12094        let mut d = wysiwyg_doc("tbl_mid", &src);
12095        d.caret = TABLE.rfind("12").unwrap() + 2;
12096        d.move_right(false);
12097        assert_eq!(d.caret, TABLE.trim_end_matches('\n').len());
12098        d.move_right(false);
12099        assert_eq!(d.caret, src.find("after").unwrap());
12100        // Typing at the stop still opens a paragraph, and the text below keeps
12101        // its own.
12102        d.move_left(false);
12103        d.insert("x");
12104        assert_eq!(d.source, format!("{TABLE}\nx\n\nafter\n"));
12105    }
12106
12107    #[test]
12108    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
12109        let mut d = wysiwyg_doc("tbl_break", TABLE);
12110        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
12111        assert!(d.cell_line_break(), "acts as a table key");
12112        assert!(
12113            d.source.contains("Pear<br>"),
12114            "spelled as an inline <br>: {}",
12115            d.source
12116        );
12117        assert!(d.caret_in_table(), "still in the cell, past the break");
12118        // The break renders as a real line: the "Pear" cell now draws two lines,
12119        // so the table's picture is one row taller than a single-line table.
12120        d.build_visual(80);
12121        let table = &d.vmap.tables[0];
12122        let cell = &table.grid[1].cells[0]; // first body row, first column
12123        assert!(
12124            cell.glyphs.iter().any(|g| g.ch == '\n'),
12125            "the cell carries the break as a newline glyph for the frontend to split"
12126        );
12127    }
12128
12129    #[test]
12130    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
12131        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
12132        // back as structure — the whole point of routing through insert_line_break
12133        // instead of splicing raw `<br>` bytes.
12134        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
12135        d.caret = TABLE.find("Pear").unwrap() + 4;
12136        assert!(d.cell_line_break());
12137        let kinds: Vec<Kind> = d
12138            .editor
12139            .nodes()
12140            .unwrap()
12141            .iter()
12142            .map(|n| n.kind.clone())
12143            .collect();
12144        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
12145        assert!(
12146            !kinds.contains(&Kind::RawInline),
12147            "still raw HTML: {kinds:?}"
12148        );
12149    }
12150
12151    #[test]
12152    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
12153        // The `<br>` draws as one newline glyph, so Backspace over it must take
12154        // all four bytes — a one-byte delete would strand a visible `<br` in the
12155        // cell (the reported bug).
12156        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
12157        d.caret = TABLE.find("Pear").unwrap() + 4;
12158        assert!(d.cell_line_break());
12159        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
12160        d.backspace(); // caret sits just past the break
12161        assert!(
12162            !d.source.contains("<br"),
12163            "no half-deleted <br left: {}",
12164            d.source
12165        );
12166        assert!(
12167            d.source.contains("| Pear |"),
12168            "the cell is back to one line: {}",
12169            d.source
12170        );
12171    }
12172
12173    #[test]
12174    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
12175        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
12176        d.caret = TABLE.find("Pear").unwrap() + 4;
12177        assert!(d.cell_line_break());
12178        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
12179        d.delete_forward();
12180        assert!(
12181            !d.source.contains("<br"),
12182            "no half-deleted <br: {}",
12183            d.source
12184        );
12185        assert!(
12186            d.source.contains("| Pear |"),
12187            "cell back to one line: {}",
12188            d.source
12189        );
12190    }
12191
12192    #[test]
12193    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
12194        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
12195        // still consumed (a real newline would split the one-line row), but the
12196        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
12197        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
12198        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
12199        d.caret = src.find("Pear").unwrap() + 4;
12200        assert!(d.caret_in_table(), "caret should be inside the djot table");
12201        assert!(
12202            d.cell_line_break(),
12203            "the key is consumed, not passed to the frontend"
12204        );
12205        assert_eq!(d.source, src, "the djot cell is left untouched");
12206        assert!(
12207            !d.source.contains("<br>"),
12208            "no non-idiomatic <br> spliced into djot"
12209        );
12210        assert!(
12211            d.status.is_some(),
12212            "the refusal is surfaced on the status line"
12213        );
12214    }
12215
12216    #[test]
12217    fn typing_in_a_cell_edits_that_cell() {
12218        // Editing comes free once offsets map correctly: the caret is a source
12219        // offset, so a normal splice lands inside the pipe table.
12220        let mut d = wysiwyg_doc("tbl_type", TABLE);
12221        d.caret = TABLE.find("Pear").unwrap() + 4;
12222        d.insert("s");
12223        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
12224    }
12225
12226    #[test]
12227    fn motion_and_delete_treat_an_emoji_as_one_character() {
12228        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
12229        // bytes, several codepoints. Right-arrow must clear it in one step, and
12230        // backspace must remove the whole cluster, not a stray joiner.
12231        let family = "👨‍👩‍👧";
12232        let mut d = doc_with("emoji", &format!("a{family}b\n"));
12233        d.caret = 1; // just after 'a', before the emoji
12234        d.move_right(false);
12235        assert_eq!(
12236            d.caret,
12237            1 + family.len(),
12238            "one step clears the whole cluster"
12239        );
12240        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
12241
12242        d.backspace(); // delete the emoji as a unit
12243        assert_eq!(d.source, "ab\n");
12244        assert_eq!(d.caret, 1);
12245    }
12246
12247    #[test]
12248    fn motion_handles_a_combining_accent_as_one_character() {
12249        // "e" + U+0301 (combining acute) renders as one é.
12250        let mut d = doc_with("combining", "e\u{0301}x\n");
12251        d.caret = 0;
12252        d.move_right(false);
12253        assert_eq!(
12254            d.caret,
12255            "e\u{0301}".len(),
12256            "steps past base + combining mark"
12257        );
12258    }
12259
12260    #[test]
12261    fn undo_then_redo_round_trips_an_edit() {
12262        let mut d = doc_with("undo", "hello\n");
12263        d.caret = 5;
12264        d.insert("!");
12265        assert_eq!(d.source, "hello!\n");
12266        d.undo();
12267        assert_eq!(d.source, "hello\n");
12268        assert_eq!(d.caret, 5, "undo restores the caret");
12269        d.redo();
12270        assert_eq!(d.source, "hello!\n");
12271    }
12272
12273    #[test]
12274    fn a_run_of_typing_undoes_as_one_step() {
12275        let mut d = doc_with("coalesce", "\n");
12276        d.caret = 0;
12277        d.insert("a");
12278        d.insert("b");
12279        d.insert("c");
12280        assert_eq!(d.source, "abc\n");
12281        d.undo(); // the whole typed run, not just "c"
12282        assert_eq!(d.source, "\n");
12283        d.undo(); // nothing left — the run was one step
12284        assert_eq!(d.source, "\n");
12285        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
12286    }
12287
12288    // ── IME composition ──────────────────────────────────────────────────────
12289
12290    #[test]
12291    fn a_composition_run_undoes_as_one_step() {
12292        let mut d = doc_with("compose", "\n");
12293        d.caret = 0;
12294        // What an IME does: each step replaces the last one's provisional bytes.
12295        d.edit_composing(0, 0, "k");
12296        d.edit_composing(0, 1, "か");
12297        d.edit_composing(0, 3, "かん");
12298        d.edit_composing(0, 6, "感"); // the commit
12299        d.end_composition();
12300        assert_eq!(d.source, "感\n");
12301        d.undo(); // the whole composition, not its last keystroke
12302        assert_eq!(d.source, "\n");
12303        assert_eq!(d.status.as_deref(), None, "the run was a single step");
12304    }
12305
12306    #[test]
12307    fn two_compositions_are_two_undo_steps() {
12308        let mut d = doc_with("compose_two", "\n");
12309        d.caret = 0;
12310        d.edit_composing(0, 0, "か");
12311        d.edit_composing(0, 3, "蚊");
12312        d.end_composition();
12313        d.edit_composing(3, 3, "き");
12314        d.edit_composing(3, 6, "木");
12315        d.end_composition();
12316        assert_eq!(d.source, "蚊木\n");
12317        d.undo();
12318        assert_eq!(d.source, "蚊\n", "only the second composition");
12319        d.undo();
12320        assert_eq!(d.source, "\n");
12321    }
12322
12323    #[test]
12324    fn a_composition_does_not_fold_into_the_typing_around_it() {
12325        let mut d = doc_with("compose_typing", "\n");
12326        d.caret = 0;
12327        d.insert("a");
12328        d.insert("b");
12329        d.edit_composing(2, 2, "か");
12330        d.edit_composing(2, 5, "蚊");
12331        d.end_composition();
12332        d.insert("c");
12333        assert_eq!(d.source, "ab蚊c\n");
12334        d.undo();
12335        assert_eq!(d.source, "ab蚊\n");
12336        d.undo();
12337        assert_eq!(d.source, "ab\n");
12338        d.undo();
12339        assert_eq!(d.source, "\n");
12340    }
12341
12342    #[test]
12343    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
12344        let mut d = doc_with("compose_spurious", "\n");
12345        d.caret = 0;
12346        d.insert("a");
12347        d.end_composition(); // an IME unmarking unprompted
12348        d.insert("b");
12349        assert_eq!(d.source, "ab\n");
12350        d.undo();
12351        assert_eq!(d.source, "\n", "still one typed run");
12352    }
12353
12354    // ── the clipboard's rich flavor ──────────────────────────────────────────
12355
12356    #[test]
12357    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
12358        let mut d = doc_with("sel_inline", "a **bold** c\n");
12359        d.anchor = Some(2);
12360        d.caret = 10; // `**bold**`, inside the paragraph
12361        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
12362    }
12363
12364    #[test]
12365    fn a_whole_block_selection_keeps_its_paragraph() {
12366        let mut d = doc_with("sel_block", "a **bold** c\n");
12367        d.anchor = Some(0);
12368        d.caret = 12; // the entire paragraph
12369        assert_eq!(
12370            d.selection_html().as_deref(),
12371            Some("<p>a <strong>bold</strong> c</p>")
12372        );
12373    }
12374
12375    #[test]
12376    fn a_multi_block_selection_keeps_its_structure() {
12377        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
12378        d.select_all();
12379        let html = d.selection_html().expect("renders");
12380        assert!(html.contains("<p>para</p>"), "{html:?}");
12381        assert!(html.contains("<li>one</li>"), "{html:?}");
12382    }
12383
12384    #[test]
12385    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
12386        // The fragment `Head` is a paragraph standalone; the *document* says it
12387        // sits inside one block, so the wrapper is an artifact either way.
12388        let mut d = doc_with("sel_heading", "# Head line\n");
12389        d.anchor = Some(2);
12390        d.caret = 6;
12391        assert_eq!(d.selection_html().as_deref(), Some("Head"));
12392    }
12393
12394    #[test]
12395    fn no_selection_publishes_no_html() {
12396        let mut d = doc_with("sel_none", "a b\n");
12397        d.caret = 1;
12398        assert_eq!(d.selection_html(), None);
12399    }
12400
12401    #[test]
12402    fn pasting_html_converts_it_and_is_one_undo_step() {
12403        let mut d = doc_with("paste_html", "x\n");
12404        d.caret = 1;
12405        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
12406        assert_eq!(d.source, "xa **b** c\n");
12407        d.undo();
12408        assert_eq!(d.source, "x\n", "the whole paste, in one step");
12409    }
12410
12411    #[test]
12412    fn pasting_html_replaces_the_selection() {
12413        let mut d = doc_with("paste_html_sel", "keep drop\n");
12414        d.anchor = Some(5);
12415        d.caret = 9;
12416        assert!(d.paste_html("<em>new</em>"));
12417        assert_eq!(d.source, "keep *new*\n");
12418    }
12419
12420    #[test]
12421    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
12422        let mut d = doc_with("paste_html_bad", "x\n");
12423        d.caret = 1;
12424        // twig builds no table from HTML; raw `<table>` in prose is worse than
12425        // the plain flavor the caller still holds.
12426        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
12427        assert_eq!(d.source, "x\n", "declined edits nothing");
12428    }
12429
12430    #[test]
12431    fn copy_then_paste_round_trips_through_the_html_flavor() {
12432        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
12433        d.select_all();
12434        let html = d.selection_html().expect("renders");
12435        let mut into = doc_with("clip_round_dst", "\n");
12436        into.caret = 0;
12437        assert!(into.paste_html(&html));
12438        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
12439    }
12440
12441    #[test]
12442    fn moving_the_caret_starts_a_new_undo_group() {
12443        let mut d = doc_with("break", "\n");
12444        d.caret = 0;
12445        d.insert("a");
12446        d.insert("b"); // "ab\n", caret at 2
12447        d.move_left(false); // breaks the run
12448        d.insert("X"); // "aXb\n"
12449        assert_eq!(d.source, "aXb\n");
12450        d.undo();
12451        assert_eq!(
12452            d.source, "ab\n",
12453            "first undo removes only the post-move insert"
12454        );
12455        d.undo();
12456        assert_eq!(d.source, "\n", "second undo removes the earlier run");
12457    }
12458
12459    #[test]
12460    fn undo_reverses_a_format_toggle() {
12461        let mut d = doc_with("fmt_undo", "a word b\n");
12462        d.anchor = Some(2);
12463        d.caret = 6;
12464        d.toggle(InlineKind::Strong);
12465        assert_eq!(d.source, "a **word** b\n");
12466        d.undo();
12467        assert_eq!(d.source, "a word b\n");
12468    }
12469
12470    #[test]
12471    fn undo_back_to_the_saved_state_clears_dirty() {
12472        let mut d = doc_with("dirty_undo", "hello\n");
12473        assert!(!d.dirty);
12474        d.caret = 5;
12475        d.insert("!");
12476        assert!(d.dirty);
12477        d.undo();
12478        assert!(
12479            !d.dirty,
12480            "undoing to the saved source is not a modification"
12481        );
12482    }
12483
12484    #[test]
12485    fn a_new_edit_invalidates_redo() {
12486        let mut d = doc_with("redo_inv", "\n");
12487        d.caret = 0;
12488        d.insert("a");
12489        d.undo();
12490        d.insert("b"); // diverges — the redo of "a" is now gone
12491        d.redo();
12492        assert_eq!(d.source, "b\n");
12493    }
12494
12495    #[test]
12496    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
12497        let mut d = doc_with("can_undo", "hello\n");
12498        assert!(
12499            !d.can_undo() && !d.can_redo(),
12500            "a fresh document has no history"
12501        );
12502        d.caret = 5;
12503        d.insert("!");
12504        assert!(
12505            d.can_undo() && !d.can_redo(),
12506            "an edit is a step to take back"
12507        );
12508        d.undo();
12509        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
12510        d.redo();
12511        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
12512        d.undo();
12513        d.insert("?");
12514        assert!(
12515            d.can_undo() && !d.can_redo(),
12516            "a fresh edit ends the redo chain"
12517        );
12518        // A coalesced run over-counts steps — the bound is what a menu needs,
12519        // and it reconciles the moment twig reports the history empty.
12520        d.insert("a");
12521        d.insert("b");
12522        while d.can_undo() {
12523            d.undo();
12524        }
12525        assert_eq!(d.source, "hello\n");
12526        assert!(!d.can_undo());
12527        // A reading surface has nothing to undo, whatever the history holds.
12528        d.redo();
12529        d.set_read_only(true);
12530        assert!(!d.can_undo() && !d.can_redo());
12531    }
12532
12533    #[test]
12534    fn undo_on_empty_history_is_a_no_op() {
12535        let mut d = doc_with("undo_empty", "hi\n");
12536        d.undo();
12537        assert_eq!(d.source, "hi\n");
12538        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
12539    }
12540
12541    #[test]
12542    fn a_one_character_paste_is_its_own_undo_step() {
12543        for view in [View::Source, View::Wysiwyg] {
12544            let mut d = doc_in(view, "paste_step", "ab\n");
12545            d.caret = 0;
12546            d.insert("x");
12547            d.insert("y"); // a run of typing
12548            d.paste("z"); // one character, but pasted — not part of that run
12549            assert_eq!(d.source, "xyzab\n");
12550            d.undo();
12551            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
12552            assert_eq!(d.caret, 2, "and hands back the caret it found");
12553            d.undo();
12554            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
12555        }
12556    }
12557
12558    #[test]
12559    fn the_same_character_typed_still_joins_the_run() {
12560        // The other half of the pair: `z` is a keystroke here and a paste above,
12561        // and the two undo differently. Nothing about the *string* says which —
12562        // which is why provenance has to come from the door the caller uses.
12563        for view in [View::Source, View::Wysiwyg] {
12564            let mut d = doc_in(view, "typed_run", "ab\n");
12565            d.caret = 0;
12566            d.insert("x");
12567            d.insert("y");
12568            d.insert("z");
12569            d.undo();
12570            assert_eq!(d.source, "ab\n", "one run, one step");
12571        }
12572    }
12573
12574    #[test]
12575    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
12576        for view in [View::Source, View::Wysiwyg] {
12577            let mut d = doc_in(view, "undo_caret", "hello world\n");
12578            d.caret = 11; // standing at the end of "world", away from the edit
12579            d.edit(0, 5, "goodbye");
12580            assert_eq!(d.source, "goodbye world\n");
12581            d.undo();
12582            assert_eq!(d.source, "hello world\n");
12583            // The undone edit ends at offset 5; the user was at 11.
12584            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
12585        }
12586    }
12587
12588    #[test]
12589    fn undo_restores_the_selection_the_edit_replaced() {
12590        for view in [View::Source, View::Wysiwyg] {
12591            let mut d = doc_in(view, "undo_sel", "a word b\n");
12592            d.anchor = Some(2);
12593            d.caret = 6; // "word" selected
12594            d.insert("X");
12595            assert_eq!(d.source, "a X b\n");
12596            d.undo();
12597            assert_eq!(d.source, "a word b\n");
12598            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
12599        }
12600    }
12601
12602    #[test]
12603    fn redo_restores_the_caret_the_edit_left_behind() {
12604        for view in [View::Source, View::Wysiwyg] {
12605            let mut d = doc_in(view, "redo_caret", "hello world\n");
12606            d.caret = 11;
12607            d.edit(0, 5, "goodbye");
12608            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
12609            d.undo();
12610            d.redo();
12611            assert_eq!(d.source, "goodbye world\n");
12612            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
12613        }
12614    }
12615
12616    #[test]
12617    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
12618        for view in [View::Source, View::Wysiwyg] {
12619            let mut d = doc_in(view, "run_caret", "hi\n");
12620            d.caret = 2;
12621            d.insert("a");
12622            d.insert("b");
12623            d.insert("c");
12624            assert_eq!(d.source, "hiabc\n");
12625            d.undo();
12626            assert_eq!(d.source, "hi\n");
12627            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
12628            d.redo();
12629            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
12630        }
12631    }
12632
12633    #[test]
12634    fn undo_restores_the_caret_across_a_format_toggle() {
12635        // A toggle reaches twig without going through `splice`, so it has to
12636        // record its own step — miss it and every stack depth below it is off by
12637        // one, and undo starts handing back another edit's caret.
12638        for view in [View::Source, View::Wysiwyg] {
12639            let mut d = doc_in(view, "fmt_caret", "a word b\n");
12640            d.caret = 8;
12641            d.anchor = Some(2);
12642            d.caret = 6;
12643            d.toggle(InlineKind::Strong);
12644            assert_eq!(d.source, "a **word** b\n");
12645            d.undo();
12646            assert_eq!(d.source, "a word b\n");
12647            assert_eq!(
12648                d.selection(),
12649                Some((2, 6)),
12650                "the toggled selection comes back"
12651            );
12652        }
12653    }
12654
12655    #[test]
12656    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
12657        // The drift that would never announce itself: twig drops its redo stack
12658        // on any fresh edit, so a leaf redo entry that outlives it would restore
12659        // a caret from the timeline that edit abandoned.
12660        for view in [View::Source, View::Wysiwyg] {
12661            let mut d = doc_in(view, "redo_trunc", "hello world\n");
12662            d.caret = 11;
12663            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
12664            d.undo();
12665            assert_eq!(d.caret, 11);
12666            d.caret = 0;
12667            d.insert("X"); // diverges: A's redo is gone from twig
12668            assert_eq!(d.source, "Xhello world\n");
12669
12670            d.redo();
12671            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
12672            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
12673            d.undo();
12674            assert_eq!(d.source, "hello world\n");
12675            assert_eq!(
12676                d.caret, 0,
12677                "the surviving step's caret, not the dropped one"
12678            );
12679        }
12680    }
12681
12682    #[test]
12683    fn indent_and_outdent_move_the_caret_line_with_its_text() {
12684        for view in [View::Source, View::Wysiwyg] {
12685            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
12686            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
12687            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
12688            // Indentation the caret is standing *in* collapses to the line start
12689            // rather than dragging the caret into the text.
12690            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
12691            // A line with none to give back is left exactly as it was.
12692            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
12693            // Less than a full level gives back what it has.
12694            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
12695            // A tab is one level however many spaces it isn't.
12696            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
12697        }
12698    }
12699
12700    #[test]
12701    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
12702        // Why the level is two spaces and not the four both frontends type
12703        // today. Four is markdown's indented-code-block marker, so a Tab on a
12704        // paragraph would silently restyle it as code — a width that changes
12705        // what the document *means* isn't an indent. Pinned because the number
12706        // is the kind of thing a later list-aware pass would reach for.
12707        let mut d = doc_with("indent_kind", "hello\n");
12708        d.caret = 2;
12709        d.indent();
12710        assert_eq!(d.source, "  hello\n");
12711        assert!(
12712            d.nodes().iter().any(|n| n.kind == Kind::Para),
12713            "still prose after a Tab"
12714        );
12715        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
12716
12717        // The four-space level this replaces, for contrast: same text, and twig
12718        // reparses the paragraph into a code block.
12719        let mut wide = doc_with("indent_kind_4", "    hello\n");
12720        wide.build_visual(80);
12721        assert!(
12722            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
12723            "four spaces is a code block, not an indented paragraph"
12724        );
12725    }
12726
12727    #[test]
12728    fn indent_nests_a_list_item_under_its_parent() {
12729        // Tab indents a list item by its own marker width, landing its marker at
12730        // the parent's content column so twig reparses it as a nested list.
12731        for view in [View::Source, View::Wysiwyg] {
12732            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
12733            d.caret = 6; // on the second item
12734            d.indent();
12735            assert_eq!(d.source, "- a\n  - b\n");
12736            let lists = d
12737                .nodes()
12738                .iter()
12739                .filter(|n| n.kind == Kind::BulletList)
12740                .count();
12741            assert_eq!(lists, 2, "the indented item is a nested list");
12742        }
12743    }
12744
12745    #[test]
12746    fn indent_nests_an_ordered_item_at_its_marker_width() {
12747        // An ordered marker `1. ` is three columns wide, so a two-space step
12748        // (which nests a bullet) leaves it flat. Regression: Tab must use the
12749        // marker width, three, so the item actually nests — and the source
12750        // renumbers so the sub-list restarts at 1 and the outer list resumes.
12751        for view in [View::Source, View::Wysiwyg] {
12752            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
12753            d.caret = d.source.find('b').unwrap();
12754            d.indent();
12755            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
12756            let lists = d
12757                .nodes()
12758                .iter()
12759                .filter(|n| n.kind == Kind::OrderedList)
12760                .count();
12761            assert_eq!(lists, 2, "the indented item is a nested ordered list");
12762        }
12763    }
12764
12765    #[test]
12766    fn indent_leaves_a_lists_first_item_put() {
12767        // The first item of a list has no sibling above it to nest under, so Tab
12768        // is a no-op there — the marker stays at column zero rather than being
12769        // shoved into indentation twig can't read as a sub-list.
12770        for view in [View::Source, View::Wysiwyg] {
12771            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
12772            d.caret = 1; // on the FIRST item
12773            d.indent();
12774            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
12775            // The sibling below still nests, proving the guard is per-item.
12776            d.caret = d.source.find('b').unwrap();
12777            d.indent();
12778            assert_eq!(d.source, "- a\n  - b\n");
12779        }
12780    }
12781
12782    #[test]
12783    fn hidden_mode_keeps_typed_markup_literal() {
12784        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
12785        // twig escapes what would open markup, so the source is `\*hi\*` and the
12786        // AST is a plain string. Formatting is the commands' job in this mode.
12787        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
12788        d.insert("*hi*");
12789        assert_eq!(d.source, "\\*hi\\*");
12790        assert!(
12791            d.nodes()
12792                .iter()
12793                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
12794        );
12795    }
12796
12797    #[test]
12798    fn hidden_mode_escapes_a_line_start_block_marker() {
12799        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
12800        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
12801        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
12802        d.insert("# hi");
12803        assert_eq!(d.source, "\\# hi");
12804        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
12805    }
12806
12807    #[test]
12808    fn authoring_modes_keep_typed_markup_live() {
12809        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
12810        // (no escape), the same as source view — escaping is `None`'s alone, and
12811        // it's the axis, not the reveal, that decides.
12812        for (view, mode) in [
12813            (View::Wysiwyg, MarkupMode::Shortcuts),
12814            (View::Wysiwyg, MarkupMode::Full),
12815            (View::Source, MarkupMode::None),
12816        ] {
12817            let mut d = doc_in(view, "live_markup", "");
12818            d.set_markup_mode(mode);
12819            d.insert("*hi*");
12820            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
12821        }
12822    }
12823
12824    #[test]
12825    fn hidden_mode_overwrite_undoes_in_one_step() {
12826        // Typing over a selection escapes the replacement *and* stays a single
12827        // undo — the selection-delete and the literal insert fold together, so
12828        // one undo brings the whole selection back, like a plain overwrite.
12829        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
12830        d.anchor = Some(2);
12831        d.caret = 6; // "word"
12832        d.insert("*");
12833        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
12834        d.undo();
12835        assert_eq!(d.source, "a word b\n");
12836        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
12837    }
12838
12839    #[test]
12840    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
12841        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
12842        // the whole visual character, never stranding the hidden `\`.
12843        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
12844        d.insert("*");
12845        assert_eq!(d.source, "\\*");
12846        d.backspace();
12847        assert_eq!(d.source, "", "the escape backslash went with the *");
12848        // A *literal* backslash (source view, no escape) is an ordinary char.
12849        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
12850        s.caret = 3; // after `b`
12851        s.backspace();
12852        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
12853    }
12854
12855    #[test]
12856    fn hidden_mode_leaves_structural_markup_alone() {
12857        // Enter continues a bullet list by writing a real `- ` marker (an
12858        // `insert_raw`, not the typing path), so Hidden mode's escaping never
12859        // touches it — the list keeps working.
12860        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
12861        d.caret = 6;
12862        d.newline();
12863        d.insert("two");
12864        assert_eq!(d.source, "- item\n- two\n");
12865    }
12866
12867    #[test]
12868    fn markup_mode_defaults_to_none_and_round_trips() {
12869        // Diaryx's default is the clean `None` surface; a markup-fluent
12870        // frontend can climb the ladder, and the choice sticks.
12871        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
12872        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
12873        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
12874            d.set_markup_mode(mode);
12875            assert_eq!(d.markup_mode(), mode);
12876        }
12877    }
12878
12879    #[test]
12880    fn full_mode_reveals_only_the_caret_line() {
12881        // The mode's whole claim: the caret's line shows its raw delimiters and
12882        // every other line stays resolved. Two paragraphs with identical markup
12883        // so the only difference between the rows is where the caret is.
12884        let mut d = doc_in(
12885            View::Wysiwyg,
12886            "reveal_caret_line",
12887            "*one* here\n\n*two* there\n",
12888        );
12889        d.set_markup_mode(MarkupMode::Full);
12890
12891        caret_at(&mut d, "one");
12892        let rows = drawn_rows(&d);
12893        assert!(
12894            rows.iter().any(|r| r == "*one* here"),
12895            "caret's line raw: {rows:?}"
12896        );
12897        assert!(
12898            rows.iter().any(|r| r == "two there"),
12899            "other line resolved: {rows:?}"
12900        );
12901
12902        // Move to the other paragraph: the reveal follows, and the line just
12903        // left goes back to being resolved.
12904        caret_at(&mut d, "two");
12905        let rows = drawn_rows(&d);
12906        assert!(
12907            rows.iter().any(|r| r == "*two* there"),
12908            "caret's line raw: {rows:?}"
12909        );
12910        assert!(
12911            rows.iter().any(|r| r == "one here"),
12912            "left line resolved: {rows:?}"
12913        );
12914    }
12915
12916    #[test]
12917    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
12918        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
12919        // the same treatment as an emphasis's `*`: hidden while the caret is
12920        // elsewhere, shown in full where the caret lands. That falls out of
12921        // `delims` reading the bytes between the mark's span and its content
12922        // span, which is exactly `==🔴 ` and `==`, rather than from a table
12923        // of spellings — so the no-space form `==🟢green==` reveals right too.
12924        let mut d = doc_in(
12925            View::Wysiwyg,
12926            "reveal_coloured_mark",
12927            "a ==🔴 red== one\n\nb ==plain== two\n",
12928        );
12929        d.set_markup_mode(MarkupMode::Full);
12930
12931        caret_at(&mut d, "red");
12932        let rows = drawn_rows(&d);
12933        assert!(
12934            rows.iter().any(|r| r == "a ==🔴 red== one"),
12935            "the caret's line shows the colour it was written with: {rows:?}"
12936        );
12937        assert!(
12938            rows.iter().any(|r| r == "b plain two"),
12939            "and every other line stays resolved: {rows:?}"
12940        );
12941
12942        // Away from it, the emoji goes back to being markup — the reader sees
12943        // the words and the wash.
12944        caret_at(&mut d, "two");
12945        let rows = drawn_rows(&d);
12946        assert!(
12947            rows.iter().any(|r| r == "a red one"),
12948            "resolved again: {rows:?}"
12949        );
12950    }
12951
12952    #[test]
12953    fn hidden_modes_never_reveal_wherever_the_caret_is() {
12954        // The two rungs below `Full` share a rendering: delimiters stay hidden
12955        // even under the caret. `Shortcuts` differing from `None` only in what
12956        // typing does is exactly the point of splitting the axes.
12957        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
12958            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
12959            d.set_markup_mode(mode);
12960            caret_at(&mut d, "one");
12961            let rows = drawn_rows(&d);
12962            assert!(
12963                rows.iter().any(|r| r == "one here"),
12964                "{mode:?} hides: {rows:?}"
12965            );
12966            assert!(
12967                !rows.iter().any(|r| r.contains('*')),
12968                "{mode:?} shows no `*`: {rows:?}"
12969            );
12970        }
12971    }
12972
12973    #[test]
12974    fn revealed_delimiters_are_the_authors_own_spelling() {
12975        // Delimiters are re-read from the source rather than synthesized per
12976        // kind, so a line comes back spelled the way it was written: `_em_` does
12977        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
12978        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
12979        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
12980        d.set_markup_mode(MarkupMode::Full);
12981        caret_at(&mut d, "em");
12982        let rows = drawn_rows(&d);
12983        assert!(
12984            rows.iter().any(|r| r == body.trim_end()),
12985            "the revealed line is its own source: {rows:?}"
12986        );
12987    }
12988
12989    #[test]
12990    fn revealed_heading_shows_its_hashes() {
12991        // The `# ` marker is a block-level prefix, not an inline delimiter, so
12992        // it takes its own path — but it reveals on the same rule.
12993        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
12994        d.set_markup_mode(MarkupMode::Full);
12995
12996        caret_at(&mut d, "Title");
12997        assert!(
12998            drawn_rows(&d).iter().any(|r| r == "# Title"),
12999            "{:?}",
13000            drawn_rows(&d)
13001        );
13002
13003        caret_at(&mut d, "body");
13004        let rows = drawn_rows(&d);
13005        assert!(
13006            rows.iter().any(|r| r == "Title"),
13007            "hashes hidden again: {rows:?}"
13008        );
13009    }
13010
13011    #[test]
13012    fn revealed_delimiters_are_caret_stops() {
13013        // A delimiter that is drawn but can't be reached is worse than one
13014        // that's hidden: the mode exists so the markup can be *edited*. Every
13015        // revealed byte must be somewhere the caret can stand.
13016        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
13017        d.set_markup_mode(MarkupMode::Full);
13018        caret_at(&mut d, "em");
13019        let opener = d.source.find('*').unwrap();
13020        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
13021        assert!(
13022            d.vmap.is_stop(opener + 3),
13023            "the closing `*` is a caret stop"
13024        );
13025    }
13026
13027    #[test]
13028    fn setext_heading_reveals_nothing_across_its_newline() {
13029        // A setext heading's underline is on another line, so it is not the
13030        // caret line's to reveal — and emitting it would inject a `\n` glyph
13031        // that splits the row where the author wrote no break.
13032        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
13033        d.set_markup_mode(MarkupMode::Full);
13034        caret_at(&mut d, "Title");
13035        let rows = drawn_rows(&d);
13036        assert!(
13037            rows.iter().any(|r| r == "Title"),
13038            "title renders alone: {rows:?}"
13039        );
13040        assert!(
13041            !rows.iter().any(|r| r.contains('=')),
13042            "no underline leaks in: {rows:?}"
13043        );
13044    }
13045
13046    #[test]
13047    fn markup_mode_axes_split_the_ladder() {
13048        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
13049        // that authors markup but still hides it, and it's the only rung where
13050        // the two axes disagree.
13051        assert!(!MarkupMode::None.authors());
13052        assert!(!MarkupMode::None.reveals_caret_line());
13053        assert!(MarkupMode::Shortcuts.authors());
13054        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
13055        assert!(MarkupMode::Full.authors());
13056        assert!(MarkupMode::Full.reveals_caret_line());
13057    }
13058
13059    #[test]
13060    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
13061        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
13062        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
13063        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
13064        // nested bullet and `hello` stays prose: the file round-trips instead of
13065        // hiding a heading the user never asked for.
13066        for view in [View::Source, View::Wysiwyg] {
13067            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
13068            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
13069            d.indent();
13070            assert_eq!(d.source, "- hello\n  * \n");
13071            assert!(
13072                d.nodes().iter().all(|n| n.kind != Kind::Heading),
13073                "no heading"
13074            );
13075            // And it's genuinely a nested list, not a flat one.
13076            assert_eq!(
13077                d.nodes()
13078                    .iter()
13079                    .filter(|n| n.kind == Kind::BulletList)
13080                    .count(),
13081                2
13082            );
13083        }
13084    }
13085
13086    #[test]
13087    fn indenting_a_dash_item_with_content_keeps_its_dash() {
13088        // With content, `- x` can't be a setext underline, so there's nothing to
13089        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
13090        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
13091        d.caret = d.source.find('x').unwrap();
13092        d.indent();
13093        assert_eq!(d.source, "- hello\n  - x\n");
13094    }
13095
13096    #[test]
13097    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
13098        // The dash→`*` repair coalesces into the Tab, so a single undo restores
13099        // the whole pre-Tab state rather than stranding a half-collapsed doc.
13100        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
13101        d.caret = d.source.find("- \n").unwrap() + 2;
13102        d.indent();
13103        assert_eq!(d.source, "- hello\n  * \n");
13104        d.undo();
13105        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
13106    }
13107
13108    #[test]
13109    fn indent_leaves_a_nested_lists_first_item_put_too() {
13110        // The guard is about siblings, not depth: the first item of an *inner*
13111        // list (already nested under `a`) still has nothing before it at its own
13112        // level, so Tab can't take it deeper.
13113        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
13114        d.caret = d.source.find('b').unwrap();
13115        d.indent();
13116        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
13117        // But `c` (a sibling of `b`) nests under `b`.
13118        d.caret = d.source.find('c').unwrap();
13119        d.indent();
13120        assert_eq!(d.source, "- a\n  - b\n    - c\n");
13121    }
13122
13123    #[test]
13124    fn backspace_at_a_nested_item_start_outdents_it() {
13125        // Backspace with the caret right after a nested item's marker gives back
13126        // one level of nesting, the mirror of Tab — and renumbers the flattened
13127        // ordered list back to a clean run.
13128        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
13129        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
13130        d.backspace();
13131        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
13132    }
13133
13134    #[test]
13135    fn backspace_at_a_top_level_item_start_strips_the_marker() {
13136        // At the outermost level there's no nesting left to give back, so the same
13137        // keystroke drops the bullet and leaves a plain paragraph.
13138        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
13139        d.caret = d.source.find('b').unwrap(); // right after `- `
13140        d.backspace();
13141        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
13142    }
13143
13144    #[test]
13145    fn backspace_mid_item_still_deletes_a_character() {
13146        // The list behaviour is armed only at the item's content start; anywhere
13147        // else Backspace is the ordinary character delete.
13148        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
13149        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
13150        d.backspace();
13151        assert_eq!(d.source, "- b\n");
13152    }
13153
13154    #[test]
13155    fn backspace_at_a_heading_start_strips_the_marker() {
13156        // The `# ` is markup the rich view hides, so Backspace over it takes the
13157        // whole marker and leaves a paragraph. Deleting a byte of it instead left
13158        // `#Title` — no longer a heading, with the hash now literal text the user
13159        // never typed and has to delete again.
13160        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
13161        d.caret = d.source.find('T').unwrap(); // right after `## `
13162        d.backspace();
13163        assert_eq!(d.source, "Title\n");
13164        assert_eq!(
13165            d.caret, 0,
13166            "the caret stays with the text it was in front of"
13167        );
13168    }
13169
13170    #[test]
13171    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
13172        // Only the heading's own marker goes — the quote (or list) it sits in is
13173        // untouched, exactly as un-heading it should be.
13174        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
13175        d.caret = d.source.find('T').unwrap();
13176        d.backspace();
13177        assert_eq!(d.source, "> Title\n");
13178    }
13179
13180    #[test]
13181    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
13182        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
13183        // behind would surface the same stray hash the marker delete just avoided.
13184        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
13185        d.caret = d.source.find('T').unwrap();
13186        d.backspace();
13187        assert_eq!(d.source, "Title\n");
13188        // And it's one edit: a single undo puts the whole heading back.
13189        d.undo();
13190        assert_eq!(d.source, "# Title #\n");
13191    }
13192
13193    #[test]
13194    fn backspace_mid_heading_still_deletes_a_character() {
13195        // The heading behaviour is armed only at the content's start; anywhere
13196        // else Backspace is the ordinary character delete.
13197        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
13198        d.caret = d.source.find('b').unwrap();
13199        d.backspace();
13200        assert_eq!(d.source, "# b\n");
13201    }
13202
13203    #[test]
13204    fn source_view_backspace_still_edits_the_heading_marker_literally() {
13205        // In source view the `# ` is text on the screen the user is deleting a
13206        // byte of, so it keeps its literal meaning — the same split the list
13207        // ladder and Enter draw between the two views.
13208        let mut d = doc_with("bsp_head_src", "# Title\n");
13209        d.caret = d.source.find('T').unwrap();
13210        d.backspace();
13211        assert_eq!(d.source, "#Title\n");
13212    }
13213
13214    #[test]
13215    fn outdent_unnests_an_ordered_item_in_one_press() {
13216        // Shift+Tab gives back exactly the marker width the indent added, so a
13217        // nested ordered item unnests in a single press, and the flattened list
13218        // renumbers back to a clean 1, 2, 3.
13219        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
13220        d.caret = d.source.find('b').unwrap();
13221        d.outdent();
13222        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
13223        let lists = d
13224            .nodes()
13225            .iter()
13226            .filter(|n| n.kind == Kind::OrderedList)
13227            .count();
13228        assert_eq!(lists, 1, "back to one flat list");
13229    }
13230
13231    #[test]
13232    fn table_insert_row_adds_a_row_below_the_caret() {
13233        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
13234        d.caret = d.source.find('1').unwrap(); // in the body row
13235        d.table_insert_row(true);
13236        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
13237    }
13238
13239    #[test]
13240    fn table_insert_and_delete_column_at_the_caret() {
13241        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
13242        d.caret = d.source.find('a').unwrap(); // column 0
13243        d.table_insert_column(true); // add a column to the right of `a`
13244        assert_eq!(
13245            d.source,
13246            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
13247        );
13248        d.caret = d.source.find('b').unwrap(); // now the third column
13249        d.table_delete_column();
13250        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
13251    }
13252
13253    // ── ragged formats ───────────────────────────────────────────────────────
13254    // No format spells every gesture. HTML writes the inline marks as a tag pair
13255    // and no heading, list, quote or link; Markdown spells five of the eight
13256    // marks — the highlight only because leaf parses with `highlight`, which is
13257    // why the question is asked with the extensions; djot spells all eight and
13258    // no in-cell break. leaf asks twig per
13259    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
13260    // op discover the fact on its own — one of them didn't.
13261
13262    /// An HTML document in the rich view, ready for a gesture.
13263    fn html_doc(body: &str) -> Doc {
13264        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
13265        d.view = View::Wysiwyg;
13266        d.build_visual(80);
13267        d
13268    }
13269
13270    #[test]
13271    fn a_table_gesture_leaves_an_html_table_alone() {
13272        // The regression this guard exists for. twig's table editor consults no
13273        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
13274        // HTML `<table>` as a *pipe table* and reported success: the whole
13275        // element replaced by `| a | b |`, silently, on one press of a toolbar
13276        // button. Every grid op went the same way.
13277        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
13278        // A table of named operations, which is what it looks like.
13279        #[allow(clippy::type_complexity)]
13280        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
13281            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
13282            ("delete row", &|d: &mut Doc| d.table_delete_row()),
13283            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
13284            ("delete column", &|d: &mut Doc| d.table_delete_column()),
13285            ("align", &|d: &mut Doc| {
13286                d.table_set_alignment(Alignment::Right)
13287            }),
13288            ("move row", &|d: &mut Doc| d.table_move_row(true)),
13289            ("move column", &|d: &mut Doc| d.table_move_column(true)),
13290        ];
13291        for (name, op) in ops {
13292            let mut d = html_doc(src);
13293            d.caret = d.source.find('a').unwrap();
13294            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
13295            op(&mut d);
13296            assert_eq!(d.source, src, "{name} rewrote an HTML table");
13297            assert!(
13298                !d.dirty,
13299                "{name} marked the document dirty without editing it"
13300            );
13301            assert!(d.status.is_some(), "{name} refused without saying why");
13302        }
13303    }
13304
13305    #[test]
13306    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
13307        // A task box is a form control in HTML and a footnote has no native
13308        // spelling at all — the two gestures twig 3.5 still spells nothing
13309        // for, now that a quote, a list, a link and an image print through
13310        // its renderer (see the test below).
13311        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
13312        // A table of named operations, which is what it looks like.
13313        #[allow(clippy::type_complexity)]
13314        let ops: [(&str, &dyn Fn(&mut Doc)); 3] = [
13315            ("task item", &|d: &mut Doc| d.toggle_task_item()),
13316            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
13317            ("footnote", &|d: &mut Doc| d.insert_footnote()),
13318        ];
13319        for (name, op) in ops {
13320            let mut d = html_doc(src);
13321            let at = d.source.find("Hello").unwrap();
13322            d.caret = at;
13323            d.anchor = Some(at + 5); // a selection, for the ops that want one
13324            op(&mut d);
13325            assert_eq!(d.source, src, "{name} edited an HTML document");
13326            assert!(
13327                !d.dirty,
13328                "{name} marked the document dirty without editing it"
13329            );
13330            let status = d.status.as_deref().unwrap_or("");
13331            assert!(
13332                status.contains("html"),
13333                "{name}: the refusal should name the format, got {status:?}"
13334            );
13335        }
13336    }
13337
13338    #[test]
13339    fn html_spells_a_quote_a_list_a_link_and_an_image_through_the_renderer() {
13340        // twig 3.5: where HTML has no marker alphabet it prints the fresh
13341        // node — a `<blockquote>` around the paragraph, a `<ul>`/`<ol>` with
13342        // the paragraph as its item, an `<a>` or `<img>` over the selection.
13343        // Until then every one of these was a refusal; now each is a real
13344        // edit, which is what the toolbar's capability flags say too.
13345        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
13346        #[allow(clippy::type_complexity)]
13347        let ops: [(&str, &dyn Fn(&mut Doc), &str); 5] = [
13348            (
13349                "quote",
13350                &|d: &mut Doc| d.toggle_blockquote(),
13351                "<blockquote>",
13352            ),
13353            ("list", &|d: &mut Doc| d.toggle_list(false), "<ul>\n<li>"),
13354            (
13355                "ordered list",
13356                &|d: &mut Doc| d.toggle_list(true),
13357                "<ol>\n<li>",
13358            ),
13359            (
13360                "link",
13361                &|d: &mut Doc| d.insert_link("https://example.dev"),
13362                "<a href=\"https://example.dev\">Hello</a>",
13363            ),
13364            (
13365                "image",
13366                &|d: &mut Doc| d.insert_image("pic.png", "alt"),
13367                "<img alt=\"Hello\" src=\"pic.png\">",
13368            ),
13369        ];
13370        for (name, op, expect) in ops {
13371            let mut d = html_doc(src);
13372            let at = d.source.find("Hello").unwrap();
13373            d.caret = at;
13374            d.anchor = Some(at + 5);
13375            op(&mut d);
13376            assert!(d.source.contains(expect), "{name}: got {:?}", d.source);
13377            assert!(d.dirty, "{name}: a real edit");
13378            assert_eq!(
13379                d.status, None,
13380                "{name}: a supported gesture reports nothing"
13381            );
13382        }
13383    }
13384
13385    #[test]
13386    fn html_spells_a_heading_as_its_tag_pair() {
13387        // twig 3.4 rebuilds a heading or paragraph as its tag pair, attributes
13388        // along — the one block gesture whose HTML shape it can write. So ⌘2
13389        // in an HTML document is a real edit, and ⌘0 takes it back.
13390        let src = "<h1>Title</h1>\n<p>Hello world</p>\n";
13391        let mut d = html_doc(src);
13392        d.caret = d.source.find("Hello").unwrap();
13393        d.toggle_heading(2);
13394        assert_eq!(d.source, "<h1>Title</h1>\n<h2>Hello world</h2>\n");
13395        assert!(d.dirty);
13396        assert_eq!(d.status, None, "a supported gesture reports nothing");
13397        d.toggle_heading(2);
13398        assert_eq!(d.source, src, "the same level again is back to a paragraph");
13399    }
13400
13401    #[test]
13402    fn html_spells_the_inline_marks_and_the_rule() {
13403        // The other half, and why one per-document flag stopped being enough:
13404        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
13405        // already emits and the parser reads straight back as the same mark —
13406        // and the rule button writes an `<hr>`. Refusing these on the old
13407        // "HTML is parse-only" reading would now be leaf's own limitation.
13408        let mut d = html_doc("<p>Hello world</p>\n");
13409        let at = d.source.find("world").unwrap();
13410        d.caret = at;
13411        d.anchor = Some(at + 5);
13412        d.toggle(InlineKind::Strong);
13413        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
13414        assert!(d.dirty);
13415        assert_eq!(d.status, None, "a supported gesture reports nothing");
13416
13417        // And off again — the toggle reverses, which is the property that makes
13418        // authoring in HTML worth offering rather than a one-way trip.
13419        d.toggle(InlineKind::Strong);
13420        assert_eq!(d.source, "<p>Hello world</p>\n");
13421
13422        let mut d = html_doc("<p>Hello world</p>\n");
13423        d.caret = d.source.find("world").unwrap();
13424        d.insert_thematic_break();
13425        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
13426    }
13427
13428    #[test]
13429    fn a_mark_the_format_cannot_spell_arms_nothing() {
13430        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
13431        // sticky mark for the next text typed. Guarding only the twig call
13432        // leaves that path live, promising a mark the gesture will not write and
13433        // then swallowing the error inside `insert`.
13434        //
13435        // Markdown carries this, on the superscript now rather than on the
13436        // highlight: `^x^` is text there in any configuration, whereas twig
13437        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
13438        // which every leaf document does.
13439        let mut d = doc_with("mark", "Hello world\n");
13440        d.view = View::Wysiwyg;
13441        d.build_visual(80);
13442        d.caret = d.source.find("world").unwrap();
13443        d.toggle(InlineKind::Superscript);
13444        assert!(d.pending_marks.is_empty(), "no mark should be armed");
13445        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
13446        d.insert("X");
13447        assert_eq!(d.source, "Hello Xworld\n");
13448    }
13449
13450    #[test]
13451    fn markdown_authors_a_highlight_and_a_strikethrough() {
13452        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
13453        // write. `==x==` is authorable because leaf's own `parse_extensions`
13454        // turns `highlight` on — twig will only mint bytes this editor's reparse
13455        // reads back — and `~~x~~` because GFM strikethrough is parsed by
13456        // default, so the refusal there was never right for any leaf document.
13457        for (kind, marked) in [
13458            (InlineKind::Mark, "a ==word== b\n"),
13459            (InlineKind::Delete, "a ~~word~~ b\n"),
13460        ] {
13461            let mut d = doc_with("author_mark", "a word b\n");
13462            d.anchor = Some(2);
13463            d.caret = 6;
13464            d.toggle(kind);
13465            assert_eq!(d.source, marked, "{kind:?}");
13466            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
13467            assert!(d.dirty, "{kind:?}");
13468            // The region stays selected, so the second press reverses it — the
13469            // property that separates authoring from a one-way trip.
13470            d.toggle(kind);
13471            assert_eq!(d.source, "a word b\n", "{kind:?}");
13472        }
13473    }
13474
13475    #[test]
13476    fn an_authored_highlight_reads_back_as_a_mark() {
13477        // The round trip the extension gate exists to protect: what the toggle
13478        // writes, the reparse must read back as a `mark` rather than as two
13479        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
13480        // rebuilt map rather than from the source text.
13481        let mut d = doc_with("mark_roundtrip", "a word b\n");
13482        d.view = View::Wysiwyg;
13483        d.build_visual(80);
13484        d.anchor = Some(2);
13485        d.caret = 6;
13486        d.toggle(InlineKind::Mark);
13487        assert_eq!(d.source, "a ==word== b\n");
13488        d.build_visual(80);
13489        let w = d
13490            .vmap
13491            .rows
13492            .iter()
13493            .flat_map(|r| r.glyphs.iter())
13494            .find(|g| g.ch == 'w')
13495            .expect("the highlighted word");
13496        assert_eq!(w.style.role, crate::Role::Mark(None));
13497    }
13498
13499    #[test]
13500    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
13501        // The three states of one gesture, in the order a palette is pressed:
13502        // an uncoloured highlight takes the prefix, a coloured one has it
13503        // replaced, and `None` takes it away with the space that was part of the
13504        // spelling.
13505        let mut d = doc_with("mark_colour", "a ==word== b\n");
13506        d.caret = d.source.find("word").unwrap();
13507        d.set_mark_color(Some(MarkColor::Red));
13508        assert_eq!(d.source, "a ==🔴 word== b\n");
13509        assert_eq!(d.status, None);
13510        assert!(d.dirty);
13511
13512        d.set_mark_color(Some(MarkColor::Blue));
13513        assert_eq!(d.source, "a ==🔵 word== b\n");
13514
13515        d.set_mark_color(None);
13516        assert_eq!(d.source, "a ==word== b\n");
13517    }
13518
13519    #[test]
13520    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
13521        // The prefix is written *before* the word, so an offset in the word has
13522        // to ride its width — a caret that stayed put would be a caret that
13523        // walked backwards through the text it was standing in.
13524        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
13525        let word = d.source.find("word").unwrap();
13526        d.caret = word + 2; // between `wo` and `rd`
13527        d.set_mark_color(Some(MarkColor::Red));
13528        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
13529
13530        // And back the other way when the prefix goes.
13531        d.set_mark_color(None);
13532        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
13533    }
13534
13535    #[test]
13536    fn the_colour_at_the_caret_is_what_the_palette_lights() {
13537        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
13538        d.caret = d.source.find("red").unwrap();
13539        assert!(d.caret_in_mark());
13540        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
13541
13542        d.caret = d.source.find("plain").unwrap();
13543        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
13544        assert_eq!(d.mark_color_at_caret(), None);
13545
13546        d.caret = d.source.find(" and ").unwrap() + 2;
13547        assert!(!d.caret_in_mark());
13548        assert_eq!(d.mark_color_at_caret(), None);
13549    }
13550
13551    #[test]
13552    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
13553        // The gesture colours a highlight that exists; it does not make one.
13554        // Two presses is the price of a coloured highlight from bare text, and
13555        // the reason is undo — one press that spliced twice would take two
13556        // presses to take back.
13557        let mut d = doc_with("mark_colour_none", "a word b\n");
13558        d.caret = d.source.find("word").unwrap();
13559        d.set_mark_color(Some(MarkColor::Red));
13560        assert_eq!(d.source, "a word b\n");
13561        assert!(d.status.is_some(), "it should say why");
13562        assert!(!d.dirty);
13563
13564        // Clearing where there is nothing to clear is the same refusal, not a
13565        // quiet success — the caret is in no highlight either way.
13566        d.status = None;
13567        d.set_mark_color(None);
13568        assert_eq!(d.source, "a word b\n");
13569        assert!(d.status.is_some());
13570    }
13571
13572    #[test]
13573    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
13574        // twig answers this one *successfully* with a `Change` describing some
13575        // earlier edit, so a caller that trusted the change would jump the caret
13576        // to wherever that was. Core answers it before asking.
13577        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
13578        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
13579        d.caret = d.source.find("word").unwrap();
13580        let (source, caret) = (d.source.clone(), d.caret);
13581        d.set_mark_color(None);
13582        assert_eq!(d.source, source);
13583        assert_eq!(
13584            d.caret, caret,
13585            "the caret must not ride a change that isn't one"
13586        );
13587        assert_eq!(d.status, None, "and it is not an error either");
13588    }
13589
13590    #[test]
13591    fn djot_spells_the_highlight_and_not_its_colour() {
13592        // The reason the palette is its own capability rather than the Highlight
13593        // button's: `{=word=}` is a highlight djot writes happily, and there is
13594        // no djot spelling for a colour on it.
13595        assert!(Capabilities::of(Format::Djot).mark);
13596        assert!(!Capabilities::of(Format::Djot).mark_color);
13597        assert!(Capabilities::of(Format::Markdown).mark_color);
13598
13599        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
13600        d.caret = d.source.find("word").unwrap();
13601        assert!(
13602            d.caret_in_mark(),
13603            "the caret is in a highlight all the same"
13604        );
13605        d.set_mark_color(Some(MarkColor::Red));
13606        assert_eq!(d.source, "a {=word=} b\n");
13607        assert!(
13608            d.status.as_deref().unwrap_or("").contains("djot"),
13609            "and the refusal names the document's format: {:?}",
13610            d.status
13611        );
13612    }
13613
13614    #[test]
13615    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
13616        // The round trip that matters for a palette: the bytes twig writes are
13617        // bytes its own reparse reads back as a colour, so the swatch that was
13618        // pressed is the swatch that lights afterwards.
13619        let mut d = doc_with("mark_colour_undo", "a word b\n");
13620        d.anchor = Some(2);
13621        d.caret = 6;
13622        d.toggle(InlineKind::Mark);
13623        d.caret = d.source.find("word").unwrap();
13624        d.set_mark_color(Some(MarkColor::Green));
13625        assert_eq!(d.source, "a ==🟢 word== b\n");
13626        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
13627
13628        // One splice, one step: the colour comes off and the highlight stays.
13629        d.undo();
13630        assert_eq!(d.source, "a ==word== b\n");
13631        d.undo();
13632        assert_eq!(d.source, "a word b\n");
13633    }
13634
13635    #[test]
13636    fn every_colour_leaf_names_is_one_twig_writes() {
13637        // The two enums are one vocabulary, and this is what says so: each of
13638        // leaf's colours writes an emoji twig's reparse reads back as *that*
13639        // colour, so `twig_mark_color`'s table cannot quietly pair red with
13640        // orange.
13641        for color in MarkColor::ALL {
13642            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
13643            d.caret = d.source.find("word").unwrap();
13644            d.set_mark_color(Some(color));
13645            assert_eq!(d.status, None, "{color:?}");
13646            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
13647        }
13648    }
13649
13650    #[test]
13651    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
13652        // The two presses a coloured highlight is made of, in the state the
13653        // first one leaves: `toggle` selects the whole `==word==` and puts the
13654        // caret one past the closing `==`, which is *not* in the mark. Asking at
13655        // the caret alone would refuse to colour the highlight just written —
13656        // the selection's start is what answers.
13657        let mut d = doc_with("mark_colour_fresh", "a word b\n");
13658        d.anchor = Some(2);
13659        d.caret = 6;
13660        d.toggle(InlineKind::Mark);
13661        assert_eq!(d.source, "a ==word== b\n");
13662        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
13663
13664        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
13665        d.set_mark_color(Some(MarkColor::Yellow));
13666        assert_eq!(d.source, "a ==🟡 word== b\n");
13667        assert_eq!(d.status, None);
13668    }
13669
13670    #[test]
13671    fn one_press_highlights_a_selection_and_colours_it() {
13672        // What a toolbar swatch means over a plain selection, and the undo it
13673        // has to have: one press, one step. Two steps would leave an uncoloured
13674        // highlight behind on the way back, which is a state the author never
13675        // asked for and never saw.
13676        let mut d = doc_with("highlight_one", "a word b\n");
13677        d.anchor = Some(2);
13678        d.caret = 6;
13679        d.highlight(Some(MarkColor::Purple));
13680        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
13681        assert_eq!(d.status, None);
13682
13683        d.undo();
13684        assert_eq!(d.source, "a word b\n", "one press, one undo");
13685    }
13686
13687    #[test]
13688    fn one_press_on_an_existing_highlight_only_recolours_it() {
13689        // The other half: inside a highlight there is nothing to make, so the
13690        // compound is the plain gesture and the text is untouched.
13691        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
13692        d.caret = d.source.find("word").unwrap();
13693        d.highlight(Some(MarkColor::Blue));
13694        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
13695        d.undo();
13696        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
13697    }
13698
13699    #[test]
13700    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
13701        // `None` means "no colour", and over bare text that is the Highlight
13702        // button's own job. The fold must not happen here — there is no second
13703        // splice, and folding would take the *previous* edit into this one.
13704        let mut d = doc_with("highlight_none", "a word b and more\n");
13705        d.caret = d.source.find("more").unwrap() + 4; // after "more"
13706        d.insert("!"); // an earlier edit for a wrong fold to swallow
13707        d.anchor = Some(2);
13708        d.caret = 6;
13709        d.highlight(None);
13710        assert_eq!(d.source, "a ==word== b and more!\n");
13711
13712        d.undo();
13713        assert_eq!(
13714            d.source, "a word b and more!\n",
13715            "only the highlight came off"
13716        );
13717        d.undo();
13718        assert_eq!(
13719            d.source, "a word b and more\n",
13720            "and the edit before it survived"
13721        );
13722    }
13723
13724    #[test]
13725    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
13726        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
13727        // a colour cannot be armed with it — so the compound declines rather
13728        // than leaving half a promise.
13729        let mut d = doc_with("highlight_bare", "a word b\n");
13730        d.caret = 4;
13731        d.highlight(Some(MarkColor::Red));
13732        assert_eq!(d.source, "a word b\n");
13733        assert!(d.pending_marks.is_empty(), "and nothing armed");
13734        assert!(d.status.is_some());
13735    }
13736
13737    #[test]
13738    fn a_read_only_document_takes_no_colour() {
13739        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
13740        d.caret = d.source.find("word").unwrap();
13741        d.set_read_only(true);
13742        d.set_mark_color(Some(MarkColor::Red));
13743        assert_eq!(d.source, "a ==word== b\n");
13744    }
13745
13746    #[test]
13747    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
13748        // The other door into `toggle`: no selection, so nothing reaches twig
13749        // until `insert` realises the armed mark. It is armed now — the guard
13750        // above asks `Doc::supports`, which asks with the extensions — and what
13751        // it writes is the same `==…==`.
13752        let mut d = doc_with("sticky_mark", "xy\n");
13753        d.caret = 1;
13754        d.toggle(InlineKind::Mark);
13755        assert!(d.pending_marks.contains(InlineKind::Mark));
13756        d.insert("Z");
13757        assert_eq!(d.source, "x==Z==y\n");
13758    }
13759
13760    #[test]
13761    fn html_documents_still_take_typed_text() {
13762        // The guard covers *markup* gestures and must not touch plain editing:
13763        // twig's splicer is language-neutral, and typing into an HTML document
13764        // is the thing that does work today.
13765        let mut d = html_doc("<p>Hello world</p>\n");
13766        d.caret = d.source.find("world").unwrap();
13767        d.insert("big ");
13768        assert_eq!(d.source, "<p>Hello big world</p>\n");
13769        assert!(d.dirty);
13770        d.backspace();
13771        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
13772        d.undo();
13773        d.undo();
13774        assert_eq!(d.source, "<p>Hello world</p>\n");
13775    }
13776
13777    #[test]
13778    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
13779        // `authorable` only separates "there is a door in" from "there is not",
13780        // and HTML is on the near side of that line — which is exactly why a
13781        // toolbar must not be built from it.
13782        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
13783        assert!(html.authorable());
13784        assert!(
13785            !Doc::from_source("<r>x</r>".into(), Format::Xml)
13786                .unwrap()
13787                .authorable()
13788        );
13789
13790        let caps = html.capabilities();
13791        assert!(caps.bold && caps.italic && caps.code && caps.mark);
13792        assert!(caps.thematic_break && caps.cell_line_break);
13793        // A heading is a tag pair twig rebuilds (3.4), and since 3.5 so are a
13794        // quote, a list, a code block's language, a link and an image — each
13795        // printed as a fresh node where HTML has no marker to rewrite. A task
13796        // box is a form control and a footnote has no spelling, so those two
13797        // are what keeps the record ragged.
13798        assert!(caps.heading && caps.blockquote && caps.bullet_list);
13799        assert!(caps.link && caps.image && caps.code_language);
13800        assert!(!caps.task && !caps.footnote);
13801        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
13802        // twig's table editor would happily re-emit as `| a | b |`.
13803        assert!(!caps.table);
13804
13805        // The two lightweight formats spell everything leaf offers — and still
13806        // differ from each other, which is the other half of why one boolean
13807        // can't serve.
13808        for fmt in [Format::Markdown, Format::Djot] {
13809            let caps = Capabilities::of(fmt);
13810            assert!(
13811                caps.heading && caps.blockquote && caps.ordered_list,
13812                "{fmt:?}"
13813            );
13814            assert!(
13815                caps.task && caps.link && caps.image && caps.table,
13816                "{fmt:?}"
13817            );
13818        }
13819        // Both spell the highlight and the strikethrough: djot natively, and
13820        // Markdown because `Capabilities` asks with `parse_extensions` rather
13821        // than with twig's defaults — `==x==` is text under those, and a mark
13822        // under the `highlight` leaf always parses with.
13823        for fmt in [Format::Markdown, Format::Djot] {
13824            let caps = Capabilities::of(fmt);
13825            assert!(caps.mark && caps.strike, "{fmt:?}");
13826        }
13827        // What still separates them, now that the highlight doesn't: djot has
13828        // no in-cell break, and Markdown spells neither of the scripts.
13829        assert!(Capabilities::of(Format::Djot).superscript);
13830        assert!(!Capabilities::of(Format::Markdown).superscript);
13831        assert!(Capabilities::of(Format::Markdown).cell_line_break);
13832        assert!(!Capabilities::of(Format::Djot).cell_line_break);
13833
13834        // A parse-only format answers no to every one of them, so the coarse
13835        // predicate and the record agree there.
13836        let caps = Capabilities::of(Format::Xml);
13837        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
13838    }
13839
13840    #[test]
13841    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
13842        // The guard exists to name the *document's* format rather than twig's
13843        // internals, so the message has to survive being one leaf writes itself.
13844        // Checked against a gesture twig also refuses, since that is the pair
13845        // most at risk of drifting apart — the task box, once the code
13846        // language stopped being one (twig 3.5).
13847        let mut d = html_doc("<p>Hello</p>\n");
13848        d.caret = d.source.find("Hello").unwrap();
13849        d.toggle_task_item();
13850        assert_eq!(d.status.as_deref(), Some("task: not supported in html"));
13851        assert!(!d.dirty);
13852    }
13853
13854    #[test]
13855    fn table_set_alignment_respells_the_delimiter() {
13856        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
13857        d.caret = d.source.find('b').unwrap();
13858        d.table_set_alignment(Alignment::Right);
13859        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
13860    }
13861
13862    #[test]
13863    fn each_empty_table_cell_has_its_own_editable_home() {
13864        // Regression: an empty cell has no twig content_span, so both cells of a
13865        // `|  |  |` row collapsed onto the row's start (before the first `│`).
13866        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
13867        // tell the cells apart. Each empty cell must now have a distinct home
13868        // inside it.
13869        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
13870        let (c0, c1) = {
13871            let cells = &d.vmap.tables[0].grid[1].cells;
13872            (cells[0].start, cells[1].start)
13873        };
13874        assert!(
13875            c0 < c1,
13876            "the two empty cells have distinct homes: {c0} < {c1}"
13877        );
13878        d.caret = c0;
13879        d.insert("x");
13880        assert_eq!(
13881            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
13882            "typed inside the cell"
13883        );
13884    }
13885
13886    #[test]
13887    fn arrows_step_into_each_empty_table_cell() {
13888        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
13889        let (c0, c1) = {
13890            let cells = &d.vmap.tables[0].grid[1].cells;
13891            (cells[0].start, cells[1].start)
13892        };
13893        d.caret = d.source.find('b').unwrap(); // in the header's second cell
13894        let mut seen = std::collections::HashSet::new();
13895        for _ in 0..6 {
13896            d.move_right(false);
13897            seen.insert(d.caret);
13898        }
13899        assert!(
13900            seen.contains(&c0),
13901            "right arrow reaches the first empty cell"
13902        );
13903        assert!(
13904            seen.contains(&c1),
13905            "right arrow reaches the second empty cell"
13906        );
13907    }
13908
13909    #[test]
13910    fn table_op_off_a_table_is_a_no_op_with_a_status() {
13911        let mut d = doc_with("tbl_none", "just text\n");
13912        d.caret = 3;
13913        d.table_insert_row(true);
13914        assert_eq!(d.source, "just text\n", "nothing changed");
13915        assert!(d.status.is_some(), "a status explains why");
13916        assert!(!d.caret_in_table());
13917    }
13918
13919    #[test]
13920    fn enter_in_an_ordered_list_renumbers_the_following_items() {
13921        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
13922        // the renumber pass keeps them sequential, matching what the view draws.
13923        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
13924        d.caret = d.source.find('a').unwrap() + 1; // end of item a
13925        d.newline();
13926        d.insert("x");
13927        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
13928    }
13929
13930    #[test]
13931    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
13932        for view in [View::Source, View::Wysiwyg] {
13933            let mut d = doc_in(view, "outdent_noop", "hello\n");
13934            d.caret = 2;
13935            d.outdent();
13936            assert_eq!(d.source, "hello\n");
13937            assert!(!d.dirty, "a no-op is not a modification");
13938            d.undo();
13939            assert_eq!(
13940                d.status.as_deref(),
13941                Some("nothing to undo"),
13942                "spends no undo step"
13943            );
13944            assert_eq!(d.source, "hello\n");
13945        }
13946    }
13947
13948    #[test]
13949    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
13950        for view in [View::Source, View::Wysiwyg] {
13951            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
13952            d.anchor = Some(0);
13953            d.caret = 7; // through "two"
13954            d.indent();
13955            assert_eq!(
13956                d.source, "  one\n\n  two\n",
13957                "the blank line keeps no trailing pad"
13958            );
13959            // Selected, so a second Tab lands on the same lines rather than on
13960            // whatever the shifted offsets now cover.
13961            assert_eq!(d.selection(), Some((0, 12)));
13962            d.indent();
13963            assert_eq!(d.source, "    one\n\n    two\n");
13964        }
13965    }
13966
13967    #[test]
13968    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
13969        for view in [View::Source, View::Wysiwyg] {
13970            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
13971            d.anchor = Some(0);
13972            d.caret = 15;
13973            d.outdent();
13974            assert_eq!(d.source, "two\none\nnone\n");
13975        }
13976    }
13977
13978    #[test]
13979    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
13980        for view in [View::Source, View::Wysiwyg] {
13981            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
13982            d.anchor = Some(0);
13983            d.caret = 7;
13984            d.indent();
13985            assert_eq!(d.source, "  one\n\n  two\n");
13986            d.undo();
13987            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
13988            assert_eq!(
13989                d.selection(),
13990                Some((0, 7)),
13991                "with the selection it was aimed at"
13992            );
13993            d.redo();
13994            assert_eq!(d.source, "  one\n\n  two\n");
13995            assert_eq!(
13996                d.selection(),
13997                Some((0, 12)),
13998                "redo replays the caret the indent placed, not the one splice left"
13999            );
14000        }
14001    }
14002
14003    #[test]
14004    fn vertical_motion_keeps_the_column() {
14005        let mut d = doc_with("move", "abcd\nef\n");
14006        d.caret = 3; // "abc|d" on row 0, col 3
14007        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
14008        assert_eq!(d.caret, 7); // just after "ef"
14009    }
14010
14011    // ── goal column ──────────────────────────────────────────────────────────
14012
14013    #[test]
14014    fn vertical_motion_goal_column_survives_a_short_line() {
14015        // Regression: re-deriving the column from the clamped position on
14016        // every step permanently forgets it once a short line clamps it.
14017        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
14018        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
14019        assert_eq!(
14020            g("abcd|ef\nxy\nghijkl\n", |d| {
14021                d.move_down(false); // clamps to end of "xy"
14022                d.move_down(false); // restores col 4 on the long line
14023            }),
14024            "abcdef\nxy\nghij|kl\n"
14025        );
14026    }
14027
14028    #[test]
14029    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
14030        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
14031        assert_eq!(d.goal_col, None);
14032        d.caret = 4; // row 0, col 4
14033        d.move_down(false); // clamps into "xy"; goal stays the original col
14034        assert_eq!(d.goal_col, Some(4));
14035        assert_eq!(d.caret_pos(), (1, 2));
14036
14037        // A horizontal motion drops the goal column...
14038        d.move_left(false);
14039        assert_eq!(d.goal_col, None);
14040
14041        // ...so the next vertical motion picks up the *new* column (1), not
14042        // the stale one (4).
14043        d.move_down(false);
14044        assert_eq!(d.goal_col, Some(1));
14045        assert_eq!(d.caret_pos(), (2, 1));
14046    }
14047
14048    #[test]
14049    fn editing_clears_the_goal_column() {
14050        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
14051        d.caret = 4;
14052        d.move_down(false);
14053        assert_eq!(d.goal_col, Some(4));
14054        d.insert("Z");
14055        assert_eq!(d.goal_col, None);
14056    }
14057
14058    #[test]
14059    fn vertical_motion_on_an_empty_document_is_a_no_op() {
14060        let mut d = doc_with("empty_vert", "");
14061        d.move_down(false);
14062        assert_eq!(d.caret, 0);
14063        d.move_up(false);
14064        assert_eq!(d.caret, 0);
14065    }
14066
14067    // ── the document's edges ─────────────────────────────────────────────────
14068
14069    #[test]
14070    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
14071        // The reproduction, and the disagreement: Down on the last line ran to
14072        // the end of the document in the source view — by accident, an
14073        // out-of-range row clamping to the end of the string — and did nothing
14074        // whatever in the view leaf opens in. One rule now, in both.
14075        for (view, tag) in VIEWS {
14076            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
14077            d.caret = 1;
14078            d.move_down(false);
14079            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
14080            d.move_up(false);
14081            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
14082        }
14083    }
14084
14085    #[test]
14086    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
14087        // Down off the bottom is a motion like any other, so it latches a goal
14088        // column — and Up comes back to the column the caret left, not to the
14089        // one the document's end happened to be in.
14090        for (view, tag) in VIEWS {
14091            let gap = if view == View::Source { "\n" } else { "\n\n" };
14092            let src = format!("abcdef{gap}ghijkl");
14093            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
14094            d.caret = 2; // row 0, col 2
14095            d.move_down(false);
14096            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
14097            d.move_down(false);
14098            assert_eq!(
14099                d.caret,
14100                src.len(),
14101                "{tag}: Down off the bottom reaches the end"
14102            );
14103            d.move_up(false);
14104            assert_eq!(
14105                d.caret_pos().1,
14106                2,
14107                "{tag}: Up returns to the column Down left"
14108            );
14109        }
14110    }
14111
14112    #[test]
14113    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
14114        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
14115        // Up that did nothing still armed a goal column, and the next Down aimed
14116        // at a column the caret had never been in.
14117        for (view, tag) in VIEWS {
14118            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
14119            d.caret = 0;
14120            d.move_up(false);
14121            assert_eq!(d.caret, 0, "{tag}: already at the start");
14122            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
14123
14124            d.caret = d.source.len();
14125            d.move_down(false);
14126            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
14127            assert_eq!(
14128                d.goal_col, None,
14129                "{tag}: a no-op Down latched a goal column"
14130            );
14131        }
14132    }
14133
14134    // ── soft wrap ────────────────────────────────────────────────────────────
14135    // Every other test here builds the map at 80 columns, where no fixture is
14136    // long enough to fold. A wrap is where one offset belongs to two rows at
14137    // once, and it broke everything that asks the caret what row it is on.
14138
14139    /// The wrapped fixture these cases share, folded at 12 columns into
14140    /// `one two ` / `three four ` / `five six ` / `seven eight`.
14141    fn wrapped_doc(name: &str) -> Doc {
14142        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
14143        d.build_visual(12);
14144        d
14145    }
14146
14147    #[test]
14148    fn home_and_end_work_from_a_wrapped_row() {
14149        // The reproduction: offset 19 is the `f` of "five", the first character
14150        // of the third row — and also the offset the second row ends at. It
14151        // resolved to the *second* row, so End aimed at a place the caret was
14152        // already in and did nothing, while Home walked backwards onto a row the
14153        // caret had left.
14154        let mut d = wrapped_doc("wrap_home_end");
14155        d.caret = 19;
14156        assert_eq!(
14157            d.caret_pos(),
14158            (2, 0),
14159            "the wrap boundary opens the third row"
14160        );
14161        d.move_end(false);
14162        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
14163        d.move_home(false);
14164        assert_eq!(d.caret, 19, "Home left the row the caret was on");
14165    }
14166
14167    #[test]
14168    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
14169        // The row's end is the last offset that is only ever its own: the offset
14170        // past it opens the row below, and aiming there would send a second
14171        // press on to *that* row's end, and a third to the next — End walking
14172        // down the paragraph rather than sitting where it landed.
14173        let mut d = wrapped_doc("wrap_end_twice");
14174        d.caret = 12; // inside "three", on the second row
14175        d.move_end(false);
14176        assert_eq!(
14177            d.caret, 18,
14178            "the end of `three four`, before the space the wrap ate"
14179        );
14180        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
14181        d.move_end(false);
14182        assert_eq!(d.caret, 18, "a second End moved the caret");
14183        d.move_home(false);
14184        assert_eq!(d.caret, 8, "Home takes the row's own start");
14185    }
14186
14187    #[test]
14188    fn vertical_motion_crosses_a_soft_wrap() {
14189        // Down aimed at the row below's column 0, an offset that resolved *up*
14190        // to the row above's end — so it landed on the offset it already had and
14191        // the caret could never leave a paragraph's first row.
14192        let mut d = wrapped_doc("wrap_down");
14193        d.caret = 0;
14194        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
14195            d.move_down(false);
14196            assert_eq!(d.caret, want, "Down stalled");
14197            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
14198        }
14199        d.move_down(false);
14200        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
14201
14202        // ...and back up, one row per press. The goal column is the end of the
14203        // last row, past every other row's width, so each press clamps to the
14204        // row's own last offset rather than to the one that opens the next.
14205        let mut d = wrapped_doc("wrap_up");
14206        d.caret = 39;
14207        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
14208            d.move_up(false);
14209            assert_eq!(d.caret, want, "Up stalled");
14210            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
14211        }
14212    }
14213
14214    #[test]
14215    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
14216        // The kills take the same line Home and End do, so in WYSIWYG they take
14217        // the visual row — and a soft wrap has no newline in it to delete, so
14218        // nothing is joined by reaching the end of one.
14219        let mut d = wrapped_doc("wrap_kill");
14220        d.caret = 19; // the `f` of "five", opening the third row
14221        d.delete_to_line_end();
14222        // The space the wrap ate goes with the row it was drawn on: sparing it
14223        // would leave "four  seven", two spaces where the row had been.
14224        assert_eq!(d.source, "one two three four seven eight");
14225
14226        // Backwards from the row's last caret position — which is *before* that
14227        // space, so this one survives, being on the far side of the caret.
14228        let mut d = wrapped_doc("wrap_kill_back");
14229        d.caret = 27;
14230        d.delete_to_line_start();
14231        assert_eq!(d.source, "one two three four  seven eight");
14232    }
14233
14234    // ── document start / end ────────────────────────────────────────────────
14235
14236    #[test]
14237    fn move_doc_start_and_end_jump_to_the_edges() {
14238        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
14239        assert_eq!(
14240            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
14241            "|hello\nworld\n"
14242        );
14243        assert_eq!(
14244            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
14245            "hello\nworld\n|"
14246        );
14247        // Already at the edge: a no-op.
14248        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
14249        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
14250    }
14251
14252    #[test]
14253    fn move_doc_start_and_end_extend_the_selection() {
14254        assert_eq!(
14255            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
14256                .move_doc_end(true)),
14257            "hello wor[ld\n|]"
14258        );
14259        assert_eq!(
14260            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
14261                .move_doc_start(true)),
14262            "[|hello wor]ld\n"
14263        );
14264    }
14265
14266    #[test]
14267    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
14268        let mut d = doc_with("empty_edges", "");
14269        d.move_doc_end(false);
14270        assert_eq!(d.caret, 0);
14271        d.move_doc_start(false);
14272        assert_eq!(d.caret, 0);
14273    }
14274
14275    // ── arrow collapses an active selection ─────────────────────────────────
14276
14277    #[test]
14278    fn arrow_collapses_selection_to_its_near_edge() {
14279        let mut d = doc_with("collapse", "hello world\n");
14280
14281        // Forward selection (anchor before caret): Right -> end, Left -> start.
14282        d.anchor = Some(2);
14283        d.caret = 7;
14284        d.move_right(false);
14285        assert_eq!((d.caret, d.anchor), (7, None));
14286
14287        d.anchor = Some(2);
14288        d.caret = 7;
14289        d.move_left(false);
14290        assert_eq!((d.caret, d.anchor), (2, None));
14291
14292        // Backward selection (anchor after caret): edges are the same
14293        // regardless of which end the caret started on.
14294        d.anchor = Some(7);
14295        d.caret = 2;
14296        d.move_right(false);
14297        assert_eq!((d.caret, d.anchor), (7, None));
14298
14299        d.anchor = Some(7);
14300        d.caret = 2;
14301        d.move_left(false);
14302        assert_eq!((d.caret, d.anchor), (2, None));
14303    }
14304
14305    #[test]
14306    fn arrow_with_extend_keeps_growing_the_selection() {
14307        let mut d = doc_with("collapse_extend", "hello world\n");
14308        d.anchor = Some(2);
14309        d.caret = 7;
14310        d.move_right(true); // extend: no collapse, caret steps one further
14311        assert_eq!((d.caret, d.anchor), (8, Some(2)));
14312    }
14313
14314    #[test]
14315    fn arrow_without_a_selection_moves_one_character_as_before() {
14316        let mut d = doc_with("no_collapse", "hello\n");
14317        d.caret = 2;
14318        d.move_right(false);
14319        assert_eq!(d.caret, 3);
14320        d.move_left(false);
14321        assert_eq!(d.caret, 2);
14322    }
14323
14324    /// Press Right until it stops, collecting the offsets walked through. Every
14325    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
14326    /// two stops sharing one source offset can't be moved between, so the caret
14327    /// stalls on the first of them and the walk never reaches the rest.
14328    fn walk_right(d: &mut Doc) -> Vec<usize> {
14329        let mut seen = vec![d.caret];
14330        for _ in 0..2000 {
14331            let before = d.caret;
14332            d.move_right(false);
14333            if d.caret == before {
14334                break;
14335            }
14336            seen.push(d.caret);
14337        }
14338        seen
14339    }
14340
14341    #[test]
14342    fn the_caret_crosses_a_soft_break() {
14343        // A newline inside a paragraph is a `soft_break`, which twig gives no
14344        // span of its own — the space it renders as used to borrow the offset of
14345        // the character before it, and a caret can't move without changing
14346        // offset. Right must walk clean off the end of the first line.
14347        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
14348        d.caret = 0;
14349        let seen = walk_right(&mut d);
14350        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
14351    }
14352
14353    #[test]
14354    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
14355        // The paragraph holds one soft break. Folded (the default) it lays out as
14356        // a single reflowed row; Preserve re-lays it as a row per source line.
14357        // The setter must invalidate the cached map for the change to show, and
14358        // again on the way back — so a round trip returns to the folded layout.
14359        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
14360        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
14361        d.build_visual(80);
14362        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
14363
14364        d.set_line_flow(LineFlow::Preserve);
14365        d.build_visual(80);
14366        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
14367
14368        d.set_line_flow(LineFlow::Fold);
14369        d.build_visual(80);
14370        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
14371    }
14372
14373    #[test]
14374    fn the_caret_still_crosses_a_preserved_soft_break() {
14375        // Preserve renders the soft break as a row boundary rather than a space,
14376        // but the caret must still reach every offset — the break's own offset is
14377        // the first row's end stop, so Right walks clean off the end of line one
14378        // onto line two, exactly as it does when the break is folded.
14379        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
14380        d.set_line_flow(LineFlow::Preserve);
14381        d.build_visual(80);
14382        d.caret = 0;
14383        let seen = walk_right(&mut d);
14384        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
14385    }
14386
14387    #[test]
14388    fn the_caret_walks_a_code_block() {
14389        // Every glyph of a code block used to map to the block's start, so the
14390        // whole block was a single offset and the caret couldn't move inside it.
14391        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
14392        let mut d = wysiwyg_doc("code_walk", src);
14393        d.caret = 0;
14394        let seen = walk_right(&mut d);
14395        // The fences are markup: hidden, and no caret stop. The code between
14396        // them is reached a character at a time.
14397        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
14398        for off in code.clone() {
14399            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
14400        }
14401        assert!(seen.contains(&code.end), "no stop after the last line");
14402    }
14403
14404    #[test]
14405    fn the_caret_walks_an_indented_code_block() {
14406        // An indented block's text has the four-space indent stripped, so it
14407        // isn't a verbatim slice and its lines have to be re-found. The caret
14408        // lands on the code, never in the indent.
14409        let src = "    indented\n    code\n";
14410        let mut d = wysiwyg_doc("indent_code_walk", src);
14411        d.caret = 0;
14412        let seen = walk_right(&mut d);
14413        assert!(seen.contains(&src.find("indented").unwrap()));
14414        assert!(seen.contains(&src.find("code").unwrap()));
14415        assert!(
14416            !seen.contains(&0) || seen[0] == 0,
14417            "the caret starts where it was put"
14418        );
14419        // Nothing in the stripped indent is a stop.
14420        for off in [1, 2, 3] {
14421            assert!(!seen.contains(&off), "landed in the indent at {off}");
14422        }
14423    }
14424
14425    #[test]
14426    fn the_caret_leaves_a_tight_heading() {
14427        // "# H" with text directly under it: the heading row's end and the
14428        // separator row's end are the same offset. Right used to find the
14429        // separator's copy, set the caret to where it already was, and stop.
14430        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
14431        d.caret = 2; // the "H"
14432        let seen = walk_right(&mut d);
14433        assert!(
14434            seen.len() > 2,
14435            "Right stalled at the heading's end: {seen:?}"
14436        );
14437        assert!(
14438            seen.contains(&8),
14439            "never reached the end of \"text\": {seen:?}"
14440        );
14441    }
14442
14443    #[test]
14444    fn the_caret_skips_the_gap_between_two_paragraphs() {
14445        // The blank line between two paragraphs is the boundary itself. The
14446        // caret used to be able to sit on it, and typing there landed in the
14447        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
14448        // soft break, so the text visibly snapped back up.
14449        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
14450        d.caret = 1; // the end of "A"
14451        d.move_right(false);
14452        assert_eq!(d.caret, 3, "Right stopped in the gap");
14453        d.insert("x");
14454        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
14455    }
14456
14457    #[test]
14458    fn down_from_a_paragraph_lands_on_the_next_one() {
14459        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
14460        d.caret = 0;
14461        d.move_down(false);
14462        assert_eq!(d.caret, 3, "Down stopped in the gap");
14463    }
14464
14465    #[test]
14466    fn clicking_the_gap_lands_on_real_text() {
14467        // A click can still *reach* the gap — it's drawn, so it's clickable.
14468        // It has to resolve to somewhere the caret can be.
14469        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
14470        d.click(1, 0, false); // the gap row
14471        assert!(
14472            d.caret == 1 || d.caret == 3,
14473            "click left the caret in the gap at {}",
14474            d.caret
14475        );
14476        d.insert("x");
14477        // Either edge of the boundary is a fair place to land; inside it isn't.
14478        assert!(
14479            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
14480            "click in the gap typed into the boundary: {:?}",
14481            d.source
14482        );
14483    }
14484
14485    #[test]
14486    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
14487        // Enter inserts a paragraph break, which leaves a blank line spare on
14488        // either side of a new one. That middle line is a real empty paragraph:
14489        // the caret lands there, and typing makes a paragraph rather than
14490        // extending a neighbour.
14491        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
14492        d.caret = 1;
14493        d.newline();
14494        assert_eq!(d.source, "A\n\n\n\nB\n");
14495        d.build_visual(80);
14496        let (row, _) = d.caret_pos();
14497        assert!(
14498            d.vmap.row_is_navigable(row),
14499            "the caret landed on a gap row"
14500        );
14501        d.insert("x");
14502        assert_eq!(
14503            d.source, "A\n\nx\n\nB\n",
14504            "the new paragraph merged into a neighbour"
14505        );
14506    }
14507
14508    #[test]
14509    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
14510        let mut d = wysiwyg_doc("gap_eof", "A\n");
14511        d.caret = 1;
14512        d.newline();
14513        d.build_visual(80);
14514        let (row, _) = d.caret_pos();
14515        assert!(
14516            d.vmap.row_is_navigable(row),
14517            "the caret landed on a gap row"
14518        );
14519        d.insert("x");
14520        assert!(
14521            d.source.starts_with("A\n\n") && d.source.contains('x'),
14522            "typing at the end merged into A: {:?}",
14523            d.source
14524        );
14525    }
14526
14527    #[test]
14528    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
14529        // A paragraph broken over two source lines is one paragraph. Selecting
14530        // it must not stop at the newline inside it — that newline is markup the
14531        // rich-text view exists to hide.
14532        let src = "one two\nthree four\n\nnext\n";
14533        let mut d = wysiwyg_doc("triple_para", src);
14534        d.select_block_at(2);
14535        assert_eq!(
14536            d.selected_text(),
14537            Some("one two\nthree four"),
14538            "stopped at the soft break"
14539        );
14540    }
14541
14542    #[test]
14543    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
14544        // The reader scrolls down past the caret's row. Nothing moved the
14545        // caret, so the view must stay where it was put — the old code revealed
14546        // the caret every frame, which dragged the view straight back and made
14547        // the document unscrollable past the caret.
14548        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
14549        d.caret = 0;
14550        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
14551        d.scroll = 4; // the wheel
14552        d.follow_caret(0, 3, 9);
14553        assert_eq!(
14554            d.scroll, 4,
14555            "the wheel was overruled by a caret that never moved"
14556        );
14557    }
14558
14559    #[test]
14560    fn moving_the_caret_brings_the_view_back_to_it() {
14561        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
14562        d.caret = 0;
14563        d.follow_caret(0, 3, 9);
14564        d.scroll = 6; // scrolled away
14565        d.move_right(false); // ...and now the caret moves
14566        let (row, _) = d.caret_pos();
14567        d.follow_caret(row, 3, 9);
14568        assert!(
14569            d.scroll <= row && row < d.scroll + 3,
14570            "caret row {row} off screen at scroll {}",
14571            d.scroll
14572        );
14573    }
14574
14575    #[test]
14576    fn scrolling_stops_at_the_last_row() {
14577        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
14578        d.caret = 0;
14579        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
14580        d.scroll = 999; // the wheel, spun hard
14581        d.follow_caret(0, 3, 3);
14582        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
14583    }
14584
14585    #[test]
14586    fn every_cell_of_a_wide_table_is_reachable() {
14587        // A table whose cells are far wider than the surface: the columns are
14588        // cut to fit and the text wraps inside them, so no cell hangs off the
14589        // right edge where the caret can never go.
14590        let src = "| Ingredient | Notes |\n|---|---|\n\
14591                   | flour milled coarse | sift it twice before folding it in |\n";
14592        let mut d = wysiwyg_doc("wide_table_walk", src);
14593        d.build_visual(30);
14594        d.caret = 0;
14595        let seen = walk_right(&mut d);
14596        for word in ["Ingredient", "Notes", "coarse", "folding"] {
14597            let at = src.find(word).unwrap();
14598            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
14599        }
14600    }
14601
14602    // ── view parity ──────────────────────────────────────────────────────────
14603    // `doc_with` pins the source view, so everything above tests a view users
14604    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
14605    // deletion golden cases through *both*, plus the WYSIWYG cases the two
14606    // can't share: where the source carries markup the rendered text is a
14607    // different string, and the views agreeing would itself be the bug.
14608
14609    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
14610
14611    /// Run `action` in both views on one `|`-marked fixture and assert they
14612    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
14613    /// source verbatim, so the two views are looking at the same text and any
14614    /// disagreement is one of them having lost the plot.
14615    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
14616        let (src, caret) = parse_caret(marked);
14617        let run = |view: View, tag: &str| {
14618            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
14619            d.caret = caret;
14620            action(&mut d);
14621            render_caret(&d)
14622        };
14623        let source = run(VIEWS[0].0, VIEWS[0].1);
14624        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
14625        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
14626        source
14627    }
14628
14629    #[test]
14630    fn word_motion_agrees_across_the_views_on_plain_prose() {
14631        let g = both_views;
14632        assert_eq!(
14633            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
14634            "hello |world"
14635        );
14636        assert_eq!(
14637            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
14638            "|hello world"
14639        );
14640        assert_eq!(
14641            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
14642            "hello| world"
14643        );
14644        assert_eq!(
14645            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
14646            "hello world|"
14647        );
14648        assert_eq!(
14649            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
14650            "foo|.bar"
14651        );
14652        assert_eq!(
14653            g("par_ext", "hello |world", |d| d.move_word_right(true)),
14654            "hello [world|]"
14655        );
14656    }
14657
14658    #[test]
14659    fn word_deletion_agrees_across_the_views_on_plain_prose() {
14660        let g = both_views;
14661        assert_eq!(
14662            g("par_db", "hello world|", |d| d.delete_word_back()),
14663            "hello |"
14664        );
14665        assert_eq!(
14666            g("par_df", "hello |world", |d| d.delete_word_forward()),
14667            "hello |"
14668        );
14669        assert_eq!(
14670            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
14671            "|bar baz"
14672        );
14673        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
14674    }
14675
14676    #[test]
14677    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
14678        let g = both_views;
14679        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
14680        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
14681        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
14682        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
14683    }
14684
14685    #[test]
14686    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
14687        // The reproduction: the stop table was built one stop per `char`, so
14688        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
14689        // source view, which steps by grapheme, can't reach and backspace can't
14690        // survive. The two views must land on the same offset.
14691        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
14692        for (view, tag) in VIEWS {
14693            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
14694            d.caret = 1;
14695            d.move_right(false);
14696            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
14697
14698            // ...and the edit that used to sever a joiner off the front of it.
14699            d.backspace();
14700            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
14701            assert_eq!(d.caret, 1);
14702        }
14703    }
14704
14705    #[test]
14706    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
14707        for (view, tag) in VIEWS {
14708            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
14709            d.caret = 0;
14710            d.move_right(false);
14711            assert_eq!(
14712                d.caret,
14713                "e\u{0301}".len(),
14714                "{tag} stopped on the combining mark"
14715            );
14716        }
14717    }
14718
14719    #[test]
14720    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
14721        // The general form: whatever route the caret takes through a document
14722        // full of clusters, it never lands between the codepoints of one — so no
14723        // motion-then-backspace sequence can leave a dangling joiner behind.
14724        use unicode_segmentation::UnicodeSegmentation;
14725
14726        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
14727        let mut d = wysiwyg_doc("cluster_walk", src);
14728        d.caret = 0;
14729        let boundaries: Vec<usize> = src
14730            .grapheme_indices(true)
14731            .map(|(i, _)| i)
14732            .chain(std::iter::once(src.len()))
14733            .collect();
14734        for off in walk_right(&mut d) {
14735            assert!(
14736                boundaries.contains(&off),
14737                "Right stopped at {off}, inside a grapheme cluster"
14738            );
14739        }
14740    }
14741
14742    #[test]
14743    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
14744        // The reproduction: ⌥→ from inside the opening `**` computed its
14745        // boundary over the raw source and landed on byte 8 — inside the
14746        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
14747        // "bold". The caret drew past the bold word and sat inside it.
14748        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
14749        d.caret = 2;
14750        d.move_word_right(false);
14751        assert!(
14752            d.vmap.is_stop(d.caret),
14753            "landed at {}, not a caret stop",
14754            d.caret
14755        );
14756        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
14757        // The rendered row is "a bold c": column 6 is the space just past "bold",
14758        // and now the caret is really there rather than only drawn there.
14759        assert_eq!(d.caret_pos(), (0, 6));
14760
14761        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
14762        d.move_word_left(false);
14763        assert_eq!(d.caret, 4);
14764        assert_eq!(d.caret_pos(), (0, 2));
14765    }
14766
14767    #[test]
14768    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
14769        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
14770        // inside the closing `**`, and left "a ** c\n" — delimiters with no
14771        // opener. Glyph space covers the word alone, which would leave
14772        // "a **** c": markup wrapped around nothing. The word and the styling
14773        // that was only ever the word's go together.
14774        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
14775        d.caret = 10;
14776        d.delete_word_back();
14777        assert_eq!(d.source, "a  c\n");
14778        assert_eq!(d.caret, 2);
14779
14780        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
14781        d.caret = 4; // the "b"
14782        d.delete_word_forward();
14783        assert_eq!(d.source, "a  c\n");
14784    }
14785
14786    #[test]
14787    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
14788        let src = "a ***bold*** c\n";
14789        let mut d = wysiwyg_doc("wys_word_del_nest", src);
14790        d.caret = src.find(" c").unwrap();
14791        d.delete_word_back();
14792        assert_eq!(
14793            d.source, "a  c\n",
14794            "the emph inside the strong empties it too"
14795        );
14796
14797        let src = "a `code` c\n";
14798        let mut d = wysiwyg_doc("wys_word_del_code", src);
14799        d.caret = src.find(" c").unwrap();
14800        d.delete_word_back();
14801        assert_eq!(d.source, "a  c\n");
14802    }
14803
14804    #[test]
14805    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
14806        // Only an *emptied* node goes. Take one word of two and the `**` still
14807        // has a job to do — over the word that's left, with the space the delete
14808        // pushed against the opening delimiter moved out in front of it, or the
14809        // run would be no run at all (`** words**` is literal asterisks — see
14810        // the mark-edge rule on `splice`).
14811        let src = "a **two words** c\n";
14812        let mut d = wysiwyg_doc("wys_word_del_partial", src);
14813        d.caret = src.find(" words").unwrap();
14814        d.delete_word_back();
14815        assert_eq!(d.source, "a  **words** c\n");
14816    }
14817
14818    #[test]
14819    fn source_view_word_motion_still_walks_the_markup() {
14820        // The other half of the decision: in the source view the `**` are
14821        // characters like any other — they're on the screen, so word motion has
14822        // to stop at them and a word-delete has to leave them behind. Only
14823        // WYSIWYG hides them, so only WYSIWYG steps over them.
14824        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
14825        assert_eq!(
14826            g("src_word_motion", "a |**bold** c\n", |d| d
14827                .move_word_right(false)),
14828            "a **bold|** c\n"
14829        );
14830        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
14831        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
14832        assert_eq!(
14833            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
14834            "a **| c\n"
14835        );
14836    }
14837
14838    #[test]
14839    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
14840        // The single invariant both bugs violated: the caret draws and edits at
14841        // the same place only when it's on a stop. `debug_assert_on_a_stop`
14842        // makes the same claim in-place; this pins it from the outside, over a
14843        // document with every kind of thing the map has to be careful about.
14844        // At two widths: the wide one every other test builds at, where no
14845        // fixture folds, and one narrow enough that they all do. A soft wrap is
14846        // where an offset stops being on exactly one row, and testing only the
14847        // width that never wraps is how the caret came to be pinned at the first
14848        // one Down reached.
14849        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
14850                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
14851        // A table of named operations, which is what it looks like.
14852        #[allow(clippy::type_complexity)]
14853        let motions: [(&str, fn(&mut Doc)); 8] = [
14854            ("right", |d| d.move_right(false)),
14855            ("left", |d| d.move_left(false)),
14856            ("word_right", |d| d.move_word_right(false)),
14857            ("word_left", |d| d.move_word_left(false)),
14858            ("down", |d| d.move_down(false)),
14859            ("up", |d| d.move_up(false)),
14860            ("home", |d| d.move_home(false)),
14861            ("end", |d| d.move_end(false)),
14862        ];
14863        for width in [80, 12] {
14864            let mut d = wysiwyg_doc("stop_invariant", src);
14865            d.build_visual(width);
14866            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
14867            assert!(stops.len() > 20, "fixture should have plenty of stops");
14868            for start in stops {
14869                for (name, motion) in &motions {
14870                    d.caret = start;
14871                    d.anchor = None;
14872                    motion(&mut d);
14873                    assert!(
14874                        d.vmap.is_stop(d.caret),
14875                        "{name} from {start} at width {width} landed at {} — not a caret stop",
14876                        d.caret
14877                    );
14878                }
14879            }
14880        }
14881    }
14882
14883    #[test]
14884    fn no_wysiwyg_motion_is_a_dead_end() {
14885        // Down held to the bottom of a document reaches the bottom, and Up held
14886        // to the top reaches the top — from anywhere, at a width that wraps. The
14887        // invariant above says a motion lands somewhere legal; this one says it
14888        // gets somewhere at all, which is what a caret pinned at a wrap boundary
14889        // was quietly failing to do while every assertion around it held.
14890        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
14891                   - item one two three four five\n\nlast\n";
14892        for width in [80, 12] {
14893            let mut d = wysiwyg_doc("no_dead_end", src);
14894            d.build_visual(width);
14895            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
14896            let (first, last) = (stops[0], stops[stops.len() - 1]);
14897            for &start in &stops {
14898                for (name, motion, want) in [
14899                    (
14900                        "down",
14901                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
14902                        last,
14903                    ),
14904                    ("up", |d: &mut Doc| d.move_up(false), first),
14905                ] {
14906                    d.caret = start;
14907                    d.anchor = None;
14908                    d.goal_col = None;
14909                    // Every row, plus the presses the edges take, plus slack.
14910                    for _ in 0..d.vmap.num_rows() + 4 {
14911                        motion(&mut d);
14912                    }
14913                    assert_eq!(
14914                        d.caret, want,
14915                        "{name} held from {start} at width {width} never arrived"
14916                    );
14917                }
14918            }
14919        }
14920    }
14921    // ── display columns ──────────────────────────────────────────────────────
14922    // A `col` is a terminal cell, not a character. The two are the same number
14923    // for the ASCII the fixtures above are written in, which is how they came
14924    // apart in the first place: `你` is one character drawn in two cells, so a
14925    // column counted in characters names a cell the text isn't in — one earlier
14926    // for every wide character to its left.
14927
14928    #[test]
14929    fn a_wide_character_is_two_columns_wide() {
14930        // The reproduction: `你` is one char and two cells, so the caret just
14931        // past it drew at column 1 — inside the character it had already left.
14932        for (view, tag) in VIEWS {
14933            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
14934            d.caret = "你".len();
14935            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
14936            d.caret = "你好".len();
14937            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
14938        }
14939    }
14940
14941    #[test]
14942    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
14943        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
14944        // two-cell — measuring six cells one at a time, but the character they
14945        // spell is drawn in two. Width belongs to the cluster, not the glyph,
14946        // and the frontends measure it the same way.
14947        let family = "👨‍👩‍👧";
14948        for (view, tag) in VIEWS {
14949            let src = format!("a{family}b\n");
14950            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
14951            d.caret = 1 + family.len();
14952            assert_eq!(
14953                d.caret_pos(),
14954                (0, 3),
14955                "{tag}: 'a' is one cell, the family two"
14956            );
14957        }
14958    }
14959
14960    #[test]
14961    fn both_cells_of_a_wide_character_mean_the_character() {
14962        // Clicking the far half of `好` is still clicking `好`: half a character
14963        // is not a place the caret can be, so it comes to rest at the
14964        // character's start — the column it would have been drawn at anyway.
14965        for (view, tag) in VIEWS {
14966            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
14967            for col in [2, 3] {
14968                d.caret = 0;
14969                d.click(0, col, false);
14970                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
14971                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
14972            }
14973            // Past the last cell is the line's end, as it is for ASCII.
14974            d.click(0, 9, false);
14975            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
14976        }
14977    }
14978
14979    #[test]
14980    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
14981        // The mapping is only a mapping if it inverts: the cell the caret is
14982        // drawn in has to be the cell that brings it back to the same offset.
14983        // Over a fixture where a character may be one cell or two, and one
14984        // codepoint or five.
14985        use unicode_segmentation::UnicodeSegmentation;
14986
14987        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
14988
14989        let mut d = doc_in(View::Source, "roundtrip_source", src);
14990        // Every offset the source view's caret can occupy: it steps by grapheme
14991        // cluster, so those are its boundaries.
14992        for (off, _) in src
14993            .grapheme_indices(true)
14994            .chain(std::iter::once((src.len(), "")))
14995        {
14996            d.caret = off;
14997            let (row, col) = d.caret_pos();
14998            d.click(row, col, false);
14999            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
15000        }
15001
15002        // And in WYSIWYG, where the offsets the caret can occupy are the map's
15003        // stops rather than every boundary.
15004        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
15005        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
15006        assert!(stops.len() > 20, "fixture should have plenty of stops");
15007        for off in stops {
15008            d.caret = off;
15009            let (row, col) = d.caret_pos();
15010            d.click(row, col, false);
15011            assert_eq!(
15012                d.caret, off,
15013                "wysiwyg: {off} → ({row}, {col}) → {}",
15014                d.caret
15015            );
15016        }
15017    }
15018
15019    #[test]
15020    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
15021        // Down from under `世` lands under the glyph in that cell, not two
15022        // characters further along the line. The goal is a column, so a line of
15023        // wide characters and a line of ASCII line up the way they're drawn.
15024        //
15025        // The gap differs by view: a bare newline inside a paragraph is a soft
15026        // break, which WYSIWYG draws as a space on a single row. The views share
15027        // a grid only where the source's lines are the renderer's rows too.
15028        for (view, tag) in VIEWS {
15029            let gap = if view == View::Source { "\n" } else { "\n\n" };
15030            let src = format!("你好世{gap}abcdef\n");
15031            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
15032            d.caret = "你好".len();
15033            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
15034            d.move_down(false);
15035            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
15036            assert!(
15037                d.source[d.caret..].starts_with('e'),
15038                "{tag}: landed on the wrong glyph"
15039            );
15040        }
15041    }
15042
15043    #[test]
15044    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
15045        // Down from column 3 onto `你好`, whose characters start at columns 0
15046        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
15047        // between the cells of one character, so the caret rests on it — and on
15048        // its start, which is the only offset there that is a caret stop.
15049        for (view, tag) in VIEWS {
15050            let gap = if view == View::Source { "\n" } else { "\n\n" };
15051            let src = format!("abcdef{gap}你好\n");
15052            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
15053            let line = src.find('你').unwrap();
15054            d.caret = 3;
15055            d.move_down(false);
15056            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
15057            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
15058        }
15059    }
15060
15061    #[test]
15062    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
15063        // The column the cell's text is laid out in is measured in cells, so the
15064        // caret walking that text has to be too — the two agreeing is the whole
15065        // point of the grid staying square.
15066        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
15067        let at = d.source.find("你").unwrap();
15068        d.caret = at;
15069        let (row, col) = d.caret_pos();
15070        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
15071        // cells further along.
15072        assert_eq!(col, 2, "the cell's first character");
15073        d.move_right(false);
15074        assert_eq!(
15075            d.caret_pos(),
15076            (row, 4),
15077            "`好` is drawn past `你`'s two cells"
15078        );
15079        assert_eq!(d.caret, at + "你".len());
15080    }
15081
15082    // ── active inline marks ───────────────────────────────────────────────────
15083
15084    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
15085    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
15086        let (src, caret) = parse_caret(marked);
15087        let mut d = doc_in(view, name, &src);
15088        d.caret = caret;
15089        d.active_inline_marks().iter().collect()
15090    }
15091
15092    /// The marks over the selection `[start, end)`.
15093    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
15094        let mut d = doc_in(view, name, src);
15095        d.anchor = Some(start);
15096        d.caret = end;
15097        d.active_inline_marks().iter().collect()
15098    }
15099
15100    #[test]
15101    fn a_caret_in_a_mark_reports_it() {
15102        for (view, tag) in VIEWS {
15103            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
15104            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
15105            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
15106            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
15107            // Plain text under no mark lights nothing — the toolbar's resting state.
15108            assert_eq!(m("a| **bold** b"), [], "{tag}");
15109            assert!(m("plain t|ext").is_empty(), "{tag}");
15110        }
15111    }
15112
15113    #[test]
15114    fn nested_marks_all_report() {
15115        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
15116        // the ancestor chain is a chain, and every mark on it is in force.
15117        for (view, tag) in VIEWS {
15118            assert_eq!(
15119                marks(
15120                    view,
15121                    &format!("marks_nested_{tag}"),
15122                    "**bold and *bo|th*** end"
15123                ),
15124                [InlineKind::Strong, InlineKind::Emph],
15125                "{tag}"
15126            );
15127        }
15128    }
15129
15130    #[test]
15131    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
15132        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
15133        // the first byte of its text and the byte after its last — both inside
15134        // the mark's span, both places typing lands inside the bold. The offset
15135        // past the closing delimiter is the next text, and reports nothing.
15136        let src = "a **bold** b";
15137        let inner_start = src.find("bold").unwrap(); // 4
15138        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
15139        for (view, tag) in VIEWS {
15140            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
15141            for off in [2, 3, inner_start, inner_end, 9] {
15142                d.caret = off;
15143                assert!(
15144                    d.active_inline_marks().contains(InlineKind::Strong),
15145                    "{tag}: offset {off} is inside the strong span"
15146                );
15147            }
15148            for off in [0, 1, 10, 11, 12] {
15149                d.caret = off;
15150                assert!(
15151                    !d.active_inline_marks().contains(InlineKind::Strong),
15152                    "{tag}: offset {off} is outside the strong run"
15153                );
15154            }
15155        }
15156    }
15157
15158    #[test]
15159    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
15160        // Regression: twig resolves an offset that is one node's end and the
15161        // next one's start to the node that *starts* there, so `**bold**|\n`
15162        // isn't bold. With nothing following there's no tie to break and the
15163        // chain still ended at the mark, which made a trailing `\n` — not the
15164        // text — decide whether the caret after a bold word reported bold. It's
15165        // the offset past the mark either way, and typing there is plain either
15166        // way. A blank document typed into is exactly this shape.
15167        for (view, tag) in VIEWS {
15168            let m = |name: String, marked| marks(view, &name, marked);
15169            assert_eq!(
15170                m(format!("marks_eob_{tag}"), "**bold**|"),
15171                [],
15172                "{tag}: no trailing newline"
15173            );
15174            assert_eq!(
15175                m(format!("marks_eol_{tag}"), "**bold**|\n"),
15176                [],
15177                "{tag}: with one"
15178            );
15179            // And the last offset that *is* in the mark still is.
15180            assert_eq!(
15181                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
15182                [InlineKind::Strong],
15183                "{tag}"
15184            );
15185        }
15186    }
15187
15188    #[test]
15189    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
15190        let src = "a **bold** b";
15191        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
15192        for (view, tag) in VIEWS {
15193            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
15194            // The whole bold word, and a slice of it.
15195            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
15196            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
15197            // Ending exactly at the closing delimiter's start is still all-bold:
15198            // an exclusive end sits *past* the last selected character, so the
15199            // question is asked of the character, not the boundary.
15200            assert_eq!(
15201                m(b, d_ + 2),
15202                [InlineKind::Strong],
15203                "{tag}: through the close"
15204            );
15205            // Half in, half out: Bold lit here would claim a press turns it off.
15206            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
15207            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
15208        }
15209    }
15210
15211    #[test]
15212    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
15213        // Both ends are bold, but the space between them isn't — two runs are two
15214        // nodes, which is exactly what the node id catches and a kind-only
15215        // comparison would not.
15216        let src = "**one** **two**";
15217        for (view, tag) in VIEWS {
15218            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
15219            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
15220        }
15221    }
15222
15223    #[test]
15224    fn marks_read_the_document_as_it_is_edited() {
15225        // The point of asking twig every frame instead of caching: the answer has
15226        // to follow the toggle that changed it.
15227        let mut d = wysiwyg_doc("marks_live", "one two\n");
15228        d.anchor = Some(0);
15229        d.caret = 3;
15230        assert!(d.active_inline_marks().is_empty(), "plain to start");
15231        d.toggle(InlineKind::Strong);
15232        assert_eq!(d.source, "**one** two\n");
15233        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
15234        assert!(d.active_inline_marks().contains(InlineKind::Strong));
15235        d.toggle(InlineKind::Strong);
15236        assert!(d.active_inline_marks().is_empty(), "and off again");
15237    }
15238
15239    #[test]
15240    fn a_link_is_not_an_inline_mark() {
15241        // `link`/`str` are inline nodes, but nothing on the inline toolbar
15242        // toggles them — a set with a "link mark" in it would have no button.
15243        for (view, tag) in VIEWS {
15244            assert_eq!(
15245                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
15246                [],
15247                "{tag}"
15248            );
15249        }
15250    }
15251
15252    // ── blank documents ───────────────────────────────────────────────────────
15253
15254    #[test]
15255    fn a_blank_document_is_untitled_empty_and_markdown() {
15256        let mut d = Doc::blank().unwrap();
15257        assert!(d.is_untitled());
15258        assert_eq!(d.path, PathBuf::new());
15259        assert_eq!(
15260            d.file_name(),
15261            "untitled",
15262            "the header has to show something"
15263        );
15264        assert_eq!(d.format_name(), "markdown");
15265        assert_eq!(d.source, "");
15266        assert!(!d.dirty, "nothing typed yet is nothing to lose");
15267        assert_eq!(d.disk_state(), DiskState::Untitled);
15268        // And it's a document you can be in: the default view renders it.
15269        d.build_visual(80);
15270        assert_eq!(d.caret, 0);
15271    }
15272
15273    #[test]
15274    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
15275        let mut d = Doc::blank().unwrap();
15276        d.insert("hello");
15277        assert!(d.dirty);
15278        d.save();
15279        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
15280        assert!(d.dirty, "it must not come away believing it saved");
15281        assert!(d.is_untitled(), "and it still has no file");
15282    }
15283
15284    #[test]
15285    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
15286        let p = temp_path("blank_save_as");
15287        let mut d = Doc::blank().unwrap();
15288        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
15289        // be kept literal (`\#`); this test is about save-as, not escaping (which
15290        // has its own test), so it types nothing that escaping would touch.
15291        d.insert("hi");
15292        d.save_as(p.clone());
15293        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
15294        assert!(!d.is_untitled());
15295        assert!(!d.dirty);
15296        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
15297        assert_eq!(
15298            d.disk_state(),
15299            DiskState::Unchanged,
15300            "the watermark is stamped"
15301        );
15302        // And ⌘S is a plain save from here on.
15303        d.insert("!");
15304        d.save();
15305        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
15306        let _ = std::fs::remove_file(&p);
15307    }
15308
15309    // ── a file that isn't there yet ───────────────────────────────────────────
15310
15311    /// A unique path in the temp dir with the given extension, guaranteed not to
15312    /// exist — what `leaf notes.md` is handed when the file has never been made.
15313    fn missing_path(name: &str, ext: &str) -> PathBuf {
15314        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
15315        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15316        let mut p = std::env::temp_dir();
15317        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
15318        let _ = std::fs::remove_file(&p);
15319        p
15320    }
15321
15322    #[test]
15323    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
15324        let p = missing_path("named", "md");
15325        let mut d = Doc::open_or_create(p.clone()).unwrap();
15326
15327        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
15328        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
15329        assert!(
15330            !d.is_untitled(),
15331            "it has the name the user asked for — ^S must not detour to Save As"
15332        );
15333        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
15334        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
15335        assert!(!p.exists(), "and opening it wrote nothing");
15336        // And it's a document you can be in.
15337        d.build_visual(80);
15338        assert_eq!(d.caret, 0);
15339    }
15340
15341    #[test]
15342    fn a_new_file_is_created_by_its_first_save() {
15343        let p = missing_path("first_save", "md");
15344        let mut d = Doc::open_or_create(p.clone()).unwrap();
15345        d.insert("hello\n");
15346        assert!(d.dirty);
15347        d.save();
15348
15349        assert_eq!(
15350            std::fs::read_to_string(&p).unwrap(),
15351            "hello\n",
15352            "a plain ^S wrote it — no Save As, no name to invent"
15353        );
15354        assert!(!d.dirty);
15355        assert_eq!(d.disk_state(), DiskState::Unchanged);
15356        let _ = std::fs::remove_file(&p);
15357    }
15358
15359    #[test]
15360    fn a_new_file_takes_its_format_from_the_extension() {
15361        // The one thing `blank` can't do: with no name it has to assume Markdown,
15362        // and typing djot into a Markdown parse is the wrong buffer.
15363        let dj = missing_path("format", "dj");
15364        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
15365        let md = missing_path("format", "md");
15366        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
15367    }
15368
15369    #[test]
15370    fn a_new_file_reports_itself_missing_until_it_is_saved() {
15371        // Not `Untitled` — that's the answer for a document with no path, and it
15372        // would tell a frontend there is nothing a save could collide with. Here
15373        // there is a path, and the file simply isn't at it yet.
15374        let p = missing_path("disk_state", "md");
15375        let mut d = Doc::open_or_create(p.clone()).unwrap();
15376        assert_eq!(d.disk_state(), DiskState::Missing);
15377
15378        // Somebody else creates it while the buffer is open: that's an overwrite
15379        // the frontend has to be able to prompt about, exactly as for an opened
15380        // file. Their bytes, not ours, so `Changed`.
15381        std::fs::write(&p, "theirs\n").unwrap();
15382        assert_eq!(d.disk_state(), DiskState::Changed);
15383
15384        // Saving makes the file ours and re-stamps the watermark.
15385        d.insert("ours\n");
15386        d.save();
15387        assert_eq!(d.disk_state(), DiskState::Unchanged);
15388        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
15389        let _ = std::fs::remove_file(&p);
15390    }
15391
15392    #[test]
15393    fn open_or_create_still_opens_a_file_that_is_there() {
15394        let d = doc_with("open_or_create_existing", "body\n");
15395        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
15396        assert_eq!(reopened.source, "body\n");
15397        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
15398    }
15399
15400    #[test]
15401    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
15402        // A mistyped flag or a stray argument must not become a buffer promising
15403        // to save somewhere — the same refusal `open` gives a real file.
15404        let mut p = std::env::temp_dir();
15405        p.push("leaf_test_new_bad_ext.wat");
15406        assert!(Doc::open_or_create(p).is_err());
15407        let mut none = std::env::temp_dir();
15408        none.push("leaf_test_new_no_ext");
15409        assert!(Doc::open_or_create(none).is_err());
15410    }
15411
15412    #[test]
15413    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
15414        // Opening reads nothing, so there is nothing to fail on yet; the write is
15415        // where it fails, and it says so rather than claiming a save.
15416        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
15417        let mut d = Doc::open_or_create(p).unwrap();
15418        d.insert("x");
15419        d.save();
15420        assert!(
15421            d.status.as_deref().unwrap().starts_with("save failed:"),
15422            "got {:?}",
15423            d.status
15424        );
15425        assert!(d.dirty, "it must not come away believing it saved");
15426    }
15427
15428    // ── save as ───────────────────────────────────────────────────────────────
15429
15430    /// A unique path in the temp dir that no fixture wrote — a Save As target.
15431    fn temp_path(name: &str) -> PathBuf {
15432        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
15433        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15434        let mut p = std::env::temp_dir();
15435        p.push(format!("leaf_test_target_{name}_{seq}.md"));
15436        let _ = std::fs::remove_file(&p);
15437        p
15438    }
15439
15440    #[test]
15441    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
15442        let mut d = doc_with("save_as_move", "original\n");
15443        let old = d.path.clone();
15444        let new = temp_path("save_as_move");
15445        d.insert("edited: ");
15446        d.save_as(new.clone());
15447
15448        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
15449        assert_eq!(
15450            std::fs::read_to_string(&old).unwrap(),
15451            "original\n",
15452            "Save As doesn't touch the file it came from"
15453        );
15454        assert_eq!(d.path, new, "the document moved");
15455        assert!(!d.dirty);
15456        assert_eq!(
15457            d.status.as_deref(),
15458            Some(&*format!("saved {}", d.file_name()))
15459        );
15460
15461        // Every later save follows it, which is the whole difference from a copy.
15462        d.caret = 0;
15463        d.insert("re-");
15464        d.save();
15465        assert_eq!(
15466            std::fs::read_to_string(&new).unwrap(),
15467            "re-edited: original\n"
15468        );
15469        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
15470        let _ = std::fs::remove_file(&new);
15471    }
15472
15473    #[test]
15474    fn save_as_overwrites_an_existing_target() {
15475        // The picker already asked; asking again down here is the same question
15476        // twice, and the second one has no way to be answered.
15477        let new = temp_path("save_as_over");
15478        std::fs::write(&new, "theirs\n").unwrap();
15479        let mut d = doc_with("save_as_over", "ours\n");
15480        d.save_as(new.clone());
15481        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
15482        let _ = std::fs::remove_file(&new);
15483    }
15484
15485    #[test]
15486    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
15487        let mut d = doc_with("save_as_fail", "body\n");
15488        let old = d.path.clone();
15489        d.insert("x");
15490        // A directory that doesn't exist: the write can't land.
15491        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
15492        d.save_as(bad);
15493
15494        assert_eq!(
15495            d.path, old,
15496            "the document must not move to a file that isn't there"
15497        );
15498        assert!(d.dirty, "and must not believe it saved");
15499        assert!(
15500            d.status.as_deref().unwrap().starts_with("save failed:"),
15501            "the same failure a plain save reports, got {:?}",
15502            d.status
15503        );
15504        // The original is still the document's file, and still saveable.
15505        d.save();
15506        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
15507        assert!(!d.dirty);
15508    }
15509
15510    #[test]
15511    fn save_as_renames_without_reparsing_the_format() {
15512        // `.dj` on the name doesn't make the buffer djot: it was parsed as
15513        // Markdown and still is, and saying otherwise would be a conversion the
15514        // user never asked for (and an undo history thrown away to do it).
15515        let mut d = doc_with("save_as_format", "**b**\n");
15516        let mut new = temp_path("save_as_format");
15517        new.set_extension("dj");
15518        d.save_as(new.clone());
15519        assert_eq!(d.format_name(), "markdown");
15520        let _ = std::fs::remove_file(&new);
15521    }
15522
15523    // ── external change / reload ──────────────────────────────────────────────
15524
15525    #[test]
15526    fn an_untouched_file_reports_unchanged() {
15527        let mut d = doc_with("disk_clean", "body\n");
15528        assert_eq!(d.disk_state(), DiskState::Unchanged);
15529        // Editing the buffer is not editing the file.
15530        d.insert("x");
15531        assert_eq!(d.disk_state(), DiskState::Unchanged);
15532        assert!(d.dirty);
15533        // Saving re-stamps the watermark rather than reporting our own bytes back.
15534        d.save();
15535        assert_eq!(d.disk_state(), DiskState::Unchanged);
15536    }
15537
15538    #[test]
15539    fn a_file_written_underneath_reports_changed() {
15540        let mut d = doc_with("disk_changed", "body\n");
15541        std::fs::write(&d.path, "someone else\n").unwrap();
15542        assert_eq!(d.disk_state(), DiskState::Changed);
15543        // Dirty *and* changed is the clobber: both halves are readable, and
15544        // leaf-core takes neither side.
15545        d.insert("x");
15546        assert!(d.dirty && d.disk_state() == DiskState::Changed);
15547        // Saving anyway is allowed — the frontend asked, or chose not to.
15548        d.save();
15549        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
15550        assert_eq!(d.disk_state(), DiskState::Unchanged);
15551    }
15552
15553    #[test]
15554    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
15555        // The hash is what makes this honest: the file was written (a fresh
15556        // mtime), and nothing about the document is stale.
15557        let d = doc_with("disk_same_bytes", "body\n");
15558        std::fs::write(&d.path, "body\n").unwrap();
15559        assert_eq!(d.disk_state(), DiskState::Unchanged);
15560    }
15561
15562    #[test]
15563    fn a_deleted_file_reports_missing() {
15564        let mut d = doc_with("disk_missing", "body\n");
15565        std::fs::remove_file(&d.path).unwrap();
15566        assert_eq!(d.disk_state(), DiskState::Missing);
15567        // A save recreates it, and the document is whole again.
15568        d.save();
15569        assert_eq!(d.disk_state(), DiskState::Unchanged);
15570        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
15571    }
15572
15573    #[test]
15574    fn reload_replaces_the_document_with_the_file() {
15575        for (view, tag) in VIEWS {
15576            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
15577            d.insert("edited ");
15578            assert!(d.dirty);
15579            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
15580            d.reload();
15581
15582            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
15583            assert!(!d.dirty, "{tag}: the file is what we have");
15584            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
15585            assert_eq!(
15586                d.status.as_deref(),
15587                Some(&*format!("reloaded {}", d.file_name()))
15588            );
15589            // The reloaded tree is live, not the old parse.
15590            d.caret = d.source.find("three").unwrap();
15591            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
15592        }
15593    }
15594
15595    #[test]
15596    fn reload_clamps_the_caret_and_drops_the_selection() {
15597        let mut d = doc_with("reload_caret", "a long first line\n");
15598        d.caret = 12;
15599        d.anchor = Some(4);
15600        std::fs::write(&d.path, "short\n").unwrap();
15601        d.reload();
15602        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
15603        assert_eq!(
15604            d.anchor, None,
15605            "a selection over bytes that changed is a lie"
15606        );
15607        assert!(d.selection().is_none());
15608
15609        // A caret the file still has room for stays put.
15610        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
15611        d.caret = 2;
15612        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
15613        d.reload();
15614        assert_eq!(d.caret, 2);
15615    }
15616
15617    /// A silent reload is something that happened *to* a reader — a formatter,
15618    /// a `git checkout` — so it has to be undoable like anything else that
15619    /// changes the document, and undoable as one step rather than as however
15620    /// many the file happens to differ by.
15621    #[test]
15622    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
15623        let mut d = doc_with("reload_undo", "body\n");
15624        d.insert("x");
15625        assert_eq!(d.source, "xbody\n");
15626        std::fs::write(&d.path, "replaced\n").unwrap();
15627        d.reload();
15628        assert_eq!(d.source, "replaced\n");
15629        assert!(!d.dirty, "a reload lands clean");
15630
15631        // One ^Z takes the whole swap off, and hands back the unsaved work it
15632        // replaced — which is unsaved again, because the file no longer says it.
15633        d.undo();
15634        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
15635        assert!(d.dirty, "and what it comes back to is unsaved");
15636        // …and the history under it is still there.
15637        d.undo();
15638        assert_eq!(
15639            d.source, "body\n",
15640            "the typing before the reload undoes too"
15641        );
15642        // Redo walks back up through the reload.
15643        d.redo();
15644        d.redo();
15645        assert_eq!(d.source, "replaced\n");
15646    }
15647
15648    /// A file rewritten with the bytes it already had is not an edit, so it
15649    /// must not leave an undo step behind for something nobody did.
15650    #[test]
15651    fn reloading_identical_bytes_pushes_no_undo_step() {
15652        let mut d = doc_with("reload_same", "body\n");
15653        d.insert("x");
15654        std::fs::write(&d.path, "xbody\n").unwrap();
15655        d.reload();
15656        assert_eq!(d.source, "xbody\n");
15657        assert!(!d.dirty, "the file now says what the buffer does");
15658        d.undo();
15659        assert_eq!(
15660            d.source, "body\n",
15661            "one step back is the typing, not a no-op"
15662        );
15663    }
15664
15665    #[test]
15666    fn a_reload_that_cant_read_leaves_the_document_alone() {
15667        let mut d = doc_with("reload_gone", "body\n");
15668        d.insert("x");
15669        std::fs::remove_file(&d.path).unwrap();
15670        d.reload();
15671        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
15672        assert!(d.dirty);
15673        assert!(
15674            d.status.as_deref().unwrap().starts_with("reload failed:"),
15675            "{:?}",
15676            d.status
15677        );
15678
15679        // And an untitled document has nothing to reload from.
15680        let mut d = Doc::blank().unwrap();
15681        d.insert("typed");
15682        d.reload();
15683        assert_eq!(d.source, "typed");
15684        assert_eq!(d.status.as_deref(), Some("no file to reload"));
15685    }
15686
15687    #[test]
15688    fn a_read_only_document_refuses_every_door() {
15689        let mut d = doc_with("readonly", "one two three\n");
15690        d.insert("x");
15691        assert!(d.dirty, "writable first, so the undo step exists");
15692        d.set_read_only(true);
15693        let before = d.source.clone();
15694        d.insert("y");
15695        d.backspace();
15696        d.undo();
15697        d.redo();
15698        assert_eq!(d.source, before, "no door moved a byte");
15699        d.set_read_only(false);
15700        d.undo();
15701        assert_ne!(d.source, before, "off again, the same doors work");
15702    }
15703
15704    /// The doors that go to twig's own verbs rather than through the splice.
15705    /// Typed text in the rendered view under the default markup mode is the
15706    /// everyday one — it is what a keystroke in leaf-web or the Apple views
15707    /// becomes — and it walked straight past the gate.
15708    #[test]
15709    fn a_read_only_document_refuses_the_doors_around_the_splice() {
15710        let mut d = wysiwyg_doc(
15711            "readonly-doors",
15712            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
15713        );
15714        d.set_markup_mode(MarkupMode::None);
15715        d.set_read_only(true);
15716        let before = d.source.clone();
15717        d.place_caret(3, false);
15718        d.insert("y");
15719        d.insert_link("https://example.com");
15720        d.insert_image("a.png", "alt");
15721        d.insert_thematic_break();
15722        d.insert_footnote();
15723        d.place_caret(0, false);
15724        d.place_caret(3, true);
15725        d.toggle(InlineKind::Strong);
15726        d.toggle_heading(2);
15727        d.set_block(BlockKind::Paragraph);
15728        d.toggle_list(false);
15729        d.toggle_blockquote();
15730        d.toggle_task_item();
15731        d.newline();
15732        d.indent();
15733        d.set_code_language("rust");
15734        let in_cell = d.source.find("| c").unwrap() + 2;
15735        d.place_caret(in_cell, false);
15736        assert!(d.caret_in_table(), "the caret is in the grid");
15737        assert!(!d.cell_line_break(), "the cell break reports the refusal");
15738        assert_eq!(d.source, before, "no door moved a byte");
15739        assert!(!d.dirty, "nothing to save");
15740        d.set_read_only(false);
15741        d.place_caret(3, false);
15742        d.insert("y");
15743        assert_ne!(d.source, before, "off again, the same doors work");
15744    }
15745
15746    #[test]
15747    fn a_selection_quote_carries_its_context_on_char_boundaries() {
15748        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
15749        let start = d.source.find("exact").unwrap();
15750        d.place_caret(start, false);
15751        d.place_caret(start + "exact".len(), true);
15752        let q = d.selection_quote(3).unwrap();
15753        assert_eq!(q.exact, "exact");
15754        assert_eq!(
15755            q.prefix, "你好 ",
15756            "chars, not bytes — the multibyte pair counts as two"
15757        );
15758        assert_eq!(q.suffix, " 世界");
15759        assert_eq!(&d.source[q.start..q.end], "exact");
15760        // At the edges the context clips rather than erring.
15761        d.place_caret(0, false);
15762        d.place_caret(6, true);
15763        let q = d.selection_quote(40).unwrap();
15764        assert_eq!(q.prefix, "");
15765        assert_eq!(q.exact, "before");
15766        // No selection is no quote.
15767        d.place_caret(0, false);
15768        assert!(d.selection_quote(3).is_none());
15769    }
15770
15771    #[test]
15772    fn highlights_are_kept_sorted_and_answer_point_queries() {
15773        let mut d = doc_with("hl", "one two three\n");
15774        d.set_highlights(vec![
15775            Highlight {
15776                start: 8,
15777                end: 13,
15778                id: "b".into(),
15779                color: None,
15780                marker: None,
15781            },
15782            Highlight {
15783                start: 0,
15784                end: 3,
15785                id: "a".into(),
15786                color: Some("#ffe066".into()),
15787                marker: None,
15788            },
15789            Highlight {
15790                start: 5,
15791                end: 5,
15792                id: "empty".into(),
15793                color: None,
15794                marker: None,
15795            },
15796        ]);
15797        assert_eq!(
15798            d.highlights()
15799                .iter()
15800                .map(|h| h.id.as_str())
15801                .collect::<Vec<_>>(),
15802            ["a", "b"],
15803            "sorted by start, the empty range dropped"
15804        );
15805        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
15806        assert_eq!(d.highlight_at(3), None, "end is exclusive");
15807        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
15808        d.set_highlights(Vec::new());
15809        assert!(d.highlights().is_empty(), "a replace is a replace");
15810    }
15811
15812    /// `Highlight::covering` and the cursor over it are what both painters ask
15813    /// per glyph, so they have to answer the same as the scan they replaced —
15814    /// including in the gaps, which is where most glyphs are.
15815    #[test]
15816    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
15817        let hl = |start: usize, end: usize, id: &str| Highlight {
15818            start,
15819            end,
15820            id: id.into(),
15821            color: None,
15822            marker: None,
15823        };
15824        // Disjoint, as search hits are: in a range, in a gap, and past the end.
15825        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
15826        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
15827        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
15828        assert_eq!(
15829            Highlight::covering(&hits, 105),
15830            None,
15831            "a gap covers nothing"
15832        );
15833        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
15834        assert_eq!(Highlight::covering(&hits, 9_999), None);
15835        assert_eq!(Highlight::covering(&[], 0), None);
15836
15837        // Nested: first by start, so a hit inside an annotation still resolves
15838        // to the annotation — and the range that stops short doesn't mask it.
15839        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
15840        assert_eq!(
15841            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
15842            Some("outer")
15843        );
15844        assert_eq!(
15845            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
15846            Some("outer")
15847        );
15848    }
15849
15850    /// The cursor is an optimisation, so the only thing worth asserting is that
15851    /// it is not also a change of answer — at every offset, over a list with a
15852    /// nest in it, walked forwards and then backwards.
15853    #[test]
15854    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
15855        let hl = |start: usize, end: usize, id: &str| Highlight {
15856            start,
15857            end,
15858            id: id.into(),
15859            color: None,
15860            marker: None,
15861        };
15862        let mut list = vec![
15863            hl(0, 20, "outer"),
15864            hl(5, 10, "inner"),
15865            hl(30, 33, "hit"),
15866            hl(40, 43, "hit"),
15867        ];
15868        list.sort_by_key(|h| (h.start, h.end));
15869
15870        let mut cursor = HighlightCursor::new(&list);
15871        for offset in 0..50 {
15872            assert_eq!(
15873                cursor.at(offset).map(|h| h.id.as_str()),
15874                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
15875                "cursor disagrees at {offset}"
15876            );
15877        }
15878        // Backwards: the cursor re-seats rather than answering from where it
15879        // had got to, so a painter that revisits a row is still told the truth.
15880        for offset in (0..50).rev() {
15881            assert_eq!(
15882                cursor.at(offset).map(|h| h.id.as_str()),
15883                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
15884                "cursor disagrees walking back at {offset}"
15885            );
15886        }
15887    }
15888
15889    // ── the presentation vocabulary ─────────────────────────────────────────
15890
15891    /// A document in `format`, for the gesture tests that want more than the
15892    /// Markdown `doc_with` writes.
15893    fn fmt_doc(body: &str, format: Format) -> Doc {
15894        Doc::from_source(body.to_string(), format).unwrap()
15895    }
15896
15897    /// Alignment is a block property, so the gesture is `set_block_attrs` on
15898    /// the caret's block whatever is selected — and each format spells it its
15899    /// own way: djot's `{…}` line above the block, a `<div>` around it in
15900    /// Markdown (the format has nowhere else to put it), the tag in HTML.
15901    #[test]
15902    fn set_alignment_spells_the_class_the_format_s_own_way() {
15903        let mut dj = fmt_doc("hello\n", Format::Djot);
15904        dj.caret = 1;
15905        dj.set_alignment(Some(Align::Center));
15906        assert_eq!(dj.source, "{.center}\nhello\n");
15907        assert!(dj.dirty);
15908        assert_eq!(dj.status, None);
15909
15910        let mut md = fmt_doc("hello\n", Format::Markdown);
15911        md.caret = 1;
15912        md.set_alignment(Some(Align::Right));
15913        assert_eq!(md.source, "<div class=\"right\">\n\nhello\n\n</div>\n");
15914
15915        let mut html = fmt_doc("<p>hello</p>\n", Format::Html);
15916        html.caret = html.source.find("hello").unwrap();
15917        html.set_alignment(Some(Align::Justify));
15918        assert_eq!(html.source, "<p class=\"justify\">hello</p>\n");
15919    }
15920
15921    /// Each gesture edits **one key and keeps the rest** — twig's contract is
15922    /// replace-not-merge, so leaf reads the node's attributes, edits its own
15923    /// key out of them, and passes the list back whole. A document from
15924    /// elsewhere passes through the editor unharmed.
15925    #[test]
15926    fn a_presentation_gesture_keeps_every_attribute_it_did_not_write() {
15927        let mut d = fmt_doc(
15928            "{.lead .center #intro data-line-height=\"1.5\"}\nhello\n",
15929            Format::Djot,
15930        );
15931        d.caret = d.source.find("hello").unwrap();
15932        d.set_alignment(Some(Align::Right));
15933        // `center` goes, `lead` stays, and neither the id nor the spacing is
15934        // touched.
15935        // The serializer picks the order; what matters is which keys survive.
15936        assert!(d.source.contains(".lead"), "{:?}", d.source);
15937        assert!(d.source.contains(".right"), "{:?}", d.source);
15938        assert!(!d.source.contains(".center"), "{:?}", d.source);
15939        assert!(d.source.contains("#intro"), "{:?}", d.source);
15940        assert!(
15941            d.source.contains("data-line-height=\"1.5\""),
15942            "{:?}",
15943            d.source
15944        );
15945        assert_eq!(d.alignment_at_caret(), Some(Align::Right));
15946        assert_eq!(
15947            d.line_spacing_at_caret(),
15948            Some(LineHeight::Step(LineSpacing::OneHalf))
15949        );
15950
15951        // And the other way round: the spacing gesture leaves the classes be.
15952        d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
15953        assert!(d.source.contains(".lead"), "{:?}", d.source);
15954        assert!(d.source.contains(".right"), "{:?}", d.source);
15955        assert_eq!(
15956            d.line_spacing_at_caret(),
15957            Some(LineHeight::Step(LineSpacing::Double))
15958        );
15959    }
15960
15961    /// Clearing is the same gesture with `None`: the key goes, the tokens leaf
15962    /// owns go out of `class`, and a block left with nothing at all is spelled
15963    /// bare again — in Markdown by unwrapping the div twig wrapped it in.
15964    #[test]
15965    fn none_clears_a_key_and_an_empty_set_unwraps_the_block() {
15966        let mut dj = fmt_doc("{.lead .center}\nhello\n", Format::Djot);
15967        dj.caret = dj.source.find("hello").unwrap();
15968        dj.set_alignment(None);
15969        assert_eq!(dj.source, "{.lead}\nhello\n", "the foreign class stays");
15970        assert_eq!(dj.alignment_at_caret(), None);
15971
15972        let mut bare = fmt_doc("{.center}\nhello\n", Format::Djot);
15973        bare.caret = bare.source.find("hello").unwrap();
15974        bare.set_alignment(None);
15975        assert_eq!(
15976            bare.source, "hello\n",
15977            "the last key takes the line with it"
15978        );
15979
15980        let mut md = fmt_doc("hello\n", Format::Markdown);
15981        md.caret = 1;
15982        md.set_alignment(Some(Align::Center));
15983        assert_eq!(md.source, "<div class=\"center\">\n\nhello\n\n</div>\n");
15984        md.caret = md.source.find("hello").unwrap();
15985        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::OneFifteen)));
15986        assert_eq!(
15987            md.source, "<div class=\"center\" data-line-height=\"1.15\">\n\nhello\n\n</div>\n",
15988            "the second key rewrites the div rather than nesting a second"
15989        );
15990        md.caret = md.source.find("hello").unwrap();
15991        md.set_alignment(None);
15992        md.caret = md.source.find("hello").unwrap();
15993        md.set_line_spacing(None);
15994        assert_eq!(md.source, "hello\n", "an empty set unwraps the div");
15995    }
15996
15997    /// Size, face and colour are the run's over a selection and the block's
15998    /// with none — so "make this paragraph larger" is a click with the caret in
15999    /// it rather than a select-all first.
16000    #[test]
16001    fn a_run_gesture_wraps_a_selection_and_sets_the_block_without_one() {
16002        // With a selection: a span, in each format's own spelling.
16003        let mut dj = fmt_doc("a big b\n", Format::Djot);
16004        dj.anchor = Some(2);
16005        dj.caret = 5;
16006        dj.set_font_size(Some(FontSize::Step(SizeStep::Large)));
16007        assert_eq!(dj.source, "a [big]{data-size=\"large\"} b\n");
16008        assert_eq!(
16009            dj.font_size_at_caret(),
16010            Some(FontSize::Step(SizeStep::Large))
16011        );
16012
16013        let mut md = fmt_doc("a big b\n", Format::Markdown);
16014        md.anchor = Some(2);
16015        md.caret = 5;
16016        md.set_text_color(Some(TextColor::Named(MarkColor::Blue)));
16017        assert_eq!(md.source, "a <span data-color=\"blue\">big</span> b\n");
16018        assert_eq!(
16019            md.text_color_at_caret(),
16020            Some(TextColor::Named(MarkColor::Blue))
16021        );
16022
16023        // Without one: the caret's block, through the block gesture.
16024        let mut block = fmt_doc("a big b\n", Format::Djot);
16025        block.caret = 3;
16026        block.set_font_family(Some(FontFace::Generic(FontFamily::Monospace)));
16027        assert_eq!(block.source, "{data-font=\"monospace\"}\na big b\n");
16028        assert_eq!(
16029            block.font_family_at_caret(),
16030            Some(FontFace::Generic(FontFamily::Monospace))
16031        );
16032    }
16033
16034    /// The *Other…* row of each of the four menus: a value goes into the
16035    /// document in its canonical spelling and comes back out of the query as
16036    /// the same value. One round trip per property, because the four go out
16037    /// through different doors — two block gestures, and the run three through
16038    /// the span that `wrap_range_attrs` mints.
16039    #[test]
16040    fn an_exact_value_round_trips_through_the_gesture_and_the_query() {
16041        // Size: the run three, over a selection.
16042        let mut d = fmt_doc("a big b\n", Format::Djot);
16043        d.anchor = Some(2);
16044        d.caret = 5;
16045        d.set_font_size(FontSize::points(14.0));
16046        assert_eq!(d.source, "a [big]{data-size=\"14pt\"} b\n");
16047        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
16048
16049        // Colour, onto the same span — the gesture keeps the size it finds.
16050        d.set_text_color(Some(TextColor::Rgb {
16051            r: 0xc0,
16052            g: 0x30,
16053            b: 0x30,
16054        }));
16055        assert_eq!(
16056            d.source,
16057            "a [big]{data-size=\"14pt\" data-color=\"#c03030\"} b\n"
16058        );
16059        assert_eq!(
16060            d.text_color_at_caret(),
16061            Some(TextColor::Rgb {
16062                r: 0xc0,
16063                g: 0x30,
16064                b: 0x30
16065            })
16066        );
16067
16068        // Face: a family name, as given.
16069        d.set_font_family(Some(FontFace::Named("Garamond".into())));
16070        assert!(
16071            d.source.contains("data-font=\"Garamond\""),
16072            "{:?}",
16073            d.source
16074        );
16075        assert_eq!(
16076            d.font_family_at_caret(),
16077            Some(FontFace::Named("Garamond".into()))
16078        );
16079
16080        // Line spacing: a block gesture, and an exact ratio.
16081        let mut block = fmt_doc("hello\n", Format::Djot);
16082        block.caret = 1;
16083        block.set_line_spacing(LineHeight::ratio(1.3));
16084        assert_eq!(block.source, "{data-line-height=\"1.3\"}\nhello\n");
16085        assert_eq!(block.line_spacing_at_caret(), LineHeight::ratio(1.3));
16086
16087        // And a value spelled long is written back short, so the same press
16088        // twice writes the same bytes: `14.0pt` in, `14pt` out.
16089        let mut long = fmt_doc("{data-size=\"14.0pt\"}\nhello\n", Format::Djot);
16090        long.caret = long.source.find("hello").unwrap();
16091        assert_eq!(long.font_size_at_caret(), FontSize::points(14.0));
16092        let in_force = long.font_size_at_caret();
16093        long.set_font_size(in_force);
16094        assert_eq!(long.source, "{data-size=\"14pt\"}\nhello\n");
16095    }
16096
16097    /// A value the grammar does not cover is what it was before the vocabulary
16098    /// opened: carried untouched by the document, answered `None` by the query
16099    /// so the menu ticks *Default*, and rewritten only by a gesture on its own
16100    /// key. leaf is not going to grow a CSS parser to guess at `1.3em`.
16101    #[test]
16102    fn a_value_outside_the_grammar_is_carried_and_the_menu_ticks_the_default() {
16103        let src =
16104            "{data-size=\"huge\" data-color=\"rgb(1,2,3)\" data-line-height=\"1.3em\"}\nhello\n";
16105        let mut d = fmt_doc(src, Format::Djot);
16106        d.caret = d.source.find("hello").unwrap();
16107        assert_eq!(d.font_size_at_caret(), None);
16108        assert_eq!(d.text_color_at_caret(), None);
16109        assert_eq!(d.line_spacing_at_caret(), None);
16110
16111        // The keys are still there, untouched, after a gesture on a *different*
16112        // key — "edit one key and keep the rest" holds for a value it cannot
16113        // read as readily as for one it can.
16114        d.set_alignment(Some(Align::Center));
16115        assert!(d.source.contains("data-size=\"huge\""), "{:?}", d.source);
16116        assert!(
16117            d.source.contains("data-color=\"rgb(1,2,3)\""),
16118            "{:?}",
16119            d.source
16120        );
16121        assert!(
16122            d.source.contains("data-line-height=\"1.3em\""),
16123            "{:?}",
16124            d.source
16125        );
16126        // And the gesture on its *own* key replaces it, which is the one way a
16127        // carried value ever changes.
16128        d.caret = d.source.find("hello").unwrap();
16129        d.set_font_size(FontSize::points(12.0));
16130        assert!(d.source.contains("data-size=\"12pt\""), "{:?}", d.source);
16131        assert!(!d.source.contains("huge"), "{:?}", d.source);
16132    }
16133
16134    /// The nearest node wins whichever *form* either node wrote: a value inside
16135    /// a name, a name inside a value. The fold has one rule and does not learn
16136    /// a second one for exact values.
16137    #[test]
16138    fn the_nearest_node_wins_whether_it_named_a_size_or_measured_one() {
16139        // A value inside a name: the block says `small`, the span says `14pt`.
16140        let mut d = fmt_doc(
16141            "{data-size=\"small\"}\nx [y]{data-size=\"14pt\"} z\n",
16142            Format::Djot,
16143        );
16144        d.caret = d.source.find('y').unwrap();
16145        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
16146        d.caret = d.source.find('x').unwrap();
16147        assert_eq!(
16148            d.font_size_at_caret(),
16149            Some(FontSize::Step(SizeStep::Small))
16150        );
16151
16152        // And a name inside a value, which is the same rule read the other way.
16153        let mut e = fmt_doc(
16154            "{data-size=\"14pt\" data-color=\"#c03030\"}\nx [y]{data-size=\"small\"} z\n",
16155            Format::Djot,
16156        );
16157        e.caret = e.source.find('y').unwrap();
16158        assert_eq!(
16159            e.font_size_at_caret(),
16160            Some(FontSize::Step(SizeStep::Small))
16161        );
16162        assert_eq!(
16163            e.text_color_at_caret(),
16164            Some(TextColor::Rgb {
16165                r: 0xc0,
16166                g: 0x30,
16167                b: 0x30
16168            }),
16169            "the block's colour still reaches the span"
16170        );
16171        e.caret = e.source.find('x').unwrap();
16172        assert_eq!(e.font_size_at_caret(), FontSize::points(14.0));
16173    }
16174
16175    /// twig re-styles the span a range already lies in rather than nesting a
16176    /// second, and an empty set unwraps it — so a second press of the menu
16177    /// fixes the size instead of building `[[big]{.a}]{.b}`, and the entry that
16178    /// means "the theme's own" takes the span away.
16179    #[test]
16180    fn a_second_run_gesture_re_styles_the_span_and_none_unwraps_it() {
16181        let mut d = fmt_doc("a big b\n", Format::Djot);
16182        d.anchor = Some(2);
16183        d.caret = 5;
16184        d.set_font_size(Some(FontSize::Step(SizeStep::Large)));
16185        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
16186
16187        // The selection `wrap_range_attrs` left behind covers the whole span;
16188        // colouring it now keeps the size, because the gesture reads the span's
16189        // attributes before it edits its own key.
16190        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
16191        assert_eq!(
16192            d.source, "a [big]{data-size=\"large\" data-color=\"red\"} b\n",
16193            "one span, both keys"
16194        );
16195        assert_eq!(
16196            d.font_size_at_caret(),
16197            Some(FontSize::Step(SizeStep::Large))
16198        );
16199        assert_eq!(
16200            d.text_color_at_caret(),
16201            Some(TextColor::Named(MarkColor::Red))
16202        );
16203
16204        d.set_text_color(None);
16205        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
16206        d.set_font_size(None);
16207        assert_eq!(d.source, "a big b\n", "the last key unwraps the span");
16208        assert_eq!(d.font_size_at_caret(), None);
16209    }
16210
16211    /// The queries read the nearest node that names the property: the span the
16212    /// caret is in, then its block, then the `div`s around it.
16213    #[test]
16214    fn a_presentation_query_reads_the_nearest_node_that_names_it() {
16215        let mut d = fmt_doc(
16216            "{.center data-size=\"small\" data-font=\"serif\"}\nx [y]{data-size=\"xx-large\"} z\n",
16217            Format::Djot,
16218        );
16219        // In the span: its own size, the block's face and alignment.
16220        d.caret = d.source.find('y').unwrap();
16221        assert_eq!(
16222            d.font_size_at_caret(),
16223            Some(FontSize::Step(SizeStep::XxLarge))
16224        );
16225        assert_eq!(
16226            d.font_family_at_caret(),
16227            Some(FontFace::Generic(FontFamily::Serif))
16228        );
16229        assert_eq!(d.alignment_at_caret(), Some(Align::Center));
16230        assert_eq!(d.line_spacing_at_caret(), None);
16231        assert_eq!(d.text_color_at_caret(), None);
16232
16233        // Outside it: the block's size.
16234        d.caret = d.source.find('x').unwrap();
16235        assert_eq!(
16236            d.font_size_at_caret(),
16237            Some(FontSize::Step(SizeStep::Small))
16238        );
16239
16240        // And through a Markdown div, which is where a Markdown block's
16241        // attributes live.
16242        let mut md = fmt_doc(
16243            "<div class=\"center\" data-size=\"large\">\n\nhello\n\n</div>\n",
16244            Format::Markdown,
16245        );
16246        md.caret = md.source.find("hello").unwrap();
16247        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
16248        assert_eq!(
16249            md.font_size_at_caret(),
16250            Some(FontSize::Step(SizeStep::Large))
16251        );
16252
16253        // A document that names none of it answers `None` everywhere, which is
16254        // "the theme's own" and what every toolbar draws unlit.
16255        let mut plain = doc_with("plain_presentation", "hello\n");
16256        plain.caret = 1;
16257        assert_eq!(plain.alignment_at_caret(), None);
16258        assert_eq!(plain.line_spacing_at_caret(), None);
16259        assert_eq!(plain.font_size_at_caret(), None);
16260        assert_eq!(plain.font_family_at_caret(), None);
16261        assert_eq!(plain.text_color_at_caret(), None);
16262    }
16263
16264    /// A djot fenced div is anonymous the way an attributed span is, and is a
16265    /// block all the same — the *form* is the whole of what tells them apart.
16266    /// Read as a span it poisoned both halves: the run gesture copied the div's
16267    /// entire attribute set onto the span it minted, duplicating the `id`, and
16268    /// the run and block queries answered off a node the walker draws nothing
16269    /// for.
16270    #[test]
16271    fn a_djot_fenced_div_is_not_an_attributed_span() {
16272        let src = "{.center data-size=\"small\" #box}\n:::\nhello world\n:::\n";
16273        let mut d = fmt_doc(src, Format::Djot);
16274        let at = d.source.find("world").unwrap();
16275        d.anchor = Some(at);
16276        d.caret = at + "world".len();
16277        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
16278        assert_eq!(
16279            d.source,
16280            "{.center data-size=\"small\" #box}\n:::\nhello [world]{data-color=\"red\"}\n:::\n",
16281            "the span carries its own key and nothing of the div's"
16282        );
16283
16284        // And the queries stop at the block: a djot div is not a `<div>`, the
16285        // walker lends its keys to nothing inside it, and a query that said
16286        // otherwise would tick a menu entry no glyph on screen obeys.
16287        assert_eq!(
16288            d.text_color_at_caret(),
16289            Some(TextColor::Named(MarkColor::Red))
16290        );
16291        assert_eq!(d.font_size_at_caret(), None);
16292        assert_eq!(d.alignment_at_caret(), None);
16293    }
16294
16295    /// Clearing a property the block does not name and a `div` around it does
16296    /// would write nothing and change nothing — twig's `set_block_attrs`
16297    /// reaches one node, and the div is not it. The gesture says so instead of
16298    /// leaving the author pressing an entry that never ticks.
16299    #[test]
16300    fn clearing_a_property_an_enclosing_div_names_says_so_and_writes_nothing() {
16301        // Markdown, two paragraphs in one div: not the sole-child shape twig
16302        // writes, so `block_attrs_at_caret` reads the paragraph and the
16303        // paragraph names none of it.
16304        let src = "<div class=\"center\" data-line-height=\"1.5\" data-size=\"large\">\n\nhello\n\nworld\n\n</div>\n";
16305        let mut md = fmt_doc(src, Format::Markdown);
16306        md.caret = md.source.find("hello").unwrap();
16307        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
16308
16309        md.set_alignment(None);
16310        assert_eq!(md.source, src, "nothing written");
16311        assert!(!md.dirty);
16312        assert_eq!(
16313            md.status.as_deref(),
16314            Some("alignment: set on the div around the block")
16315        );
16316        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
16317
16318        // The same for a `data-` key, at both levels — the block pair and the
16319        // run three, the run three at a bare caret being the block gesture.
16320        md.set_line_spacing(None);
16321        assert_eq!(md.source, src);
16322        assert_eq!(
16323            md.status.as_deref(),
16324            Some("line spacing: set on the div around the block")
16325        );
16326        md.set_font_size(None);
16327        assert_eq!(md.source, src);
16328        assert_eq!(
16329            md.status.as_deref(),
16330            Some("size: set on the div around the block")
16331        );
16332
16333        // HTML has no sole-child fold at all: a block's attributes go on the
16334        // block, so the div around one is always out of reach.
16335        let html_src = "<div class=\"center\"><p>hi</p></div>\n";
16336        let mut html = fmt_doc(html_src, Format::Html);
16337        html.caret = html.source.find("hi").unwrap();
16338        assert_eq!(html.alignment_at_caret(), Some(Align::Center));
16339        html.set_alignment(None);
16340        assert_eq!(html.source, html_src);
16341        assert!(!html.dirty);
16342        assert_eq!(
16343            html.status.as_deref(),
16344            Some("alignment: set on the div around the block")
16345        );
16346
16347        // And it is a refusal, not a rule against clearing: a block that names
16348        // the property itself still loses it, div or no div.
16349        let mut own = fmt_doc(
16350            "<div class=\"center\"><p class=\"right\">hi</p></div>\n",
16351            Format::Html,
16352        );
16353        own.caret = own.source.find("hi").unwrap();
16354        own.set_alignment(None);
16355        assert_eq!(own.source, "<div class=\"center\"><p>hi</p></div>\n");
16356        assert_eq!(own.status, None);
16357    }
16358
16359    /// An edited key is rewritten **where it stands**. The proposal's worked
16360    /// example is the test: a paragraph that came in as `id="intro"
16361    /// class="lead center" data-line-height="1.5"` and is right-aligned goes
16362    /// out as the same list with one token changed. Removing the key and
16363    /// pushing it back shuffled a document's attributes on every press.
16364    #[test]
16365    fn an_edited_key_keeps_its_place_among_the_attributes() {
16366        let mut html = fmt_doc(
16367            "<p id=\"intro\" class=\"lead center\" data-line-height=\"1.5\">hello</p>\n",
16368            Format::Html,
16369        );
16370        html.caret = html.source.find("hello").unwrap();
16371        html.set_alignment(Some(Align::Right));
16372        assert_eq!(
16373            html.source,
16374            "<p id=\"intro\" class=\"lead right\" data-line-height=\"1.5\">hello</p>\n"
16375        );
16376
16377        // A `data-` key the same way, and a key the block did not have still
16378        // goes on the end.
16379        html.caret = html.source.find("hello").unwrap();
16380        html.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
16381        assert_eq!(
16382            html.source,
16383            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\">hello</p>\n"
16384        );
16385        html.caret = html.source.find("hello").unwrap();
16386        html.set_font_size(Some(FontSize::Step(SizeStep::Large)));
16387        assert_eq!(
16388            html.source,
16389            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\" data-size=\"large\">hello</p>\n"
16390        );
16391
16392        // Djot writes the same list in its own spelling, and the order is the
16393        // author's there too.
16394        let mut dj = fmt_doc(
16395            "{#intro .lead .center data-line-height=\"1.5\"}\nhello\n",
16396            Format::Djot,
16397        );
16398        dj.caret = dj.source.find("hello").unwrap();
16399        dj.set_alignment(Some(Align::Right));
16400        assert_eq!(
16401            dj.source,
16402            "{#intro .lead .right data-line-height=\"1.5\"}\nhello\n"
16403        );
16404    }
16405
16406    /// A page break is a block, so twig alone lands one after the caret's whole
16407    /// block; the paragraph is parted at the caret first, exactly as
16408    /// `insert_thematic_break` parts it, and each format spells the directive
16409    /// its own way.
16410    #[test]
16411    fn insert_page_break_parts_the_paragraph_and_spells_the_directive() {
16412        let mut md = doc_with("page_break_md", "hello world\n");
16413        md.caret = 5;
16414        md.insert_page_break();
16415        assert_eq!(md.source, "hello\n\n::page-break\n\nworld\n");
16416        assert!(md.dirty);
16417        assert_eq!(md.status, None);
16418
16419        let mut dj = fmt_doc("hello world\n", Format::Djot);
16420        dj.caret = 5;
16421        dj.insert_page_break();
16422        assert_eq!(dj.source, "hello\n\n::: page-break\n:::\n\nworld\n");
16423
16424        // At a block's end there is no second half to mint, so the break simply
16425        // follows the block — the rule the rule button already has.
16426        let mut end = doc_with("page_break_end", "hello\n");
16427        end.caret = 5;
16428        end.insert_page_break();
16429        assert_eq!(end.source, "hello\n\n::page-break\n");
16430
16431        // And it reaches the map as the placeholder row a frontend paginates on.
16432        end.view = View::Wysiwyg;
16433        end.build_visual(80);
16434        assert_eq!(
16435            end.vmap
16436                .rows
16437                .iter()
16438                .find_map(|r| r.leaf_directive.as_ref())
16439                .map(|m| m.name.as_str()),
16440            Some(PAGE_BREAK)
16441        );
16442    }
16443
16444    /// The vocabulary's capabilities, per format. The two block properties are
16445    /// `SetBlockAttrs` and the three run ones `WrapRangeAttrs`, which is why
16446    /// AsciiDoc can align a paragraph and not size a run: its `[#id.role]#text#`
16447    /// keeps an id and a role and has no slot for a `data-` key.
16448    #[test]
16449    fn the_presentation_capabilities_are_ragged_per_format() {
16450        for fmt in [Format::Markdown, Format::Djot, Format::Html] {
16451            let c = Capabilities::of(fmt);
16452            assert!(c.alignment, "{fmt:?} alignment");
16453            assert!(c.line_spacing, "{fmt:?} line spacing");
16454            assert!(c.font_size, "{fmt:?} size");
16455            assert!(c.font_family, "{fmt:?} face");
16456            assert!(c.text_color, "{fmt:?} colour");
16457        }
16458        // Markdown spells both only under the extensions leaf parses with — a
16459        // `<div>` and a `<span>` read back as containers under `html_elements`,
16460        // and `::page-break` as a directive under `directives`. Ask twig's own
16461        // defaults and the answer is no, which is why `Capabilities` is built
16462        // with `supports_with`.
16463        assert!(!Format::Markdown.supports(Gesture::SetBlockAttrs));
16464        assert!(!Format::Markdown.supports(Gesture::WrapRangeAttrs));
16465        assert!(!Format::Markdown.supports(Gesture::InsertDirective));
16466
16467        let adoc = Capabilities::of(Format::Asciidoc);
16468        assert!(adoc.alignment && adoc.line_spacing, "AsciiDoc's `[…]` line");
16469        assert!(
16470            !adoc.font_size && !adoc.font_family && !adoc.text_color,
16471            "AsciiDoc has no inline spelling that keeps a data- key"
16472        );
16473
16474        // XML spells none of it, and neither page break.
16475        let xml = Capabilities::of(Format::Xml);
16476        assert!(!xml.alignment && !xml.font_size && !xml.page_break);
16477        assert!(Capabilities::of(Format::Markdown).page_break);
16478        assert!(Capabilities::of(Format::Djot).page_break);
16479
16480        // And those two *only*, though twig spells the gesture in HTML and
16481        // AsciiDoc as well: it spells it differently there —
16482        // `<page-break></page-break>` and `<<<` — and the walker reads neither,
16483        // so the button would write a break that draws as nothing at all in
16484        // HTML and as an empty unlabelled row in AsciiDoc. The flag describes
16485        // what leaf can show, not what twig can write. See
16486        // `docs/tasks/page-break-in-html-and-asciidoc.md`.
16487        let exts = parse_extensions();
16488        assert!(Format::Html.supports_with(exts, Gesture::InsertDirective));
16489        assert!(Format::Asciidoc.supports_with(exts, Gesture::InsertDirective));
16490        assert!(!Capabilities::of(Format::Html).page_break);
16491        assert!(!Capabilities::of(Format::Asciidoc).page_break);
16492    }
16493
16494    /// A format that cannot spell a property refuses in its own words and
16495    /// writes nothing — the guard every other gesture has.
16496    #[test]
16497    fn a_presentation_gesture_a_format_cannot_spell_is_refused_with_a_reason() {
16498        let src = "<doc><p>hello</p></doc>\n";
16499        #[allow(clippy::type_complexity)]
16500        let ops: [(&str, &dyn Fn(&mut Doc)); 6] = [
16501            ("alignment", &|d: &mut Doc| {
16502                d.set_alignment(Some(Align::Center))
16503            }),
16504            ("line spacing", &|d: &mut Doc| {
16505                d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)))
16506            }),
16507            ("size", &|d: &mut Doc| {
16508                d.set_font_size(Some(FontSize::Step(SizeStep::Large)))
16509            }),
16510            ("face", &|d: &mut Doc| {
16511                d.set_font_family(Some(FontFace::Generic(FontFamily::Serif)))
16512            }),
16513            ("colour", &|d: &mut Doc| {
16514                d.set_text_color(Some(TextColor::Named(MarkColor::Red)))
16515            }),
16516            ("page break", &|d: &mut Doc| d.insert_page_break()),
16517        ];
16518        for (name, op) in ops {
16519            let mut d = fmt_doc(src, Format::Xml);
16520            let at = d.source.find("hello").unwrap();
16521            d.caret = at;
16522            d.anchor = Some(at + 5);
16523            op(&mut d);
16524            assert_eq!(d.source, src, "{name} edited an XML document");
16525            assert!(!d.dirty, "{name} marked the document dirty");
16526            let status = d.status.as_deref().unwrap_or("");
16527            assert!(
16528                status.contains("xml"),
16529                "{name}: the refusal should name the format, got {status:?}"
16530            );
16531        }
16532
16533        // AsciiDoc is the ragged one: the block gesture works where the run
16534        // gesture does not, and a *selection* is what tells the two apart.
16535        let mut adoc = fmt_doc("hello world\n", Format::Asciidoc);
16536        adoc.anchor = Some(0);
16537        adoc.caret = 5;
16538        adoc.set_font_size(Some(FontSize::Step(SizeStep::Large)));
16539        assert_eq!(adoc.source, "hello world\n", "no inline spelling");
16540        assert!(adoc.status.is_some());
16541    }
16542
16543    /// A read-only document takes none of it, and a caret on a blank line has
16544    /// no block to carry an attribute — both say so rather than writing.
16545    #[test]
16546    fn a_presentation_gesture_respects_read_only_and_a_blank_line() {
16547        let mut ro = fmt_doc("hello\n", Format::Djot);
16548        ro.read_only = true;
16549        ro.caret = 1;
16550        ro.set_alignment(Some(Align::Center));
16551        assert_eq!(ro.source, "hello\n");
16552
16553        let mut blank = fmt_doc("a\n\n\nb\n", Format::Djot);
16554        blank.caret = 2; // the empty line between the two paragraphs
16555        blank.set_alignment(Some(Align::Center));
16556        assert_eq!(blank.source, "a\n\n\nb\n");
16557        assert!(
16558            blank.status.as_deref().unwrap_or("").contains("no block"),
16559            "got {:?}",
16560            blank.status
16561        );
16562    }
16563
16564    /// A block attribute gesture keeps the caret on the **text** it was on, not
16565    /// on the byte offset it had. Markdown has nowhere to put a paragraph's
16566    /// attributes but a `<div>` around it, and twig splices the div and the
16567    /// block it wraps as one region — so a caret that kept its offset landed in
16568    /// the markup, and every press after the first answered "no block at the
16569    /// caret" with the toolbar's queries reading nothing.
16570    #[test]
16571    fn a_markdown_block_gesture_keeps_the_caret_on_its_text() {
16572        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
16573        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
16574        md.caret = md.source.find("brown").unwrap() + 2; // "br|own"
16575
16576        // Wrapping: the div and two blank lines open above the block.
16577        md.set_alignment(Some(Align::Center));
16578        assert_eq!(
16579            md.source,
16580            "<div class=\"center\">\n\nthe quick brown fox\n\n</div>\n"
16581        );
16582        assert_eq!(word(&md), 2, "the caret left its word: {}", md.caret);
16583        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
16584
16585        // Re-styling: the attribute line changes length under the same caret,
16586        // and the second press reaches the same block rather than nothing.
16587        md.set_alignment(Some(Align::Right));
16588        assert_eq!(
16589            md.source, "<div class=\"right\">\n\nthe quick brown fox\n\n</div>\n",
16590            "a second press re-styles the div"
16591        );
16592        assert_eq!(md.status, None);
16593        assert_eq!(word(&md), 2);
16594
16595        // A second key on the same div — the line grows, the caret rides it.
16596        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
16597        assert_eq!(
16598            md.source,
16599            "<div class=\"right\" data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
16600        );
16601        assert_eq!(word(&md), 2);
16602        assert_eq!(
16603            md.line_spacing_at_caret(),
16604            Some(LineHeight::Step(LineSpacing::Double))
16605        );
16606
16607        // Unwrapping: the line shrinks, and then the div goes altogether.
16608        md.set_alignment(None);
16609        assert_eq!(
16610            md.source,
16611            "<div data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
16612        );
16613        assert_eq!(word(&md), 2);
16614        md.set_line_spacing(None);
16615        assert_eq!(md.source, "the quick brown fox\n", "the last key unwraps");
16616        assert_eq!(word(&md), 2, "the caret came back down with the block");
16617        assert_eq!(md.alignment_at_caret(), None);
16618        assert_eq!(md.status, None);
16619    }
16620
16621    /// The same rule in djot, where the spelling is a `{…}` line *above* the
16622    /// block rather than a wrapper around it: inserting it pushes the block
16623    /// down, re-styling it changes the line's length, and clearing the last key
16624    /// takes the line away again. The caret rides all three.
16625    #[test]
16626    fn a_djot_attribute_line_keeps_the_caret_on_its_text() {
16627        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
16628        let mut dj = fmt_doc("the quick brown fox\n", Format::Djot);
16629        dj.caret = dj.source.find("brown").unwrap() + 2;
16630
16631        dj.set_alignment(Some(Align::Center));
16632        assert_eq!(dj.source, "{.center}\nthe quick brown fox\n");
16633        assert_eq!(word(&dj), 2);
16634        assert_eq!(dj.alignment_at_caret(), Some(Align::Center));
16635
16636        dj.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
16637        assert_eq!(
16638            dj.source, "{.center data-line-height=\"2\"}\nthe quick brown fox\n",
16639            "a second press edits the line the first wrote"
16640        );
16641        assert_eq!(word(&dj), 2);
16642
16643        dj.set_alignment(None);
16644        assert_eq!(dj.source, "{data-line-height=\"2\"}\nthe quick brown fox\n");
16645        assert_eq!(word(&dj), 2);
16646
16647        dj.set_line_spacing(None);
16648        assert_eq!(dj.source, "the quick brown fox\n");
16649        assert_eq!(word(&dj), 2);
16650        assert_eq!(dj.status, None);
16651    }
16652
16653    /// The run gestures with no selection are the block gesture, so they keep
16654    /// the caret the same way — and a heading keeps it inside the heading's own
16655    /// text, past the `# ` its content span starts after. A selection rides
16656    /// along whole: a block gesture is not a run gesture, and what was selected
16657    /// before the press is still selected after it.
16658    #[test]
16659    fn a_block_gesture_carries_a_selection_and_a_heading_caret_too() {
16660        // No selection: the run gesture goes through the block door.
16661        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
16662        md.caret = md.source.find("brown").unwrap() + 2;
16663        md.set_font_size(Some(FontSize::Step(SizeStep::Large)));
16664        assert_eq!(
16665            md.source,
16666            "<div data-size=\"large\">\n\nthe quick brown fox\n\n</div>\n"
16667        );
16668        assert_eq!(md.caret - md.source.find("brown").unwrap(), 2);
16669        assert_eq!(
16670            md.font_size_at_caret(),
16671            Some(FontSize::Step(SizeStep::Large))
16672        );
16673        md.set_font_size(Some(FontSize::Step(SizeStep::Small)));
16674        assert_eq!(
16675            md.font_size_at_caret(),
16676            Some(FontSize::Step(SizeStep::Small)),
16677            "the second press reached the same block"
16678        );
16679
16680        // A selection: alignment is the block's whatever is selected, and the
16681        // words stay selected.
16682        let mut sel = fmt_doc("the quick brown fox\n", Format::Markdown);
16683        let at = sel.source.find("brown").unwrap();
16684        sel.anchor = Some(at);
16685        sel.caret = at + 5;
16686        sel.set_alignment(Some(Align::Center));
16687        let now = sel.source.find("brown").unwrap();
16688        assert_eq!(sel.selection(), Some((now, now + 5)), "the words moved out");
16689
16690        // A heading: the content span starts past the `# `.
16691        let mut h = fmt_doc("# hi there\n\nbody\n", Format::Markdown);
16692        h.caret = h.source.find("there").unwrap() + 1;
16693        h.set_alignment(Some(Align::Right));
16694        assert_eq!(
16695            h.source,
16696            "<div class=\"right\">\n\n# hi there\n\n</div>\n\nbody\n"
16697        );
16698        assert_eq!(h.caret, h.source.find("there").unwrap() + 1);
16699        assert_eq!(h.alignment_at_caret(), Some(Align::Right));
16700    }
16701
16702    /// A djot document open in the rich view, with its map built as
16703    /// [`wysiwyg_doc`] builds a Markdown one's.
16704    fn wysiwyg_djot(body: &str) -> Doc {
16705        let mut d = fmt_doc(body, Format::Djot);
16706        d.view = View::Wysiwyg;
16707        d.build_visual(80);
16708        d
16709    }
16710
16711    /// Backspace at the start of a block whose presentation is spelled as
16712    /// hidden markup before it strips that presentation, the way Backspace at
16713    /// a heading's start strips its `#`. The ordinary delete fused djot's
16714    /// `{.center}` line onto the text and took the blank line a Markdown div
16715    /// needs between its tag and its paragraph.
16716    #[test]
16717    fn backspace_at_the_start_of_a_centred_paragraph_strips_its_attributes() {
16718        let mut md = wysiwyg_doc(
16719            "wys_attr_bksp",
16720            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
16721        );
16722        md.caret = md.source.find("hello").unwrap();
16723        md.backspace();
16724        assert_eq!(
16725            md.source, "above\n\nhello\n\nbelow\n",
16726            "the div is unwrapped"
16727        );
16728        assert_eq!(md.caret, 7, "the caret stays at the start of its text");
16729        md.backspace();
16730        assert_eq!(
16731            md.source, "above\nhello\n\nbelow\n",
16732            "the next press joins the paragraphs, as it always did"
16733        );
16734
16735        let mut dj = wysiwyg_djot("above\n\n{.center}\nhello\n\nbelow\n");
16736        dj.caret = dj.source.find("hello").unwrap();
16737        dj.backspace();
16738        assert_eq!(
16739            dj.source, "above\n\nhello\n\nbelow\n",
16740            "the attribute line goes"
16741        );
16742        assert_eq!(dj.caret, 7);
16743
16744        // A heading's own marker is the nearer hidden markup, and goes first;
16745        // the attributes are the next press's.
16746        let mut dj = wysiwyg_djot("{.center}\n# Title\n");
16747        dj.caret = dj.source.find("Title").unwrap();
16748        dj.backspace();
16749        assert_eq!(dj.source, "{.center}\nTitle\n", "the `#` first");
16750        dj.build_visual(80);
16751        dj.backspace();
16752        assert_eq!(dj.source, "Title\n", "then the attributes");
16753        assert_eq!(dj.caret, 0);
16754    }
16755
16756    /// A div around several blocks has no sole child for twig to unwrap, so
16757    /// at its first block the caret steps back to the stop before rather than
16758    /// taking the div apart; a later block has an ordinary paragraph above it
16759    /// and joins as any paragraph does.
16760    #[test]
16761    fn backspace_at_the_first_of_a_div_s_blocks_steps_back_and_a_later_one_joins() {
16762        let src = "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n";
16763        let mut d = wysiwyg_doc("wys_div_first", src);
16764        d.caret = d.source.find("hello").unwrap();
16765        d.backspace();
16766        assert_eq!(d.source, src, "nothing is deleted");
16767        assert_eq!(d.caret, 5, "the caret steps back to the end of `above`");
16768
16769        let mut d = wysiwyg_doc("wys_div_later", src);
16770        d.caret = d.source.find("world").unwrap();
16771        d.backspace();
16772        assert_eq!(
16773            d.source, "above\n\n<div class=\"center\">\n\nhello\nworld\n\n</div>\n",
16774            "a later block joins the one above it"
16775        );
16776    }
16777
16778    /// Backspace at the start of the paragraph after a Markdown div joins it
16779    /// into the div's last paragraph — the join any two paragraphs make, with
16780    /// the hidden `</div>` carried past the joined text. The ordinary delete
16781    /// took the newline under the tag, which drew nothing different, and the
16782    /// next press took the `>` and left the div unclosed.
16783    #[test]
16784    fn backspace_after_a_div_joins_the_paragraph_into_it() {
16785        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
16786        let mut d = wysiwyg_doc("wys_div_join", src);
16787        d.caret = d.source.find("below").unwrap();
16788        d.backspace();
16789        assert_eq!(
16790            d.source,
16791            "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n"
16792        );
16793        assert_eq!(
16794            d.caret,
16795            d.source.find("below").unwrap(),
16796            "the caret stays at the start of the joined text"
16797        );
16798        d.build_visual(80);
16799        assert_eq!(
16800            d.alignment_at_caret(),
16801            Some(Align::Center),
16802            "and is centred now"
16803        );
16804        d.undo();
16805        assert_eq!(d.source, src, "one undo step");
16806
16807        // A list closes the div: the paragraph joins the last item's text,
16808        // under the item's continuation indent, inside the div.
16809        let src = "<div class=\"center\">\n\n- item\n\n</div>\n\nbelow\n";
16810        let mut d = wysiwyg_doc("wys_div_list", src);
16811        d.caret = d.source.find("below").unwrap();
16812        d.backspace();
16813        assert_eq!(
16814            d.source, "<div class=\"center\">\n\n- item\n  below\n\n</div>\n",
16815            "the paragraph joins the item"
16816        );
16817        assert_eq!(d.caret, d.source.find("below").unwrap());
16818
16819        // And where twig has nothing to join into — a code block above — the
16820        // caret steps back to the stop before, and nothing is deleted.
16821        let src = "```\ncode\n```\n\nbelow\n";
16822        let mut d = wysiwyg_doc("wys_code_then_para", src);
16823        d.caret = d.source.find("below").unwrap();
16824        d.backspace();
16825        assert_eq!(d.source, src, "nothing is deleted");
16826        assert!(
16827            d.caret < d.source.find("below").unwrap(),
16828            "the caret stepped back"
16829        );
16830    }
16831
16832    /// Backspace on a blank line collapses to the stop before it — but not
16833    /// across hidden markup, which that collapse deleted whole: a `</div>`,
16834    /// or a comment between two blocks. There the blank line goes alone, and
16835    /// the caret lands where the collapse would have put it.
16836    #[test]
16837    fn backspace_on_a_blank_line_after_hidden_markup_keeps_the_markup() {
16838        let mut d = wysiwyg_doc(
16839            "wys_div_blank",
16840            "<div class=\"center\">\n\nhello\n\n</div>\n\n\n\nbelow\n",
16841        );
16842        d.caret = d.source.find("below").unwrap() - 2; // the empty paragraph
16843        assert!(
16844            d.vmap.is_stop(d.caret),
16845            "the empty paragraph is a caret home"
16846        );
16847        d.backspace();
16848        assert_eq!(
16849            d.source, "<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
16850            "the blank line goes and the div stays closed"
16851        );
16852        assert_eq!(
16853            d.caret,
16854            d.source.find("hello").unwrap() + 5,
16855            "onto the end of `hello`"
16856        );
16857
16858        let mut d = wysiwyg_doc("wys_comment_blank", "above\n\n<!-- note -->\n\n\n\nbelow\n");
16859        d.caret = d.source.find("below").unwrap() - 2;
16860        assert!(d.vmap.is_stop(d.caret));
16861        d.backspace();
16862        assert_eq!(
16863            d.source, "above\n\n<!-- note -->\n\nbelow\n",
16864            "the comment stays"
16865        );
16866        assert_eq!(d.caret, 5);
16867    }
16868
16869    /// Backspace at the end of an attributed span steps inside its hidden
16870    /// closing tag the way it steps inside a `**`, and takes the span with
16871    /// its last letter. Before, the byte-step took the `>` of `</span>`,
16872    /// which left the paragraph unparseable: it vanished from the rich view,
16873    /// and the Backspace after that joined the next block into the wreck.
16874    #[test]
16875    fn backspace_walks_into_a_sized_span_and_takes_the_emptied_span_with_its_space() {
16876        let src = "above\n\nThis <span data-size=\"x-large\">is</span> a test\n\nTest 2\n";
16877        let mut d = wysiwyg_doc("wys_span_bs", src);
16878        d.caret = d.source.find("a test").unwrap() + 6;
16879        for _ in 0..7 {
16880            d.backspace();
16881        }
16882        assert_eq!(
16883            d.source,
16884            "above\n\nThis <span data-size=\"x-large\">is</span>\n\nTest 2\n"
16885        );
16886        d.backspace();
16887        assert_eq!(
16888            d.source, "above\n\nThis <span data-size=\"x-large\">i</span>\n\nTest 2\n",
16889            "the first Backspace after the tag takes the letter, not the `>`"
16890        );
16891        d.backspace();
16892        assert_eq!(
16893            d.source, "above\n\nThis \n\nTest 2\n",
16894            "the last letter takes the span with it"
16895        );
16896        assert_eq!(d.caret, 12, "the caret is where the letter was");
16897        d.backspace();
16898        assert_eq!(d.source, "above\n\nThis\n\nTest 2\n");
16899        assert_eq!(d.caret, 11);
16900        d.build_visual(80);
16901        assert!(
16902            d.vmap
16903                .rows
16904                .iter()
16905                .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "This"),
16906            "the paragraph is still drawn"
16907        );
16908    }
16909
16910    #[test]
16911    fn backspace_walks_into_a_djot_sized_span_too() {
16912        let mut d = wysiwyg_djot("This [is]{data-size=\"x-large\"}\n\nTest 2\n");
16913        d.caret = d.source.find("\n\nTest 2").unwrap();
16914        // The caret home at the paragraph's end is inside the span, before
16915        // its `]`: the map offers no stop after `]{…}`.
16916        d.build_visual(80);
16917        assert_eq!(d.vmap.stop_before(31), Some(8));
16918        d.caret = 8;
16919        d.backspace();
16920        assert_eq!(d.source, "This [i]{data-size=\"x-large\"}\n\nTest 2\n");
16921        d.backspace();
16922        assert_eq!(
16923            d.source, "This \n\nTest 2\n",
16924            "the attribute block outside the span goes with it"
16925        );
16926        d.backspace();
16927        assert_eq!(d.source, "This\n\nTest 2\n");
16928        assert_eq!(d.caret, 4);
16929    }
16930
16931    /// A span that is empty as the file was written has no stop of its own;
16932    /// Backspace reaching it from behind takes it with the character before
16933    /// it, the character the key looked aimed at.
16934    #[test]
16935    fn backspace_over_an_already_empty_span_takes_it_with_the_character_before() {
16936        let src = "This <span data-size=\"x-large\"></span> a test\n";
16937        let mut d = wysiwyg_doc("wys_span_empty", src);
16938        d.caret = d.source.find(" a test").unwrap();
16939        d.backspace();
16940        assert_eq!(d.source, "This a test\n");
16941        assert_eq!(d.caret, 4);
16942    }
16943
16944    /// The mirror: Delete in front of a span's opening tag takes its first
16945    /// letter, and the span with its last.
16946    #[test]
16947    fn delete_walks_into_a_sized_span_and_takes_the_span_with_its_last_letter() {
16948        let src = "This <span data-size=\"x-large\">is</span> a test\n";
16949        let mut d = wysiwyg_doc("wys_span_del", src);
16950        d.caret = 5;
16951        d.delete_forward();
16952        assert_eq!(
16953            d.source,
16954            "This <span data-size=\"x-large\">s</span> a test\n"
16955        );
16956        d.delete_forward();
16957        assert_eq!(d.source, "This  a test\n");
16958        assert_eq!(d.caret, 5);
16959        d.delete_forward();
16960        assert_eq!(d.source, "This a test\n");
16961        assert_eq!(d.caret, 5);
16962    }
16963
16964    /// The block version of the span's emptying rule. Centre a one-letter
16965    /// paragraph — Markdown spells that as a `<div>` around it — and
16966    /// Backspace the letter: the div goes with it, leaving a plain blank line
16967    /// the caret is at home on, in the incremental map and the from-scratch
16968    /// one alike. Before, the letter went alone; the emptied div drew a
16969    /// caret home only the stale map had, and the next Backspace collapsed
16970    /// the line and left `<div class="center">\n\n</div>` standing invisibly
16971    /// in the file.
16972    #[test]
16973    fn backspace_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
16974        let mut d = wysiwyg_doc("wys_div_empty", "Try the toolbar.\n\nT\n");
16975        d.caret = d.source.len() - 1;
16976        d.set_alignment(Some(Align::Center));
16977        assert_eq!(
16978            d.source,
16979            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n"
16980        );
16981        d.backspace();
16982        assert_eq!(d.source, "Try the toolbar.\n\n\n");
16983        assert_eq!(d.caret, 18, "on the blank line where the letter was");
16984        // The host rebuilds the map after every key; the spliced map and a
16985        // fresh one both give the line a caret home.
16986        d.build_visual_unwrapped();
16987        assert!(d.vmap.is_stop(18));
16988        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
16989        d.backspace();
16990        assert_eq!(
16991            d.source, "Try the toolbar.\n",
16992            "then the blank line collapses"
16993        );
16994        assert_eq!(d.caret, 16);
16995
16996        // With a block after the div the blank line keeps a gap each side.
16997        let mut d = wysiwyg_doc(
16998            "wys_div_empty_mid",
16999            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n\nbelow\n",
17000        );
17001        d.caret = d.source.find("T\n").unwrap() + 1;
17002        d.backspace();
17003        assert_eq!(d.source, "Try the toolbar.\n\n\n\nbelow\n");
17004        assert_eq!(d.caret, 18);
17005        d.build_visual_unwrapped();
17006        assert!(d.vmap.is_stop(18));
17007        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
17008    }
17009
17010    /// djot spells the same paragraph as a `{.center}` line above it, and
17011    /// twig has no node at all for that line once the paragraph is gone —
17012    /// so the line goes with the letter too.
17013    #[test]
17014    fn backspace_that_empties_a_centred_paragraph_takes_its_djot_attrs_line_too() {
17015        let mut d = fmt_doc("Try the toolbar.\n\nT\n", Format::Djot);
17016        d.build_visual(80);
17017        d.caret = d.source.len() - 1;
17018        d.set_alignment(Some(Align::Center));
17019        assert_eq!(d.source, "Try the toolbar.\n\n{.center}\nT\n");
17020        d.backspace();
17021        assert_eq!(d.source, "Try the toolbar.\n\n\n");
17022        assert_eq!(d.caret, 18);
17023        d.build_visual(80);
17024        assert!(d.vmap.is_stop(18));
17025    }
17026
17027    /// The rule is for a block that would be no block: a div holding more
17028    /// keeps its tags, and an emptied heading is still a heading.
17029    #[test]
17030    fn emptying_a_paragraph_keeps_a_div_that_holds_more_and_a_heading_its_marker() {
17031        let mut d = wysiwyg_doc(
17032            "wys_div_more",
17033            "<div class=\"center\">\n\nText\n\nT\n\n</div>\n",
17034        );
17035        d.caret = d.source.find("T\n").unwrap() + 1;
17036        d.backspace();
17037        assert_eq!(d.source, "<div class=\"center\">\n\nText\n\n\n\n</div>\n");
17038        assert_eq!(d.caret, 28, "the blank line inside the div, as after Enter");
17039
17040        let mut d = wysiwyg_doc(
17041            "wys_div_heading",
17042            "<div class=\"center\">\n\n# T\n\n</div>\n",
17043        );
17044        d.caret = d.source.find("T\n").unwrap() + 1;
17045        d.backspace();
17046        assert_eq!(d.source, "<div class=\"center\">\n\n# \n\n</div>\n");
17047        assert_eq!(d.caret, 24);
17048        d.build_visual(80);
17049        assert!(
17050            d.vmap.is_stop(24),
17051            "the empty heading is still a caret home"
17052        );
17053    }
17054
17055    /// The mirror: Delete in front of the letter takes the div with it.
17056    #[test]
17057    fn delete_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
17058        let mut d = wysiwyg_doc(
17059            "wys_div_empty_del",
17060            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n",
17061        );
17062        d.caret = d.source.find("T\n").unwrap();
17063        d.delete_forward();
17064        assert_eq!(d.source, "Try the toolbar.\n\n\n");
17065        assert_eq!(d.caret, 18);
17066        d.build_visual(80);
17067        assert!(d.vmap.is_stop(18));
17068
17069        let mut d = fmt_doc("Try the toolbar.\n\n{.center}\nT\n", Format::Djot);
17070        d.build_visual(80);
17071        d.caret = d.source.find("T\n").unwrap();
17072        d.delete_forward();
17073        assert_eq!(d.source, "Try the toolbar.\n\n\n");
17074        assert_eq!(d.caret, 18);
17075    }
17076
17077    /// Backspace at a block's start is twig's join, spelled per format — so
17078    /// the cases the one-newline delete got wrong come out right: a
17079    /// paragraph joins onto a heading's line, HTML's `</p><p>` goes as one,
17080    /// and a quote's prefix is written on the joined line.
17081    #[test]
17082    fn backspace_at_a_block_start_joins_it_the_format_s_way() {
17083        let mut d = wysiwyg_doc("wys_join_heading", "# Title\n\nbelow\n");
17084        d.caret = d.source.find("below").unwrap();
17085        d.backspace();
17086        assert_eq!(d.source, "# Title below\n", "onto the heading's line");
17087        assert_eq!(d.caret, d.source.find("below").unwrap());
17088        d.undo();
17089        assert_eq!(d.source, "# Title\n\nbelow\n", "one undo step");
17090
17091        let mut d = wysiwyg_doc("wys_join_quote", "> a\n\nb\n");
17092        d.caret = d.source.find('b').unwrap();
17093        d.backspace();
17094        assert_eq!(d.source, "> a\n> b\n", "into the quote, with its prefix");
17095        assert_eq!(d.caret, d.source.find('b').unwrap());
17096
17097        let mut h = fmt_doc("<p>above</p>\n<p class=\"x\">below</p>\n", Format::Html);
17098        h.view = View::Wysiwyg;
17099        h.build_visual(80);
17100        h.caret = h.source.find("below").unwrap();
17101        h.backspace();
17102        assert_eq!(
17103            h.source, "<p>above\nbelow</p>\n",
17104            "one paragraph, the tag gone whole"
17105        );
17106        assert_eq!(h.caret, h.source.find("below").unwrap());
17107    }
17108
17109    /// Delete at the end of a block's content is the same join aimed at the
17110    /// block after it, and the caret stays where the joined text now begins.
17111    #[test]
17112    fn delete_at_a_block_end_joins_the_next_block_into_it() {
17113        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
17114        let mut d = wysiwyg_doc("wys_del_join", src);
17115        d.caret = d.source.find("hello").unwrap() + 5;
17116        d.delete_forward();
17117        assert_eq!(
17118            d.source, "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n",
17119            "below joins hello inside the div"
17120        );
17121        assert_eq!(
17122            d.caret,
17123            d.source.find("hello").unwrap() + 5,
17124            "the caret stays"
17125        );
17126
17127        let mut d = wysiwyg_doc("wys_del_join_head", "above\n\n# Title\n");
17128        d.caret = 5;
17129        d.delete_forward();
17130        assert_eq!(
17131            d.source, "above\nTitle\n",
17132            "the heading's marker goes with the join"
17133        );
17134        assert_eq!(d.caret, 5);
17135
17136        // A code block after the paragraph: nothing to join, the caret steps
17137        // forward onto the next stop and nothing is deleted.
17138        let src = "above\n\n```\ncode\n```\n";
17139        let mut d = wysiwyg_doc("wys_del_code", src);
17140        d.caret = 5;
17141        d.delete_forward();
17142        assert_eq!(d.source, src);
17143        assert!(d.caret > 5, "the caret stepped forward");
17144    }
17145
17146    // ── Text statistics ──────────────────────────────────────────────────────
17147
17148    /// The counts of `body`, from a document open in the WYSIWYG view — the
17149    /// shape every case below starts from.
17150    fn counts_of(name: &str, body: &str) -> TextCounts {
17151        doc_in(View::Wysiwyg, name, body).counts()
17152    }
17153
17154    #[test]
17155    fn counts_tally_plain_prose() {
17156        let c = counts_of(
17157            "counts_prose",
17158            "The quick brown fox jumps over the lazy dog.\n",
17159        );
17160        assert_eq!(
17161            c,
17162            TextCounts {
17163                words: 9,
17164                characters: 44,
17165                characters_without_spaces: 36,
17166                paragraphs: 1,
17167            }
17168        );
17169    }
17170
17171    #[test]
17172    fn counts_read_the_text_and_not_the_markup() {
17173        // The `**` are four bytes of source and no part of the word.
17174        assert_eq!(
17175            counts_of("counts_marks", "a **bold** word\n"),
17176            TextCounts {
17177                words: 3,
17178                characters: 11,
17179                characters_without_spaces: 9,
17180                paragraphs: 1,
17181            }
17182        );
17183        // A link is its label; the destination is plumbing, however long.
17184        assert_eq!(
17185            counts_of(
17186                "counts_link",
17187                "see [the label](https://example.com/a/b/c) here\n"
17188            ),
17189            TextCounts {
17190                words: 4,
17191                characters: 18,
17192                characters_without_spaces: 15,
17193                paragraphs: 1,
17194            }
17195        );
17196    }
17197
17198    #[test]
17199    fn counts_spend_nothing_on_a_picture() {
17200        // A block image renders as a `🖼 alt` placeholder — a picture, not a
17201        // sentence, and not a paragraph either.
17202        assert_eq!(
17203            counts_of("counts_image", "![a long caption](pic.png)\n"),
17204            TextCounts::default()
17205        );
17206        // And it adds nothing to the prose around it.
17207        assert_eq!(
17208            counts_of("counts_image_prose", "text\n\n![a long caption](pic.png)\n"),
17209            TextCounts {
17210                words: 1,
17211                characters: 4,
17212                characters_without_spaces: 4,
17213                paragraphs: 1,
17214            }
17215        );
17216    }
17217
17218    #[test]
17219    fn counts_spend_nothing_on_drawn_furniture() {
17220        // A thematic break is drawn, not written, and an empty paragraph has
17221        // nothing in it — neither is a paragraph of the document.
17222        assert_eq!(
17223            counts_of("counts_rule", "one\n\n---\n\ntwo\n"),
17224            TextCounts {
17225                words: 2,
17226                characters: 6,
17227                characters_without_spaces: 6,
17228                paragraphs: 2,
17229            }
17230        );
17231    }
17232
17233    #[test]
17234    fn counts_measure_characters_as_a_reader_does() {
17235        // Four Han characters (each its own word under UAX#29), one ZWJ emoji
17236        // family that is a single grapheme cluster, and two letters.
17237        let c = counts_of(
17238            "counts_graphemes",
17239            "你好世界 👩\u{200d}👩\u{200d}👧\u{200d}👦 ok\n",
17240        );
17241        assert_eq!(
17242            c,
17243            TextCounts {
17244                words: 5,
17245                characters: 9,
17246                characters_without_spaces: 7,
17247                paragraphs: 1,
17248            }
17249        );
17250    }
17251
17252    #[test]
17253    fn counts_take_a_code_block_as_one_paragraph() {
17254        let c = counts_of("counts_code", "```rust\nlet x = 1;\n\nlet y = 2;\n```\n");
17255        assert_eq!(
17256            c,
17257            TextCounts {
17258                words: 6,
17259                characters: 20,
17260                characters_without_spaces: 14,
17261                paragraphs: 1,
17262            }
17263        );
17264    }
17265
17266    #[test]
17267    fn counts_take_a_table_as_one_paragraph() {
17268        // The box-drawn borders and the column padding are the renderer's, not
17269        // the author's; the cells are what was written.
17270        let c = counts_of("counts_table", "| a b | c |\n| - | - |\n| d | e |\n");
17271        assert_eq!(
17272            c,
17273            TextCounts {
17274                words: 5,
17275                characters: 6,
17276                characters_without_spaces: 5,
17277                paragraphs: 1,
17278            }
17279        );
17280    }
17281
17282    #[test]
17283    fn counts_give_every_item_and_every_quoted_paragraph_its_own_paragraph() {
17284        let c = counts_of(
17285            "counts_blocks",
17286            "- one\n- two\n- three\n\n> first quoted\n>\n> second quoted\n",
17287        );
17288        assert_eq!(
17289            c,
17290            TextCounts {
17291                words: 7,
17292                characters: 36,
17293                characters_without_spaces: 34,
17294                paragraphs: 5,
17295            }
17296        );
17297    }
17298
17299    #[test]
17300    fn counts_leave_the_frontmatter_out() {
17301        // The WYSIWYG view doesn't render it and a writer didn't write it.
17302        let c = counts_of(
17303            "counts_frontmatter",
17304            "---\ntitle: Hidden\n---\n\nvisible words here\n",
17305        );
17306        assert_eq!(
17307            c,
17308            TextCounts {
17309                words: 3,
17310                characters: 18,
17311                characters_without_spaces: 16,
17312                paragraphs: 1,
17313            }
17314        );
17315    }
17316
17317    #[test]
17318    fn counts_of_an_empty_document_are_all_zero() {
17319        assert_eq!(counts_of("counts_empty", ""), TextCounts::default());
17320    }
17321
17322    /// UAX#29 puts a boundary at the hyphen, so a hyphenated compound is two
17323    /// words. Recorded rather than corrected: it is what the algorithm says,
17324    /// and what every other UAX#29 counter reports.
17325    #[test]
17326    fn counts_split_a_hyphenated_compound_in_two() {
17327        let c = counts_of("counts_hyphen", "well-known example\n");
17328        assert_eq!(c.words, 3);
17329        assert_eq!(c.characters, 18);
17330        // Punctuation on its own is no word, and an apostrophe doesn't split one.
17331        assert_eq!(counts_of("counts_punct", "don't ... stop\n").words, 2);
17332    }
17333
17334    #[test]
17335    fn selection_counts_measure_the_selection_and_nothing_without_one() {
17336        let src = "alpha beta\n\ngamma delta\n";
17337        let mut d = doc_in(View::Wysiwyg, "counts_sel", src);
17338        assert_eq!(d.selection_counts(), None, "no selection, no counts");
17339
17340        // From the `b` of `beta` to the end of `gamma`: two blocks clipped.
17341        d.select_range(6, 17);
17342        assert_eq!(
17343            d.selection_counts(),
17344            Some(TextCounts {
17345                words: 2,
17346                characters: 9,
17347                characters_without_spaces: 9,
17348                paragraphs: 2,
17349            })
17350        );
17351    }
17352
17353    /// The count is of the document, not of the window it is shown in — so
17354    /// ⌘E must not move it, and neither must a resize or an edit made with no
17355    /// map built at all.
17356    #[test]
17357    fn counts_agree_across_the_views() {
17358        let src =
17359            "# Head\n\nA **bold** word, a [label](http://x), and more.\n\n- item one\n- item two\n";
17360        let mut d = doc_in(View::Wysiwyg, "counts_views", src);
17361        let wysiwyg = d.counts();
17362        assert!(wysiwyg.words > 0 && wysiwyg.paragraphs == 4);
17363
17364        d.toggle_view();
17365        assert_eq!(d.view, View::Source);
17366        d.build_source();
17367        assert_eq!(d.counts(), wysiwyg, "the source view counts the same text");
17368
17369        // A narrower measure is a narrower window, not a shorter document.
17370        d.toggle_view();
17371        d.build_visual(24);
17372        assert_eq!(d.counts(), wysiwyg, "wrapping is not an input");
17373
17374        // And an edit made in the source view, with the visual map left stale,
17375        // still counts the document as it now stands.
17376        d.toggle_view();
17377        d.caret = d.source.len();
17378        d.insert("\n\ntail words\n");
17379        let after = d.counts();
17380        assert_eq!(after.paragraphs, wysiwyg.paragraphs + 1);
17381        assert_eq!(after.words, wysiwyg.words + 2);
17382    }
17383}