Skip to main content

leaf_core/
doc.rs

1//! The document model: a `twig::Editor` plus a byte-offset caret and selection.
2//!
3//! Where bough moves a selection through the *tree*, leaf moves a *caret*
4//! through the *characters* — a normal text editor's model — and expresses
5//! every mutation as one of twig's offset-addressed ops:
6//!
7//!   - typing / delete  → `edit_range(start, end, text)`   (P0)
8//!   - re-anchoring      → the returned `Change`            (P1)
9//!   - cursor context    → `node_at` / `ancestors_at`       (P3)
10//!   - the toolbar       → `wrap_range`/`toggle_inline`/`set_block`,
11//!                         `toggle_block_container`/`insert_link`   (P5)
12//!
13//! twig reparses after every edit and leaves everything outside the splice
14//! byte-for-byte untouched, so the document stays a live, navigable AST while
15//! you type into it.
16
17// `PathBuf` names the `path` field and the untitled marker on every build;
18// `Path` is only touched by the filesystem I/O gated behind the `fs` feature.
19// The docs in this file lay their `- key → meaning` lists out in aligned
20// columns, which puts a continuation line further right than clippy's
21// list-indent rule likes. A lazy continuation renders as the same paragraph
22// either way, and the alignment is what makes those tables readable, so the
23// layout wins over the lint.
24#![allow(clippy::doc_overindented_list_items)]
25
26use std::collections::HashMap;
27use std::ops::Range;
28#[cfg(feature = "fs")]
29use std::path::Path;
30use std::path::PathBuf;
31
32#[cfg(feature = "fs")]
33use anyhow::Context;
34use anyhow::{Result, anyhow};
35use twig::{
36    Alignment, BlockContainerKind, BlockKind, Change, Editor, FlatNode, Format, Gesture,
37    InlineKind, Kind, MarkdownExtensions, NodeId, QueryMatch,
38};
39use unicode_segmentation::GraphemeCursor;
40
41use crate::html;
42use crate::source::{self, SourceMap};
43use crate::style::{Align, FontFamily, LineSpacing, MarkColor, SizeStep};
44use crate::wysiwyg::{self, MediaKind, MediaStop, VisualMap};
45
46/// Which view the body shows.
47#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48pub enum View {
49    /// The raw document with a caret in source bytes.
50    Source,
51    /// Markup resolved to real styles, caret riding the rendered glyphs.
52    Wysiwyg,
53}
54
55/// How much of the source markup the WYSIWYG view exposes — a per-editor
56/// preference, orthogonal to [`View`]. Named for markup rather than for Markdown
57/// because leaf is grammar-agnostic: twig hands it Djot, HTML and XML on the same
58/// terms, and every rung below is about *delimiters*, whatever grammar spells
59/// them. The examples are Markdown only because that is what most documents are.
60///
61/// A single ladder over two underlying axes, because only three of their four
62/// combinations are coherent:
63///
64/// | | authoring off | authoring on |
65/// |---|---|---|
66/// | delimiters hidden | [`None`](Self::None) | [`Shortcuts`](Self::Shortcuts) |
67/// | caret line revealed | *incoherent* | [`Full`](Self::Full) |
68///
69/// The empty quadrant would show delimiters on the caret's line and then escape
70/// the ones you type — a surface that displays a syntax it refuses to accept.
71/// Someone who wants to read raw markup without authoring it has
72/// [`View::Source`], which is the better tool for it.
73///
74/// The two axes are read separately by the code that cares — see
75/// [`reveals_caret_line`](Self::reveals_caret_line) and
76/// [`authors`](Self::authors) — so neither behaviour has to know it's spelled
77/// as a ladder.
78#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
79pub enum MarkupMode {
80    /// Delimiters stay hidden even on the caret's line, and typed syntax stays
81    /// literal — twig escapes anything that would open markup, so formatting
82    /// comes from commands (⌘b, the toolbar) instead of from spelling. The clean
83    /// reading surface for people who don't write markup by hand; the default,
84    /// and what Diaryx ships.
85    #[default]
86    None,
87    /// Delimiters stay hidden, but typing them authors real markup: `*x*`
88    /// becomes italic and the asterisks disappear into the styling
89    /// (Typora/Bear-shaped). For someone who knows the syntax but wants the
90    /// clean surface back once it has been applied.
91    Shortcuts,
92    /// The caret's line shows its raw markup while every other line renders
93    /// resolved (Obsidian live-preview-shaped), and typed syntax authors markup
94    /// — for people fluent in the document's grammar who want to see and edit
95    /// the delimiters they type.
96    Full,
97}
98
99impl MarkupMode {
100    /// Whether the rich view shows raw delimiters on the line holding the caret.
101    /// The rendering axis — read by [`Doc::reveal_line`] and threaded into the
102    /// WYSIWYG builder.
103    pub fn reveals_caret_line(self) -> bool {
104        matches!(self, MarkupMode::Full)
105    }
106
107    /// Whether typed markup characters author real formatting. The editing axis
108    /// — read by [`Doc::insert`], which escapes typed syntax when this is false.
109    pub fn authors(self) -> bool {
110        !matches!(self, MarkupMode::None)
111    }
112}
113
114/// How the WYSIWYG view treats a *soft break* — a bare newline inside a
115/// paragraph. An axis of its own, orthogonal to [`MarkupMode`] (which governs
116/// inline-markup delimiters) and to [`View`]: any reveal preference pairs with
117/// either flow. The renderer consults it when it lays a block's inline content
118/// into visual rows.
119#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
120pub enum LineFlow {
121    /// A soft break folds into a space and the paragraph reflows to the
122    /// viewport width — flowing prose, where the source's line wrapping is
123    /// insignificant. The default, and what Diaryx ships.
124    #[default]
125    Fold,
126    /// A soft break renders as a line break exactly where it was written, so
127    /// the author's source line structure shows on screen unchanged — the mode
128    /// for people who lay out their prose deliberately (one sentence or clause
129    /// per line, semantic line breaks). The break is still a soft break in the
130    /// source; only its rendering changes.
131    Preserve,
132}
133
134/// What the file behind a document looks like right now, against the bytes leaf
135/// last read from it or wrote to it — the question a frontend asks before it
136/// saves (a `Changed` file plus a `dirty` document is an overwrite about to
137/// happen) or when its window regains focus. See [`Doc::disk_state`].
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub enum DiskState {
140    /// The file holds exactly the bytes leaf last read or wrote.
141    Unchanged,
142    /// Someone else wrote the file since. Saving overwrites their work; see
143    /// [`Doc::reload`] for the other direction.
144    Changed,
145    /// The file is gone — deleted or renamed away. A save recreates it.
146    Missing,
147    /// There is a path, but the file couldn't be read (permissions, a directory
148    /// in the way): leaf can't tell, and won't guess.
149    Unreadable,
150    /// No file behind this document yet — see [`Doc::blank`]. Nothing can have
151    /// changed under a document that was never on disk.
152    Untitled,
153}
154
155/// The inline marks in force at a point in the document — what a toolbar
156/// lights up. A `Copy` bitset rather than a `HashSet`, because
157/// [`Doc::active_inline_marks`] is called on every frame that draws a toolbar
158/// and a set that allocates to answer "is Bold on?" is a set that shouldn't.
159#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
160pub struct InlineMarks(u8);
161
162impl InlineMarks {
163    /// Every kind, in the order [`InlineMarks::iter`] yields them.
164    const ALL: [InlineKind; 8] = [
165        InlineKind::Strong,
166        InlineKind::Emph,
167        InlineKind::Verbatim,
168        InlineKind::Mark,
169        InlineKind::Superscript,
170        InlineKind::Subscript,
171        InlineKind::Insert,
172        InlineKind::Delete,
173    ];
174
175    pub const fn empty() -> Self {
176        InlineMarks(0)
177    }
178
179    /// Private: the set is an *answer*, and adding a mark to it doesn't mark
180    /// anything ([`Doc::toggle`] does that). `FromIterator` is the way in.
181    fn insert(&mut self, kind: InlineKind) {
182        self.0 |= Self::bit(kind);
183    }
184
185    /// Flip `kind` in the set — the sticky-marks toggle at a collapsed caret.
186    fn flip(&mut self, kind: InlineKind) {
187        self.0 ^= Self::bit(kind);
188    }
189
190    /// The symmetric difference: which marks differ between the two sets. Used
191    /// to resolve the marks already in force at the caret against the pending
192    /// delta — a bit set in the delta flips the base mark for the next keystroke.
193    fn xor(self, other: InlineMarks) -> InlineMarks {
194        InlineMarks(self.0 ^ other.0)
195    }
196
197    /// Whether `kind` is in force — the toolbar's "is Bold active?".
198    pub fn contains(self, kind: InlineKind) -> bool {
199        self.0 & Self::bit(kind) != 0
200    }
201
202    pub fn is_empty(self) -> bool {
203        self.0 == 0
204    }
205
206    /// The marks in force, for a frontend that renders whatever is on rather
207    /// than asking after a fixed list.
208    pub fn iter(self) -> impl Iterator<Item = InlineKind> {
209        Self::ALL.into_iter().filter(move |&k| self.contains(k))
210    }
211
212    fn bit(kind: InlineKind) -> u8 {
213        1 << match kind {
214            InlineKind::Strong => 0,
215            InlineKind::Emph => 1,
216            InlineKind::Verbatim => 2,
217            InlineKind::Mark => 3,
218            InlineKind::Superscript => 4,
219            InlineKind::Subscript => 5,
220            InlineKind::Insert => 6,
221            InlineKind::Delete => 7,
222        }
223    }
224}
225
226impl FromIterator<InlineKind> for InlineMarks {
227    fn from_iter<I: IntoIterator<Item = InlineKind>>(iter: I) -> Self {
228        let mut m = InlineMarks::empty();
229        for k in iter {
230            m.insert(k);
231        }
232        m
233    }
234}
235
236/// What kind of edit produced an undo group. Same-kind edits in a row coalesce
237/// into one undo step (a run of typed characters undoes together); `Other` never
238/// coalesces, so a paste, format toggle, or block change is always its own step.
239#[derive(Clone, Copy, PartialEq, Eq)]
240enum EditKind {
241    Insert,
242    Delete,
243    /// One step of an IME composition — see [`Doc::edit_composing`]. Its own kind
244    /// rather than `Insert`'s because a composition is not typing: each step
245    /// *replaces* the last (`か` → `かん` → `感`), so the run has to coalesce even
246    /// though no two steps insert the same bytes, and it must not fold into the
247    /// typed characters on either side of it.
248    Compose,
249    Other,
250}
251
252/// Which side of the caret a delete looks for an in-cell `<br>` break to swallow
253/// whole — see [`Doc::cell_break_at`]. `Backward` is Backspace (a break ending at
254/// the caret), `Forward` is Delete (one starting at it).
255#[derive(Clone, Copy)]
256enum BreakEdge {
257    Backward,
258    Forward,
259}
260
261/// A re-spelling of one inline mark run, held ready in case the edit about to
262/// happen breaks it — see [`Doc::mark_edge_fix`] and [`Doc::repair_mark_edges`].
263/// Every offset in it is in the coordinates the document will have *after* the
264/// plain edit, since that is when it may be applied.
265struct MarkEdgeFix {
266    /// The run's kind, and an offset inside what was its content: together they
267    /// answer "did the plain edit actually break this mark?" — the question that
268    /// decides whether any of this is applied at all.
269    kind: InlineKind,
270    probe: usize,
271    /// The byte range to re-spell (the run's delimiters included) and its new
272    /// spelling, with the edge whitespace moved outside the delimiters.
273    start: usize,
274    end: usize,
275    text: String,
276    /// Where the caret belongs afterwards — the same place on screen it would
277    /// have had, which is now on the other side of a delimiter.
278    caret: usize,
279    /// The marks in force for text typed at that caret. The caret can land
280    /// outside a run it was inside, and the marks have to survive the move or
281    /// the toolbar goes dark mid-word.
282    want: InlineMarks,
283}
284
285/// The caret and selection at one moment — the part of a history step twig's
286/// `Change` cannot carry, because the caret is leaf's state and twig only knows
287/// about bytes. leaf serializes it into the opaque per-state blob twig now
288/// stores in its own undo history (see `record_caret`), so undo and redo hand
289/// back the caret that matches the source they restore.
290#[derive(Clone, Copy)]
291struct CaretState {
292    caret: usize,
293    anchor: Option<usize>,
294}
295
296impl CaretState {
297    /// Pack into the fixed 17-byte blob leaf hands twig: the caret as a u64,
298    /// then an anchor-present flag and the anchor. twig copies these bytes and
299    /// never reads them.
300    fn to_blob(self) -> [u8; 17] {
301        let mut b = [0u8; 17];
302        b[..8].copy_from_slice(&(self.caret as u64).to_le_bytes());
303        if let Some(a) = self.anchor {
304            b[8] = 1;
305            b[9..].copy_from_slice(&(a as u64).to_le_bytes());
306        }
307        b
308    }
309
310    /// Recover a state from twig's blob, or `None` when it is empty or the wrong
311    /// length — a state twig restored that never had a caret set on it, which
312    /// leaves the caller to fall back to the edit site.
313    fn from_blob(b: &[u8]) -> Option<Self> {
314        let b: &[u8; 17] = b.try_into().ok()?;
315        let caret = u64::from_le_bytes(b[..8].try_into().unwrap()) as usize;
316        let anchor = (b[8] != 0).then(|| u64::from_le_bytes(b[9..].try_into().unwrap()) as usize);
317        Some(CaretState { caret, anchor })
318    }
319}
320
321/// A footnote reference and the note it names — the answer to
322/// [`Doc::footnote_at`].
323///
324/// The two `Option`s move together: a reference whose definition is missing has
325/// neither a body to show nor a place to jump to, and one that resolved has
326/// both.
327#[derive(Clone, PartialEq, Eq, Debug)]
328pub struct FootnoteRef {
329    /// The reference's label — the `1` of `[^1]`, with neither the `^` that
330    /// spells it a footnote nor the brackets around it.
331    pub label: String,
332    /// The note's body as source bytes (see
333    /// [`wysiwyg::footnote_body_span`](crate::wysiwyg)), or `None` when the
334    /// document defines no `[^label]:` to read one from.
335    pub text: Option<String>,
336    /// Where the note's *body* starts, for a "go to note" that moves the caret
337    /// there. `None` alongside a `None` `text`.
338    ///
339    /// The body rather than the definition, because this is an offset to put a
340    /// caret on and the `[^1]:` marker is decoration the caret can't occupy —
341    /// aiming at the definition's first byte snaps to the nearest real stop,
342    /// which is up in the paragraph above the note. It is also simply where a
343    /// reader following a reference wants to land: at the note's first word,
344    /// ready to read or amend it.
345    pub offset: Option<usize>,
346    /// Where the note's body ends, exclusive — so a frontend can ask which
347    /// *rendered rows* the note occupies and draw those instead of [`text`](Self::text).
348    ///
349    /// The rows are the note with its markup resolved: `see *later*` reaches a
350    /// frontend as an italic run, not as asterisks. `text` is the source bytes
351    /// and stays the honest answer for anything that wants the note as written
352    /// (a search index, a copy); this pair of offsets is for anything that wants
353    /// it as *read*. `None` alongside a `None` `offset`.
354    pub end: Option<usize>,
355}
356
357/// A footnote definition and the reference that sends a reader to it — the
358/// answer to [`Doc::footnote_definition_at`], and the other half of the round
359/// trip [`FootnoteRef`] starts.
360///
361/// A note is a place a reader *arrives*, so the useful thing to know while
362/// standing in one is the way back. Without this the jump to a note is a
363/// one-way door: the definitions sit at the foot of the document, so returning
364/// by hand means scrolling back up and finding the sentence again.
365#[derive(Clone, PartialEq, Eq, Debug)]
366pub struct FootnoteDef {
367    /// The definition's label — the `1` of `[^1]: …`, marker and colon stripped,
368    /// spelled exactly as [`FootnoteRef::label`] spells the same footnote's.
369    pub label: String,
370    /// Where the reference's *label* is, for a "back to reference" that moves
371    /// the caret there. `None` for a note nothing refers to — an orphan, which
372    /// is worth being able to say rather than silently doing nothing.
373    ///
374    /// The label rather than the reference's first byte, for
375    /// [`FootnoteRef::offset`]'s reason: a reference's brackets are decoration
376    /// and its label is the only part of it the caret can rest on.
377    ///
378    /// The *first* reference, when a label is cited more than once: a repeated
379    /// citation has no one true home, and the first is both the one a reader
380    /// most likely came from and the only choice that doesn't depend on how
381    /// they got here.
382    pub offset: Option<usize>,
383}
384
385/// Where a locator lands — the answer to [`Doc::locate`].
386///
387/// A locator (the `v2` of a `chapter.dj#v2`) names a *place* rather than a
388/// document, and a place is a span rather than a point: a reader following one
389/// wants the caret at its first byte, and a reader merely *peeking* at one wants
390/// the block it covers drawn. Both are served by carrying the whole span, and
391/// only one of the two can be recovered from an offset alone.
392#[derive(Clone, PartialEq, Eq, Debug)]
393pub struct Landing {
394    /// The first byte of the block the locator names — where a caret goes.
395    pub start: usize,
396    /// One past its last byte, so a frontend can map the pair through
397    /// [`VisualMap::row_range_for`](crate::wysiwyg::VisualMap::row_range_for) to the rendered rows the block occupies and draw
398    /// those, the way a footnote peek draws a note ([`FootnoteRef::end`]).
399    pub end: usize,
400}
401
402/// A selection cited out of the source: the text itself, up to a requested
403/// number of characters either side, and the byte range it came from. See
404/// [`Doc::selection_quote`].
405///
406/// The prefix and suffix are what make the quote *re-findable*: the same text
407/// can occur twice, and a little of what surrounded it is how a later reader —
408/// or the same document after an edit — tells the occurrences apart. The Web
409/// Annotation model calls this a `TextQuoteSelector`; the shape is older than
410/// the name.
411#[derive(Debug, Clone, PartialEq, Eq)]
412pub struct Quote {
413    /// The selected source, verbatim.
414    pub exact: String,
415    /// What immediately preceded it — possibly empty, at the document's start.
416    pub prefix: String,
417    /// What immediately followed it — possibly empty, at the document's end.
418    pub suffix: String,
419    /// Byte offset in the source where the selection begins.
420    pub start: usize,
421    /// Byte offset where it ends (exclusive).
422    pub end: usize,
423}
424
425/// A host-painted range of the source — an annotation's footprint, a search
426/// hit, a reviewer's mark. Leaf renders it (a background wash behind the
427/// glyphs whose source falls inside it) and hands back the `id` when the
428/// reader activates it; what the range *means* is entirely the host's.
429///
430/// Ranges are source bytes, like the caret and the selection, so a host that
431/// anchors quotes against the source ([`Doc::selection_quote`] is the other
432/// half of that loop) can paint what it found without any coordinate
433/// conversion. A range that drifts off the text it meant is the host's to
434/// re-anchor; leaf draws what it is told.
435#[derive(Debug, Clone, PartialEq, Eq)]
436pub struct Highlight {
437    /// Byte offset in the source where the wash begins.
438    pub start: usize,
439    /// Byte offset where it ends (exclusive).
440    pub end: usize,
441    /// The host's name for it, handed back on activation. Opaque to leaf.
442    pub id: String,
443    /// A rendering hint the frontend maps — a `#RRGGBB` hex string, or
444    /// nothing for the theme's default wash.
445    pub color: Option<String>,
446    /// A margin glyph's name, or nothing for wash-only ink. A highlight with
447    /// a marker gets a small glyph in the margin beside its first line, and
448    /// the glyph — not the wash — is what activates it: the wash is ink, the
449    /// marker is the control, which is what lets a reader put a caret in (or
450    /// copy from) annotated text without a card leaping at them. The name is
451    /// opaque to leaf; an Apple frontend reads it as an SF Symbol, a web one
452    /// as a class.
453    pub marker: Option<String>,
454}
455
456impl Highlight {
457    /// The range covering source `offset` in a list [`Doc::set_highlights`]
458    /// sorted, first by start where several overlap — the one place that
459    /// question is answered, for the frontends that paint by asking it as well
460    /// as for [`Doc::highlight_at`].
461    ///
462    /// The list is sorted by `(start, end)`, so the scan can stop at the first
463    /// range starting past `offset` rather than running to the end. A painter
464    /// asking once per glyph wants [`HighlightCursor`] instead; this is the
465    /// one-shot form, for the host asking what the reader just activated.
466    pub fn covering(highlights: &[Highlight], offset: usize) -> Option<&Highlight> {
467        highlights
468            .iter()
469            .take_while(|h| h.start <= offset)
470            .find(|h| offset < h.end)
471    }
472}
473
474/// [`Highlight::covering`] for a caller walking the document in order — which
475/// is every painter, since a frontend draws rows top to bottom and glyphs left
476/// to right.
477///
478/// The one-shot form is a scan from the front of the list per glyph, and a
479/// document with two hundred search hits pays that two hundred times a row. A
480/// range that ends at or before an offset can never cover that offset *or any
481/// later one*, so the cursor retires those permanently and each glyph costs the
482/// ranges that actually reach it. The answer is identical to
483/// [`Highlight::covering`]'s, offset for offset — this is the same scan with
484/// the part that was being redone dropped, not a cheaper approximation.
485///
486/// Offsets are expected to arrive non-decreasing. One that goes backwards is
487/// still answered correctly: the cursor re-seats to the front, since a painter
488/// that revisits a row is asking a question the retired ranges may own again.
489pub struct HighlightCursor<'a> {
490    highlights: &'a [Highlight],
491    /// The first range not yet retired.
492    at: usize,
493    /// The last offset asked about, to notice a caller going backwards.
494    last: usize,
495}
496
497impl<'a> HighlightCursor<'a> {
498    pub fn new(highlights: &'a [Highlight]) -> Self {
499        HighlightCursor {
500            highlights,
501            at: 0,
502            last: 0,
503        }
504    }
505
506    /// The range covering `offset`, advancing the cursor past every range that
507    /// can no longer cover anything.
508    pub fn at(&mut self, offset: usize) -> Option<&'a Highlight> {
509        if offset < self.last {
510            self.at = 0;
511        }
512        self.last = offset;
513        while self
514            .highlights
515            .get(self.at)
516            .is_some_and(|h| h.end <= offset)
517        {
518            self.at += 1;
519        }
520        Highlight::covering(&self.highlights[self.at..], offset)
521    }
522}
523
524/// The identity of a built [`VisualMap`] — see [`Doc::visual_key`]. Opaque on
525/// purpose: the only useful question is whether two of them are the same map,
526/// and what is behind it — which `Doc` built it, and the (revision, wrap,
527/// reveal line) it was built from — is core's business.
528///
529/// The document is part of it because the rest is not unique to one: two
530/// documents opened at the same width are both at revision zero with no reveal
531/// line, and a frontend holding one copy of a map across the two would take
532/// the second's key for the first's and paint the wrong document.
533#[derive(Clone, PartialEq, Eq, Debug)]
534pub struct VisualKey(u64, Option<(u64, Option<usize>, Option<Range<usize>>)>);
535
536pub struct Doc {
537    editor: Editor,
538    pub format: Format,
539    pub path: PathBuf,
540    /// Current source, refreshed from the editor after every successful edit.
541    pub source: String,
542    /// The caret, as a byte offset into `source` (always on a char boundary).
543    pub caret: usize,
544    /// The selection's fixed end, if a selection is active; the moving end is
545    /// the caret. `None` means no selection.
546    pub anchor: Option<usize>,
547    pub dirty: bool,
548    pub status: Option<String>,
549    pub view: View,
550    /// Whether the document refuses to change — a *reading* surface over the
551    /// same rendering, selection, and navigation the editor has.
552    ///
553    /// Enforced here rather than by each frontend hiding its input paths,
554    /// because every mutation funnels through a few doors —
555    /// [`splice_exact`](Self::splice_exact), [`undo`](Self::undo),
556    /// [`redo`](Self::redo), and the handful of inserts that go to twig's own
557    /// verbs directly rather than through the splice (a typed literal, a link,
558    /// an image, a rule, a footnote, a cell's line break) — and guarded doors
559    /// are a guarantee where a frontend's suppressed keyboard is a hope. A
560    /// gated door reports exactly like a rolled-back splice, a path every
561    /// caller already handles. `a_read_only_document_refuses_every_door` is
562    /// the list; a new `self.editor.insert_*` call belongs on it.
563    read_only: bool,
564    /// The host-painted ranges, kept sorted by start — see [`Highlight`].
565    /// State like the selection rather than like the text: no edit history,
566    /// no dirty bit, redrawn from whatever the host last set.
567    highlights: Vec<Highlight>,
568    /// How much of the source markup the rich view exposes — a frontend preference (see
569    /// [`MarkupMode`]). Its two axes are read apart: the rendering one by
570    /// [`reveal_line`](Self::reveal_line), the editing one by
571    /// [`insert`](Self::insert).
572    markup_mode: MarkupMode,
573    /// Whether soft breaks fold into the reflowed paragraph or render where
574    /// they were written (see [`LineFlow`]) — an independent frontend
575    /// preference the WYSIWYG builder consults when it lays out a block.
576    line_flow: LineFlow,
577    /// The kind of the last edit, for coalescing: twig owns the undo *history*
578    /// (see `undo`/`redo`), but "what counts as one undo step" is a frontend-UX
579    /// call, so leaf decides when a run continues and tells twig to coalesce.
580    last_edit_kind: Option<EditKind>,
581    /// The inline marks the user has toggled *at a collapsed caret* with no
582    /// selection — "start typing bold here". Held as the XOR delta from the marks
583    /// already in force at [`pending_at`](Self::pending_at): a set bit means
584    /// "flip this kind for the next typed text", so it both turns a mark on where
585    /// none is (type into bold) and off where one already covers the caret (type
586    /// past the bold you're standing in). [`Doc::insert`] realises it onto the
587    /// freshly typed text and then clears it — a mark once realised is carried by
588    /// the caret sitting inside the run, not by this delta.
589    pending_marks: InlineMarks,
590    /// The caret offset [`pending_marks`](Self::pending_marks) applies to. The
591    /// delta is live only while the caret still stands here with no selection;
592    /// any motion or edit ([`move_to`](Self::move_to), a splice, a click) drops
593    /// it, so a toggled-but-never-typed format doesn't leak onto text elsewhere.
594    pending_at: Option<usize>,
595    /// The source as of the last open/save — `dirty` is `source != clean_source`,
596    /// so undoing back to the saved state correctly clears the modified flag.
597    clean_source: String,
598    /// A hash of the bytes leaf last read from `path` or wrote to it; `None`
599    /// while the document has no file behind it. [`Doc::disk_state`] compares
600    /// the file against this to catch an edit made *outside* leaf before a save
601    /// silently overwrites it — `clean_source` only knows what leaf itself did.
602    ///
603    /// A hash, not an mtime: mtime is the cheap answer and the wrong one — two
604    /// writes inside one filesystem timestamp tick are indistinguishable, a
605    /// clock that steps backwards (or a writer that restores an mtime) hides a
606    /// real change, and a `touch` invents one. The whole point of the watermark
607    /// is to not clobber someone's work, so it reads the bytes and compares what
608    /// is actually there. That costs a file read per question, which is why the
609    /// question is asked on a user event (focus, save) and not every frame.
610    disk_hash: Option<u64>,
611    /// The "sticky" display column vertical motion aims for, in the active
612    /// view's grid. Set on the first `move_up`/`move_down` of a run and
613    /// reused by every subsequent one in that run, so passing through a
614    /// shorter line doesn't permanently forget the original column. Any
615    /// horizontal motion or edit clears it.
616    ///
617    /// A column, not a character index: dropping down a line of `你好` onto one
618    /// of ASCII has to land under the glyph the caret was drawn beneath, which
619    /// is the only thing the user can see to aim by. Where the goal falls inside
620    /// a wide character on the target line, the mapping resolves it to that
621    /// character — the caret lands on it rather than between its cells.
622    goal_col: Option<usize>,
623    /// The rendered map for the WYSIWYG view; empty in the source view. Movement
624    /// and clicks read it to stay in visible space.
625    pub vmap: VisualMap,
626    /// The syntax map for the source view; empty in the WYSIWYG view, which
627    /// styles resolved glyphs instead. Built by [`Doc::build_source`] — a
628    /// frontend that never calls it paints raw source unstyled, which is what
629    /// every frontend did before this map existed.
630    pub smap: SourceMap,
631    /// The revision `smap` was built from, or `None` before the first build.
632    /// The map is a pure function of the text alone — no width, no caret, no
633    /// reveal line — so unlike [`vmap_key`](Self::vmap_key) the revision is the
634    /// whole key.
635    smap_key: Option<u64>,
636    /// Everything the map is built from, as one number: bumped whenever the
637    /// document's text changes, and never by a motion, a selection, or a save.
638    /// A frontend can hold work against it — see [`Doc::revision`].
639    revision: u64,
640    /// How many history steps stand behind the caret, and how many ahead of
641    /// it — the answer to a native Edit menu's "may Undo be enabled?", which
642    /// twig's history does not ask itself. Counted at [`refresh`](Self::refresh),
643    /// the funnel every edit comes through, and moved back and forth by
644    /// [`undo`](Self::undo)/[`redo`](Self::redo). An upper bound rather than
645    /// an exact depth: a coalesced run of typing is one of twig's steps but
646    /// several of these, and twig's own cap on history is not mirrored here.
647    /// Neither error can make `can_undo` false while a step remains, which is
648    /// the only property a menu needs; the one place the bound can be wrong the
649    /// other way — the cap has retired every step — is reconciled the moment
650    /// twig reports nothing to undo.
651    undo_steps: usize,
652    redo_steps: usize,
653    /// What `vmap` was built from, or `None` before the first build. The map is
654    /// a pure function of `(revision, wrap, reveal line)`, so when those haven't
655    /// moved, rebuilding it produces the identical map — see
656    /// [`Doc::build_visual`].
657    ///
658    /// The reveal line ([`Doc::reveal_line`]) is the caret's, and is `None` in
659    /// every mode but [`MarkupMode::Full`] — so outside that mode the key is
660    /// text and width alone, and a caret motion still rebuilds nothing.
661    vmap_key: Option<(u64, Option<usize>, Option<Range<usize>>)>,
662    /// Which `Doc` this is, distinct from every other one built in this
663    /// process. Folded into [`VisualKey`] so that a map stashed by a frontend
664    /// can never be mistaken for another document's — see
665    /// [`Doc::visual_key`]. Nothing else reads it.
666    identity: u64,
667    /// Per-block row cache backing the incremental rebuild: when the text
668    /// changes, only the top-level blocks whose bytes moved are re-rendered and
669    /// the rest are reused shifted (see [`wysiwyg::BlockCache`]). Persists across
670    /// builds; a pure accelerator, so it's never read for correctness.
671    block_cache: wysiwyg::BlockCache,
672    /// How many visual rows each block image reserves, keyed by its destination —
673    /// set by the frontend through [`Doc::set_media_rows`] once it has decoded and
674    /// measured the pictures. Core does no image I/O, so this is the only way it
675    /// learns a picture's height; a destination not in the map reserves the bare
676    /// one-row placeholder. Threaded into the builder so [`wysiwyg::build_cached`]
677    /// sizes each placeholder, and folded into `vmap_key` so a height change
678    /// rebuilds the map.
679    media_rows: HashMap<String, usize>,
680
681    // View geometry the renderer stamps each frame, so mouse events can map a
682    // screen cell back to a byte offset.
683    pub scroll: usize,
684    pub body_origin: (u16, u16),
685    /// Width of the body rectangle last painted by the frontend. Zero means
686    /// unknown (used by tests or a frontend that has not drawn yet).
687    pub body_width: u16,
688    pub body_height: u16,
689    /// The caret as of the last frame drawn, or `None` before the first.
690    ///
691    /// Scrolling is the viewport's business, not the caret's: the view follows
692    /// the caret when the caret *moves*, but a wheel that doesn't touch the
693    /// caret has to be free to scroll away from it — otherwise the view is
694    /// pinned to the caret and stops dead at the edge of the document you can
695    /// see. Comparing against this is what tells the two apart, and it catches a
696    /// caret set by any route, including a frontend assigning the field itself.
697    pub drawn_caret: Option<usize>,
698}
699
700/// The Markdown extensions every leaf document is parsed with — four of them,
701/// each departing from twig's defaults for a reason leaf can state.
702///
703/// `html_elements` promotes embedded raw HTML (`<img>`, `<picture>`,
704/// `<source>`, …) into semantic AST nodes, so a picture becomes a real `image`
705/// node the frontends can frame and rasterize instead of opaque `raw_block`
706/// text. `directives` turns on generic `:::name{.class}` fenced-div containers
707/// (`directive` nodes), which a host app uses for its own semantics (diaryx's
708/// `:::vis{.audience}` visibility blocks) — core renders any directive as a
709/// plain tinted container, agnostic of `name`.
710///
711/// `highlight` and `highlight_colors` are the pair that makes Markdown read
712/// `==text==` as a `mark` node, and `==🔴 text==` as one carrying a
713/// `data-color`. leaf already had somewhere to put both: the
714/// [`Mark`](crate::Role::Mark) role and the ⌘⇧M highlight button predate them,
715/// and until twig 3.3 a Markdown document could only ever *receive* a highlight
716/// from a Djot one it was converted from — the button wrote `==…==` and the
717/// reparse read it straight back as text.
718/// They are on together because a colour is inert without the highlight itself,
719/// and a document that writes `==🔴 x==` means the colour by it.
720///
721/// Every flag is inert for non-Markdown formats, so it's safe to pass them
722/// unconditionally. Threading this through every constructor (not just `open`)
723/// keeps `from_source`, `blank`, and `reload` parsing the same document the same
724/// way — twig reparses with these same flags after each edit.
725pub(crate) fn parse_extensions() -> MarkdownExtensions {
726    MarkdownExtensions {
727        html_elements: true,
728        directives: true,
729        highlight: true,
730        highlight_colors: true,
731        ..Default::default()
732    }
733}
734
735/// Build an editor over `bytes` in `format` with leaf's [`parse_extensions`],
736/// mapping twig's error into the `anyhow` context every constructor shares.
737fn new_editor(bytes: &[u8], format: Format) -> Result<Editor> {
738    Editor::new_ext(bytes, format, parse_extensions()).map_err(|e| anyhow!("twig parse: {e}"))
739}
740
741/// Does `format` spell a table as a **pipe table** — the one grid twig's table
742/// editor knows how to emit?
743///
744/// This is the single capability leaf still has to answer for itself, and the
745/// only hand-maintained format list left in this file. Every other gesture is
746/// [`Format::supports`], which is twig's own answer read across the C ABI — but
747/// twig deliberately leaves the table ops out of that query, because they read
748/// no `Syntax` table at all. They rewrite a grid that is already in the source
749/// and refuse on *position*, never on format. Handed a caret inside an HTML
750/// `<table>`, `table_insert_row` therefore re-emits the whole element as
751/// `| a | b |` and reports success — a real splice, a clean reparse, an honest
752/// `dirty` flag, and nothing downstream able to tell it from a good edit.
753///
754/// So the list is narrow on purpose. `Format` is `#[non_exhaustive]`, and the
755/// wildcard answers "no" for a format leaf has never heard of: a new twig
756/// language that *does* spell pipe tables loses its grid controls until this
757/// line is updated, which shows up as a missing button. The other default hands
758/// it to [`Doc::table_op`], which rewrites documents it cannot spell.
759fn spells_pipe_tables(format: Format) -> bool {
760    matches!(format, Format::Markdown | Format::Djot)
761}
762
763/// Which of leaf's authoring controls this document's format can actually
764/// spell — one flag per toolbar button, resolved once so a frontend can build
765/// its chrome instead of discovering each refusal on a click.
766///
767/// Every field but [`table`](Self::table) is `Format::supports_with` on the
768/// gesture the matching [`Doc`] method calls, so this record cannot drift from
769/// what the ops do; `table` is [`spells_pipe_tables`], the one answer twig
770/// doesn't export.
771///
772/// `supports_with` rather than `supports` because two of these are facts about
773/// the *parse options* as much as about the format. `Format::supports` answers
774/// for twig's defaults, and leaf never parses with those — it parses with
775/// [`parse_extensions`], and a document's toolbar has to describe the document
776/// it is over. A Markdown editor holding `highlight` authors `==text==`; one
777/// without it would mint bytes its own reparse hands back as plain text, which
778/// is why twig asks before it writes.
779///
780/// **The formats are ragged, and that is the point.** A single per-document
781/// boolean was enough while the two authorable formats were Markdown and djot
782/// and everything else spelled nothing. HTML is neither: it writes seven of the
783/// eight inline marks as a tag pair, plus `<code>`, `<hr>`, an in-cell
784/// `<br>`, and — since twig 3.4 — a heading or paragraph rebuilt as its tag
785/// pair, and since 3.5 a quote, a list, a code block, a link and an image
786/// printed as fresh nodes; it spells no task box (a form control there) and
787/// no footnote, and its `<table>` is one twig reads but will not write. So
788/// ⌘B, ⌘1 and the quote button work in an HTML document and the task and
789/// table buttons do not, and no one flag can say that. Markdown and djot
790/// differ from each other too:
791/// `^superscript^` is djot-only, and an in-cell `<br>` is Markdown-only.
792#[derive(Clone, Copy, Debug, Eq, PartialEq)]
793pub struct Capabilities {
794    /// ⌘B — `InlineKind::Strong`.
795    pub bold: bool,
796    /// ⌘I — `InlineKind::Emph`.
797    pub italic: bool,
798    /// Inline code — `InlineKind::Verbatim`.
799    pub code: bool,
800    /// Highlight — `InlineKind::Mark`. Djot spells it, and so does Markdown
801    /// under the `highlight` extension [`parse_extensions`] turns on: the
802    /// button writes `==text==`, which is what the reparse reads back.
803    pub mark: bool,
804    /// ⌘U — `InlineKind::Insert`, which every format that marks at all spells.
805    pub underline: bool,
806    /// Strikethrough — `InlineKind::Delete`. Markdown spells GFM's `~~text~~`
807    /// out of the box, since twig parses it out of the box.
808    pub strike: bool,
809    /// The highlight *palette* — [`Doc::set_mark_color`]. Narrower than
810    /// [`mark`](Self::mark) and deliberately its own flag: Markdown spells a
811    /// colour on a highlight (`==🔴 text==`) and djot spells only the highlight,
812    /// so a toolbar offering the swatches wherever the button lights would offer
813    /// them in a document that cannot write one. Pair with
814    /// [`Doc::caret_in_mark`], which asks the other question — the palette needs
815    /// a highlight to colour as much as a format that spells one.
816    pub mark_color: bool,
817    pub superscript: bool,
818    pub subscript: bool,
819    /// Heading levels and "make this a paragraph" — [`Doc::set_block`].
820    pub heading: bool,
821    pub blockquote: bool,
822    pub bullet_list: bool,
823    pub ordered_list: bool,
824    /// The checkbox controls: giving an item a box, and ticking one.
825    pub task: bool,
826    pub link: bool,
827    /// Covers [`Doc::insert_media`] too — see the note there on why the three
828    /// media kinds stand or fall together.
829    pub image: bool,
830    /// The horizontal-rule button. HTML spells this one (`<hr>`).
831    pub thematic_break: bool,
832    /// The footnote button — [`Doc::insert_footnote`]. Markdown and djot spell
833    /// the pair; HTML has no footnote of its own, so the button goes away rather
834    /// than writing brackets that would render as brackets.
835    pub footnote: bool,
836    /// Setting a fenced block's language — a control only ever offered with the
837    /// caret already in a fence.
838    pub code_language: bool,
839    /// The grid controls: insert/delete/move a row or column, set a column's
840    /// alignment. Pair with [`Doc::caret_in_table`], which asks the other
841    /// question — an HTML `<table>` holds the caret and still can't be edited.
842    pub table: bool,
843    /// Shift+Return inside a cell. Markdown and HTML spell it; djot has no
844    /// idiomatic in-cell break.
845    pub cell_line_break: bool,
846    /// The alignment control — [`Doc::set_alignment`], twig's
847    /// `Gesture::SetBlockAttrs`. Every format leaf opens but XML spells a
848    /// block's attributes, Markdown under the `html_elements`
849    /// [`parse_extensions`] turns on (a `<div>` around the block) and AsciiDoc
850    /// through its `[…]` line.
851    pub alignment: bool,
852    /// The line-spacing menu — [`Doc::set_line_spacing`]. The same gesture as
853    /// [`alignment`](Self::alignment) and so the same answer, and its own flag
854    /// because a toolbar dims controls one at a time and the pair may yet
855    /// diverge.
856    pub line_spacing: bool,
857    /// The size menu — [`Doc::set_font_size`], twig's `Gesture::WrapRangeAttrs`
858    /// over a selection. **Narrower than the block pair**: AsciiDoc's
859    /// `[#id.role]#text#` keeps an id and a role and has no slot for a
860    /// `data-` key, so twig refuses the span there and this is `false` while
861    /// [`alignment`](Self::alignment) is `true`. The block-level form of the
862    /// same property — the caret in a paragraph, no selection — goes through
863    /// `SetBlockAttrs` and still works, which is why the flag describes the
864    /// control rather than the caret.
865    pub font_size: bool,
866    /// The face menu — [`Doc::set_font_family`]. `WrapRangeAttrs`, as
867    /// [`font_size`](Self::font_size) is.
868    pub font_family: bool,
869    /// The text-colour swatches — [`Doc::set_text_color`]. `WrapRangeAttrs`,
870    /// and not to be confused with [`mark_color`](Self::mark_color): that is a
871    /// highlight's background and rides the `mark` node twig already owns,
872    /// this is a run's foreground and rides an attributed span.
873    pub text_color: bool,
874    /// The page-break button — [`Doc::insert_page_break`], twig's
875    /// `Gesture::InsertDirective`. Markdown under the `directives` extension
876    /// [`parse_extensions`] turns on (`::page-break`) and djot, which spells
877    /// it as an empty `::: page-break` fence.
878    ///
879    /// **Those two and no others**, though twig spells the gesture in HTML and
880    /// AsciiDoc as well — see [`Capabilities::of`].
881    pub page_break: bool,
882}
883
884impl Capabilities {
885    /// Resolve every flag for `format`, as leaf parses it. Pure and cheap —
886    /// twig computes each from a static table — but a frontend that wants to
887    /// hold them can.
888    ///
889    /// The extensions are not a parameter because they are not a choice a
890    /// caller makes: every leaf document is parsed with [`parse_extensions`],
891    /// so the format is the whole of what varies.
892    pub fn of(format: Format) -> Self {
893        let exts = parse_extensions();
894        let supports = |g| format.supports_with(exts, g);
895        let inline = |k| supports(Gesture::ToggleInline(k));
896        let container = |k| supports(Gesture::ToggleBlockContainer(k));
897        Self {
898            bold: inline(InlineKind::Strong),
899            italic: inline(InlineKind::Emph),
900            code: inline(InlineKind::Verbatim),
901            mark: inline(InlineKind::Mark),
902            underline: inline(InlineKind::Insert),
903            strike: inline(InlineKind::Delete),
904            mark_color: supports(Gesture::SetMarkColor),
905            superscript: inline(InlineKind::Superscript),
906            subscript: inline(InlineKind::Subscript),
907            heading: supports(Gesture::SetBlock),
908            blockquote: container(BlockContainerKind::BlockQuote),
909            bullet_list: container(BlockContainerKind::BulletList),
910            ordered_list: container(BlockContainerKind::OrderedList),
911            // Both halves of the checkbox story, and leaf offers no control that
912            // needs only one: the item gesture mints the box, the checked one
913            // ticks it, and a format spelling a `task_marker` spells both.
914            task: supports(Gesture::ToggleTaskItem) && supports(Gesture::ToggleTaskChecked),
915            link: supports(Gesture::InsertLink),
916            image: supports(Gesture::InsertImage),
917            thematic_break: supports(Gesture::InsertThematicBreak),
918            footnote: supports(Gesture::InsertFootnote),
919            code_language: supports(Gesture::SetCodeLanguage),
920            table: spells_pipe_tables(format),
921            cell_line_break: supports(Gesture::InsertLineBreak),
922            // The presentation vocabulary, one gesture per level: the two
923            // line-level properties are a block's attributes and the three
924            // run-level ones a span's. They are asked separately because the
925            // formats answer differently — AsciiDoc spells the block and not
926            // the span — and a toolbar that dimmed all five together would dim
927            // three controls that work.
928            alignment: supports(Gesture::SetBlockAttrs),
929            line_spacing: supports(Gesture::SetBlockAttrs),
930            font_size: supports(Gesture::WrapRangeAttrs),
931            font_family: supports(Gesture::WrapRangeAttrs),
932            text_color: supports(Gesture::WrapRangeAttrs),
933            // Narrower than the gesture, on purpose. Twig spells
934            // `InsertDirective` in HTML and AsciiDoc too, and spells it
935            // *differently* there — `<page-break></page-break>` and `<<<` —
936            // and the walker reads only the two spellings above. An HTML page
937            // break draws as nothing at all (no row, no caret home) and an
938            // AsciiDoc one as an empty unlabelled row, so the button would
939            // write a break the author cannot see and cannot get back to.
940            // The proposal claims Markdown and djot, and this is that claim.
941            // Widening it is the walker's work, not this line's — see
942            // `docs/tasks/page-break-in-html-and-asciidoc.md`.
943            page_break: supports(Gesture::InsertDirective)
944                && matches!(format, Format::Markdown | Format::Djot),
945        }
946    }
947}
948
949/// The source of [`Doc::identity`], one per document ever built.
950static NEXT_IDENTITY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
951
952impl Doc {
953    #[cfg(feature = "fs")]
954    pub fn open(path: PathBuf) -> Result<Self> {
955        let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
956        Self::from_disk_bytes(path, bytes)
957    }
958
959    /// An empty document *named* `path`, for a file that isn't there yet — what
960    /// every other terminal editor gives you when you name a file that doesn't
961    /// exist. It is a real named document, not a [`Doc::blank`]: `is_untitled`
962    /// is false, so ⌘S writes straight to `path` with no Save As detour, and
963    /// the header shows the name the user asked for.
964    ///
965    /// The format comes from the extension, exactly as [`Doc::open`] reads it —
966    /// so `leaf notes.dj` starts a djot buffer rather than the Markdown
967    /// [`Doc::blank`] has to assume for want of a name. An extension leaf can't
968    /// parse is still an error: a mistyped flag or a stray argument should say
969    /// so, not open a buffer promising to save somewhere.
970    ///
971    /// The watermark is the hash of *no bytes*, not `None`, and that is the
972    /// whole trick: `None` means untitled, and would leave [`Doc::disk_state`]
973    /// answering [`DiskState::Untitled`] for a document that has a path and
974    /// intends to write to it. Hashing `""` instead makes the answers the true
975    /// ones — [`DiskState::Missing`] while the file still isn't there (a save
976    /// recreates it, which is exactly what this is for), and
977    /// [`DiskState::Changed`] if somebody creates it underneath us between
978    /// launch and save, so the frontend's overwrite prompt guards a new file as
979    /// it guards an opened one.
980    ///
981    /// Nothing is written here. A buffer that is never typed into never touches
982    /// the filesystem, and a `path` whose directory doesn't exist is allowed to
983    /// open — the write is where that fails, and it says so then.
984    #[cfg(feature = "fs")]
985    pub fn create(path: PathBuf) -> Result<Self> {
986        Self::from_disk_bytes(path, Vec::new())
987    }
988
989    /// [`Doc::open`] when the file is there, [`Doc::create`] when it isn't —
990    /// the call a CLI frontend wants for its path argument.
991    ///
992    /// The decision is made from the failed read itself rather than a `exists()`
993    /// check first, so there is no window between the two for the file to appear
994    /// or vanish in. Only `NotFound` opens a new buffer: a permissions error or
995    /// a directory in the way is still an error, because pretending those are
996    /// "no file yet" would offer to save over something leaf couldn't read.
997    #[cfg(feature = "fs")]
998    pub fn open_or_create(path: PathBuf) -> Result<Self> {
999        match std::fs::read(&path) {
1000            Ok(bytes) => Self::from_disk_bytes(path, bytes),
1001            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::create(path),
1002            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
1003        }
1004    }
1005
1006    /// The shared body of [`Doc::open`] and [`Doc::create`]: bytes that are (or
1007    /// stand in for) the file at `path`, parsed as the format its extension
1008    /// names. Keeping the two on one path is what makes a new file's document
1009    /// identical in every respect to an opened one but its contents.
1010    #[cfg(feature = "fs")]
1011    fn from_disk_bytes(path: PathBuf, bytes: Vec<u8>) -> Result<Self> {
1012        let format = detect_format(&path)?;
1013        let editor = new_editor(&bytes, format)?;
1014        let source = String::from_utf8(bytes).map_err(|_| anyhow!("document is not UTF-8"))?;
1015        let disk_hash = Some(hash_bytes(source.as_bytes()));
1016        // Store the document's *absolute* path. A relative one (`leaf README.md`)
1017        // has an empty parent, so a frontend can't resolve a relative image
1018        // destination (`![](pic.png)`) against the document's directory and the
1019        // picture silently falls back to its text placeholder. `absolute` is
1020        // purely lexical — it prefixes the current directory and normalizes, but
1021        // reads nothing and resolves no symlinks — so `file_name` and save are
1022        // unchanged; it only gives `path.parent()` something to join against.
1023        let path = std::path::absolute(&path).unwrap_or(path);
1024        Ok(Doc::from_parts(editor, format, path, source, disk_hash))
1025    }
1026
1027    /// Build a document from an in-memory string, the format named explicitly —
1028    /// the portable, filesystem-free counterpart to [`Doc::open`] (which reads a
1029    /// path and sniffs the format from its extension). A wasm or FFI host, which
1030    /// has no path to read, uses this: it hands over bytes it fetched however it
1031    /// could, and later persists [`Doc::source`] however it can (a browser
1032    /// download, `localStorage`, a backend `PUT`) and calls [`Doc::mark_saved`].
1033    ///
1034    /// No file backs the result, so it starts untitled ([`Doc::is_untitled`] is
1035    /// true) exactly like a [`Doc::blank`] that has been given content.
1036    pub fn from_source(source: String, format: Format) -> Result<Self> {
1037        let editor = new_editor(source.as_bytes(), format)?;
1038        Ok(Doc::from_parts(
1039            editor,
1040            format,
1041            PathBuf::new(),
1042            source,
1043            None,
1044        ))
1045    }
1046
1047    /// An untitled, empty document — the `+` button and a `leaf` launched with
1048    /// no file argument. Nothing on disk backs it until a [`Doc::save_as`].
1049    ///
1050    /// It is Markdown, because a format has to be chosen before a name exists to
1051    /// read one from: `detect_format` reads the extension and an untitled
1052    /// document has neither. Markdown is what leaf's own files are, what its
1053    /// block markers are already written for (`insert_block_prefix`), and the
1054    /// extension a Save As will overwhelmingly pick — a wrong guess here would
1055    /// mean typing djot into a buffer parsing it as Markdown. Note that Save As
1056    /// *doesn't* revisit this: see [`Doc::save_as`].
1057    pub fn blank() -> Result<Self> {
1058        let format = Format::Markdown;
1059        let editor = new_editor(b"", format)?;
1060        // An empty `path` is the untitled marker (`path` is a public `PathBuf`
1061        // field two frontends already read; making it an `Option` to say this
1062        // would break both). `is_untitled` is the question to ask, not the
1063        // representation to copy.
1064        Ok(Doc::from_parts(
1065            editor,
1066            format,
1067            PathBuf::new(),
1068            String::new(),
1069            None,
1070        ))
1071    }
1072
1073    /// The fields every constructor agrees on, so `open` and `blank` can't drift
1074    /// apart in the ones neither of them has an opinion about.
1075    // `identity` is taken from a counter rather than from the `Doc`'s address,
1076    // which moves — a session that holds one is moved into and out of
1077    // containers freely, and an identity that changed with it would defeat the
1078    // one comparison it exists for.
1079    fn from_parts(
1080        editor: Editor,
1081        format: Format,
1082        path: PathBuf,
1083        source: String,
1084        disk_hash: Option<u64>,
1085    ) -> Self {
1086        Doc {
1087            editor,
1088            format,
1089            path,
1090            disk_hash,
1091            clean_source: source.clone(),
1092            source,
1093            caret: 0,
1094            anchor: None,
1095            dirty: false,
1096            status: None,
1097            read_only: false,
1098            highlights: Vec::new(),
1099            // leaf opens in the rich-text (WYSIWYG) view by default — the
1100            // markup-resolved surface is leaf's differentiator. Frontends can
1101            // still start in source view explicitly (e.g. a CLI flag), and ⌘e/⌥w
1102            // toggles at runtime.
1103            view: View::Wysiwyg,
1104            // `None` by default — the clean surface Diaryx ships, with typed
1105            // syntax kept literal; a markup-fluent frontend can climb the
1106            // ladder to `Shortcuts` or `Full`.
1107            markup_mode: MarkupMode::default(),
1108            // Fold by default — flowing prose that reflows to the viewport, the
1109            // behaviour every frontend had before this preference existed.
1110            line_flow: LineFlow::default(),
1111            last_edit_kind: None,
1112            pending_marks: InlineMarks::empty(),
1113            pending_at: None,
1114            goal_col: None,
1115            vmap: VisualMap::default(),
1116            smap: SourceMap::default(),
1117            // No map yet — the first `build_source` always builds.
1118            smap_key: None,
1119            revision: 0,
1120            undo_steps: 0,
1121            redo_steps: 0,
1122            // No map yet — the first `build_visual` always builds.
1123            vmap_key: None,
1124            identity: NEXT_IDENTITY.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
1125            block_cache: wysiwyg::BlockCache::default(),
1126            media_rows: HashMap::new(),
1127            scroll: 0,
1128            body_origin: (0, 0),
1129            body_width: 0,
1130            body_height: 0,
1131            drawn_caret: None,
1132        }
1133    }
1134
1135    /// Whether this document has no file behind it yet — a [`Doc::blank`] that
1136    /// has never been saved. The question a ⌘S handler asks to know it should
1137    /// open a Save As picker instead ([`Doc::save`] won't guess a name), and the
1138    /// header asks to know the name it shows is a placeholder.
1139    pub fn is_untitled(&self) -> bool {
1140        self.path.as_os_str().is_empty()
1141    }
1142
1143    pub fn toggle_view(&mut self) {
1144        self.view = match self.view {
1145            View::Source => View::Wysiwyg,
1146            View::Wysiwyg => View::Source,
1147        };
1148        self.scroll = 0;
1149        self.status = None;
1150        // Entering WYSIWYG, the caret may be sitting in now-hidden frontmatter;
1151        // lift it to the first rendered offset.
1152        self.clamp_caret();
1153    }
1154
1155    /// The current markup-exposure preference (see [`MarkupMode`]).
1156    pub fn markup_mode(&self) -> MarkupMode {
1157        self.markup_mode
1158    }
1159
1160    /// Set the markup-exposure preference. Both of its axes take effect at
1161    /// once: the editing one on the next [`insert`](Self::insert), and the
1162    /// rendering one on the next build — which is why this drops the cached
1163    /// visual map and the per-block render cache, exactly as
1164    /// [`set_line_flow`](Self::set_line_flow) does.
1165    pub fn set_markup_mode(&mut self, mode: MarkupMode) {
1166        if self.markup_mode == mode {
1167            return;
1168        }
1169        self.markup_mode = mode;
1170        // Neither cache is keyed on the mode, and moving between `Full` and the
1171        // hidden modes changes every row the caret's line renders to — so
1172        // invalidate both explicitly.
1173        self.vmap_key = None;
1174        self.block_cache = wysiwyg::BlockCache::default();
1175    }
1176
1177    /// The source byte range of the line the caret sits on, when that line
1178    /// should render its raw delimiters — `None` in every mode and view that
1179    /// hides them, which is what the builder reads as "reveal nothing".
1180    ///
1181    /// A *source* line (newline to newline), not a visual row: a wrapped
1182    /// paragraph and a `LineFlow::Preserve` soft break both split one source
1183    /// line across several rows, and revealing half a delimiter pair because the
1184    /// other half wrapped would be worse than revealing neither. The range
1185    /// excludes the terminating newline and is empty-but-present on a blank
1186    /// line, which reveals nothing but still keys the caches correctly.
1187    ///
1188    /// Only in [`View::Wysiwyg`]: source view already shows every byte, so
1189    /// there is nothing there to reveal.
1190    pub(crate) fn reveal_line(&self) -> Option<Range<usize>> {
1191        if !self.markup_mode.reveals_caret_line() || self.view != View::Wysiwyg {
1192            return None;
1193        }
1194        Some(source_line_range(&self.source, self.caret))
1195    }
1196
1197    /// The current soft-break flow preference (see [`LineFlow`]).
1198    pub fn line_flow(&self) -> LineFlow {
1199        self.line_flow
1200    }
1201
1202    /// Set the soft-break flow preference. The mode changes how every block lays
1203    /// out, so a change drops the cached visual map and the per-block render
1204    /// cache, forcing the next [`build_visual`] to rebuild under the new flow.
1205    ///
1206    /// [`build_visual`]: Self::build_visual
1207    pub fn set_line_flow(&mut self, mode: LineFlow) {
1208        if self.line_flow == mode {
1209            return;
1210        }
1211        self.line_flow = mode;
1212        // Both caches are keyed on `(revision, wrap)`, neither of which moved —
1213        // so invalidate them explicitly, or the next build would reuse rows laid
1214        // out under the old flow.
1215        self.vmap_key = None;
1216        self.block_cache = wysiwyg::BlockCache::default();
1217    }
1218
1219    pub fn view_name(&self) -> &'static str {
1220        match self.view {
1221            View::Source => "source",
1222            View::Wysiwyg => "wysiwyg",
1223        }
1224    }
1225
1226    /// Rebuild the WYSIWYG visual map for the current tree at `width` columns
1227    /// (called by the renderer each frame it's in the WYSIWYG view).
1228    /// Build the WYSIWYG map, wrapped at `width` display columns.
1229    ///
1230    /// Cheap to call every frame, which is what both frontends do: the map is a
1231    /// pure function of the document and the wrap width, so a call that would
1232    /// rebuild the same map returns the one already built. Only an edit (or a
1233    /// resize) pays.
1234    ///
1235    /// That isn't a micro-optimisation. A frontend repaints for reasons that have
1236    /// nothing to do with the text — a blinking caret, a scroll, a focus change —
1237    /// and rebuilding here is O(document): 23 ms on a 1 MB file, of which 5 ms is
1238    /// marshalling twig's AST across the C ABI. Paid twice a second by the GUI's
1239    /// blink timer, that was 14% of a core spent redrawing an unchanged document.
1240    /// (`cargo run --release -p leaf-core --example bench` for the numbers.)
1241    pub fn build_visual(&mut self, width: usize) {
1242        self.build_map(Some(width));
1243    }
1244
1245    /// Build the WYSIWYG map with each block as a single unwrapped row — for a
1246    /// frontend (the GUI) that wraps at its own proportional pixel width rather
1247    /// than a fixed character column.
1248    pub fn build_visual_unwrapped(&mut self) {
1249        self.build_map(None);
1250    }
1251
1252    /// Build the source view's syntax map ([`Doc::smap`]) — the styling for
1253    /// [`View::Source`], the way [`build_visual`](Self::build_visual) is the
1254    /// styling for [`View::Wysiwyg`].
1255    ///
1256    /// A frontend calls this before painting raw source. One that doesn't gets
1257    /// an empty map and paints unstyled text, so this is additive: nothing
1258    /// breaks by not calling it.
1259    ///
1260    /// Built at most once per revision, and the revision is the whole key — the
1261    /// map has no width and no caret in it, so it survives every resize, every
1262    /// motion, and every selection change.
1263    ///
1264    /// The builds it does do cost a whole-arena marshal, which is precisely what
1265    /// the WYSIWYG path works to avoid, so this has no incremental path where
1266    /// that one has two. From `cargo run --release -p leaf-core --example
1267    /// bench`, per keystroke, against the WYSIWYG build the source view is
1268    /// *not* doing:
1269    ///
1270    /// |  size |  nodes | marshal | `source::build` | (`wysiwyg::build`) |
1271    /// |------:|-------:|--------:|----------------:|-------------------:|
1272    /// |  10 KB|    613 |  0.16 ms|         0.07 ms |            0.28 ms |
1273    /// | 100 KB|  6 097 |  0.84 ms|         0.38 ms |            2.43 ms |
1274    /// |   1 MB| 60 601 |  5.67 ms|         3.12 ms |           23.39 ms |
1275    ///
1276    /// Linear, two thirds of it the marshal, and the build itself five to seven
1277    /// times cheaper than the one it stands in for at every size. Comfortable
1278    /// well past any document a person edits in a terminal — a megabyte is where
1279    /// it would want [`Editor::dirty_range`] and the same splice treatment
1280    /// `build_spliced` gives the other map. The door is open; nothing has needed
1281    /// it yet.
1282    pub fn build_source(&mut self) {
1283        if self.smap_key == Some(self.revision) {
1284            return;
1285        }
1286        let nodes = self.nodes();
1287        self.smap = source::build(&nodes, &self.source);
1288        self.smap_key = Some(self.revision);
1289    }
1290
1291    /// Tell the model how many visual rows each block image should reserve, keyed
1292    /// by the image's destination. A terminal frontend calls this once it has
1293    /// decoded and measured its pictures — core does no image I/O, so this is the
1294    /// only way it learns a height — and the next [`Doc::build_visual`] lays each
1295    /// placeholder out that tall (the label row plus blank filler rows the
1296    /// frontend paints the raster over). A destination left out of the map falls
1297    /// back to the bare one-row placeholder, which is also what a frontend that
1298    /// can't draw pictures (or lays them out in its own units, like the GUI) gets
1299    /// by never calling this.
1300    ///
1301    /// Cheap to call every frame with the same map: only a *change* invalidates
1302    /// the built map (and the block-row cache, since a height isn't part of a
1303    /// block's bytes and so wouldn't otherwise re-render it). Steady state is a
1304    /// no-op, so a frontend can just hand over its current measurements each frame.
1305    pub fn set_media_rows(&mut self, rows: HashMap<String, usize>) {
1306        if self.media_rows == rows {
1307            return;
1308        }
1309        self.media_rows = rows;
1310        // A height lives outside the block's source bytes, so the content-keyed
1311        // block cache would hand back the old-height rows on a hit. Drop it (and
1312        // the splice layout it carries) so the next build re-renders every block
1313        // at the new heights, and force that build by clearing the map key.
1314        self.block_cache = wysiwyg::BlockCache::default();
1315        self.vmap_key = None;
1316    }
1317
1318    /// The revision the document's text is at — bumped by every edit, undo,
1319    /// redo, and reload, and by nothing else. A frontend caches against this to
1320    /// tell a repaint that needs new work from one that doesn't.
1321    ///
1322    /// It counts *edits*, not distinct texts: typing `x` and deleting it again
1323    /// lands on the same text two revisions later. Work is only ever rebuilt
1324    /// needlessly, never wrongly reused.
1325    pub fn revision(&self) -> u64 {
1326        self.revision
1327    }
1328
1329    /// The identity of the map presently in [`vmap`](Self::vmap) — what the last
1330    /// [`build_visual`](Self::build_visual) built it from, or the identity of an
1331    /// unbuilt map before the first one.
1332    ///
1333    /// This is *not* [`revision`](Self::revision). The revision says where the
1334    /// text is; this says where the map is, and the two part company the moment
1335    /// an edit lands, until something rebuilds. A frontend that keeps its own
1336    /// copy of the map — leaf-ratatui stashes core's before splicing filler rows
1337    /// under an oversized heading — compares this against the value it held when
1338    /// it took the copy, and learns whether `vmap` is still the map it stashed
1339    /// or one somebody else has since rebuilt. Restoring a copy over a newer
1340    /// map would paint a stale document; restoring nothing hands core's
1341    /// incremental rebuild a map it never built.
1342    ///
1343    /// "Somebody else" includes another document. The key names the `Doc`
1344    /// as well as the build, so a frontend that draws two documents through
1345    /// one stash — a host with several buffers, or one that opens the next
1346    /// document where the last one stood — never has the copy it took of one
1347    /// accepted by the other, however alike their builds are.
1348    pub fn visual_key(&self) -> VisualKey {
1349        VisualKey(self.identity, self.vmap_key.clone())
1350    }
1351
1352    /// The map, built at most once per `(revision, wrap)`. `clamp_caret` still
1353    /// runs on every call: the caret moves without the document changing, and
1354    /// keeping it on a legal stop is this function's job either way.
1355    fn build_map(&mut self, wrap: Option<usize>) {
1356        // Under `MarkupMode::Full` the map is a function of the caret's *line*
1357        // as well as the text, so the line joins the key: moving within a line
1358        // still reuses the map, and crossing into another one rebuilds it. In
1359        // every other mode `reveal_line` is `None` and the key is what it was,
1360        // so caret motion goes on costing nothing.
1361        let reveal = self.reveal_line();
1362        let key = (self.revision, wrap, reveal.clone());
1363        if self.vmap_key.as_ref() != Some(&key) {
1364            // Enumerate the top-level blocks cheaply — no whole-arena marshal.
1365            // A subtree is pulled only for the block(s) that actually changed, so
1366            // the FFI marshal shrinks from O(document) to O(edited block).
1367            let top = self.top_blocks();
1368
1369            // Fast path: when twig reports a dirty byte range, try to patch the
1370            // previous map in place — a single-block edit moves the prefix,
1371            // shifts the suffix, and re-renders only one block. `build_spliced`
1372            // returns `None` (and we fall back to the always-correct full rebuild)
1373            // whenever the edit reshaped the block structure, hit a table, or
1374            // there's no previous map to patch.
1375            // Preserve soft breaks as written when the flow preference asks for
1376            // it — the builder renders each as its own visual row instead of
1377            // folding it into the reflowed paragraph.
1378            let preserve_soft = self.line_flow == LineFlow::Preserve;
1379            let spliced = match self.editor.dirty_range() {
1380                Some(dirty) => {
1381                    let prev = std::mem::take(&mut self.vmap);
1382                    let source = &self.source;
1383                    let cache = &mut self.block_cache;
1384                    let media_rows = &self.media_rows;
1385                    let editor = &mut self.editor;
1386                    wysiwyg::build_spliced(
1387                        prev,
1388                        source,
1389                        wrap,
1390                        preserve_soft,
1391                        &top,
1392                        dirty,
1393                        media_rows,
1394                        reveal.clone(),
1395                        cache,
1396                        |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1397                    )
1398                }
1399                None => None,
1400            };
1401            self.vmap = spliced.unwrap_or_else(|| {
1402                let source = &self.source;
1403                let cache = &mut self.block_cache;
1404                let media_rows = &self.media_rows;
1405                let editor = &mut self.editor;
1406                wysiwyg::build_cached(
1407                    &top,
1408                    source,
1409                    wrap,
1410                    preserve_soft,
1411                    media_rows,
1412                    reveal,
1413                    cache,
1414                    |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1415                )
1416            });
1417            // Acknowledge the dirty range so the next edit's range starts fresh.
1418            self.editor.clear_dirty();
1419            self.vmap_key = Some(key);
1420        }
1421        self.clamp_caret();
1422    }
1423
1424    fn nodes(&mut self) -> Vec<FlatNode> {
1425        self.editor.nodes().unwrap_or_default()
1426    }
1427
1428    /// The document's top-level blocks for the incremental render. See
1429    /// [`wysiwyg::top_blocks`] for why this isn't simply `child_spans(None)`.
1430    fn top_blocks(&mut self) -> Vec<QueryMatch> {
1431        wysiwyg::top_blocks(&mut self.editor)
1432    }
1433
1434    pub fn format_name(&self) -> &'static str {
1435        // `Format` is `#[non_exhaustive]` as of twig 3.0, so the wildcard is
1436        // required. It also covers `Asciidoc`, which twig parses but cannot
1437        // serialize — leaf never opens a document in it (see `Doc::open`).
1438        match self.format {
1439            Format::Djot => "djot",
1440            Format::Markdown => "markdown",
1441            Format::Xml => "xml",
1442            Format::Html => "html",
1443            _ => "unknown",
1444        }
1445    }
1446
1447    /// Whether this document's format offers *any* door in — `false` only for a
1448    /// wholly parse-only format (XML, AsciiDoc), where every gesture refuses and
1449    /// a frontend may as well open the file read-only.
1450    ///
1451    /// This is a much weaker claim than the name suggests, and driving per-button
1452    /// state from it is exactly the mistake to avoid: HTML answers `true` because
1453    /// it spells the inline marks with a tag pair (`<strong>`, `<em>`, `<code>`)
1454    /// while a heading, a quote, a list, a task box, a link and a code fence all
1455    /// remain unspellable there. Ask [`capabilities`](Self::capabilities) — or
1456    /// [`supports`](Self::supports) — per control.
1457    pub fn authorable(&self) -> bool {
1458        self.format.is_authorable()
1459    }
1460
1461    /// Whether this document can spell `gesture`, which is twig's own answer
1462    /// rather than a copy of it: `Format::supports_with` reads the same
1463    /// `Syntax` table the `Editor` method consults before refusing, chosen by
1464    /// the very [`parse_extensions`] this document's editor reparses with — so
1465    /// what the toolbar offers and what the splice will accept are one table.
1466    ///
1467    /// It is a fact about the *document*, not about the caret. `true` does not
1468    /// promise the gesture succeeds where it is standing — a link over a table
1469    /// border still fails — only that it will not fail with
1470    /// `UnsupportedFormat`. Gray out on `false`; don't read `true` as "this
1471    /// will work here".
1472    pub fn supports(&self, gesture: Gesture) -> bool {
1473        self.format.supports_with(parse_extensions(), gesture)
1474    }
1475
1476    /// Every control's enabled state in one read — what a toolbar builds itself
1477    /// from when a document opens or its format changes. See [`Capabilities`].
1478    pub fn capabilities(&self) -> Capabilities {
1479        Capabilities::of(self.format)
1480    }
1481
1482    /// Refuse a gesture this document's format cannot spell, saying so in the
1483    /// status line. `true` means the caller must return without calling twig.
1484    ///
1485    /// Most of these refusals duplicate one twig would make anyway, and they are
1486    /// made here regardless because a message naming the *document's* format
1487    /// reads better than one naming twig's internals. Two of them are not
1488    /// duplicates and are the reason this is a guard rather than an error
1489    /// translation:
1490    ///
1491    /// - The table family (see [`table_op`](Self::table_op)) consults no
1492    ///   `Syntax` table, so twig does not refuse it at all.
1493    /// - [`toggle`](Self::toggle) at a collapsed caret never reaches twig — it
1494    ///   arms a sticky mark for text not yet typed, which is a promise `insert`
1495    ///   could not keep.
1496    fn refuse_unsupported(&mut self, what: &str, gesture: Gesture) -> bool {
1497        self.refuse_unless(what, self.supports(gesture))
1498    }
1499
1500    /// [`refuse_unsupported`](Self::refuse_unsupported) against a capability leaf
1501    /// answers itself — today only [`spells_pipe_tables`].
1502    fn refuse_unless(&mut self, what: &str, supported: bool) -> bool {
1503        if supported {
1504            return false;
1505        }
1506        self.status = Some(format!("{what}: not supported in {}", self.format_name()));
1507        true
1508    }
1509
1510    /// The name to show for this document. An untitled one has no file to name
1511    /// it, and both frontends put this straight on screen — an empty path
1512    /// renders as an empty header, so it says so instead.
1513    pub fn file_name(&self) -> String {
1514        if self.is_untitled() {
1515            return "untitled".into();
1516        }
1517        self.path
1518            .file_name()
1519            .map(|s| s.to_string_lossy().into_owned())
1520            .unwrap_or_else(|| self.path.display().to_string())
1521    }
1522
1523    /// The selection as an ordered `[start, end)` byte range, or `None` when the
1524    /// caret and anchor coincide (an empty selection is no selection).
1525    pub fn selection(&self) -> Option<(usize, usize)> {
1526        self.anchor
1527            .map(|a| (a.min(self.caret), a.max(self.caret)))
1528            .filter(|(s, e)| s != e)
1529    }
1530
1531    /// The selected text, or `None` when there's no selection — the source
1532    /// slice a copy/cut hands to the system clipboard.
1533    pub fn selected_text(&self) -> Option<&str> {
1534        self.selection().map(|(s, e)| &self.source[s..e])
1535    }
1536
1537    /// The selection as a quote with a little of what surrounds it — the shape
1538    /// a host that cites, annotates, or searches for a passage wants, cut from
1539    /// the **source** rather than from anything rendered, so the quote is
1540    /// findable in the document again by plain string search.
1541    ///
1542    /// `context` is a count of characters (not bytes) on each side, clipped at
1543    /// the document's edges; the slices land on char boundaries by
1544    /// construction. `None` when nothing is selected.
1545    pub fn selection_quote(&self, context: usize) -> Option<Quote> {
1546        let (start, end) = self.selection()?;
1547        let mut before = start;
1548        for _ in 0..context {
1549            match self.source[..before].chars().next_back() {
1550                Some(c) => before -= c.len_utf8(),
1551                None => break,
1552            }
1553        }
1554        let mut after = end;
1555        for _ in 0..context {
1556            match self.source[after..].chars().next() {
1557                Some(c) => after += c.len_utf8(),
1558                None => break,
1559            }
1560        }
1561        Some(Quote {
1562            exact: self.source[start..end].to_string(),
1563            prefix: self.source[before..start].to_string(),
1564            suffix: self.source[end..after].to_string(),
1565            start,
1566            end,
1567        })
1568    }
1569
1570    /// Whether the document refuses to change — see the field.
1571    pub fn read_only(&self) -> bool {
1572        self.read_only
1573    }
1574
1575    /// Turn the read-only gate on or off. A frontend preference like
1576    /// [`set_markup_mode`](Self::set_markup_mode): nothing about the document
1577    /// itself changes, only what may be done to it from here on.
1578    pub fn set_read_only(&mut self, on: bool) {
1579        self.read_only = on;
1580    }
1581
1582    /// The host-painted ranges, sorted by start — see [`Highlight`].
1583    pub fn highlights(&self) -> &[Highlight] {
1584        &self.highlights
1585    }
1586
1587    /// Replace the host-painted ranges wholesale. The whole set each time,
1588    /// rather than add/remove verbs: the host owns the list (it derives it
1589    /// from its own state — annotations, search hits), and a replace can
1590    /// never leave the two disagreeing about what should be on screen.
1591    pub fn set_highlights(&mut self, mut highlights: Vec<Highlight>) {
1592        highlights.retain(|h| h.start < h.end);
1593        highlights.sort_by_key(|h| (h.start, h.end));
1594        self.highlights = highlights;
1595    }
1596
1597    /// The highlight covering source `offset`, if one does — first by start
1598    /// when several overlap, which makes overlapping washes resolvable rather
1599    /// than undefined. What a frontend asks when the reader activates a spot.
1600    ///
1601    /// [`Highlight::covering`] is the whole of it: the frontends paint by
1602    /// asking the same question per glyph, against a slice they were handed
1603    /// rather than against a `Doc`, and one answer for both is what keeps a
1604    /// wash and an activation agreeing about which range a spot is in.
1605    pub fn highlight_at(&self, offset: usize) -> Option<&Highlight> {
1606        Highlight::covering(&self.highlights, offset)
1607    }
1608
1609    /// The AST breadcrumb at the caret (root → deepest), e.g.
1610    /// `doc › para › strong`. Read live from twig via `ancestors_at`.
1611    pub fn breadcrumb(&mut self) -> String {
1612        match self.editor.ancestors_at(self.caret) {
1613            Ok(chain) => chain
1614                .iter()
1615                .map(|m| m.kind.as_str())
1616                .collect::<Vec<_>>()
1617                .join(" › "),
1618            Err(_) => String::new(),
1619        }
1620    }
1621
1622    // ── editing ──────────────────────────────────────────────────────────────
1623
1624    /// Replace the byte range `[start, end)` with `text`, re-anchoring the caret
1625    /// after it. The public form of the internal splice — a pixel frontend that
1626    /// hit-tests to a byte offset (or an IME that hands back an explicit range)
1627    /// edits through this, the same twig `edit_range` the caret ops use.
1628    pub fn edit(&mut self, start: usize, end: usize, text: &str) {
1629        self.splice(start, end, text, EditKind::Other);
1630    }
1631
1632    /// Insert typed `text` at the caret, replacing the selection if there is one.
1633    /// A single typed character coalesces with the run of typing before it; a
1634    /// newline or a multi-character insert is its own undo step.
1635    ///
1636    /// Typed input only — clipboard text goes through [`paste`](Self::paste).
1637    pub fn insert(&mut self, text: &str) {
1638        // The read-only gate, up front: the paths below reach twig by several
1639        // verbs, not all of them through the splice — see the field.
1640        if self.read_only {
1641            return;
1642        }
1643        // Typing against a block picture would dissolve it, and typing past a
1644        // table would grow it a row — see `open_paragraph_at_block_edge`. Give
1645        // the text a paragraph first, so what the caret was standing beside
1646        // stays what it was.
1647        self.open_paragraph_at_block_edge(text);
1648        // Armed sticky marks (⌘b with no selection) turn the next typed text
1649        // bold/italic/… and then retire — see `insert_with_marks`. Whitespace is
1650        // the exception: it takes no mark of its own and keeps the delta armed
1651        // for the character behind it — see `insert_space_with_marks`.
1652        let pending = self.pending_here();
1653        if !pending.is_empty() && self.selection().is_none() && !text.is_empty() {
1654            if text.trim().is_empty() {
1655                self.insert_space_with_marks(self.caret, text, pending);
1656            } else {
1657                self.insert_with_marks(self.caret, text, pending);
1658            }
1659            return;
1660        }
1661        // `MarkupMode::None`: typed syntax stays literal — twig escapes
1662        // anything that would open markup, so a Diaryx user never mints
1663        // formatting by keyboard (it comes from commands instead). The other two
1664        // rungs of the ladder author markup from what you type, which is the
1665        // whole difference between them and this one. Only in the rendered view
1666        // (source view is for typing raw markup) and only where the format has a
1667        // literal spelling at all: escaping is a backslash before a byte from the
1668        // format's own alphabet, and a format with no such alphabet (HTML escapes
1669        // with entities, XML spells nothing) would have `\&` written into it,
1670        // which is two literal characters and not an escape. Marks (⌘b) still
1671        // format — that path returned above; and leaf's own structural inserts go
1672        // through `insert_raw`, never here, so a list marker or quote gutter is
1673        // written as the markup it is.
1674        if !self.markup_mode.authors()
1675            && self.view == View::Wysiwyg
1676            && !text.is_empty()
1677            && self.supports(Gesture::InsertLiteral)
1678        {
1679            self.insert_literal_typed(text);
1680            return;
1681        }
1682        self.insert_raw(text);
1683    }
1684
1685    /// Insert `text` verbatim at the caret (replacing any selection) — the plain
1686    /// path with no Hidden-mode literal escaping. leaf's own structural inserts
1687    /// (a list marker, a quote gutter, an in-cell `<br>`) call this: they ARE
1688    /// markup by design and must not be escaped.
1689    fn insert_raw(&mut self, text: &str) {
1690        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
1691        self.splice(s, e, text, typed_edit_kind(text));
1692    }
1693
1694    /// Open a paragraph for text about to be inserted at one of a block media's
1695    /// two caret stops, or at a table's trailing stop, and leave the caret
1696    /// standing in it.
1697    ///
1698    /// A block image is a paragraph whose entire content is the picture, and the
1699    /// caret's only homes on it are in front of it and just past it (see
1700    /// [`VisualMap::block_media_stop`]). Text inserted at either offset joins
1701    /// *that* paragraph — and a paragraph holding anything besides the image is
1702    /// no longer a block image but a line of text with an inline one in it. The
1703    /// frontend that was painting a photo there paints a text run instead; the
1704    /// picture is still in the file, and nothing said a word. Those two offsets
1705    /// are also exactly where a click on the picture lands, so the whole accident
1706    /// is one tap and one keystroke.
1707    ///
1708    /// So the break goes in first and the text lands in the new empty paragraph —
1709    /// what pressing Return before typing would have done, which is a habit no
1710    /// one should have to learn from losing a photo. A no-op everywhere else, and
1711    /// over a selection (which is replaced, not joined into).
1712    ///
1713    /// A picture inside a quote or a list leaves its container, because `\n\n`
1714    /// ends the block. The alternative is worse: the `\n> ` / next-item
1715    /// continuation [`newline`](Self::newline) writes stays in the same
1716    /// *paragraph*, which is the thing being prevented.
1717    ///
1718    /// A table's trailing stop ([`VisualMap::table_end_stop`]) is the same
1719    /// accident from the other side of a different block: the stop sits at the
1720    /// end of the table's last source line, and a line glued under a table is
1721    /// a row of it — `| 1 | 2 |x` is a three-cell row, not a paragraph. So the
1722    /// break goes in there too, and the text lands under the table.
1723    ///
1724    /// Only in the rendered view. Source view is for typing raw markup, where
1725    /// putting a character against an image is exactly what it looks like.
1726    fn open_paragraph_at_block_edge(&mut self, text: &str) {
1727        if self.view != View::Wysiwyg || text.is_empty() || text == "\n" {
1728            return;
1729        }
1730        if self.selection().is_some() {
1731            return;
1732        }
1733        // The map may be a revision behind (nothing has drawn since the last
1734        // edit), and this asks it about offsets — a stale answer would splice a
1735        // break into the wrong place. Free when it is already current, which it
1736        // is whenever a frontend drew a frame between keystrokes.
1737        self.rebuild_map();
1738        let at = self.caret;
1739        let side = match self.vmap.block_media_stop(at) {
1740            Some((side, _)) => side,
1741            None if self.vmap.table_end_stop(at) => MediaStop::After,
1742            None => return,
1743        };
1744        if !self.splice(at, at, "\n\n", EditKind::Other) {
1745            return;
1746        }
1747        // The break is part of the keystroke, not an edit of its own: leave the
1748        // run marked as typing so the character about to arrive folds into it and
1749        // one undo puts the document back the way it was found. (A paste, or a
1750        // multi-character insert, is `EditKind::Other` and stays its own step —
1751        // as it would have been anywhere else in the document.)
1752        self.last_edit_kind = Some(EditKind::Insert);
1753        if side == MediaStop::Before {
1754            // The break went in above the picture and the caret rode to the end
1755            // of it — which is still hard against the picture. Step back onto the
1756            // blank line it opened, so the text lands above rather than in front.
1757            self.caret = at;
1758        }
1759    }
1760
1761    /// A delete key pressed at one of a block picture's two caret stops, handled
1762    /// as the picture being an *atom* rather than a run of bytes. Returns whether
1763    /// the key was consumed.
1764    ///
1765    /// The caret rests in front of a block image and just past it, never inside
1766    /// its markup — which the rendered view doesn't show. So the byte a delete
1767    /// key nominally takes there is one the writer cannot see, and taking it
1768    /// leaves the picture as broken markup rather than as anything anyone asked
1769    /// for: Backspace at the stop past `![](p.png)` removes the closing paren, and
1770    /// a photo becomes the literal text `![](p.png`. That is how a picture goes
1771    /// missing from a document with nobody having touched it — the same
1772    /// dissolution [`open_paragraph_at_block_edge`](Self::open_paragraph_at_block_edge)
1773    /// prevents from the typing side, and it cost this repository's own test vault
1774    /// a photo before it was found.
1775    ///
1776    /// So the key aimed *at* the picture deletes the picture, whole — Backspace
1777    /// when it is behind the caret, Delete when it is in front — which is what
1778    /// every editor does with an embed, and one undo away. The key aimed *away*
1779    /// from it would otherwise delete the paragraph break and merge a neighbour
1780    /// into the picture's own paragraph, which dissolves it just as surely; it
1781    /// steps the caret over the boundary instead and leaves the
1782    /// next press to delete in the block it has reached — the same "first press
1783    /// steps out of the atom, second press deletes" every delete key here gets,
1784    /// word-deletes included (⌥⌫ in front of a picture is aimed at the prose
1785    /// above, and reaches it on the second press rather than taking the break and
1786    /// the picture with it on the first).
1787    fn delete_around_block_media(&mut self, forward: bool) -> bool {
1788        // The map answers about offsets, so it has to be this revision's — see
1789        // the same call in `open_paragraph_at_block_edge`.
1790        self.rebuild_map();
1791        let Some((side, span)) = self.vmap.block_media_stop(self.caret) else {
1792            return false;
1793        };
1794        let aimed_at_it = side
1795            == if forward {
1796                MediaStop::Before
1797            } else {
1798                MediaStop::After
1799            };
1800        if !aimed_at_it {
1801            let over = if forward {
1802                self.vmap.stop_after(self.caret)
1803            } else {
1804                self.vmap.stop_before(self.caret)
1805            };
1806            if let Some(off) = over.filter(|&o| o >= self.caret_floor()) {
1807                self.caret = off;
1808                self.anchor = None;
1809                self.goal_col = None;
1810            }
1811            return true;
1812        }
1813        // Take the break that held the picture apart from its neighbour with it,
1814        // so the delete doesn't leave a blank paragraph standing where the
1815        // picture was. The last arm is a picture that is the whole document.
1816        let (from, to) = if self.source[..span.start].ends_with("\n\n") {
1817            (span.start - 2, span.end)
1818        } else if self.source[span.end..].starts_with("\n\n") {
1819            (span.start, span.end + 2)
1820        } else {
1821            (span.start, span.end)
1822        };
1823        self.splice(from.max(self.caret_floor()), to, "", EditKind::Other);
1824        true
1825    }
1826
1827    /// The Hidden-mode typing path: replace any selection, then insert `text`
1828    /// escaped so it stays literal. When it replaces a selection the two edits
1829    /// fold into one undo step, so an overwrite undoes atomically (and restores
1830    /// the selection) exactly as a plain one does.
1831    fn insert_literal_typed(&mut self, text: &str) {
1832        let kind = typed_edit_kind(text);
1833        match self.selection() {
1834            Some((s, e)) => {
1835                if !self.splice(s, e, "", EditKind::Other) {
1836                    return;
1837                }
1838                // Typing over a whole marked run takes its delimiters with it
1839                // (the empty content couldn't hold them — see
1840                // `repair_mark_edges`) and leaves its marks armed at the caret.
1841                // The text taking the run's place inherits them, exactly as it
1842                // would have by landing inside a run that survived.
1843                let pending = self.pending_here();
1844                if !pending.is_empty() && !text.trim().is_empty() {
1845                    self.insert_with_marks(self.caret, text, pending);
1846                    return;
1847                }
1848                self.insert_literal_at(self.caret, text, kind, true);
1849            }
1850            None => {
1851                self.insert_literal_at(self.caret, text, kind, false);
1852            }
1853        }
1854    }
1855
1856    /// The sticky-mark delta that is live right now: the marks armed by [`toggle`]
1857    /// at a collapsed caret, but only while the caret still stands where they
1858    /// were armed and nothing is selected. Empty otherwise, so a stale delta
1859    /// never styles text it wasn't meant for.
1860    fn pending_here(&self) -> InlineMarks {
1861        if self.anchor.is_none() && self.pending_at == Some(self.caret) {
1862            self.pending_marks
1863        } else {
1864            InlineMarks::empty()
1865        }
1866    }
1867
1868    /// Drop the armed sticky marks — any caret motion, selection, or edit does
1869    /// this, so "start bold here" only ever applies at the exact spot it was
1870    /// asked for.
1871    fn clear_pending(&mut self) {
1872        self.pending_marks = InlineMarks::empty();
1873        self.pending_at = None;
1874    }
1875
1876    /// Insert `text` at `at` carrying the armed sticky `marks`: a mark not yet in
1877    /// force is wrapped around the freshly typed text; a mark the caret already
1878    /// stands inside is *shed* — the text is inserted past the run's end so it
1879    /// lands unmarked ("type normally again"). The caret comes to rest inside any
1880    /// added runs, so continued typing inherits the marks with no re-wrapping,
1881    /// and the delta is cleared: the marks now live in the document, not here.
1882    fn insert_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
1883        let base = self.mark_spans_at(at);
1884        let base_set: InlineMarks = base.iter().map(|(k, _)| *k).collect();
1885        // Nothing to shed, and a run of exactly these marks standing just behind
1886        // the caret: carry on writing *that* run rather than opening a second
1887        // one beside it.
1888        if base_set.is_empty() && self.rejoin_run(at, text, marks) {
1889            return;
1890        }
1891        // Shed the marks we're turning off: step the insertion point past the
1892        // end of each run the caret sits in, so the new text falls outside it.
1893        let mut ins_at = at;
1894        for (kind, span) in &base {
1895            if marks.contains(*kind) {
1896                ins_at = ins_at.max(span.end);
1897            }
1898        }
1899        if !self.splice_exact(ins_at, ins_at, text, EditKind::Other) {
1900            return;
1901        }
1902        // The plain splice inserted exactly `text` at `ins_at`; that byte range
1903        // is the content every added mark wraps.
1904        let (mut cs, mut ce) = (ins_at, ins_at + text.len());
1905        for kind in marks.iter() {
1906            if !base_set.contains(kind) {
1907                let (ncs, nce) = self.wrap_span(cs, ce, kind);
1908                cs = ncs;
1909                ce = nce;
1910            }
1911        }
1912        self.caret = ce.min(self.source.len());
1913        self.anchor = None;
1914        self.last_edit_kind = None;
1915        // Realised: the marks are in the document now, and the caret sits inside
1916        // them, so there is no delta left to carry. Arm nothing, but remember the
1917        // spot so a *further* toggle before typing starts a clean delta here.
1918        self.pending_marks = InlineMarks::empty();
1919        self.pending_at = Some(self.caret);
1920        self.clamp_caret();
1921        self.record_caret();
1922    }
1923
1924    /// Carry on the marked run just behind `at` — moving its closing delimiters
1925    /// out past the new text — instead of opening a second run of the same marks
1926    /// beside it. Returns whether it did.
1927    ///
1928    /// This is the far half of the mark-edge rule (see [`splice`](Self::splice)).
1929    /// A space typed after a bold word steps the caret out of the run, because
1930    /// `**bold **` is not bold; the next character has to step back *in*, or the
1931    /// writer who typed one bold phrase is left with `**bold** **and**` — two
1932    /// runs that read the same to a reader but spell the file in a way nobody
1933    /// wrote. Only whitespace may stand in the gap (a run doesn't reach across
1934    /// words it isn't marking), and the marks behind it must be exactly the ones
1935    /// armed — a run of *some* other kind is a neighbour, not this phrase.
1936    fn rejoin_run(&mut self, at: usize, text: &str, marks: InlineMarks) -> bool {
1937        if text.is_empty() || text.trim() != text {
1938            return false;
1939        }
1940        let gap_at = self.source[..at].trim_end_matches([' ', '\t']).len();
1941        // Walk in through the delimiters stacked at that point, innermost last:
1942        // `***both*** ` closes two runs with one `***`, and rejoining means
1943        // getting behind all of them.
1944        let (mut cut, mut kinds) = (gap_at, InlineMarks::empty());
1945        while let Some((kind, content_end)) = self
1946            .editor
1947            .ancestors_at(prev_boundary(&self.source, cut))
1948            .unwrap_or_default()
1949            .into_iter()
1950            .filter(|m| m.span.end == cut)
1951            .find_map(|m| Some((inline_kind(&m.kind)?, m.content_span.clone()?.end)))
1952        {
1953            if content_end >= cut {
1954                break; // a mark with no closing delimiter to step behind
1955            }
1956            kinds.insert(kind);
1957            cut = content_end;
1958        }
1959        if cut == gap_at || kinds != marks {
1960            return false;
1961        }
1962        // Re-spell the tail: the gap, then the new text, then the delimiters that
1963        // used to close in front of them — read out of the document rather than
1964        // written from a table, so whatever twig spells them with is what moves.
1965        let tail = format!(
1966            "{}{text}{}",
1967            &self.source[gap_at..at],
1968            &self.source[cut..gap_at]
1969        );
1970        if !self.splice_exact(cut, at, &tail, EditKind::Other) {
1971            return false;
1972        }
1973        self.caret = (cut + (at - gap_at) + text.len()).min(self.source.len());
1974        self.anchor = None;
1975        self.last_edit_kind = None;
1976        self.pending_marks = InlineMarks::empty();
1977        self.pending_at = Some(self.caret);
1978        self.clamp_caret();
1979        self.record_caret();
1980        true
1981    }
1982
1983    /// Insert typed whitespace at a caret with sticky marks armed. Whitespace is
1984    /// never itself wrapped: a mark around a space draws nothing a reader can
1985    /// see, and in Markdown and Djot it draws its own delimiters instead
1986    /// (`** **`). So the space goes in unmarked — outside any run the armed
1987    /// marks are shedding — and the marks stay armed for the character after it,
1988    /// which rejoins the run (see [`rejoin_run`](Self::rejoin_run)).
1989    fn insert_space_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
1990        let base = self.mark_spans_at(at);
1991        // What the *next* character carries: the armed delta resolved against the
1992        // marks in force here, which the space must not quietly drop.
1993        let want = base
1994            .iter()
1995            .map(|(k, _)| *k)
1996            .collect::<InlineMarks>()
1997            .xor(marks);
1998        let mut ins_at = at;
1999        for (kind, span) in &base {
2000            if marks.contains(*kind) {
2001                ins_at = ins_at.max(span.end);
2002            }
2003        }
2004        if !self.splice(ins_at, ins_at, text, typed_edit_kind(text)) {
2005            return;
2006        }
2007        self.rearm(want);
2008        self.record_caret();
2009    }
2010
2011    /// Wrap `[s, e)` in `kind` via twig and return the byte span the *content*
2012    /// (not the delimiters) occupies afterwards. Markdown/Djot inline delimiters
2013    /// are symmetric (`**`…`**`, `_`…`_`, `` ` ``…`` ` ``), so the bytes twig
2014    /// added split evenly around the content — half the growth on each side.
2015    fn wrap_span(&mut self, s: usize, e: usize, kind: InlineKind) -> (usize, usize) {
2016        // The read-only gate — this door reaches twig without the splice.
2017        if self.read_only {
2018            return (s, e);
2019        }
2020        match self.editor.toggle_inline(s, e, kind) {
2021            Ok(change) => {
2022                self.last_edit_kind = None;
2023                self.refresh();
2024                self.dirty = self.source != self.clean_source;
2025                let added = (change.new.end - change.new.start).saturating_sub(e - s);
2026                let half = added / 2;
2027                (change.new.start + half, change.new.end - half)
2028            }
2029            // Unsupported here (e.g. mark on Markdown): leave the text unwrapped
2030            // rather than lose the keystroke.
2031            Err(e2) => {
2032                self.status = Some(format!("{kind:?}: {e2}"));
2033                (s, e)
2034            }
2035        }
2036    }
2037
2038    /// The safe offset to splice a block-level break at, given a caret that may
2039    /// sit exactly between an inline mark's content and its own closing
2040    /// delimiter (`content_span.end == off < span.end` for some enclosing mark
2041    /// — the WYSIWYG caret's natural resting place at the end of `**bold**`
2042    /// with nothing following it on the line: the closing `**` renders no
2043    /// glyph of its own, so the caret's "end of line" offset lands right
2044    /// before it). Splicing a paragraph/list/quote break at `off` itself would
2045    /// sever the delimiter from its content, stranding it alone on the new
2046    /// line. Walks out to the *outermost* such mark's `span.end` instead, so
2047    /// nested marks closing at the same point (`**_x_**`) all clear together.
2048    /// A no-op everywhere else — mid-run, or past real trailing content, no
2049    /// mark's `content_span` ends exactly at `off`.
2050    fn skip_trailing_close_delims(&mut self, off: usize) -> usize {
2051        let off = off.min(self.source.len());
2052        let runs = self.run_span_ids();
2053        self.editor
2054            .ancestors_at(off)
2055            .unwrap_or_default()
2056            .into_iter()
2057            .filter(|m| hides_delims(m, &runs))
2058            .filter(|m| off < m.span.end && m.content_span.as_ref().is_some_and(|c| c.end == off))
2059            .map(|m| m.span.end)
2060            .max()
2061            .unwrap_or(off)
2062    }
2063
2064    /// The offset a *delete* aimed at the character before `off` should stop at,
2065    /// when `off` is the start of a run's text and the bytes behind it are that
2066    /// run's opening delimiter. The rich view draws no glyph for a `**`, so the
2067    /// byte behind the caret at the start of a bold word is not a character the
2068    /// writer can see, let alone one they aimed Backspace at: taking it leaves
2069    /// `a *bold** c` — the styling gone and a literal asterisk in its place. The
2070    /// delete steps over the whole delimiter to the visible character in front of
2071    /// it instead. Walks out to the *outermost* mark opening there, so
2072    /// `**_x_**` clears every delimiter at once, and is a no-op anywhere else.
2073    fn skip_leading_open_delims(&mut self, off: usize) -> usize {
2074        let off = off.min(self.source.len());
2075        let runs = self.run_span_ids();
2076        self.editor
2077            .ancestors_at(off)
2078            .unwrap_or_default()
2079            .into_iter()
2080            .filter(|m| hides_delims(m, &runs))
2081            .filter(|m| {
2082                m.span.start < off && m.content_span.as_ref().is_some_and(|c| c.start == off)
2083            })
2084            .map(|m| m.span.start)
2085            .min()
2086            .unwrap_or(off)
2087    }
2088
2089    /// `off` moved *inside* the run whose closing delimiters end there — the
2090    /// other offset the rich view draws in the same place, since a `**` renders
2091    /// no glyph of its own. `**bold**` has a caret home on each side of its
2092    /// closing delimiter, one column apart on screen and eight bytes and a whole
2093    /// run apart in the file, and a plain ← lands on the outer one whenever a
2094    /// space follows the phrase. The inner one is what the writer is pointing at
2095    /// there: the end of their bold word. Walks in through every mark closing at
2096    /// that point, innermost last, so `***both***` lands inside both. A no-op
2097    /// anywhere else — mid-run, or in prose, no mark's span ends at `off`.
2098    fn step_inside_close_delims(&mut self, off: usize) -> usize {
2099        let mut off = off.min(self.source.len());
2100        let runs = self.run_span_ids();
2101        loop {
2102            let inner = self
2103                .editor
2104                .ancestors_at(prev_boundary(&self.source, off))
2105                .unwrap_or_default()
2106                .into_iter()
2107                .filter(|m| hides_delims(m, &runs) && m.span.end == off)
2108                .filter_map(|m| m.content_span.clone().map(|c| c.end))
2109                .filter(|&end| end < off)
2110                .max();
2111            match inner {
2112                Some(end) => off = end,
2113                None => return off,
2114            }
2115        }
2116    }
2117
2118    /// The mirror at the opening edge: `off` moved inside the run whose
2119    /// delimiters *start* there, onto the first character of its text. See
2120    /// [`step_inside_close_delims`](Self::step_inside_close_delims).
2121    fn step_inside_open_delims(&mut self, off: usize) -> usize {
2122        let mut off = off.min(self.source.len());
2123        let runs = self.run_span_ids();
2124        loop {
2125            let inner = self
2126                .editor
2127                .ancestors_at(off)
2128                .unwrap_or_default()
2129                .into_iter()
2130                .filter(|m| hides_delims(m, &runs) && m.span.start == off)
2131                .filter_map(|m| m.content_span.clone().map(|c| c.start))
2132                .filter(|&start| start > off)
2133                .min();
2134            match inner {
2135                Some(start) => off = start,
2136                None => return off,
2137            }
2138        }
2139    }
2140
2141    /// The ids of the document's attributed run spans — the inline
2142    /// `Container`s [`wysiwyg::is_run_span`] picks out — for [`hides_delims`],
2143    /// which sees an ancestor chain and so only a kind. Read once per gesture,
2144    /// not once per step of a walk.
2145    fn run_span_ids(&mut self) -> Vec<NodeId> {
2146        self.nodes()
2147            .iter()
2148            .filter(|n| wysiwyg::is_run_span(n))
2149            .map(|n| n.id)
2150            .collect()
2151    }
2152
2153    /// The attributed span whose text is exactly `content` — the whole of
2154    /// `<span …>i</span>`'s `i`, or nothing at all when `content` is empty
2155    /// and sits between the tags of `<span …></span>` — as the whole range
2156    /// spelling the span: the node's span, widened to its attribute block
2157    /// where the format writes that outside the node, as djot's
2158    /// `[i]{data-size="large"}` does. `None` for any other range, including
2159    /// part of a span's text.
2160    ///
2161    /// An empty span has an interior of no bytes, or no known interior at
2162    /// all: twig gives Markdown's `<span …></span>` the first and djot's
2163    /// `[]{…}` the second, and the chain already says the offset is inside.
2164    fn run_span_of_content(&mut self, content: Range<usize>) -> Option<Range<usize>> {
2165        let runs = self.run_span_ids();
2166        let m = self
2167            .editor
2168            .ancestors_at(content.start)
2169            .unwrap_or_default()
2170            .into_iter()
2171            .filter(|m| runs.contains(&NodeId(m.node_id)))
2172            .find(|m| match &m.content_span {
2173                Some(c) => *c == content,
2174                None => content.is_empty(),
2175            })?;
2176        let mut range = m.span;
2177        if let Some(attrs) = self
2178            .editor
2179            .document()
2180            .ok()
2181            .and_then(|mut d| d.attrs_span(NodeId(m.node_id)).ok().flatten())
2182        {
2183            range.start = range.start.min(attrs.start);
2184            range.end = range.end.max(attrs.end);
2185        }
2186        Some(range)
2187    }
2188
2189    /// The inline mark kinds whose span covers `off`, each with that span — the
2190    /// span-carrying sibling of [`marks_at`](Self::marks_at), which reports node
2191    /// ids instead. Used to shed a mark by stepping past the end of its run.
2192    fn mark_spans_at(&mut self, off: usize) -> Vec<(InlineKind, std::ops::Range<usize>)> {
2193        let off = off.min(self.source.len());
2194        self.editor
2195            .ancestors_at(off)
2196            .unwrap_or_default()
2197            .into_iter()
2198            .filter(|m| off < m.span.end)
2199            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.span.clone())))
2200            .collect()
2201    }
2202
2203    /// Insert clipboard `text` at the caret, replacing the selection if there is
2204    /// one — always its own undo step, whatever its length.
2205    ///
2206    /// Provenance is the whole point, and only the caller has it. `insert` reads
2207    /// a lone character as a keystroke and folds it into the run around it,
2208    /// which is right for typing and wrong for a one-character paste: that paste
2209    /// would vanish mid-run on an undo it was never part of, and the characters
2210    /// the user actually typed would go with it. Length can't tell the two
2211    /// apart — `⌘V` of `x` and typing `x` are the same string — so the door the
2212    /// caller comes through is what says which happened.
2213    pub fn paste(&mut self, text: &str) {
2214        // Pasting against a block picture or a table's end joins the block
2215        // exactly as typing does, and for the same reason — see
2216        // `open_paragraph_at_block_edge`.
2217        self.open_paragraph_at_block_edge(text);
2218        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2219        self.splice(s, e, text, EditKind::Other);
2220    }
2221
2222    /// Replace `[start, end)` with `text` as one step of an IME composition —
2223    /// the same splice as [`edit`](Self::edit), but marked so the run of steps
2224    /// folds into a single undo.
2225    ///
2226    /// A composition is *one* act of writing. Typing `かんじ` and picking 感じ is a
2227    /// dozen calls here, each replacing the last one's provisional bytes, and an
2228    /// undo step per call means undoing a word means pressing ⌘Z until the reading
2229    /// unspools backwards through kana — the intermediate states were never text
2230    /// the user wrote. Only the frontend knows a call is provisional (the bytes
2231    /// look like any other edit), so the door the caller comes through is what
2232    /// says so, exactly as it is for [`paste`](Self::paste) versus
2233    /// [`insert`](Self::insert).
2234    ///
2235    /// Pair with [`end_composition`](Self::end_composition), or the *next*
2236    /// composition folds into this one.
2237    pub fn edit_composing(&mut self, start: usize, end: usize, text: &str) {
2238        self.splice(start, end, text, EditKind::Compose);
2239    }
2240
2241    /// Close the open composition run, so the next one is its own undo step.
2242    /// Call when the IME commits or withdraws a composition.
2243    ///
2244    /// Only clears a *composition* run: a frontend that reports an end it never
2245    /// began (some IMEs unmark unprompted) would otherwise split the run of
2246    /// typing around it into two undo steps for no reason the user can see.
2247    pub fn end_composition(&mut self) {
2248        if self.last_edit_kind == Some(EditKind::Compose) {
2249            self.last_edit_kind = None;
2250        }
2251    }
2252
2253    // ── the clipboard's rich flavor ──────────────────────────────────────────
2254
2255    /// The selection rendered as HTML, for the clipboard's `text/html` flavor —
2256    /// what lets a paste into Docs/Mail/Slack keep its formatting. `None` when
2257    /// nothing is selected, or when the selection doesn't render (the caller
2258    /// still has [`selected_text`](Self::selected_text), which is what to publish
2259    /// as `text/plain` either way).
2260    ///
2261    /// **The fragment is a source substring, and that is the honest limit here.**
2262    /// It's parsed standalone, so a selection whose meaning depends on its
2263    /// surroundings converts as what it literally says rather than what it looks
2264    /// like on screen: half a list item is a paragraph, a row torn out of a table
2265    /// is the text of a row, the `**` of a bold run selected without its closing
2266    /// `**` is two asterisks. Every one of those still *renders* — there's no
2267    /// error to report — it just renders as the fragment and not as the document.
2268    /// Widening the range to whole blocks would publish text the user didn't
2269    /// select, which is a worse lie than a fragment being a fragment; the plain
2270    /// flavor has the same substring, so the two flavors at least agree.
2271    pub fn selection_html(&mut self) -> Option<String> {
2272        let (start, end) = self.selection()?;
2273        let inline = self.selection_is_inline(start, end);
2274        let html = html::render_fragment(&self.source[start..end], self.format)?;
2275        Some(match inline {
2276            true => html::strip_sole_paragraph(html),
2277            false => html,
2278        })
2279    }
2280
2281    /// Paste the clipboard's `text/html` flavor, converting it to this document's
2282    /// format first. Its own undo step, like any [`paste`](Self::paste).
2283    ///
2284    /// Returns whether it landed. `false` means the HTML didn't convert to
2285    /// anything worth pasting — the caller should fall back to the plain flavor
2286    /// rather than treat it as an error. The `html` module has the full list of
2287    /// what that covers: a table twig won't build, markup it doesn't recognise,
2288    /// an empty result.
2289    pub fn paste_html(&mut self, html: &str) -> bool {
2290        match html::parse_fragment(html, self.format) {
2291            Some(source) => {
2292                self.paste(&source);
2293                true
2294            }
2295            None => false,
2296        }
2297    }
2298
2299    /// Does the selection live *inside* a single top-level block?
2300    ///
2301    /// The question [`selection_html`](Self::selection_html) needs and the
2302    /// fragment can't answer: `**bold**` renders as `<p><strong>bold</strong></p>`
2303    /// whether the user selected one word of a sentence or a whole paragraph, and
2304    /// only the document knows which. Selecting a word and pasting into Docs
2305    /// should extend the line you paste into; selecting the paragraph should make
2306    /// a paragraph. So a selection strictly within one block is inline (its `<p>`
2307    /// is an artifact of standalone parsing), and one that covers a whole block —
2308    /// or spans two — keeps its structure.
2309    ///
2310    /// Reads the block from twig rather than guessing from the bytes:
2311    /// `ancestors_at` is `[doc, block, …inline]`, so index 1 is the top-level
2312    /// block containing an offset, and two ends inside the same one cannot have
2313    /// crossed a block boundary.
2314    fn selection_is_inline(&mut self, start: usize, end: usize) -> bool {
2315        // The last *character*, not `end - 1`: the selection's end is exclusive
2316        // and may sit mid-codepoint's-worth of bytes past the last char.
2317        let Some((off, _)) = self.source[start..end].char_indices().next_back() else {
2318            return false;
2319        };
2320        let (Some(head), Some(tail)) =
2321            (self.top_block_span(start), self.top_block_span(start + off))
2322        else {
2323            return false;
2324        };
2325        head == tail && !(start <= head.start && end >= head.end)
2326    }
2327
2328    /// The byte span of the top-level block containing `offset`, or `None` at an
2329    /// offset that belongs to no block (the blank line between two of them).
2330    fn top_block_span(&mut self, offset: usize) -> Option<std::ops::Range<usize>> {
2331        self.editor
2332            .ancestors_at(offset)
2333            .ok()?
2334            .get(1)
2335            .map(|m| m.span.clone())
2336    }
2337
2338    // ── indentation ──────────────────────────────────────────────────────────
2339
2340    /// One indent level.
2341    ///
2342    /// Two spaces, not the four both frontends type for Tab today, because in a
2343    /// markdown document four columns isn't a width — it's a *meaning*. Four
2344    /// spaces at the head of a line is markdown's indented-code-block marker, so
2345    /// one Tab on a paragraph would reparse it into code and style it as such;
2346    /// two cannot, and the line stays the prose it was. Two is also exactly
2347    /// where a `- ` bullet's content starts, so an indented line lands under its
2348    /// parent item's text instead of beside it — the column a list-aware indent
2349    /// has to hit anyway, which keeps this width from being relitigated later.
2350    const INDENT: &'static str = "  ";
2351
2352    /// Indent the selected lines — or the caret's line, with no selection — by
2353    /// one level (Tab).
2354    pub fn indent(&mut self) {
2355        self.reindent(true);
2356        // Nesting changes an ordered list's numbering (the nested item restarts,
2357        // its old siblings resume) — keep the source markers in step.
2358        self.renumber_here();
2359        // Nesting an empty `-` item under a text line reparses that text as a
2360        // setext heading; swap the dash for a `*` before it can (a no-op unless
2361        // the collapse actually happened).
2362        self.avoid_setext_collapse();
2363    }
2364
2365    /// Take one indent level back off the selected lines, or the caret's line
2366    /// (Shift+Tab). A line with no indentation is left exactly as it is.
2367    ///
2368    /// A line with *less* than a full level gives back what it has rather than
2369    /// refusing: outdent's job is to walk a line left, and real documents — hand
2370    /// written, or reflowed by some other editor — are full of indentation that
2371    /// was never a clean multiple of anything. Refusing there would strand the
2372    /// line at a depth Shift+Tab couldn't undo.
2373    pub fn outdent(&mut self) {
2374        self.reindent(false);
2375        self.renumber_here();
2376    }
2377
2378    /// The body of [`indent`](Self::indent) / [`outdent`](Self::outdent).
2379    ///
2380    /// One splice across the whole line range, never one per line: a Tab is one
2381    /// thing the user did, so it has to be one undo step and one reparse. Per
2382    /// line, twig would reparse the document once per line and leave a stack of
2383    /// steps that Shift+⌘Z walks back one line at a time.
2384    fn reindent(&mut self, add: bool) {
2385        let (sel_start, sel_end) = self.selection().unwrap_or((self.caret, self.caret));
2386        let start = source_line_range(&self.source, sel_start).start;
2387        let end = source_line_range(&self.source, sel_end).end;
2388        let region = self.source[start..end].to_string();
2389        let lines: Vec<&str> = region.split('\n').collect();
2390        // A blank line has no text to move, and padding it would leave nothing
2391        // but trailing whitespace — but Tab on a blank line *is* a request for
2392        // indentation to type into, so the skip only applies where the op has
2393        // other lines to do real work on.
2394        let skip_blank = add && lines.len() > 1;
2395
2396        let mut out = String::with_capacity(region.len() + lines.len() * Self::INDENT.len());
2397        let mut deltas: Vec<isize> = Vec::with_capacity(lines.len());
2398        let mut line_off = start;
2399        for (i, full) in lines.iter().enumerate() {
2400            if i > 0 {
2401                out.push('\n');
2402            }
2403            // A list item moves by having its whole leading prefix *replaced*,
2404            // never by having spaces pushed in front of the line. twig spells
2405            // both prefixes, so the quote markers, the parent's indent and an
2406            // ordered marker's extra column all come out right without leaf
2407            // measuring any of them — and a line that only looks like an item
2408            // (a Djot continuation) reports no marker and is left to the plain
2409            // path, where a Tab is just a Tab.
2410            let marker = self.list_marker_on_line(line_off);
2411            let own = marker
2412                .as_ref()
2413                .map(|m| m.marker_start - m.line_start)
2414                .unwrap_or(0);
2415            let delta = if add {
2416                if skip_blank && full.trim().is_empty() {
2417                    out.push_str(full);
2418                    0
2419                } else if marker.is_some() && self.first_item_of_list(line_off) {
2420                    // The first item of a list has no preceding sibling to nest
2421                    // under, so a Tab here can't spell a sub-list — twig would
2422                    // reparse the shoved-over marker as the same list, only
2423                    // indented, which Shift+Tab then can't cleanly undo. Leave the
2424                    // item where it is, the way every list editor refuses to
2425                    // over-indent a list's first line.
2426                    out.push_str(full);
2427                    0
2428                } else if marker.is_some() {
2429                    // Nesting means standing where a *continuation* of this line
2430                    // would stand: past the parent's marker, inside its content
2431                    // column. That is `continuation_prefix`, less a checkbox.
2432                    let new = self.nesting_prefix_at(line_off);
2433                    let delta = new.len() as isize - own as isize;
2434                    out.push_str(&new);
2435                    out.push_str(&full[own..]);
2436                    delta
2437                } else {
2438                    out.push_str(Self::INDENT);
2439                    out.push_str(full);
2440                    Self::INDENT.len() as isize
2441                }
2442            } else if marker.is_some() {
2443                // Unnesting is the mirror: stand where the parent item's own
2444                // line starts, which drops exactly the level it contributed.
2445                let new = self.outdent_prefix_at(line_off);
2446                let delta = new.len() as isize - own as isize;
2447                out.push_str(&new);
2448                out.push_str(&full[own..]);
2449                delta
2450            } else {
2451                // A plain line gives back the ordinary step.
2452                let strip = outdent_width(full, Self::INDENT.len());
2453                out.push_str(&full[strip..]);
2454                -(strip as isize)
2455            };
2456            deltas.push(delta);
2457            line_off += full.len() + 1;
2458        }
2459        // Nothing to give back. Returning before the splice keeps an outdent at
2460        // column zero from spending an undo step on a document it never changed.
2461        if deltas.iter().all(|d| *d == 0) {
2462            return;
2463        }
2464
2465        // Every line's text keeps its offset *within the line*, so the caret is
2466        // remapped by its column, not by its byte offset — which the prefixes on
2467        // the lines above it have already invalidated.
2468        let remap = |off: usize| -> usize {
2469            let (mut old_ls, mut new_ls) = (start, start);
2470            for (line, delta) in lines.iter().zip(&deltas) {
2471                let old_le = old_ls + line.len();
2472                let new_len = (line.len() as isize + delta) as usize;
2473                if off <= old_le {
2474                    let col = (off - old_ls) as isize;
2475                    return new_ls + ((col + delta).max(0) as usize).min(new_len);
2476                }
2477                old_ls = old_le + 1;
2478                new_ls += new_len + 1;
2479            }
2480            start + out.len()
2481        };
2482        let placed = match self.selection() {
2483            // Keep the rewritten region selected, the way a container toggle
2484            // keeps its own: it leaves a second Tab aimed at the same lines
2485            // rather than at whatever the shifted offsets now happen to cover.
2486            Some(_) => (start + out.len(), Some(start)),
2487            None => (remap(self.caret), None),
2488        };
2489
2490        // A rolled-back splice leaves the old source in place, where every offset
2491        // computed above addresses text that was never written.
2492        if !self.splice(start, end, &out, EditKind::Other) {
2493            return;
2494        }
2495        // `splice` re-anchors to the end of the `Change`, which for a whole-region
2496        // rewrite is the last line's end — nowhere the caret was. Place it, then
2497        // re-record the caret so this is the state redo restores, not the one
2498        // `splice` left behind from the `Change`.
2499        self.caret = placed.0.min(self.source.len());
2500        self.anchor = placed.1;
2501        self.clamp_caret();
2502        self.record_caret();
2503    }
2504
2505    /// The Enter key.
2506    ///
2507    /// In source view it's a literal newline. In WYSIWYG it's **AST-aware**: a
2508    /// bare `\n` is only a markdown soft break (same paragraph), so the block the
2509    /// caret is in decides what actually gets written.
2510    ///
2511    ///   - paragraph            → twig's [`Editor::split_block`], which parts the
2512    ///                            block at the caret and reopens its container
2513    ///   - list item            → likewise: the next item, its indent, quote
2514    ///                            prefix and `[ ]` box all reproduced by twig —
2515    ///                            except an *empty* item, which exits the list
2516    ///   - block quote          → likewise: a new paragraph inside the quote
2517    ///   - heading              → a new *paragraph*, not another heading
2518    ///   - code block           → a literal newline (stay in the block)
2519    ///   - blank line           → a literal newline (one Backspace undoes it)
2520    ///   - [`LineFlow::Preserve`] → a single soft break, which renders as a
2521    ///                            visible line
2522    ///
2523    /// Where `split_block` is used it replaces markup leaf used to spell by hand,
2524    /// and it is better at it: it drops the whitespace the caret was sitting in
2525    /// front of instead of stranding it at the head of the second half, and it
2526    /// knows continuations leaf's marker scan never covered — a checklist item
2527    /// continues as an *unchecked* checklist item rather than a plain bullet.
2528    ///
2529    /// The exceptions above are exceptions because `split_block` is either wrong
2530    /// there or refuses: parting a fence yields two fences with the code split
2531    /// between them, parting a heading yields a second heading where every editor
2532    /// gives a paragraph, and a blank line, an empty item, a setext heading and a
2533    /// table all report an error rather than a split.
2534    pub fn newline(&mut self) {
2535        if self.view == View::Source {
2536            self.insert_raw("\n");
2537            return;
2538        }
2539        // Enter over a selection replaces it with a paragraph break.
2540        if let Some((s, e)) = self.selection() {
2541            self.splice(s, e, "\n\n", EditKind::Other);
2542            return;
2543        }
2544        // A caret resting exactly between an inline mark's content and its own
2545        // closing delimiter (`**bold**` with nothing after it on the line —
2546        // the WYSIWYG caret's natural end-of-line position) must not splice a
2547        // block break there: every path below eventually does via
2548        // `insert_raw`/`self.caret`, and splicing before the hidden closing
2549        // delimiter would strand it alone on the new line.
2550        self.caret = self.skip_trailing_close_delims(self.caret);
2551        // The block the caret is in. `block_offset_for_caret` nudges off a line
2552        // end (where the caret sits at the doc level); on a bare line (e.g. an
2553        // empty list item) fall back to the caret so the enclosing list/quote is
2554        // still visible in the ancestors.
2555        let off = self.block_offset_for_caret().unwrap_or(self.caret);
2556        let kinds: Vec<Kind> = self
2557            .editor
2558            .ancestors_at(off)
2559            .map(|c| c.into_iter().map(|m| m.kind).collect())
2560            .unwrap_or_default();
2561        let has = |k: Kind| kinds.contains(&k);
2562
2563        if has(Kind::CodeBlock) {
2564            self.insert_raw("\n");
2565            return;
2566        }
2567        // An *empty* list item exits the list — the standard double-Enter — which
2568        // `split_block` reports as an error rather than a split (there is no
2569        // content to part), so it stays leaf's. `list_marker_on_line` is itself
2570        // the AST gate — it answers from the tree, so a `- ` that reads as a
2571        // marker byte-for-byte but opens no item (a setext underline, a Djot
2572        // continuation line) never reaches here.
2573        if let Some(marker) = self.list_marker_on_line(self.caret)
2574            && self.item_is_empty(&marker)
2575        {
2576            self.exit_list(&marker);
2577            return;
2578        }
2579        // On an *empty* paragraph line, a lone Enter should add a single blank line,
2580        // not another full paragraph break — so it moves down one line and one
2581        // Backspace undoes it, not two. (`split_block` errors here too.)
2582        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
2583        let line_end = self.source[self.caret..]
2584            .find('\n')
2585            .map_or(self.source.len(), |i| self.caret + i);
2586        if self.source[line_start..line_end].trim().is_empty() {
2587            self.insert_raw("\n");
2588            return;
2589        }
2590        // In `Preserve` flow a soft break is a *visible* line the author means to
2591        // make, so Enter writes a single `\n` and typing continues the same
2592        // paragraph on the next line — the behaviour of an ordinary text editor.
2593        // A second Enter then lands on the blank line above and takes the
2594        // empty-line branch, so double-Enter still promotes to a full paragraph
2595        // break; and Backspace, which deletes a lone `\n` over a soft break,
2596        // undoes a single Enter symmetrically. In `Fold` flow a lone `\n` would
2597        // render as an invisible space, so Enter keeps making the paragraph break
2598        // that actually shows.
2599        //
2600        // Only in running prose. A list or a quote has a continuation of its own
2601        // to write, and a `\n` there is not a soft line but a lost container.
2602        let in_container = has(Kind::ListItem) || has(Kind::TaskListItem) || has(Kind::BlockQuote);
2603        if self.line_flow == LineFlow::Preserve && !in_container {
2604            self.insert_raw("\n");
2605            return;
2606        }
2607        // A heading gets a *paragraph*, never a second heading: Enter at the end
2608        // of a title is how every editor is asked for the body under it, and
2609        // `split_block` would repeat the `#` instead. Whitespace at the split
2610        // point goes with the break rather than opening the new paragraph, which
2611        // is what `split_block` does everywhere else.
2612        if has(Kind::Heading) {
2613            let mut end = self.caret;
2614            while self.source.as_bytes().get(end) == Some(&b' ') {
2615                end += 1;
2616            }
2617            self.splice(self.caret, end, "\n\n", EditKind::Other);
2618            return;
2619        }
2620        self.split_block_here();
2621    }
2622
2623    /// Part the block at the caret with twig's [`Editor::split_block`], leaving
2624    /// the caret in the second half.
2625    ///
2626    /// twig reopens whatever the first half was inside of — the bullet with its
2627    /// indent, the quote's `>`, a checklist item's `[ ]` — which is the whole
2628    /// reason this replaced the markup leaf used to spell from the line's bytes.
2629    /// It renumbers nothing, though: a new item mid-list is written with its
2630    /// neighbour's number, so [`renumber_here`](Self::renumber_here) still runs
2631    /// behind it, folded into the same undo step.
2632    ///
2633    /// Falls back to a plain paragraph break if twig declines, so an unhandled
2634    /// shape still moves the caret down rather than swallowing the keystroke.
2635    fn split_block_here(&mut self) {
2636        // The read-only gate — this door reaches twig without the splice.
2637        if self.read_only {
2638            return;
2639        }
2640        match self.editor.split_block(self.caret) {
2641            Ok(change) => {
2642                self.last_edit_kind = None;
2643                self.refresh();
2644                self.anchor = None;
2645                self.caret = change.new.end;
2646                self.dirty = self.source != self.clean_source;
2647                self.status = None;
2648                self.clamp_caret();
2649                self.record_caret();
2650                // Aimed at the new block's *start*: the caret twig leaves is one
2651                // past the marker it wrote, where there is no list in reach.
2652                self.renumber_at(change.new.start);
2653            }
2654            Err(_) => self.insert_raw("\n\n"),
2655        }
2656    }
2657
2658    /// Whether the item on the marker's line carries no content — the shape
2659    /// double-Enter reads as "I'm done with this list."
2660    fn item_is_empty(&self, line: &ListMarker) -> bool {
2661        let content_start = line.content_start().min(self.source.len());
2662        let line_end = self.source[self.caret..]
2663            .find('\n')
2664            .map(|i| self.caret + i)
2665            .unwrap_or(self.source.len());
2666        self.source[content_start..line_end.max(content_start)]
2667            .trim()
2668            .is_empty()
2669    }
2670
2671    /// Leave the list: replace the empty item's marker with a blank line, so the
2672    /// caret lands in a fresh paragraph below it.
2673    ///
2674    /// Inside a quote the blank line has to stay quoted (a bare one would end the
2675    /// quote), and the caret's new line keeps the `> ` it was already behind —
2676    /// leaving the list without also leaving the quote.
2677    fn exit_list(&mut self, line: &ListMarker) {
2678        let prefix = self.quote_prefix_at(line.marker_start);
2679        let blank = prefix.trim_end();
2680        self.splice(
2681            line.line_start,
2682            self.caret,
2683            &format!("{blank}\n{prefix}"),
2684            EditKind::Other,
2685        );
2686    }
2687
2688    /// What a line continuing the containers at `off` has to open with — the
2689    /// quote markers reproduced, each enclosing item's marker as its width in
2690    /// spaces. Also the column a nested item's marker stands in, which is what
2691    /// makes it Tab's answer.
2692    fn continuation_prefix_at(&mut self, off: usize) -> String {
2693        self.editor
2694            .document()
2695            .and_then(|mut d| d.continuation_prefix(off))
2696            .map(|p| p.text)
2697            .unwrap_or_default()
2698    }
2699
2700    /// The column a *nested list* may open at inside the item at `off` — which
2701    /// is not always where the item's own text continues.
2702    ///
2703    /// twig counts a task item's `[ ] ` box as part of its marker, correctly:
2704    /// it is markup a rich view hides, and the item's own wrapped text does
2705    /// stand past it. But a nested list may only open at the *list* marker's
2706    /// column, and four columns further in is an indented continuation of the
2707    /// paragraph instead — `- [ ] a` + `      - [ ] b` is one item, not two.
2708    /// So the box's own width goes back.
2709    ///
2710    /// The one place leaf still reads a checkbox's spelling. It goes when twig
2711    /// reports the list marker's column apart from the box; `checked` is what
2712    /// says a box is there at all, so only its width is being measured here.
2713    fn nesting_prefix_at(&mut self, off: usize) -> String {
2714        let cont = self.continuation_prefix_at(off);
2715        let Some(item) = self.innermost_list_item(off) else {
2716            return cont;
2717        };
2718        if item.checked.is_none() {
2719            return cont;
2720        }
2721        let box_width = item
2722            .marker_span
2723            .and_then(|m| self.source.get(m))
2724            .and_then(|marker| marker.rfind('[').map(|i| marker.len() - i))
2725            .unwrap_or(0);
2726        // The trailing columns are the ones the item's own marker contributed,
2727        // so trimming from the end leaves any quote prefix standing.
2728        cont[..cont.len().saturating_sub(box_width)].to_string()
2729    }
2730
2731    /// Where the line of the item *containing* the item at `off` begins — the
2732    /// prefix Shift+Tab moves back to, which gives up exactly the level the
2733    /// parent contributed. The quote prefix alone for a top-level item, which
2734    /// has no level left to give.
2735    fn outdent_prefix_at(&mut self, off: usize) -> String {
2736        let items: Vec<usize> = self
2737            .editor
2738            .document()
2739            .and_then(|mut d| d.ancestors_at_caret(off))
2740            .map(|c| {
2741                c.into_iter()
2742                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2743                    .map(|m| m.span.start)
2744                    .collect()
2745            })
2746            .unwrap_or_default();
2747        // The second-innermost item is the parent; its own line's indent is the
2748        // target. `list_marker_on_line` gives that line's prefix directly.
2749        let parent = items.len().checked_sub(2).map(|i| items[i]);
2750        match parent.and_then(|p| self.list_marker_on_line(p)) {
2751            Some(m) => self.source[m.line_start..m.marker_start].to_string(),
2752            None => self.quote_prefix_at(off),
2753        }
2754    }
2755
2756    /// The block-quote prefix in force at `off` — `""` outside a quote, `"> "`
2757    /// inside one, `"> > "` inside two.
2758    ///
2759    /// Assembled from each enclosing quote's own [`FlatNode::marker_span`], so
2760    /// the `>` and the space after it are twig's spelling rather than leaf's.
2761    /// The whole line prefix can't answer this: it also carries the indent of
2762    /// whatever the quote holds, which a blank separator line must *not* repeat.
2763    fn quote_prefix_at(&mut self, off: usize) -> String {
2764        let Ok(chain) = self
2765            .editor
2766            .document()
2767            .and_then(|mut d| d.ancestors_at_caret(off))
2768        else {
2769            return String::new();
2770        };
2771        let quotes: Vec<usize> = chain
2772            .iter()
2773            .filter(|m| m.kind == Kind::BlockQuote)
2774            .map(|m| m.node_id as usize)
2775            .collect();
2776        let Ok(nodes) = self.editor.nodes() else {
2777            return String::new();
2778        };
2779        quotes
2780            .iter()
2781            .filter_map(|id| nodes.get(*id)?.marker_span.clone())
2782            .filter_map(|s| self.source.get(s))
2783            .collect()
2784    }
2785
2786    /// Whether the item at `off` sits inside another one — the test Backspace
2787    /// uses to choose between outdenting and dropping the marker.
2788    ///
2789    /// Counted from the AST rather than from the line's leading whitespace,
2790    /// which is indentation in Markdown and, in Djot, may be nothing at all.
2791    fn item_is_nested(&mut self, off: usize) -> bool {
2792        self.editor
2793            .document()
2794            .and_then(|mut d| d.ancestors_at_caret(off))
2795            .map(|c| {
2796                c.into_iter()
2797                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
2798                    .count()
2799                    > 1
2800            })
2801            .unwrap_or(false)
2802    }
2803
2804    /// The innermost list item containing `probe`, under twig's **caret**
2805    /// containment rule — a block's end is inside it.
2806    ///
2807    /// Half-open containment can't answer this. An empty item's span is exactly
2808    /// its marker, so the caret sitting after `- ` is one past the end and the
2809    /// item it is plainly in tests as out of reach; that is the shape
2810    /// double-Enter has to recognise to leave the list.
2811    fn innermost_list_item(&mut self, probe: usize) -> Option<FlatNode> {
2812        let chain = self
2813            .editor
2814            .document()
2815            .and_then(|mut d| d.ancestors_at_caret(probe))
2816            .ok()?;
2817        let id = chain
2818            .iter()
2819            .rev()
2820            .find(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)?
2821            .node_id as usize;
2822        self.editor.nodes().ok()?.get(id).cloned()
2823    }
2824
2825    /// The list marker opening `off`'s line, per twig — `None` when that line
2826    /// opens no list item.
2827    ///
2828    /// [`Document::line_prefix`] is the whole hidden run from the line start:
2829    /// `>   1. ` is a quote's marker, an indent, and an item's marker together,
2830    /// and it is `None` on a *continuation* line, which opens nothing. That last
2831    /// case is the one leaf could never get right by reading bytes. `- a\n  - b`
2832    /// is two items in Markdown and one in Djot, where a marker cannot interrupt
2833    /// a paragraph and `  - b` is literal text — identical bytes, and only the
2834    /// parser knows which document it is looking at.
2835    ///
2836    /// The item's own marker is separated out via its
2837    /// [`FlatNode::marker_span`], so `marker_start` splits the prefix into what
2838    /// the containers around it contribute and what the item does.
2839    fn list_marker_on_line(&mut self, off: usize) -> Option<ListMarker> {
2840        let off = off.min(self.source.len());
2841        let prefix = self.editor.document().ok()?.line_prefix(off).ok()??;
2842        // The prefix belongs to a list only when an item's marker closes it —
2843        // a heading's `# ` or a bare quote's `> ` is a prefix too.
2844        let item = self.innermost_list_item(prefix.end.min(self.source.len()))?;
2845        let marker = item.marker_span.clone()?;
2846        if marker.end != prefix.end {
2847            return None;
2848        }
2849        Some(ListMarker {
2850            line_start: prefix.start,
2851            marker_start: marker.start,
2852            text: self.source.get(prefix)?.to_string(),
2853        })
2854    }
2855
2856    /// Whether the list item on `line_start`'s line is the **first item** of its
2857    /// list — the one Tab must not nest, because nesting needs a preceding
2858    /// sibling to become the new parent and a first item has none. `false` for a
2859    /// line that isn't a list item, and for an item with a sibling above it (the
2860    /// one Tab *can* nest). Gated on the AST, not the marker bytes: `- ` reads
2861    /// the same in a setext underline that opens no list at all.
2862    fn first_item_of_list(&mut self, line_start: usize) -> bool {
2863        let Some(marker) = self.list_marker_on_line(line_start) else {
2864            return false;
2865        };
2866        // Probe just inside the marker, where the item's own node is in reach —
2867        // the marker offset itself can resolve to the enclosing list, not the
2868        // `list_item`, whose span starts at the marker.
2869        let probe = marker.content_start().min(self.source.len());
2870        let Some(item) = self.innermost_list_item(probe) else {
2871            return false;
2872        };
2873        let Ok(nodes) = self.editor.nodes() else {
2874            return false;
2875        };
2876        match item.parent {
2877            // First when the parent list opens with this very item.
2878            Some(pid) => nodes
2879                .get(pid.0 as usize)
2880                .is_some_and(|p| p.first_child == Some(item.id)),
2881            // A parentless item is trivially the first (and only) one.
2882            None => true,
2883        }
2884    }
2885
2886    pub fn backspace(&mut self) {
2887        if let Some((s, e)) = self.selection() {
2888            self.splice(s, e, "", EditKind::Other);
2889            return;
2890        }
2891        // WYSIWYG: Backspace at the very start of a list item's content is a
2892        // structural key, not a character delete — it walks the "un-indent, then
2893        // un-list" ladder every list editor gives that keystroke (outdent a
2894        // nested item, strip a top-level one's marker to a paragraph). In source
2895        // view the `- ` is visible text the user is deleting a byte of, so it
2896        // keeps its literal meaning there, like Enter does.
2897        if self.view != View::Source && self.backspace_list_start() {
2898            return;
2899        }
2900        // WYSIWYG: and the same at the start of a heading's content — the `# `
2901        // there is markup the rich view hides, not text the user typed.
2902        if self.view != View::Source && self.backspace_heading_start() {
2903            return;
2904        }
2905        // WYSIWYG: and at the start of a block whose presentation is spelled
2906        // as hidden markup before it — djot's `{.center}` line, Markdown's
2907        // `<div class="center">` — Backspace takes that markup, the way it
2908        // takes a heading's `#`, rather than a byte out of it.
2909        if self.view != View::Source && self.backspace_attributed_block_start() {
2910            return;
2911        }
2912        // WYSIWYG: at a block picture's stops, a byte-at-a-time delete would take
2913        // the markup apart under a caret that cannot see it — see
2914        // `delete_around_block_media`.
2915        if self.view != View::Source && self.delete_around_block_media(false) {
2916            return;
2917        }
2918        // WYSIWYG: Backspace at a table's trailing stop steps back into its last
2919        // cell rather than taking the byte behind the caret — the row's closing
2920        // `|`, which the rich view never drew, so the key would have looked like
2921        // it did nothing. The stop before is the last cell's end.
2922        if self.view != View::Source && self.backspace_at_table_end() {
2923            return;
2924        }
2925        // WYSIWYG: at the start of a block's content, the byte behind the caret
2926        // is a block boundary, and Backspace over one is a join — twig's, so
2927        // that what a join is in each format is not this file's to know. After
2928        // the picture and table cases, which are block starts with their own
2929        // answers.
2930        if self.view != View::Source && self.backspace_joins_block() {
2931            return;
2932        }
2933        // WYSIWYG: Backspace on a *blank line* deletes back to the previous caret
2934        // stop, not a single newline. On a line with no text of its own, the byte
2935        // before the caret is a `\n` that spells part of a block boundary — the gap
2936        // between two blocks, drawn but never a caret home. Removing just it strands
2937        // the caret in that gap and leaves an odd blank line the eye reads as one
2938        // separator but the caret can't land on: the "extra newline" left behind
2939        // after leaving a list (Enter, Enter) or a paragraph and pressing Backspace.
2940        // Deleting to the previous stop instead collapses the whole break at once,
2941        // landing the caret at the end of the block above. Two blank lines in a row
2942        // are one stop apart, so this still removes exactly one — the lone-Enter /
2943        // lone-Backspace symmetry the empty-line case is built on is untouched.
2944        if self.view != View::Source
2945            && self.caret > self.caret_floor()
2946            && self.caret_on_blank_line()
2947            && let Some(stop) = self.vmap.stop_before(self.caret)
2948        {
2949            let stop = stop.max(self.caret_floor());
2950            if stop < self.caret {
2951                if self.source[stop..self.caret].trim().is_empty() {
2952                    self.splice(stop, self.caret, "", EditKind::Delete);
2953                } else {
2954                    // Hidden markup stands between the stop and the caret — a
2955                    // `</div>`, a comment, a link reference definition — and
2956                    // collapsing to the stop would delete it. Take the blank
2957                    // line alone, with the newline that opened it, and land
2958                    // the caret where the collapse would have.
2959                    self.delete_blank_line_to(stop);
2960                }
2961                return;
2962            }
2963        }
2964        if self.caret > self.caret_floor() {
2965            // An in-cell `<br>` draws as one newline glyph, so Backspace over it
2966            // takes the whole tag — a single-byte step would leave a broken `<br`
2967            // showing in the cell. Rich view only (source view edits the literal).
2968            if self.view != View::Source
2969                && let Some((start, end)) = self.cell_break_at(BreakEdge::Backward)
2970            {
2971                let start = start.max(self.caret_floor());
2972                if start < end {
2973                    self.splice(start, end, "", EditKind::Delete);
2974                    return;
2975                }
2976            }
2977            // Aim the delete at the character the writer can *see* behind the
2978            // caret, never at a delimiter the rich view drew nothing for. Two
2979            // steps, and either can apply: from the far side of a run's closing
2980            // `**` step back into the run (the caret is drawn at the end of its
2981            // word), and at the start of a run's text step out past its opening
2982            // `**` to the character in front of it, leaving the run standing.
2983            // Without them a plain Backspace unspells the phrase it is editing
2984            // and leaves a literal asterisk on screen.
2985            let end = if self.view == View::Source {
2986                self.caret
2987            } else {
2988                let inside = self.step_inside_close_delims(self.caret);
2989                // An attributed span with no text — `<span …></span>` as the
2990                // file was written — is hidden markup around nothing, and a
2991                // byte-step here would take its `>`. Backspace takes the span
2992                // whole, with the character before it: the character the key
2993                // looks aimed at, since the span draws nothing.
2994                if let Some(span) = self.run_span_of_content(inside..inside) {
2995                    let from = if self.source[..span.start].ends_with('\n') {
2996                        span.start
2997                    } else {
2998                        prev_boundary(&self.source, span.start)
2999                    };
3000                    let from = from.max(self.caret_floor());
3001                    self.splice(from, span.end, "", EditKind::Delete);
3002                    return;
3003                }
3004                self.skip_leading_open_delims(inside)
3005                    .max(self.caret_floor())
3006            };
3007            // Never delete back across the floor — that would eat hidden
3008            // frontmatter the WYSIWYG caret can't even see.
3009            let mut prev = prev_boundary(&self.source, end).max(self.caret_floor());
3010            // Take a hidden escape backslash with the char it escapes: the rich
3011            // view draws `\*` as a single `*`, so Backspace over it must delete
3012            // both bytes, never strand the `\` as a lone visible backslash (the
3013            // mirror of the Hidden-mode typing that wrote the escape). Source view
3014            // shows the `\`, so there it is an ordinary character.
3015            if self.view != View::Source
3016                && prev > self.caret_floor()
3017                && self.is_hidden_escape(prev - 1)
3018            {
3019                prev -= 1;
3020            }
3021            // The delete that takes the last of a span's text takes the span
3022            // with it, in the same edit: `<span …>i</span>` losing its `i`
3023            // would leave an empty span the map has no stop inside, so the
3024            // caret would draw at the next stop — a line away — until a
3025            // further key removed the span. Landing on the span's start is
3026            // where the letter was.
3027            if self.view != View::Source
3028                && let Some(span) = self.run_span_of_content(prev..end)
3029            {
3030                self.splice(span.start, span.end, "", EditKind::Delete);
3031                return;
3032            }
3033            if prev < end {
3034                self.splice(prev, end, "", EditKind::Delete);
3035            }
3036        }
3037    }
3038
3039    /// Remove the blank line the caret is on — its own newline and the one
3040    /// that ended the line before it — and put the caret on `stop`, the caret
3041    /// stop before it. The [`backspace`](Self::backspace) blank-line rule for a
3042    /// blank line that hidden markup separates from the block above: the
3043    /// navigable blank row after a `</div>` is always one of at least three
3044    /// newlines under the tag (the drawn separators either side of it), so
3045    /// taking two leaves the blank line the tag needs under it.
3046    fn delete_blank_line_to(&mut self, stop: usize) {
3047        let caret = self.caret;
3048        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
3049        let line_end = self.source[caret..]
3050            .find('\n')
3051            .map_or(self.source.len(), |i| caret + i);
3052        let from = line_start.saturating_sub(1).max(stop);
3053        let to = (line_end + 1).min(self.source.len());
3054        self.splice(from, to, "", EditKind::Delete);
3055        self.caret = stop;
3056        self.anchor = None;
3057        self.goal_col = None;
3058        self.record_caret();
3059    }
3060
3061    /// Move the caret to the stop before it and consume the key — what
3062    /// Backspace does where the byte behind the caret is hidden markup it
3063    /// has no structural answer for, rather than take that markup apart.
3064    fn step_back_to_stop(&mut self) {
3065        // The map answers about offsets, so it has to be this revision's — see
3066        // `open_paragraph_at_block_edge`.
3067        self.rebuild_map();
3068        if let Some(off) = self
3069            .vmap
3070            .stop_before(self.caret)
3071            .filter(|&o| o >= self.caret_floor())
3072        {
3073            self.caret = off;
3074            self.anchor = None;
3075            self.goal_col = None;
3076        }
3077    }
3078
3079    /// Backspace's presentation behaviour: with the caret exactly at the start
3080    /// of a block's content, and that block's attributes spelled as hidden
3081    /// markup before it, strip the attributes. The peer of
3082    /// [`backspace_heading_start`](Self::backspace_heading_start), and the same
3083    /// reasoning: the `{.center}` line above a djot block and the
3084    /// `<div class="center">` around a Markdown one are what the byte behind
3085    /// the caret belongs to, and the rich view draws neither. The ordinary
3086    /// delete took the newline out of `{.center}\nhello` and left
3087    /// `{.center}hello` — the attribute line fused onto the text as prose —
3088    /// and out of `<div …>\n\nhello` it took the blank line the div needs.
3089    ///
3090    /// The whole attribute set goes, the way the whole `#` marker does — the
3091    /// press is over the line that spells it, not over one key of it — and
3092    /// twig's `set_block_attrs` with an empty list is the edit: it removes the
3093    /// djot line and unwraps the Markdown div. Where the block is the first of
3094    /// several in a div, twig has no sole child to unwrap and answers with a
3095    /// no-op, so the caret steps back to the stop before instead, as it does
3096    /// at a table's end. A later child of the div has an ordinary paragraph
3097    /// above it and is not this rule's.
3098    ///
3099    /// Returns whether it acted; `false` leaves Backspace its character delete.
3100    fn backspace_attributed_block_start(&mut self) -> bool {
3101        if !matches!(self.format, Format::Markdown | Format::Djot) {
3102            return false;
3103        }
3104        let caret = self.caret;
3105        let nodes = self.nodes();
3106        let Some(block) = nodes
3107            .iter()
3108            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3109            .find(|n| n.content_span.as_ref().map_or(n.span.start, |c| c.start) == caret)
3110        else {
3111            return false;
3112        };
3113        match self.format {
3114            Format::Djot => {
3115                // twig records where the `{…}` block was written, so this is
3116                // the parser's own answer and not a scan for a `{` above the
3117                // block; `None` (a synthesized or merged set) is not a line
3118                // the caret is standing after.
3119                let spelled = self
3120                    .editor
3121                    .document()
3122                    .ok()
3123                    .and_then(|mut d| d.attrs_span(block.id).ok().flatten())
3124                    .is_some_and(|s| s.end <= caret);
3125                if !spelled {
3126                    return false;
3127                }
3128            }
3129            _ => {
3130                let Some(div) = block
3131                    .parent
3132                    .and_then(|p| nodes.iter().find(|n| n.id == p))
3133                    .filter(|p| wysiwyg::element_tag(p) == Some("div"))
3134                else {
3135                    return false;
3136                };
3137                let mut kids = nodes.iter().filter(|n| n.parent == Some(div.id));
3138                if kids.clone().any(|k| k.span.start < block.span.start) {
3139                    return false;
3140                }
3141                if kids.nth(1).is_some() {
3142                    self.step_back_to_stop();
3143                    return true;
3144                }
3145            }
3146        }
3147        self.write_block_attrs("block attributes", Vec::new());
3148        true
3149    }
3150
3151    /// Backspace at the start of a block's content: join the block into the
3152    /// block before it, as one gesture — twig's `join_blocks`, the inverse of
3153    /// the split Enter makes, spelled the format's way. Two paragraphs join
3154    /// on a soft break; a paragraph under a marker heading joins onto the
3155    /// heading's line; a paragraph after a Markdown `<div>` moves inside it,
3156    /// the hidden `</div>` carried past the joined text; HTML's `</p><p>` is
3157    /// taken as one; a quote's or an item's continuation prefix is written.
3158    /// The joined text takes the block above's presentation and containers,
3159    /// which is the rule every editor with a centred paragraph follows.
3160    ///
3161    /// Leaf used to join by deleting the one newline behind the caret, which
3162    /// is the right bytes for two Markdown paragraphs and nothing else: under
3163    /// a heading it left two blocks, in HTML it took the `>` off a tag, and
3164    /// after a div it took the newline under the hidden `</div>`, which drew
3165    /// nothing different and took the tag apart on the next press. What a
3166    /// join is in each format is twig's to know, and now it does.
3167    ///
3168    /// Where twig refuses — the block above is a code block, a table or a
3169    /// rule with no text to join into, or the caret's block would have to
3170    /// leave a div that holds more after it — the caret steps back to the
3171    /// stop before instead, as it does at a table's end: the key moves the
3172    /// caret and takes no markup apart. Where nothing precedes the block, or
3173    /// the format cannot join at all, Backspace keeps its character delete.
3174    ///
3175    /// Returns whether it acted.
3176    fn backspace_joins_block(&mut self) -> bool {
3177        let caret = self.caret;
3178        if caret <= self.caret_floor() {
3179            return false;
3180        }
3181        let Some(text) = self.text_block_opening_at(caret) else {
3182            return false;
3183        };
3184        match self.join_blocks(caret) {
3185            Ok(change) => {
3186                // The caret keeps its place at the start of the text it stood
3187                // on, wherever the join put that text — after a soft break,
3188                // a space, or a quote's prefix. Found by the bytes, as
3189                // `block_content_in` finds a re-spelled block.
3190                let region = &self.source[change.new.clone()];
3191                let at = region
3192                    .find(&text)
3193                    .map_or(change.new.start, |i| change.new.start + i);
3194                self.land_after_join(at);
3195                true
3196            }
3197            Err(twig::Error::NotEditable) => {
3198                self.step_back_to_stop();
3199                true
3200            }
3201            Err(twig::Error::NotFound | twig::Error::UnsupportedFormat) => false,
3202            Err(e) => {
3203                self.status = Some(format!("join: {e}"));
3204                true
3205            }
3206        }
3207    }
3208
3209    /// Delete at the end of a block's content: join the block after it into
3210    /// this one — [`backspace_joins_block`](Self::backspace_joins_block)'s
3211    /// mirror, and the same twig gesture aimed at the next block. The caret
3212    /// stays where it was, which is where the joined text now begins after
3213    /// the separator. Where twig refuses, the caret steps forward to the next
3214    /// stop instead; where no block follows, Delete keeps its character
3215    /// delete.
3216    fn delete_forward_joins_block(&mut self) -> bool {
3217        let caret = self.caret;
3218        let at_end = self
3219            .nodes()
3220            .iter()
3221            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3222            .any(|n| n.content_span.as_ref().is_some_and(|c| c.end == caret));
3223        if !at_end {
3224            return false;
3225        }
3226        // The next stop, across a line end, in a block: what Delete at a
3227        // block's end points at. On the same line it is a hidden delimiter's
3228        // far side, which the ordinary delete handles; on a blank line it is
3229        // the empty paragraph the byte delete has always closed.
3230        self.rebuild_map();
3231        let Some(stop) = self.vmap.stop_after(caret) else {
3232            return false;
3233        };
3234        if !self.source[caret..stop].contains('\n') || !self.has_block_at(stop) {
3235            return false;
3236        }
3237        match self.join_blocks(stop) {
3238            Ok(change) => {
3239                self.land_after_join(change.old.start);
3240                true
3241            }
3242            Err(twig::Error::NotEditable | twig::Error::NotFound) => {
3243                self.caret = stop;
3244                self.anchor = None;
3245                self.goal_col = None;
3246                true
3247            }
3248            Err(twig::Error::UnsupportedFormat) => false,
3249            Err(e) => {
3250                self.status = Some(format!("join: {e}"));
3251                true
3252            }
3253        }
3254    }
3255
3256    /// The content bytes of the paragraph or heading whose content opens
3257    /// exactly at `off` — the block a Backspace there is at the start of.
3258    fn text_block_opening_at(&mut self, off: usize) -> Option<String> {
3259        self.nodes()
3260            .into_iter()
3261            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3262            .find_map(|n| {
3263                let c = n.content_span?;
3264                (c.start == off).then(|| self.source[c].to_string())
3265            })
3266    }
3267
3268    /// Hand the block at `offset` to twig's `join_blocks`, with the undo
3269    /// plumbing every structural gesture has; the caret is the caller's to
3270    /// place from the change, via [`land_after_join`](Self::land_after_join).
3271    fn join_blocks(&mut self, offset: usize) -> Result<Change, twig::Error> {
3272        if self.read_only {
3273            return Err(twig::Error::NotEditable);
3274        }
3275        self.record_caret();
3276        let change = self.editor.join_blocks(offset)?;
3277        self.last_edit_kind = None; // structural edit is its own undo step
3278        self.refresh();
3279        Ok(change)
3280    }
3281
3282    /// Finish a join: the caret at `at`, no selection, the map this
3283    /// revision's before the clamp — see `write_block_attrs` for why.
3284    fn land_after_join(&mut self, at: usize) {
3285        self.caret = at;
3286        self.anchor = None;
3287        self.goal_col = None;
3288        self.dirty = self.source != self.clean_source;
3289        self.status = None;
3290        self.rebuild_map();
3291        self.clamp_caret();
3292        self.record_caret();
3293    }
3294
3295    /// Backspace at a table's trailing stop: move onto the stop before it (the
3296    /// last cell's end) and consume the key. `false` anywhere else. See
3297    /// [`VisualMap::table_end_stop`] for why the byte behind the caret there is
3298    /// not one to delete.
3299    fn backspace_at_table_end(&mut self) -> bool {
3300        // The map answers about offsets, so it has to be this revision's — see
3301        // `open_paragraph_at_block_edge`.
3302        self.rebuild_map();
3303        if !self.vmap.table_end_stop(self.caret) {
3304            return false;
3305        }
3306        if let Some(off) = self
3307            .vmap
3308            .stop_before(self.caret)
3309            .filter(|&o| o >= self.caret_floor())
3310        {
3311            self.caret = off;
3312            self.anchor = None;
3313            self.goal_col = None;
3314        }
3315        true
3316    }
3317
3318    /// Whether the caret's own source line holds nothing but whitespace — an
3319    /// empty paragraph, or the blank line a block boundary is spelled with. The
3320    /// test for [`backspace`](Self::backspace)'s stop-wise delete: such a line has
3321    /// no text of its own, so the newline before the caret belongs to the gap
3322    /// between blocks rather than to any word the caret is editing.
3323    fn caret_on_blank_line(&self) -> bool {
3324        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
3325        let line_end = self.source[self.caret..]
3326            .find('\n')
3327            .map_or(self.source.len(), |i| self.caret + i);
3328        self.source[line_start..line_end].trim().is_empty()
3329    }
3330
3331    /// The source span of an in-cell hard break (`<br>`) touching the caret on the
3332    /// `edge` side — the byte range to delete whole. A table row is one source
3333    /// line, so its break is spelled `<br>` yet drawn as a single newline glyph
3334    /// (see `wysiwyg.rs`); a delete over it must take every byte, or a one-byte
3335    /// step strands a broken `<br` in the cell. `Backward` matches a break ending
3336    /// at the caret (Backspace), `Forward` one starting at it (Delete). `None`
3337    /// when no such break is adjacent. Only the in-cell break is spelled `<br>`
3338    /// (an ordinary hard break is `  \n`), so the leading `<` alone tells them
3339    /// apart — no ancestor walk needed. Rich view only; source view shows the
3340    /// literal tag and deletes it a byte at a time.
3341    fn cell_break_at(&mut self, edge: BreakEdge) -> Option<(usize, usize)> {
3342        let caret = self.caret;
3343        let nodes = self.nodes();
3344        let src = self.source.as_bytes();
3345        nodes
3346            .iter()
3347            .find(|n| {
3348                n.kind == Kind::HardBreak
3349                    && n.span.start < n.span.end
3350                    && src.get(n.span.start) == Some(&b'<')
3351                    && match edge {
3352                        BreakEdge::Backward => n.span.end == caret,
3353                        BreakEdge::Forward => n.span.start == caret,
3354                    }
3355            })
3356            .map(|n| (n.span.start, n.span.end))
3357    }
3358
3359    /// Whether the source byte at `off` is a backslash twig consumed as an escape
3360    /// (hidden in the rich view), as against a literal backslash (drawn). A
3361    /// backslash escapes exactly an ASCII-punctuation character (the CommonMark /
3362    /// Djot rule twig follows), so `\` + punctuation is the whole test — no AST
3363    /// round-trip needed.
3364    fn is_hidden_escape(&self, off: usize) -> bool {
3365        let b = self.source.as_bytes();
3366        b.get(off) == Some(&b'\\') && b.get(off + 1).is_some_and(u8::is_ascii_punctuation)
3367    }
3368
3369    /// Backspace's list behaviour: when the caret sits exactly at the start of a
3370    /// list item's content (right after its marker), outdent the item if it's
3371    /// nested, else strip the marker so it becomes a paragraph. Returns whether
3372    /// it acted — `false` leaves Backspace its ordinary character delete.
3373    fn backspace_list_start(&mut self) -> bool {
3374        let Some(marker) = self.list_marker_on_line(self.caret) else {
3375            return false;
3376        };
3377        // Only right after the marker. That the line opens a real item is
3378        // already settled: `list_marker_on_line` answers from the tree.
3379        if self.caret != marker.content_start() {
3380            return false;
3381        }
3382        if self.item_is_nested(marker.marker_start) {
3383            // Nested: give back one level, keeping the marker and carrying the
3384            // caret with it.
3385            self.outdent();
3386        } else {
3387            // Top level: drop the marker, leaving a paragraph, then renumber the
3388            // siblings the removed item was counted among. Only the marker goes —
3389            // a quote prefix in front of it still has a quote to hold up.
3390            self.splice(marker.marker_start, self.caret, "", EditKind::Other);
3391            self.renumber_here();
3392        }
3393        true
3394    }
3395
3396    /// Backspace's heading behaviour: with the caret exactly at the start of an
3397    /// ATX heading's content — right after the `#` marker the rich view hides —
3398    /// strip the marker so the line becomes a paragraph. The peer of
3399    /// [`backspace_list_start`](Self::backspace_list_start)'s ladder, and the same
3400    /// reasoning: hidden block markup is structure, so the keystroke over it is
3401    /// structural.
3402    ///
3403    /// Without this the ordinary delete takes the space out of `# Title` and
3404    /// leaves `#Title`, which is no longer a heading at all — the hash the view
3405    /// had been hiding surfaces as literal text the user has to delete a second
3406    /// time, having never typed it. A closing sequence (`# Title #`, hidden at the
3407    /// other end) goes with the marker for the same reason.
3408    ///
3409    /// Returns whether it acted; `false` leaves Backspace its character delete.
3410    fn backspace_heading_start(&mut self) -> bool {
3411        let caret = self.caret;
3412        // The heading whose content opens exactly at the caret. A bare `#` has no
3413        // content span at all — its content starts (and ends) where the line does.
3414        let Some((span, content_end, marker)) = self.nodes().iter().find_map(|n| {
3415            let (start, end) = match &n.content_span {
3416                Some(c) => (c.start, c.end),
3417                None => (n.span.end, n.span.end),
3418            };
3419            (n.kind == Kind::Heading && start == caret)
3420                .then(|| (n.span.clone(), end, n.marker_span.clone()))
3421        }) else {
3422            return false;
3423        };
3424        // twig reports the marker's own extent, so there is nothing to walk back
3425        // over and no `#` in this file. A setext heading has no marker — its
3426        // content opens the line — so it falls through to the ordinary delete,
3427        // as does anything else sitting at a content start.
3428        // `m.end == caret` is what excludes a setext heading, whose marker is the
3429        // underline *after* the content rather than a prefix before it.
3430        let Some(marker) = marker.filter(|m| m.end == caret) else {
3431            return false;
3432        };
3433        let start = marker.start;
3434        // A closing `#` sequence is hidden too, so it can't be left behind. Only
3435        // when the tail really is one: trailing spaces alone are nothing to strip.
3436        let tail = &self.source[content_end..span.end];
3437        if tail.contains('#') && tail.chars().all(|c| c == '#' || c.is_whitespace()) {
3438            let kept = self.source[caret..content_end].to_string();
3439            self.splice(start, span.end, &kept, EditKind::Other);
3440            // The splice leaves the caret past the text it re-wrote; the caret
3441            // belongs where the content now starts, which is where it already was.
3442            self.caret = start;
3443            self.record_caret();
3444        } else {
3445            self.splice(start, caret, "", EditKind::Other);
3446        }
3447        true
3448    }
3449
3450    pub fn delete_forward(&mut self) {
3451        if let Some((s, e)) = self.selection() {
3452            self.splice(s, e, "", EditKind::Other);
3453        } else if self.caret < self.source.len() {
3454            // The mirror of Backspace's: forward-delete in front of a picture
3455            // would eat the `!` off its markup and leave a link where a photo was.
3456            if self.view != View::Source && self.delete_around_block_media(true) {
3457                return;
3458            }
3459            // And of Backspace's join: at the end of a block's content, Delete
3460            // joins the next block into this one.
3461            if self.view != View::Source && self.delete_forward_joins_block() {
3462                return;
3463            }
3464            // Delete forward over an in-cell `<br>` takes the whole tag, the mirror
3465            // of Backspace's swallow (see `cell_break_at`) — else a byte-step
3466            // strands a broken `<br` in the cell.
3467            if self.view != View::Source
3468                && let Some((start, end)) = self.cell_break_at(BreakEdge::Forward)
3469            {
3470                self.splice(start, end, "", EditKind::Delete);
3471                return;
3472            }
3473            // The mirror of Backspace's two steps: from in front of a run's
3474            // opening `**` step into it, onto the first letter of its text, and
3475            // at the end of a run's text step out past its closing `**` to the
3476            // character beyond. Either way Delete takes the character it looks
3477            // like it is pointing at, and never a delimiter drawn as nothing.
3478            // The caret then settles back inside the run it was standing in —
3479            // see `settle_inside_close_delims`.
3480            let from = if self.view == View::Source {
3481                self.caret
3482            } else {
3483                let inside = self.step_inside_open_delims(self.caret);
3484                // The mirror of Backspace's empty-span rule: an attributed
3485                // span with no text goes whole, with the character after it.
3486                if let Some(span) = self.run_span_of_content(inside..inside) {
3487                    let to = if self.source[span.end..].starts_with('\n') {
3488                        span.end
3489                    } else {
3490                        next_boundary(&self.source, span.end)
3491                    };
3492                    self.splice(span.start, to, "", EditKind::Delete);
3493                    return;
3494                }
3495                self.skip_trailing_close_delims(inside)
3496            };
3497            let next = next_boundary(&self.source, from);
3498            // And of its emptying rule: the span goes with its last letter.
3499            if self.view != View::Source
3500                && let Some(span) = self.run_span_of_content(from..next)
3501            {
3502                self.splice(span.start, span.end, "", EditKind::Delete);
3503                return;
3504            }
3505            if from < next {
3506                self.splice(from, next, "", EditKind::Delete);
3507            }
3508        }
3509    }
3510
3511    /// Delete from the caret back to the start of the previous word (⌥⌫ /
3512    /// Ctrl+⌫). Deletes the selection instead when one is active.
3513    pub fn delete_word_back(&mut self) {
3514        if let Some((s, e)) = self.selection() {
3515            self.splice(s, e, "", EditKind::Other);
3516        } else {
3517            // A word back from just past a picture is a word *of its markup*, and
3518            // a word back from in front of one runs through the paragraph break
3519            // into the prose above — dissolving the picture either way. See
3520            // `delete_around_block_media`.
3521            if self.view != View::Source && self.delete_around_block_media(false) {
3522                return;
3523            }
3524            let start = self.word_left_from(self.caret).max(self.caret_floor());
3525            if start < self.caret {
3526                let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3527                self.splice(s, e, "", EditKind::Delete);
3528            }
3529        }
3530    }
3531
3532    /// Delete from the caret forward to the end of the next word (⌥⌦ /
3533    /// Ctrl+Del). Deletes the selection instead when one is active.
3534    pub fn delete_word_forward(&mut self) {
3535        if let Some((s, e)) = self.selection() {
3536            self.splice(s, e, "", EditKind::Other);
3537        } else {
3538            // The mirror: a word forward from in front of a picture is its markup.
3539            if self.view != View::Source && self.delete_around_block_media(true) {
3540                return;
3541            }
3542            let end = self.word_right_from(self.caret);
3543            if end > self.caret {
3544                let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3545                self.splice(s, e, "", EditKind::Delete);
3546            }
3547        }
3548    }
3549
3550    /// Delete from the caret back to the start of its line (⌘⌫). Deletes the
3551    /// selection instead when one is active, as every other delete here does.
3552    ///
3553    /// The line is the view's own — the one Home and End work on, so in WYSIWYG
3554    /// a soft-wrapped row is a line. It is not Home's *target*, though: Home
3555    /// stops at the first character and this takes the indentation with it, the
3556    /// way Cocoa's `deleteToBeginningOfLine:` does. Stopping at the text would
3557    /// leave an indent behind that nothing can then ask to delete, where a caret
3558    /// left at column 0 is one press of Home away from either.
3559    pub fn delete_to_line_start(&mut self) {
3560        if let Some((s, e)) = self.selection() {
3561            self.splice(s, e, "", EditKind::Other);
3562            return;
3563        }
3564        // Never back across the floor: hidden frontmatter isn't on this line, or
3565        // on any line the WYSIWYG caret can see.
3566        let (start, _) = self.line_span();
3567        let start = start.max(self.caret_floor());
3568        if start < self.caret {
3569            let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
3570            self.splice(s, e, "", EditKind::Delete);
3571        }
3572    }
3573
3574    /// Kill from the caret to the end of its line (^K). Deletes the selection
3575    /// instead when one is active.
3576    ///
3577    /// At the end of the line it does nothing, rather than pulling the line
3578    /// below up into this one. Joining has no meaning to give it in both views
3579    /// at once: a WYSIWYG line ends at a soft wrap as often as at a newline, and
3580    /// there is nothing there to delete, while the newline a *source* line ends
3581    /// with is only half of the blank line that separates two paragraphs —
3582    /// deleting one leaves a soft break, which is not the join it looks like.
3583    /// The views agreeing is worth more than emacs' second press, and Delete is
3584    /// already the key that joins.
3585    pub fn delete_to_line_end(&mut self) {
3586        if let Some((s, e)) = self.selection() {
3587            self.splice(s, e, "", EditKind::Other);
3588            return;
3589        }
3590        let (_, end) = self.line_span();
3591        if end > self.caret {
3592            let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
3593            self.splice(s, e, "", EditKind::Delete);
3594        }
3595    }
3596
3597    /// Grow a WYSIWYG word-delete to swallow any inline node it empties.
3598    ///
3599    /// A glyph-space range covers what the user can see, which for `**bold**` is
3600    /// the word and never the delimiters around it — so deleting the word on its
3601    /// own leaves `a **** c`, markup wrapped around nothing. They asked for the
3602    /// word, and the styling was the word's; the two go together. Only the
3603    /// node's delimiters are taken, and those are hidden here anyway, so nothing
3604    /// visible outside the range is lost.
3605    ///
3606    /// Repeated to a fixed point: emptying `***bold***` empties the emph inside
3607    /// the strong, and only then is the strong empty too.
3608    fn widen_over_emptied_inlines(&mut self, start: usize, end: usize) -> (usize, usize) {
3609        if self.view == View::Source {
3610            return (start, end);
3611        }
3612        let nodes = self.nodes();
3613        let (mut s, mut e) = (start, end);
3614        loop {
3615            let mut grew = false;
3616            for n in nodes.iter().filter(|n| wysiwyg::is_inline(n)) {
3617                let Some(text) = inline_content_span(n, &self.source) else {
3618                    continue;
3619                };
3620                // Some of its text survives, so the node still has a job.
3621                if text.start < s || text.end > e {
3622                    continue;
3623                }
3624                if n.span.start < s || n.span.end > e {
3625                    s = s.min(n.span.start);
3626                    e = e.max(n.span.end);
3627                    grew = true;
3628                }
3629            }
3630            if !grew {
3631                return (s, e);
3632            }
3633        }
3634    }
3635
3636    /// One splice of document text, keeping the **mark-edge rule**: an inline
3637    /// mark's content never begins or ends with whitespace. In Markdown and Djot
3638    /// a delimiter standing against a space is not a delimiter at all — `**bold **`
3639    /// is four literal asterisks around a word, and a rich view drawing the
3640    /// document faithfully has no choice but to show them. That is correct
3641    /// rendering of what the file says, and nobody typing a space after a bold
3642    /// word meant to say it.
3643    ///
3644    /// So the space goes *outside* the run instead — `**bold** ` — which is the
3645    /// same document to a reader and a live one to a parser. The caret follows it
3646    /// out and keeps the marks armed (see [`rearm`](Self::rearm)), so the next
3647    /// character rejoins the run (see [`rejoin_run`](Self::rejoin_run)) and the
3648    /// writer sees one unbroken bold phrase, never a flash of raw syntax.
3649    ///
3650    /// Every ordinary edit — typing, deleting, pasting, an IME step — comes
3651    /// through here, so the rule holds however the whitespace arrives at the
3652    /// edge. The repair is decided *after* the plain edit, by asking whether the
3653    /// mark actually died: a code span's backticks aren't whitespace-sensitive
3654    /// (`` `code ` `` is still code), and nothing is re-spelled when nothing broke.
3655    fn splice(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3656        let fix = self.mark_edge_fix(start, end, text);
3657        if !self.splice_exact(start, end, text, kind) {
3658            return false;
3659        }
3660        if let Some(fix) = fix {
3661            self.repair_mark_edges(fix);
3662        }
3663        if text.is_empty() && end > start {
3664            self.settle_inside_close_delims();
3665        }
3666        true
3667    }
3668
3669    /// After a delete, take a caret left standing past a run's closing delimiters
3670    /// back inside the run.
3671    ///
3672    /// A delete leaves the caret where the deleted bytes began, and when those
3673    /// bytes were the last thing after a marked phrase — the space the mark-edge
3674    /// rule pushed out of `**bold** `, say — that spot is the far side of the
3675    /// closing `**`. The rich view has nothing to draw there: the delimiters are
3676    /// hidden, so the caret shows at the end of the word either way, and the two
3677    /// offsets are one place on screen with two different meanings. Typing at the
3678    /// outer one lands past the run, so the writer who backspaced a space out of
3679    /// their bold phrase watches the next character come out plain, and the
3680    /// toolbar button go dark, with the caret never appearing to move.
3681    ///
3682    /// The end of the run's text is the caret's home there — a delete that took
3683    /// away everything after a phrase leaves the caret at the end of that phrase,
3684    /// which is inside it — so it settles onto that
3685    /// ([`step_inside_close_delims`](Self::step_inside_close_delims) does the
3686    /// walk, through every mark closing at the point): the word stays bold, the
3687    /// button stays lit, and the next character carries on the phrase.
3688    ///
3689    /// Rich view only, and only where a mark really closes at the caret — mid-run
3690    /// or in plain prose no span ends there and the caret stays put. The opening
3691    /// edge is left alone on purpose: a caret in front of a run inherits from the
3692    /// text on its left, which is the plain text outside.
3693    fn settle_inside_close_delims(&mut self) {
3694        if self.view != View::Wysiwyg {
3695            return;
3696        }
3697        let at = self.step_inside_close_delims(self.caret);
3698        if at != self.caret {
3699            self.caret = at;
3700            self.clear_pending();
3701            self.record_caret();
3702        }
3703    }
3704
3705    /// The splice exactly as asked, with no mark-edge repair — for the callers
3706    /// that are *writing* the delimiters themselves ([`insert_with_marks`](Self::insert_with_marks)
3707    /// and [`rejoin_run`](Self::rejoin_run)) and place their own offsets around
3708    /// the bytes they inserted.
3709    ///
3710    /// One `edit_range` through twig, then re-anchor the caret from the returned
3711    /// `Change` and refresh the cached source. A reparse-breaking edit (rare for
3712    /// Markdown/Djot) leaves the document untouched and reports.
3713    ///
3714    /// Returns whether the edit landed — for a caller that has offsets of its
3715    /// own to place afterwards, which a rolled-back splice would leave pointing
3716    /// into text that never came to exist.
3717    fn splice_exact(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
3718        // The read-only gate, for every edit at once — see the field.
3719        if self.read_only {
3720            return false;
3721        }
3722        // twig records an undo step for every edit; when this one continues a
3723        // run of the same kind (typing, deleting), tell twig to fold it into the
3724        // step before it so the whole run undoes at once.
3725        let coalesce = kind != EditKind::Other && self.last_edit_kind == Some(kind);
3726        // Hand twig the pre-edit caret before the splice, so the undo step it
3727        // retires carries where the caret was standing.
3728        self.record_caret();
3729        match self.editor.edit_range(start, end, text) {
3730            Ok(change) => {
3731                if coalesce {
3732                    let _ = self.editor.coalesce_last_undo();
3733                }
3734                self.last_edit_kind = Some(kind);
3735                self.refresh();
3736                self.caret = change.new.end;
3737                self.anchor = None;
3738                self.goal_col = None;
3739                self.clear_pending();
3740                self.dirty = self.source != self.clean_source;
3741                self.status = None;
3742                // And the post-edit caret, so a later redo restores it.
3743                self.record_caret();
3744                true
3745            }
3746            // The edit was rolled back, so twig's history did not move and
3747            // neither may ours: pushing here would leave a step with no edit
3748            // under it and shift every later undo onto the wrong caret.
3749            Err(e) => {
3750                self.status = Some(format!("edit: {e}"));
3751                false
3752            }
3753        }
3754    }
3755
3756    /// The re-spelling that would keep the mark-edge rule for the edit
3757    /// `[start, end)` → `text`, or `None` when the edit leaves no whitespace
3758    /// against a delimiter and the plain splice is already right. Computed
3759    /// *before* the edit, while the run's spans and delimiters can still be read
3760    /// off the document; applied afterwards, and only if the mark really died —
3761    /// see [`repair_mark_edges`](Self::repair_mark_edges).
3762    ///
3763    /// Rich view only. Source view is for typing raw markup, where a space put
3764    /// against a `**` is exactly the character it looks like.
3765    fn mark_edge_fix(&mut self, start: usize, end: usize, text: &str) -> Option<MarkEdgeFix> {
3766        if self.view != View::Wysiwyg || start > end || end > self.source.len() {
3767            return None;
3768        }
3769        // Every inline mark standing over the edit, outermost first, with the
3770        // content span that says where its delimiters are.
3771        let chain: Vec<(InlineKind, std::ops::Range<usize>, std::ops::Range<usize>)> = self
3772            .editor
3773            .ancestors_at(start)
3774            .unwrap_or_default()
3775            .into_iter()
3776            .filter_map(|m| {
3777                let kind = inline_kind(&m.kind)?;
3778                let content = m.content_span.clone()?;
3779                Some((kind, m.span.clone(), content))
3780            })
3781            .collect();
3782        // The innermost run whose *content* holds the whole edit: the one whose
3783        // text is being changed, rather than one the edit merely sits under.
3784        let (kind, span, content) = chain
3785            .iter()
3786            .rev()
3787            .find(|(_, _, c)| c.start <= start && end <= c.end)?
3788            .clone();
3789        // What that content becomes. Whitespace at either end of it is what
3790        // would put out the mark.
3791        let body = format!(
3792            "{}{text}{}",
3793            &self.source[content.start..start],
3794            &self.source[end..content.end]
3795        );
3796        let (lead, trail) = if body.trim().is_empty() {
3797            // Nothing but whitespace left: there is no content to mark at all,
3798            // and the delimiters go with it rather than closing on a space.
3799            (body.len(), 0)
3800        } else {
3801            (
3802                body.len() - body.trim_start().len(),
3803                body.len() - body.trim_end().len(),
3804            )
3805        };
3806        // Nothing against a delimiter, and something still between them: the
3807        // plain edit stands. An emptied run is broken just as surely (`**b**`
3808        // with the `b` deleted is the literal `****`) and is re-spelt as the
3809        // nothing it now says.
3810        if lead == 0 && trail == 0 && !body.is_empty() {
3811            return None;
3812        }
3813        // Marks that open or close exactly where this one does — `***both***` is
3814        // two runs sharing an edge — spell their delimiters as one run of bytes,
3815        // so the whitespace has to clear all of them together.
3816        let (mut open_at, mut close_at) = (span.start, span.end);
3817        for _ in 0..chain.len() {
3818            match chain.iter().find(|(_, _, c)| c.start == open_at) {
3819                Some((_, s, _)) => open_at = s.start,
3820                None => break,
3821            }
3822        }
3823        for _ in 0..chain.len() {
3824            match chain.iter().find(|(_, _, c)| c.end == close_at) {
3825                Some((_, s, _)) => close_at = s.end,
3826                None => break,
3827            }
3828        }
3829        let open = &self.source[open_at..content.start];
3830        let close = &self.source[content.end..close_at];
3831        let core = &body[lead..body.len() - trail];
3832        let respelt = if core.is_empty() {
3833            body.clone()
3834        } else {
3835            format!(
3836                "{}{open}{core}{close}{}",
3837                &body[..lead],
3838                &body[body.len() - trail..]
3839            )
3840        };
3841        // The caret sits just past the inserted text within the new content —
3842        // which, when that lands in the whitespace, is now outside the delimiters.
3843        let pos = (start - content.start) + text.len();
3844        let caret = if core.is_empty() || pos <= lead {
3845            open_at + pos
3846        } else if pos >= lead + core.len() {
3847            open_at + lead + open.len() + core.len() + close.len() + (pos - lead - core.len())
3848        } else {
3849            open_at + lead + open.len() + (pos - lead)
3850        };
3851        Some(MarkEdgeFix {
3852            kind,
3853            probe: content.start,
3854            start: open_at,
3855            end: close_at + text.len() - (end - start),
3856            text: respelt,
3857            caret,
3858            // The marks in force here, resolved against any armed sticky delta —
3859            // what the writer is typing in, and so what has to still be true on
3860            // the far side of the delimiter the caret just stepped over.
3861            want: chain
3862                .iter()
3863                .filter(|(_, s, _)| start < s.end)
3864                .map(|(k, _, _)| *k)
3865                .collect::<InlineMarks>()
3866                .xor(self.pending_here()),
3867        })
3868    }
3869
3870    /// Apply a [`MarkEdgeFix`] — but only if the edit it was computed for really
3871    /// did break the mark. Whether whitespace at a delimiter is fatal is the
3872    /// format's business, not leaf's: `**bold **` is no longer strong, while
3873    /// `` `code ` `` is still perfectly good verbatim, and Djot's braced spellings
3874    /// don't care either. Asking the parser afterwards settles it for every kind
3875    /// and format at once, and costs a re-spelling only where one is due.
3876    ///
3877    /// The repair rides along with the edit that caused it — one undo step puts
3878    /// back what the writer typed, not a delimiter shuffle they never saw.
3879    fn repair_mark_edges(&mut self, fix: MarkEdgeFix) {
3880        if fix.end > self.source.len() {
3881            return;
3882        }
3883        if self.marks_at(fix.probe).iter().any(|(k, _)| *k == fix.kind) {
3884            return; // still a mark: these delimiters don't mind the whitespace
3885        }
3886        let resumed = self.last_edit_kind;
3887        if !self.splice_exact(fix.start, fix.end, &fix.text, EditKind::Other) {
3888            return;
3889        }
3890        let _ = self.editor.coalesce_last_undo();
3891        // The keystroke owns the undo step, so the run of typing it belongs to
3892        // keeps coalescing over the repair rather than breaking in two here.
3893        self.last_edit_kind = resumed;
3894        self.caret = fix.caret.min(self.source.len());
3895        self.anchor = None;
3896        self.goal_col = None;
3897        self.rearm(fix.want);
3898        self.clamp_caret();
3899        self.record_caret();
3900    }
3901
3902    /// Arm whatever sticky delta reproduces `want` at the caret — the marks the
3903    /// writer is typing in, carried across an edit that moved the caret out of
3904    /// the run holding them. Arms nothing when the caret already stands in
3905    /// exactly those marks, but still remembers the spot, so a further ⌘b starts
3906    /// a clean delta here (see [`toggle`](Self::toggle)).
3907    fn rearm(&mut self, want: InlineMarks) {
3908        let here: InlineMarks = self
3909            .marks_at(self.caret)
3910            .into_iter()
3911            .map(|(k, _)| k)
3912            .collect();
3913        self.pending_marks = want.xor(here);
3914        self.pending_at = Some(self.caret);
3915    }
3916
3917    /// Insert `text` at `at` as a *literal* run via twig's `insert_literal`,
3918    /// which backslash-escapes any character that would otherwise open markup in
3919    /// this format and position (`*` → `\*`, a line-start `#` → `\#`). The mirror
3920    /// of [`splice`](Self::splice) for the Hidden reveal mode's typing path, with
3921    /// the same caret re-anchor, coalescing, and rollback contract. `at` must be
3922    /// a collapsed point — a selection is deleted by the caller first, since
3923    /// `insert_literal` inserts rather than replaces.
3924    fn insert_literal_at(
3925        &mut self,
3926        at: usize,
3927        text: &str,
3928        kind: EditKind,
3929        force_coalesce: bool,
3930    ) -> bool {
3931        // The read-only gate: this door goes to twig directly, not through
3932        // `splice_exact`, so it guards itself — see the field.
3933        if self.read_only {
3934            return false;
3935        }
3936        // `force_coalesce` folds this into the immediately preceding edit (the
3937        // selection-delete of an overwrite) so the pair is one undo step; else it
3938        // coalesces only when it continues a run of the same-kind typing.
3939        let coalesce =
3940            force_coalesce || (kind != EditKind::Other && self.last_edit_kind == Some(kind));
3941        // The mark-edge rule holds for typed text however it is spelled — see
3942        // `splice`. Only an insert twig passed through unchanged can use it,
3943        // since a fix is measured in the bytes that actually land, and an escape
3944        // adds bytes this couldn't have counted.
3945        let fix = self.mark_edge_fix(at, at, text);
3946        self.record_caret();
3947        match self.editor.insert_literal(at, text) {
3948            Ok(change) => {
3949                if coalesce {
3950                    let _ = self.editor.coalesce_last_undo();
3951                }
3952                self.last_edit_kind = Some(kind);
3953                self.refresh();
3954                self.caret = change.new.end;
3955                self.anchor = None;
3956                self.goal_col = None;
3957                self.clear_pending();
3958                self.dirty = self.source != self.clean_source;
3959                self.status = None;
3960                self.record_caret();
3961                if let Some(fix) = fix.filter(|_| change.new.end - change.new.start == text.len()) {
3962                    self.repair_mark_edges(fix);
3963                }
3964                true
3965            }
3966            Err(e) => {
3967                self.status = Some(format!("edit: {e}"));
3968                false
3969            }
3970        }
3971    }
3972
3973    /// After a structural list edit (a new item, a nest/unnest), renumber the
3974    /// ordered list the caret sits in so its source markers run `1, 2, 3, …`
3975    /// again — a raw splice leaves them stale (`1. 2. 2. 3.`). twig does the
3976    /// renumber as its own edit; fold it into the edit that triggered it so the
3977    /// two undo as one, and only when it actually changed the source (a no-op or
3978    /// a caret outside any ordered list must not coalesce the real edit into the
3979    /// step before it).
3980    fn renumber_here(&mut self) {
3981        self.renumber_at(self.caret);
3982    }
3983
3984    /// [`renumber_here`](Self::renumber_here) aimed somewhere other than the
3985    /// caret — for an edit that leaves the caret one past the item it just wrote,
3986    /// where twig resolves no list to renumber.
3987    fn renumber_at(&mut self, off: usize) {
3988        // The read-only gate — this door reaches twig without the splice.
3989        if self.read_only {
3990            return;
3991        }
3992        let before = self.source.clone();
3993        if self.editor.renumber_ordered_lists(off).is_err() {
3994            return; // not inside an ordered list — nothing to renumber
3995        }
3996        self.refresh();
3997        if self.source != before {
3998            let _ = self.editor.coalesce_last_undo();
3999            self.dirty = self.source != self.clean_source;
4000            self.clamp_caret();
4001            self.record_caret();
4002        }
4003    }
4004
4005    /// Repair the one trap a list edit can spring on itself. An *empty* `-`
4006    /// sub-item written directly beneath a text line reparses that text as a
4007    /// setext heading — `- hello\n  - ` is `<h2>hello</h2>`, because a lone `-`
4008    /// is also a setext-H2 underline (twig is right; pandoc agrees). `*` and `+`
4009    /// bullets can't underline anything, so swap the dash for a `*`: the item
4010    /// stays an empty nested bullet, the parent stays prose, and the source
4011    /// round-trips instead of hiding a heading the user never asked for. Folded
4012    /// into the triggering edit's undo step, the way renumbering is.
4013    ///
4014    /// Gated on the collapse having actually happened (the swapped dash was
4015    /// swallowed into a `heading`), so a real setext heading the author wrote —
4016    /// or a `- x` with content, which can't underline anything — is never
4017    /// touched. This has to live in the *edit*, not the renderer: leaving the
4018    /// hazardous bytes on disk and only painting over them would ship a file
4019    /// every other CommonMark tool reads as a heading.
4020    ///
4021    /// This one keeps its own byte scan, and has to: the hazard is precisely
4022    /// that the dash stopped being a list marker, so [`list_marker_on_line`] —
4023    /// which asks twig which lines open an item — reports nothing here. There is
4024    /// no node to ask about. It is also the last Markdown spelling leaf writes on
4025    /// purpose rather than for want of an answer; once twig spells continuations
4026    /// itself, avoiding the trap becomes twig's, and this goes.
4027    ///
4028    /// [`list_marker_on_line`]: Self::list_marker_on_line
4029    fn avoid_setext_collapse(&mut self) {
4030        let caret = self.caret.min(self.source.len());
4031        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
4032        let bytes = self.source.as_bytes();
4033        let mut dash = line_start;
4034        while matches!(bytes.get(dash), Some(b' ' | b'\t')) {
4035            dash += 1;
4036        }
4037        // A dash bullet is the only marker that doubles as a setext underline.
4038        if bytes.get(dash) != Some(&b'-') {
4039            return;
4040        }
4041        // Only an *empty* item is a bare underline; `- x` carries content and
4042        // can't fold the line above into a heading.
4043        let line_end = self.source[dash..]
4044            .find('\n')
4045            .map_or(self.source.len(), |i| dash + i);
4046        if !self.source[dash + 1..line_end].trim().is_empty() {
4047            return;
4048        }
4049        // The tell: that dash was swallowed into a `heading`. A properly nested
4050        // empty item sits under a `list_item`, with no heading in reach. Probe
4051        // the dash byte itself (well inside the heading), not the caret, whose
4052        // end-of-line offset can fall on the half-open span boundary.
4053        let collapsed = self
4054            .editor
4055            .ancestors_at(dash)
4056            .map(|c| c.into_iter().any(|m| m.kind == Kind::Heading))
4057            .unwrap_or(false);
4058        if !collapsed {
4059            return;
4060        }
4061        let caret = self.caret;
4062        if self.splice(dash, dash + 1, "*", EditKind::Other) {
4063            // Same width, so the caret keeps its column; fold into the edit that
4064            // triggered this so Tab stays one undo step.
4065            let _ = self.editor.coalesce_last_undo();
4066            self.caret = caret.min(self.source.len());
4067            self.clamp_caret();
4068            self.record_caret();
4069        }
4070    }
4071
4072    fn snapshot(&self) -> CaretState {
4073        CaretState {
4074            caret: self.caret,
4075            anchor: self.anchor,
4076        }
4077    }
4078
4079    /// Hand twig the current caret and selection as the blob for the live
4080    /// document state. Called before an edit — so the step twig retires records
4081    /// where the caret was, and undo can restore it — and again once the op has
4082    /// placed the caret, so redo restores where the edit left it.
4083    ///
4084    /// This is the whole of leaf's undo-caret bookkeeping now. twig carries the
4085    /// caret through its own history, so coalescing falls out for free (folding
4086    /// two twig steps into one drops the intermediate blob, keeping the run's
4087    /// first) and the parallel stacks that had to march in lockstep — and could
4088    /// silently drift out of it — are gone.
4089    fn record_caret(&mut self) {
4090        let _ = self.editor.set_caret_blob(&self.snapshot().to_blob());
4091    }
4092
4093    /// Toggle an inline mark over the selection (Bold / Italic / Code / …). Keeps
4094    /// the toggled region selected so a second press cleanly reverses it.
4095    pub fn toggle(&mut self, kind: InlineKind) {
4096        // The read-only gate — this door reaches twig without the splice.
4097        if self.read_only {
4098            return;
4099        }
4100        // Ahead of the no-selection branch below: arming a mark for text not yet
4101        // typed is a promise `insert` cannot keep in a format with no delimiters
4102        // to spell it with. Per *kind*, not per format — Markdown spells five
4103        // of the eight marks (highlight among them, under the `highlight`
4104        // extension leaf parses with), djot all eight, HTML seven.
4105        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleInline(kind)) {
4106            return;
4107        }
4108        let Some((s, e)) = self.selection() else {
4109            // No selection: arm the mark for the next text typed here, the way a
4110            // word processor does. `⌘b`, type, `⌘b` again toggles bold on and off
4111            // in the flow of typing without ever selecting anything — the delta
4112            // is realised onto the freshly typed text by `insert`. A fresh caret
4113            // position starts the delta over from the marks actually in force.
4114            if self.pending_at != Some(self.caret) {
4115                self.pending_marks = InlineMarks::empty();
4116                self.pending_at = Some(self.caret);
4117            }
4118            self.pending_marks.flip(kind);
4119            self.status = None;
4120            return;
4121        };
4122        // Whitespace at the edge of a selection is not part of what was chosen —
4123        // a double-click takes the space after the word with it — and a mark
4124        // cannot close against one anyway: `**word **` is four literal asterisks
4125        // (the mark-edge rule, see `splice`). Mark the words, leave the spaces.
4126        let picked = &self.source[s..e];
4127        let (s, e) = (
4128            s + (picked.len() - picked.trim_start().len()),
4129            e - (picked.len() - picked.trim_end().len()),
4130        );
4131        if s >= e {
4132            self.status = Some(format!("{kind:?}: nothing selected to mark"));
4133            return;
4134        }
4135        // Styling a selection is a one-shot act, not a sticky mode.
4136        self.clear_pending();
4137        self.record_caret();
4138        match self.editor.toggle_inline(s, e, kind) {
4139            Ok(change) => {
4140                self.last_edit_kind = None; // structural edit is its own undo step
4141                self.refresh();
4142                self.anchor = Some(change.new.start);
4143                self.caret = change.new.end;
4144                self.dirty = self.source != self.clean_source;
4145                self.status = None;
4146                self.record_caret();
4147            }
4148            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
4149        }
4150    }
4151
4152    /// Whether the caret stands in a highlight — what a frontend asks to enable
4153    /// or disable its highlight-colour controls, the way
4154    /// [`caret_in_table`](Self::caret_in_table) gates the grid ones.
4155    ///
4156    /// A fact about the *caret*, and the other half of
4157    /// [`Capabilities::mark_color`], which is the fact about the format. A
4158    /// frontend needs both: djot spells a highlight and no colour for it, so a
4159    /// caret standing in `{=word=}` answers `true` here and still has no palette
4160    /// to offer.
4161    ///
4162    /// The rule is [`active_inline_marks`](Self::active_inline_marks)' rule, so
4163    /// the palette appears exactly where the Highlight button is lit — with one
4164    /// deliberate exception: a mark *armed* at a bare caret and not yet typed
4165    /// into lights the button and answers `false` here, because there is no node
4166    /// to colour until the text exists.
4167    pub fn caret_in_mark(&mut self) -> bool {
4168        self.mark_offset().is_some()
4169    }
4170
4171    /// The offset [`set_mark_color`](Self::set_mark_color) speaks for — the one
4172    /// standing in the highlight the gesture means — or `None` when neither end
4173    /// of what is selected is in one.
4174    ///
4175    /// The caret first, and the selection's *start* after it, because of what
4176    /// [`toggle`](Self::toggle) leaves behind: a fresh `==word==` is selected
4177    /// whole, with the caret at its far edge, one past the closing `==` and so
4178    /// (by `marks_at`' half-open rule) not in the mark at all. Highlight a word
4179    /// and colour it — the two presses a coloured highlight is made of — would
4180    /// otherwise refuse on the second, having just written the highlight the
4181    /// author is pointing at.
4182    fn mark_offset(&mut self) -> Option<usize> {
4183        let in_mark = |d: &mut Self, off: usize| {
4184            d.marks_at(off)
4185                .into_iter()
4186                .any(|(k, _)| k == InlineKind::Mark)
4187                .then_some(off)
4188        };
4189        let caret = self.caret.min(self.source.len());
4190        in_mark(self, caret).or_else(|| {
4191            let start = self.selection()?.0;
4192            in_mark(self, start)
4193        })
4194    }
4195
4196    /// The colour of the highlight at the caret — `None` both when the caret is
4197    /// in no highlight and when the highlight it is in names no colour, which
4198    /// are the same answer to "which swatch is lit".
4199    ///
4200    /// The innermost mark, by span, for the same reason
4201    /// [`current_heading_level`](Self::current_heading_level) walks the tree:
4202    /// what the caret is *in* is the deepest node containing it. A `data-color`
4203    /// naming a colour this build has no variant for reads as `None` — the
4204    /// renderer already draws that as a plain highlight rather than guessing,
4205    /// and the toolbar agrees with the renderer.
4206    pub fn mark_color_at_caret(&mut self) -> Option<MarkColor> {
4207        let at = self.mark_offset()?;
4208        self.mark_color_at(at)
4209    }
4210
4211    /// [`mark_color_at_caret`](Self::mark_color_at_caret) at a given offset —
4212    /// the innermost `mark` covering it, and the colour it names.
4213    fn mark_color_at(&mut self, off: usize) -> Option<MarkColor> {
4214        self.nodes()
4215            .into_iter()
4216            .filter(|n| n.kind == Kind::Mark)
4217            .filter(|n| n.span.start <= off && off < n.span.end)
4218            .min_by_key(|n| n.span.end - n.span.start)
4219            .and_then(|n| MarkColor::from_attrs(&n.attrs))
4220    }
4221
4222    /// Colour the highlight at the caret, or clear its colour with `None` — the
4223    /// palette behind a toolbar's Highlight button.
4224    ///
4225    /// Markdown only, and the one gesture whose availability is a fact about the
4226    /// *parse extensions* rather than about the format alone: the colour is
4227    /// spelled `==🔴 text==`, an emoji twig reads back out of the content and
4228    /// records as the mark's `data-color`, and only an editor parsing with
4229    /// `highlight_colors` (which [`parse_extensions`] turns on for every leaf
4230    /// document) reads it back that way. Djot spells the highlight and no colour
4231    /// for it, so this refuses there — see [`Capabilities::mark_color`].
4232    ///
4233    /// **A colour is a property of a highlight that already exists.** There is
4234    /// no "highlight this in red" here, because that is two splices and would be
4235    /// two undo steps under one press; a frontend that wants it calls
4236    /// [`toggle`](Self::toggle) with [`InlineKind::Mark`] first, which is the
4237    /// order the two buttons already sit in. With no highlight at the caret this
4238    /// says so in the status line and writes nothing.
4239    ///
4240    /// The caret keeps its place in the *text*: the splice is entirely in the
4241    /// prefix between the opening `==` and the first word, so an offset past it
4242    /// rides the emoji's width, and one standing on the prefix itself lands
4243    /// where the prefix now ends.
4244    pub fn set_mark_color(&mut self, color: Option<MarkColor>) {
4245        // The read-only gate — this door reaches twig without the splice.
4246        if self.read_only {
4247            return;
4248        }
4249        if self.refuse_unsupported("highlight colour", Gesture::SetMarkColor) {
4250            return;
4251        }
4252        let Some(at) = self.mark_offset() else {
4253            self.status = Some("highlight colour: no highlight at the caret".into());
4254            return;
4255        };
4256        // Clearing a colour a highlight hasn't got is twig's one *successful*
4257        // no-op, and the `Change` it hands back then describes whatever edit came
4258        // before it — a stale span that would drag the caret somewhere it never
4259        // was. Answer it here, where the question is cheap, rather than trusting
4260        // a change that isn't one.
4261        if color.is_none() && self.mark_color_at(at).is_none() {
4262            self.status = None;
4263            return;
4264        }
4265        self.record_caret();
4266        match self.editor.set_mark_color(at, color.map(twig_mark_color)) {
4267            Ok(change) => {
4268                // Re-anchored from the offsets as they were, *before* `refresh`
4269                // sees the new bytes: the caret it clamps is one standing inside
4270                // a prefix that didn't exist a moment ago, and walking it back to
4271                // a char boundary of the emoji loses the place this is restoring.
4272                let caret = reanchor(self.caret, &change);
4273                let anchor = self.anchor.map(|a| reanchor(a, &change));
4274                self.last_edit_kind = None; // structural edit is its own undo step
4275                self.refresh();
4276                self.caret = caret;
4277                self.anchor = anchor;
4278                self.dirty = self.source != self.clean_source;
4279                self.status = None;
4280                self.clamp_caret();
4281                self.record_caret();
4282            }
4283            Err(e) => self.status = Some(format!("highlight colour: {e}")),
4284        }
4285    }
4286
4287    /// One press of a colour swatch: colour the highlight at the caret, or —
4288    /// over a selection that isn't highlighted yet — highlight it and colour it,
4289    /// as **one** undo step.
4290    ///
4291    /// [`set_mark_color`](Self::set_mark_color) is the exact gesture and stays
4292    /// one splice; this is the compound every toolbar actually presses, and it
4293    /// lives here rather than in each frontend because the rule it encodes —
4294    /// what a swatch means when there is no highlight under it yet — is one
4295    /// answer, not one per frontend. The two splices are folded into a single
4296    /// history step, so the press that made a red highlight is taken back by a
4297    /// single undo rather than leaving an uncoloured one behind.
4298    ///
4299    /// `None` clears the colour, and over an unhighlighted selection means
4300    /// simply "highlight this" — the same thing the Highlight button does.
4301    /// A bare caret in no highlight is left alone with a status line, because
4302    /// [`toggle`](Self::toggle) there arms a mark for text not yet typed and a
4303    /// colour cannot be armed with it.
4304    pub fn highlight(&mut self, color: Option<MarkColor>) {
4305        if self.caret_in_mark() || self.selection().is_none() {
4306            self.set_mark_color(color);
4307            return;
4308        }
4309        self.toggle(InlineKind::Mark);
4310        // The format may not spell a highlight at all (`toggle` said so), and
4311        // there is nothing to colour if it doesn't.
4312        if self.status.is_some() {
4313            return;
4314        }
4315        let before = self.revision;
4316        self.set_mark_color(color);
4317        // Only fold when the colour really spliced. `highlight(None)` over a
4318        // fresh highlight is a no-op by design, and coalescing there would eat
4319        // the *previous* edit into the toggle instead.
4320        if self.revision != before {
4321            let _ = self.editor.coalesce_last_undo();
4322        }
4323    }
4324
4325    // ── the presentation vocabulary ─────────────────────────────────────────
4326    //
4327    // Six gestures and five queries over twig's two attribute ops. Each gesture
4328    // edits **one key and keeps the rest**: it reads the node's attributes,
4329    // removes its own key (and, for alignment, its own tokens out of `class`),
4330    // adds the new value or nothing, and passes the list back whole — twig's
4331    // contract is replace-not-merge, so the read is the caller's job. A
4332    // paragraph that came in as `class="lead center" id="intro"
4333    // data-line-height="1.5"` and is right-aligned goes out as `class="lead
4334    // right" id="intro" data-line-height="1.5"`. Nothing leaf did not write is
4335    // touched, which is what lets a document from elsewhere pass through the
4336    // editor unharmed.
4337    //
4338    // Clearing is the same gesture with `None`: the key goes, and an empty list
4339    // at the end unwraps the span or the Markdown div, which twig does.
4340
4341    /// Set — or with `None` clear — the alignment of the block the caret is in.
4342    ///
4343    /// A block property, so the gesture is `set_block_attrs` on the caret's
4344    /// block **whatever is selected**: a line is a block's, and "centre this"
4345    /// with three words selected means the paragraph, not the words. The
4346    /// vocabulary is [`Align`], written as `class` tokens; other tokens on the
4347    /// same `class` are kept.
4348    ///
4349    /// In Markdown the attributes live on a `<div>` around the block — twig has
4350    /// no paragraph attribute syntax to write — and this reads them back off
4351    /// that div when the block is its sole child, so a second press rewrites
4352    /// the div rather than nesting a second one.
4353    pub fn set_alignment(&mut self, align: Option<Align>) {
4354        let attrs = self.block_attrs_at_caret();
4355        if align.is_none()
4356            && self.refuse_clear_from_div("alignment", &attrs, |a| Align::from_attrs(a).is_some())
4357        {
4358            return;
4359        }
4360        let attrs = with_class_token(
4361            &attrs,
4362            |t| Align::from_token(t).is_some(),
4363            align.map(Align::name),
4364        );
4365        self.write_block_attrs("alignment", attrs);
4366    }
4367
4368    /// Set — or with `None` clear — the line spacing of the block the caret is
4369    /// in. [`set_alignment`](Self::set_alignment)'s peer in every respect but
4370    /// the key: [`LineSpacing`] under `data-line-height`.
4371    pub fn set_line_spacing(&mut self, spacing: Option<LineSpacing>) {
4372        let attrs = self.block_attrs_at_caret();
4373        if spacing.is_none()
4374            && self.refuse_clear_from_div("line spacing", &attrs, |a| {
4375                LineSpacing::from_attrs(a).is_some()
4376            })
4377        {
4378            return;
4379        }
4380        let attrs = with_attr(&attrs, "data-line-height", spacing.map(LineSpacing::name));
4381        self.write_block_attrs("line spacing", attrs);
4382    }
4383
4384    /// Set — or with `None` clear — the size of the selected run, or of the
4385    /// caret's whole block when nothing is selected.
4386    ///
4387    /// Size, face and colour are the *run's*, and the block's when no run is
4388    /// chosen. With a selection the gesture is `wrap_range_attrs`, which wraps
4389    /// the range in an attributed span or re-styles the span it already lies in
4390    /// (never nesting a second, and unwrapping it when the last key goes). With
4391    /// no selection it is `set_block_attrs` on the caret's block, so that "make
4392    /// this paragraph larger" is a click with the caret in it rather than a
4393    /// select-all first.
4394    ///
4395    /// The walker reads the key at both levels with the nearer winning, so a
4396    /// span's `data-size` inside a block carrying its own applies to the span.
4397    pub fn set_font_size(&mut self, size: Option<SizeStep>) {
4398        self.set_run_attr("size", "data-size", size.map(SizeStep::name));
4399    }
4400
4401    /// Set — or with `None` clear — the face of the selected run, or of the
4402    /// caret's whole block. [`set_font_size`](Self::set_font_size)'s peer, with
4403    /// [`FontFamily`] under `data-font`.
4404    pub fn set_font_family(&mut self, font: Option<FontFamily>) {
4405        self.set_run_attr("font", "data-font", font.map(FontFamily::name));
4406    }
4407
4408    /// Set — or with `None` clear — the *text* colour of the selected run, or of
4409    /// the caret's whole block. [`set_font_size`](Self::set_font_size)'s peer,
4410    /// with [`MarkColor`] under `data-color`.
4411    ///
4412    /// The same key and the same seven names [`set_mark_color`](Self::set_mark_color)
4413    /// writes, and a different thing: that one colours a highlight's
4414    /// *background* and rides the `mark` node twig owns the spelling of, this
4415    /// one colours the letters and rides an attributed span. The two never
4416    /// collide, because a `mark` is a `mark` and a span is a span — and they
4417    /// share a vocabulary on purpose, so that a frontend with a red for a
4418    /// highlight has a red for text and both are *that* red.
4419    pub fn set_text_color(&mut self, color: Option<MarkColor>) {
4420        self.set_run_attr("text colour", "data-color", color.map(MarkColor::name));
4421    }
4422
4423    /// Insert a page break at the caret — `::page-break`, a leaf directive with
4424    /// no label and no attributes, which twig spells in every format that names
4425    /// a leaf container (Markdown under the `directives` extension
4426    /// [`parse_extensions`] turns on, and djot, where it is an empty `:::
4427    /// page-break` fence).
4428    ///
4429    /// Placed exactly as [`insert_thematic_break`](Self::insert_thematic_break)
4430    /// places a rule, and for the same reason: a directive is a block, so twig
4431    /// alone has nowhere to put one mid-paragraph and lands it after the
4432    /// caret's whole block. A bare paragraph is therefore parted at the caret
4433    /// first and the break aimed at the *first* half. See that method for the
4434    /// whole of the rule, including why a code block, a list item, a table and
4435    /// a setext heading are left unsplit.
4436    ///
4437    /// The frontends that paginate read the row's
4438    /// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) and open a page there;
4439    /// the ones that do not draw the `⧉ page-break` placeholder every leaf
4440    /// directive gets.
4441    pub fn insert_page_break(&mut self) {
4442        if self.read_only || self.refuse_unsupported("page break", Gesture::InsertDirective) {
4443            return;
4444        }
4445        self.caret = self.skip_trailing_close_delims(self.caret);
4446        // A selection is replaced by the break, as a rule replaces one.
4447        if let Some((s, e)) = self.selection() {
4448            self.splice(s, e, "", EditKind::Other);
4449        }
4450        self.anchor = None;
4451        self.record_caret();
4452        let at = self.caret;
4453        if self.caret_parts_bare_paragraph() {
4454            // A failure here is not fatal: the break still lands after the
4455            // block, which is what this call was trying to improve on.
4456            let _ = self.editor.split_block(at);
4457        }
4458        match self.editor.insert_directive(at, PAGE_BREAK, None, &[]) {
4459            Ok(change) => {
4460                self.last_edit_kind = None;
4461                self.refresh();
4462                self.anchor = None;
4463                self.caret = change.new.end;
4464                self.dirty = self.source != self.clean_source;
4465                self.status = None;
4466                self.clamp_caret();
4467                self.record_caret();
4468            }
4469            Err(e) => self.status = Some(format!("page break: {e}")),
4470        }
4471    }
4472
4473    /// The alignment in force at the caret, or `None` for the theme's default —
4474    /// which swatch of an alignment control is lit.
4475    ///
4476    /// Read off the nearest node that names one: the block the caret is in, and
4477    /// the `div`s around it after that. [`mark_color_at_caret`](Self::mark_color_at_caret)'s
4478    /// shape, one property along.
4479    pub fn alignment_at_caret(&mut self) -> Option<Align> {
4480        self.presentation_chain()
4481            .iter()
4482            .find_map(|attrs| Align::from_attrs(attrs))
4483    }
4484
4485    /// The line spacing in force at the caret, or `None` for the theme's own.
4486    /// [`alignment_at_caret`](Self::alignment_at_caret)'s peer.
4487    pub fn line_spacing_at_caret(&mut self) -> Option<LineSpacing> {
4488        self.presentation_chain()
4489            .iter()
4490            .find_map(|attrs| LineSpacing::from_attrs(attrs))
4491    }
4492
4493    /// The size in force at the caret, or `None` for the theme's own — the
4494    /// entry a size menu shows ticked.
4495    ///
4496    /// Run-level, so the chain starts one node deeper: the attributed span the
4497    /// caret stands in, then its block, then the `div`s around it. The nearest
4498    /// wins, which is the rule the walker draws by.
4499    pub fn font_size_at_caret(&mut self) -> Option<SizeStep> {
4500        self.presentation_chain()
4501            .iter()
4502            .find_map(|attrs| SizeStep::from_attrs(attrs))
4503    }
4504
4505    /// The face in force at the caret, or `None` for the theme's body face.
4506    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer.
4507    pub fn font_family_at_caret(&mut self) -> Option<FontFamily> {
4508        self.presentation_chain()
4509            .iter()
4510            .find_map(|attrs| FontFamily::from_attrs(attrs))
4511    }
4512
4513    /// The *text* colour in force at the caret, or `None` for the theme's.
4514    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer, and not
4515    /// [`mark_color_at_caret`](Self::mark_color_at_caret) — that one reads a
4516    /// highlight's background off a `mark`, and a `mark` is never in this chain.
4517    pub fn text_color_at_caret(&mut self) -> Option<MarkColor> {
4518        self.presentation_chain()
4519            .iter()
4520            .find_map(|attrs| MarkColor::from_attrs(attrs))
4521    }
4522
4523    /// The selection-or-caret half of the three run-level gestures: a span over
4524    /// a real selection, the caret's block over none.
4525    fn set_run_attr(&mut self, what: &str, key: &str, value: Option<&str>) {
4526        match self.selection() {
4527            Some((start, end)) => {
4528                let attrs = with_attr(&self.run_attrs_over(start, end), key, value);
4529                self.write_run_attrs(what, start, end, attrs);
4530            }
4531            None => {
4532                let own = self.block_attrs_at_caret();
4533                if value.is_none()
4534                    && self.refuse_clear_from_div(what, &own, |a| a.iter().any(|(k, _)| k == key))
4535                {
4536                    return;
4537                }
4538                let attrs = with_attr(&own, key, value);
4539                self.write_block_attrs(what, attrs);
4540            }
4541        }
4542    }
4543
4544    /// A clear this gesture cannot carry out, said out loud instead of written:
4545    /// the node it rewrites — the caret's block, or the `<div>` around it that
4546    /// [`block_attrs_at_caret`](Self::block_attrs_at_caret) folds to in Markdown
4547    /// — does not name the property at all, and a `div` further out does.
4548    ///
4549    /// Handing twig the block's attributes with the key already absent changes
4550    /// no byte, and the query goes on answering `Some` off the div: the menu
4551    /// entry the author pressed stays unticked, and nothing says why. Twig's
4552    /// `set_block_attrs` reaches one node, so leaf cannot clear a key it did not
4553    /// write on a node it is not rewriting — the honest answer is the status
4554    /// line, in the voice the other refusals use.
4555    ///
4556    /// `names` is the property's own reading of an attribute list, because
4557    /// alignment lives in a `class` token rather than a key of its own. Spans
4558    /// are skipped: one inside the block is not what a *block* gesture writes
4559    /// either, but neither is it "the div around the block", and the run-level
4560    /// gestures reach it through a selection.
4561    fn refuse_clear_from_div(
4562        &mut self,
4563        what: &str,
4564        own: &Attrs,
4565        names: impl Fn(&Attrs) -> bool,
4566    ) -> bool {
4567        if names(own) {
4568            return false;
4569        }
4570        let caret = self.caret.min(self.source.len());
4571        if !self
4572            .attr_chain_at(caret)
4573            .iter()
4574            .any(|(span, attrs)| !span && names(attrs))
4575        {
4576            return false;
4577        }
4578        self.status = Some(format!("{what}: set on the div around the block"));
4579        true
4580    }
4581
4582    /// Hand `attrs` to twig as the caret's block's whole attribute set, with the
4583    /// status, undo and caret plumbing [`set_mark_color`](Self::set_mark_color)
4584    /// has.
4585    ///
4586    /// **The caret keeps its place in the text, not its byte offset.** How a
4587    /// format spells a block's attributes is markup written *around* the block
4588    /// — djot's `{…}` line above it, a `<div …>` and two blank lines in front of
4589    /// it in Markdown, a longer opening tag in HTML — and every one of those
4590    /// grows or shrinks above the author's own bytes. Where twig's change
4591    /// rewrites the block whole (Markdown's div is spliced as one region, block
4592    /// included) the plain arithmetic of [`reanchor`] has nothing to shift by
4593    /// and parks the caret at the end of the splice, past the closing `</div>`:
4594    /// the caret is then in no block at all, so a second press of the same menu
4595    /// answers "no block at the caret" and the toolbar's queries read nothing.
4596    /// [`reanchor_in_block`] is what carries it across instead — the block's
4597    /// content span before and after, which is the one thing the respelling
4598    /// leaves alone.
4599    ///
4600    /// Read *before* the splice and applied *after* `refresh`, because both
4601    /// halves of that mapping are facts about a tree twig is between: the
4602    /// block's old bytes are gone once the edit lands, and its new ones are not
4603    /// in `self.source` until the refresh puts them there.
4604    fn write_block_attrs(&mut self, what: &str, attrs: Attrs) {
4605        if self.read_only || self.refuse_unsupported(what, Gesture::SetBlockAttrs) {
4606            return;
4607        }
4608        // A blank line has no block to carry an attribute, and twig answers
4609        // `NotFound` there — say so in leaf's own words instead.
4610        let Some(at) = self.block_offset_for_caret() else {
4611            self.status = Some(format!("{what}: no block at the caret"));
4612            return;
4613        };
4614        self.record_caret();
4615        let pairs = attr_pairs(&attrs);
4616        let was = self.block_content_at(at);
4617        let text = was.clone().map(|s| self.source[s].to_string());
4618        match self.editor.set_block_attrs(at, &pairs) {
4619            Ok(change) => {
4620                let (caret, anchor) = (self.caret, self.anchor);
4621                self.last_edit_kind = None; // structural edit is its own undo step
4622                self.refresh();
4623                let now = self.block_content_in(&change.new, text.as_deref());
4624                // A block the two halves cannot both name — a code block, a
4625                // caret in a list's marker — takes the plain arithmetic, which
4626                // is what it had before.
4627                let block = was.as_ref().zip(now.as_ref());
4628                self.caret = reanchor_in_block(caret, &change, block);
4629                self.anchor = anchor.map(|a| reanchor_in_block(a, &change, block));
4630                self.dirty = self.source != self.clean_source;
4631                self.status = None;
4632                // The clamp reads the caret floor off the map, and this edit
4633                // can move the floor: taking the `{…}` line off a djot
4634                // document's first block moves the first rendered offset to 0,
4635                // and a floor read from the old map stood the caret past the
4636                // block's text. So the map is this revision's before the clamp
4637                // — see `open_paragraph_at_block_edge`.
4638                self.rebuild_map();
4639                self.clamp_caret();
4640                self.record_caret();
4641            }
4642            Err(e) => self.status = Some(format!("{what}: {e}")),
4643        }
4644    }
4645
4646    /// The content span of the innermost paragraph or heading covering `off` —
4647    /// the author's own bytes, without the `# ` or the `<p>` that spells the
4648    /// block around them.
4649    ///
4650    /// The same two kinds [`block_attrs_at_caret`](Self::block_attrs_at_caret)
4651    /// reads, so that what a gesture re-anchors by is the block it wrote to.
4652    fn block_content_at(&mut self, off: usize) -> Option<Range<usize>> {
4653        self.nodes()
4654            .into_iter()
4655            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
4656            .filter(|n| n.span.start <= off && off <= n.span.end)
4657            .min_by_key(|n| n.span.end - n.span.start)
4658            .map(|n| n.content_span.unwrap_or(n.span))
4659    }
4660
4661    /// [`block_content_at`](Self::block_content_at)'s other half: the content
4662    /// span of the block `region` holds now, found by the bytes it held before.
4663    ///
4664    /// Matched on the text rather than taken as the first block in the region,
4665    /// because a rewritten region is markup and all — `<div class="center">`
4666    /// carries words of its own — and because the block this gesture moved is
4667    /// the one whose content the respelling did not touch. `None` where the
4668    /// region holds no block at all, which is djot's every case: the `{…}` line
4669    /// is spliced above the block and the block itself never moves through the
4670    /// change at all, only past it.
4671    fn block_content_in(
4672        &mut self,
4673        region: &Range<usize>,
4674        text: Option<&str>,
4675    ) -> Option<Range<usize>> {
4676        let text = text?;
4677        let spans: Vec<Range<usize>> = self
4678            .nodes()
4679            .into_iter()
4680            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
4681            .filter(|n| region.start <= n.span.start && n.span.end <= region.end)
4682            .map(|n| n.content_span.unwrap_or(n.span))
4683            .collect();
4684        spans
4685            .into_iter()
4686            .find(|s| self.source.get(s.clone()) == Some(text))
4687    }
4688
4689    /// Hand `attrs` to twig as the attribute set of the span over `[start,
4690    /// end)` — wrapping one, or re-styling the one the range already lies in,
4691    /// or unwrapping it when `attrs` is empty.
4692    ///
4693    /// What the splice leaves selected is the span's **content** — the author's
4694    /// words — and not the whole of `change.new`, which is markup and all:
4695    /// `[big]{data-size="large"}` in djot, `<span …>big</span>` in Markdown. A
4696    /// selection reaching past the node's own span lies in no span at all, so a
4697    /// second press of the menu would nest a fresh one instead of re-styling
4698    /// the one just written.
4699    fn write_run_attrs(&mut self, what: &str, start: usize, end: usize, attrs: Attrs) {
4700        if self.read_only || self.refuse_unsupported(what, Gesture::WrapRangeAttrs) {
4701            return;
4702        }
4703        self.record_caret();
4704        let pairs = attr_pairs(&attrs);
4705        match self.editor.wrap_range_attrs(start, end, &pairs) {
4706            Ok(change) => {
4707                self.last_edit_kind = None;
4708                self.refresh();
4709                let content = self.span_content_in(&change.new);
4710                self.anchor = Some(content.start);
4711                self.caret = content.end;
4712                self.dirty = self.source != self.clean_source;
4713                self.status = None;
4714                self.clamp_caret();
4715                self.record_caret();
4716            }
4717            Err(e) => self.status = Some(format!("{what}: {e}")),
4718        }
4719    }
4720
4721    /// The content range of the attributed span `spliced` now holds — the
4722    /// outermost one inside it, since that is the one just written — or
4723    /// `spliced` itself where the splice left no span, which is what an unwrap
4724    /// leaves behind.
4725    fn span_content_in(&mut self, spliced: &Range<usize>) -> Range<usize> {
4726        self.nodes()
4727            .into_iter()
4728            .filter(wysiwyg::is_run_span)
4729            .filter(|n| spliced.start <= n.span.start && n.span.end <= spliced.end)
4730            .max_by_key(|n| n.span.end - n.span.start)
4731            .and_then(|n| n.content_span)
4732            .unwrap_or_else(|| spliced.clone())
4733    }
4734
4735    /// The attribute set `set_block_attrs` is about to **replace** at the caret
4736    /// — which is the block's own, except in Markdown, where twig writes a
4737    /// block's attributes onto a `<div>` around it and rewrites that div when
4738    /// the block is its sole child. Reading the paragraph there would hand back
4739    /// an empty list and quietly drop everything the div said.
4740    ///
4741    /// Empty when the caret is in no block at all, which is the same list a
4742    /// block carrying no attributes gives — and the right one either way, since
4743    /// the gesture then refuses on its own.
4744    fn block_attrs_at_caret(&mut self) -> Attrs {
4745        let Some(off) = self.block_offset_for_caret() else {
4746            return Vec::new();
4747        };
4748        let nodes = self.nodes();
4749        let Some(block) = nodes
4750            .iter()
4751            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
4752            .filter(|n| n.span.start <= off && off <= n.span.end)
4753            .min_by_key(|n| n.span.end - n.span.start)
4754        else {
4755            return Vec::new();
4756        };
4757        if self.format == Format::Markdown
4758            && let Some(parent) = block.parent.and_then(|p| nodes.iter().find(|n| n.id == p))
4759            && wysiwyg::element_tag(parent) == Some("div")
4760            && nodes.iter().filter(|n| n.parent == Some(parent.id)).count() == 1
4761        {
4762            return parent.attrs.clone();
4763        }
4764        block.attrs.clone()
4765    }
4766
4767    /// The attribute set `wrap_range_attrs` is about to **replace** over
4768    /// `[start, end)` — the innermost attributed span the range lies inside,
4769    /// which twig re-styles rather than nesting a second one in. Empty when the
4770    /// range lies in no span, where the gesture mints a fresh one.
4771    fn run_attrs_over(&mut self, start: usize, end: usize) -> Attrs {
4772        self.nodes()
4773            .into_iter()
4774            .filter(wysiwyg::is_run_span)
4775            .filter(|n| n.span.start <= start && end <= n.span.end)
4776            .min_by_key(|n| n.span.end - n.span.start)
4777            .map(|n| n.attrs)
4778            .unwrap_or_default()
4779    }
4780
4781    /// The attribute lists that bear on a presentation query, **nearest first**:
4782    /// the attributed spans the caret stands in (innermost first), then its
4783    /// block, then the `div`s around it. A `find_map` down this is the whole of
4784    /// each query, and the order is the rule the walker draws by.
4785    ///
4786    /// Read at the caret, and at the selection's *start* when the caret stands
4787    /// in no span there. [`write_run_attrs`](Self::write_run_attrs) leaves the
4788    /// caret one past the span it just wrote — `toggle`'s convention — so
4789    /// asking the menu which entry that press just ticked must not answer
4790    /// `None`. Exactly the reason [`mark_offset`](Self::mark_offset) tries both.
4791    fn presentation_chain(&mut self) -> Vec<Attrs> {
4792        let caret = self.caret.min(self.source.len());
4793        let mut chain = self.attr_chain_at(caret);
4794        if !chain.iter().any(|(span, _)| *span)
4795            && let Some((start, _)) = self.selection()
4796        {
4797            let alt = self.attr_chain_at(start);
4798            if alt.iter().any(|(span, _)| *span) {
4799                chain = alt;
4800            }
4801        }
4802        chain.into_iter().map(|(_, attrs)| attrs).collect()
4803    }
4804
4805    /// [`presentation_chain`](Self::presentation_chain) at one offset — every
4806    /// node bearing the vocabulary that covers it, innermost first, each paired
4807    /// with whether it is an attributed span (which is what tells the caller
4808    /// its run-level answer came from a run).
4809    ///
4810    /// Sorted by span length, which *is* the nesting order: a span lies inside
4811    /// its block and a block inside its div, so shortest-first is
4812    /// nearest-first without a second tree walk.
4813    fn attr_chain_at(&mut self, off: usize) -> Vec<(bool, Attrs)> {
4814        let off = off.min(self.source.len());
4815        let mut hits: Vec<(usize, bool, Attrs)> = Vec::new();
4816        for n in self.nodes() {
4817            let span = wysiwyg::is_run_span(&n);
4818            let block = matches!(n.kind, Kind::Para | Kind::Heading);
4819            let div = wysiwyg::element_tag(&n) == Some("div");
4820            if !(span || block || div) {
4821                continue;
4822            }
4823            // A span is half-open, the way a mark is: the offset one past it is
4824            // the text after it. A block and a div claim their end too, so a
4825            // caret resting at the end of a line still reads its paragraph.
4826            let inside = if span {
4827                n.span.start <= off && off < n.span.end
4828            } else {
4829                n.span.start <= off && off <= n.span.end
4830            };
4831            if !inside {
4832                continue;
4833            }
4834            hits.push((n.span.end - n.span.start, span, n.attrs));
4835        }
4836        hits.sort_by_key(|(len, _, _)| *len);
4837        hits.into_iter()
4838            .map(|(_, span, attrs)| (span, attrs))
4839            .collect()
4840    }
4841
4842    /// Convert the block at the caret to a heading level or paragraph.
4843    pub fn set_block(&mut self, kind: BlockKind) {
4844        // The read-only gate — this door reaches twig without the splice.
4845        if self.read_only {
4846            return;
4847        }
4848        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::SetBlock) {
4849            return;
4850        }
4851        self.record_caret();
4852        // A blank line has no node to convert, and twig opens a block there
4853        // rather than declining — so the caret's own offset is the right thing
4854        // to hand it when `block_offset_for_caret` finds nothing.
4855        let offset = self.block_offset_for_caret().unwrap_or(self.caret);
4856        match self.editor.set_block(offset, kind) {
4857            Ok(change) => {
4858                self.last_edit_kind = None;
4859                self.refresh();
4860                // Opening a block on a blank line writes a marker the caret
4861                // belongs *after*; converting an existing one moves nothing.
4862                self.caret = self.caret.max(change.new.end);
4863                self.clamp_caret();
4864                self.anchor = None;
4865                self.dirty = self.source != self.clean_source;
4866                self.status = None;
4867                self.record_caret();
4868            }
4869            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
4870        }
4871    }
4872
4873    /// Whether `off` is inside a text block (paragraph, heading, code block…).
4874    fn has_block_at(&mut self, off: usize) -> bool {
4875        self.editor.ancestors_at(off).ok().is_some_and(|chain| {
4876            chain
4877                .iter()
4878                .any(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
4879        })
4880    }
4881
4882    /// The offset to hand twig's `set_block`: the caret when it is already inside
4883    /// a block, otherwise nudged onto the previous character (a caret at a line
4884    /// end sits at the doc level, outside the block). `None` when the caret is on
4885    /// a blank line — a new paragraph with no block node to convert.
4886    fn block_offset_for_caret(&mut self) -> Option<usize> {
4887        let caret = self.caret.min(self.source.len());
4888        if self.has_block_at(caret) {
4889            return Some(caret);
4890        }
4891        // Nudge to the previous character — but never across a newline: that would
4892        // target the previous block, and a blank line genuinely has no block.
4893        if let Some((i, ch)) = self.source[..caret].char_indices().next_back()
4894            && ch != '\n'
4895            && self.has_block_at(i)
4896        {
4897            return Some(i);
4898        }
4899        None
4900    }
4901
4902    /// The heading level of the text block at the caret, or `None` when that
4903    /// block is not a heading.
4904    pub fn current_heading_level(&mut self) -> Option<u32> {
4905        let caret = self.caret;
4906        self.nodes()
4907            .into_iter()
4908            .filter(|n| n.kind == Kind::Heading)
4909            .find(|n| n.span.start <= caret && caret <= n.span.end)
4910            .and_then(|n| n.level)
4911    }
4912
4913    /// The inline marks in force at the caret (or over the selection) — what a
4914    /// toolbar draws lit, and the block-level [`Doc::current_heading_level`]'s
4915    /// inline counterpart. Cheap enough to call every frame: one twig
4916    /// `ancestors_at` query per caret (two with a selection), each walking root
4917    /// → deepest node at one offset. It never snapshots the tree the way
4918    /// `current_heading_level` does, and the returned set is a `Copy` bitset, so
4919    /// the only allocation is twig's own small ancestor `Vec`.
4920    ///
4921    /// **A selection reports a mark only when the mark covers *all* of it.**
4922    /// That's what every real toolbar means by an active button — Bold lit over
4923    /// a half-bold selection would claim a press turns bold *off*, when
4924    /// [`Doc::toggle`] hands the range to twig and gets the whole thing bolded.
4925    /// Whole-coverage is asked as "is the same mark node standing over both the
4926    /// first and the last character?": inline nodes are contiguous, so one node
4927    /// covering both ends covers every byte between them. Two touching runs
4928    /// (`**a****b**`) are two nodes, and correctly light nothing.
4929    ///
4930    /// At a bare caret a mark is active when the caret stands inside the mark's
4931    /// span — `span.start <= caret < span.end`, delimiters included, which is
4932    /// what makes the boundaries behave. In `a **bold** b` the offsets from the
4933    /// opening `*` (2) through the last byte of the closing `**` (9) are all
4934    /// bold, so the WYSIWYG caret both before `b` and after `d` (the delimiters
4935    /// are hidden, and those offsets are 4 and 8) reports bold — matching where
4936    /// typing would actually land inside the marked run. The offset one past the
4937    /// mark (10) is the text after it and reports nothing, at the end of the
4938    /// buffer exactly as in the middle.
4939    pub fn active_inline_marks(&mut self) -> InlineMarks {
4940        let Some((start, end)) = self.selection() else {
4941            // The marks actually in force at the caret, flipped by any armed
4942            // sticky delta — so `⌘b` at a bare caret lights the Bold button
4943            // immediately, before a single character is typed.
4944            let base: InlineMarks = self
4945                .marks_at(self.caret)
4946                .into_iter()
4947                .map(|(k, _)| k)
4948                .collect();
4949            return base.xor(self.pending_here());
4950        };
4951        // The selection's *last character*, not its exclusive end: `end` is the
4952        // offset one past the selection, which for a selection ending exactly at
4953        // a mark's close is already outside it (`[4,10)` of `a **bold** b` is
4954        // entirely bold, but offset 10 is the space after).
4955        let last = prev_boundary(&self.source, end);
4956        let head = self.marks_at(start);
4957        let tail = self.marks_at(last);
4958        head.into_iter()
4959            .filter(|m| tail.contains(m))
4960            .map(|(k, _)| k)
4961            .collect()
4962    }
4963
4964    /// The inline marks whose span covers `off`, each with the id of the node
4965    /// carrying it — the id is what lets a selection tell one mark node from
4966    /// another of the same kind.
4967    fn marks_at(&mut self, off: usize) -> Vec<(InlineKind, u32)> {
4968        let off = off.min(self.source.len());
4969        self.editor
4970            .ancestors_at(off)
4971            .unwrap_or_default()
4972            .into_iter()
4973            // `span.end` is the offset one *past* the mark, so it isn't in it.
4974            // twig already resolves a boundary to whatever starts there — in
4975            // `**bold** x` offset 8 is the following text, not the strong — but
4976            // when nothing follows, the tie has nobody to break for and the
4977            // chain still ends at the mark. That would make the answer at the
4978            // last offset of the document depend on whether the file happens to
4979            // end in a newline; the rule is `span.start <= off < span.end`, and
4980            // it's the same rule at the end of a buffer as in the middle.
4981            .filter(|m| off < m.span.end)
4982            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.node_id)))
4983            .collect()
4984    }
4985
4986    /// Toggle a heading at the caret: if the block is already this heading level,
4987    /// revert it to a paragraph; otherwise convert it to this heading level.
4988    /// This gives the heading commands the same toggle feel as bold/italic/code —
4989    /// re-applying a heading a line already has turns it back into body text.
4990    pub fn toggle_heading(&mut self, level: u32) {
4991        if self.current_heading_level() == Some(level) {
4992            self.set_block(BlockKind::Paragraph);
4993        } else {
4994            self.set_block(BlockKind::Heading(level));
4995        }
4996    }
4997
4998    /// Toggle a block quote around the selection, or around the block at the
4999    /// caret — the toolbar's Quote button.
5000    pub fn toggle_blockquote(&mut self) {
5001        self.toggle_container(BlockContainerKind::BlockQuote);
5002    }
5003
5004    /// Toggle a numbered (`ordered`) or bulleted list over the selection, or
5005    /// over the block at the caret — one op with the kind as a flag, the way
5006    /// `toggle_heading` takes its level, so a frontend needs no twig type to
5007    /// name the two buttons.
5008    ///
5009    /// Pressing the *other* list's button while in a list converts in place
5010    /// rather than nesting, so the pair reads as one three-state control
5011    /// (bulleted / numbered / neither) rather than two independent wrappers.
5012    pub fn toggle_list(&mut self, ordered: bool) {
5013        self.toggle_container(if ordered {
5014            BlockContainerKind::OrderedList
5015        } else {
5016            BlockContainerKind::BulletList
5017        });
5018    }
5019
5020    // ── Task list items ──────────────────────────────────────────────────────
5021    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
5022    // inline content of the item's first paragraph rather than part of its
5023    // marker, so adding or removing one must leave the item's continuation
5024    // indentation alone, and an item inside a quote is found past the quote
5025    // markers. leaf names the gesture and the offset; the spelling is twig's.
5026
5027    /// Whether the list item at the caret carries a checkbox, and which way it
5028    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
5029    /// item or no item at all. What a toolbar reads to light its checkbox button.
5030    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
5031        self.task_checked_at(self.caret)
5032    }
5033
5034    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
5035    /// offset — what a frontend asks before deciding a click landed on a box.
5036    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
5037        self.innermost_list_item(offset.min(self.source.len()))?
5038            .checked
5039    }
5040
5041    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
5042    /// A no-op with a reported reason when the caret is in no task item — minting
5043    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
5044    pub fn toggle_task_checked(&mut self) {
5045        self.toggle_task_at(self.caret);
5046    }
5047
5048    /// Tick or untick the task item covering `offset` — what a *click* on a
5049    /// rendered checkbox is. Separate from the caret form because a click carries
5050    /// its own offset and must not first move the caret there: ticking a box
5051    /// three paragraphs away should not take the cursor with it.
5052    pub fn toggle_task_at(&mut self, offset: usize) {
5053        // The read-only gate — this door reaches twig without the splice.
5054        if self.read_only {
5055            return;
5056        }
5057        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
5058            return;
5059        }
5060        let offset = offset.min(self.source.len());
5061        self.record_caret();
5062        match self.editor.toggle_task_checked(offset) {
5063            Ok(_) => self.after_task_edit(),
5064            Err(e) => self.status = Some(format!("task: {e}")),
5065        }
5066    }
5067
5068    /// Give the list item at the caret a checkbox, or take its checkbox away —
5069    /// the gesture that converts between a plain bullet and a task. A new box
5070    /// arrives unticked.
5071    pub fn toggle_task_item(&mut self) {
5072        // The read-only gate — this door reaches twig without the splice.
5073        if self.read_only {
5074            return;
5075        }
5076        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
5077            return;
5078        }
5079        let caret = self.caret.min(self.source.len());
5080        self.record_caret();
5081        match self.editor.toggle_task_item(caret) {
5082            Ok(_) => self.after_task_edit(),
5083            Err(e) => self.status = Some(format!("task: {e}")),
5084        }
5085    }
5086
5087    /// Settle after a task gesture. The caret rides its old byte offset and is
5088    /// clamped back in: a box is three or four bytes on the item's first line, so
5089    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
5090    /// real stop either way.
5091    fn after_task_edit(&mut self) {
5092        self.last_edit_kind = None;
5093        self.refresh();
5094        self.anchor = None;
5095        self.dirty = self.source != self.clean_source;
5096        self.status = None;
5097        self.clamp_caret();
5098        self.record_caret();
5099    }
5100
5101    // ── Tables ───────────────────────────────────────────────────────────────
5102    // A table is a grid, and twig edits it as one — add/remove/move a row or
5103    // column, set a column's alignment — re-spelling the whole table in a single
5104    // splice. Every gesture is anchored at the caret's cell. leaf just names the
5105    // gesture and re-reads the result; the whole table's numbering, borders, and
5106    // delimiter are twig's to keep straight.
5107
5108    /// Whether the caret is inside a table — what a frontend asks to enable or
5109    /// disable its table controls.
5110    ///
5111    /// An HTML `<table>` still answers `true`: the caret really is in a table,
5112    /// and the reason the grid controls stay dark there is
5113    /// [`Capabilities::table`], which is a fact about the document's format
5114    /// rather than about the caret. A frontend needs both.
5115    pub fn caret_in_table(&mut self) -> bool {
5116        let caret = self.caret.min(self.source.len());
5117        self.editor
5118            .ancestors_at(caret)
5119            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
5120            .unwrap_or(false)
5121    }
5122
5123    /// One grid op, guarded and settled — the shared body of the seven below.
5124    ///
5125    /// The guard is why this exists rather than seven copies of the same three
5126    /// lines, and it is the one guard leaf cannot delegate to twig. The table
5127    /// editor is the gesture family that consults no `Syntax` table (it spells a
5128    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
5129    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
5130    /// grid as a *pipe table* and reports success, swapping the element out for
5131    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
5132    /// downstream could tell that from a successful edit — the splice is real,
5133    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
5134    /// stopping at the door rather than detecting after the fact. See
5135    /// [`spells_pipe_tables`].
5136    fn table_op(
5137        &mut self,
5138        what: &str,
5139        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
5140    ) {
5141        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
5142            return;
5143        }
5144        self.record_caret();
5145        let at = self.caret;
5146        let r = op(&mut self.editor, at);
5147        self.apply_table(r, what);
5148    }
5149
5150    /// Insert an empty row below (`below`) or above the caret's row.
5151    pub fn table_insert_row(&mut self, below: bool) {
5152        self.table_op("table row", |e, at| e.table_insert_row(at, below));
5153    }
5154
5155    /// Delete the caret's row (not the header, not the last body row).
5156    pub fn table_delete_row(&mut self) {
5157        self.table_op("table row", |e, at| e.table_delete_row(at));
5158    }
5159
5160    /// Insert an empty column right (`right`) or left of the caret's column.
5161    pub fn table_insert_column(&mut self, right: bool) {
5162        self.table_op("table column", |e, at| e.table_insert_column(at, right));
5163    }
5164
5165    /// Delete the caret's column (unless it is the only one).
5166    pub fn table_delete_column(&mut self) {
5167        self.table_op("table column", |e, at| e.table_delete_column(at));
5168    }
5169
5170    /// Set the caret's column to `alignment`.
5171    pub fn table_set_alignment(&mut self, alignment: Alignment) {
5172        self.table_op("table alignment", |e, at| {
5173            e.table_set_alignment(at, alignment)
5174        });
5175    }
5176
5177    /// Move the caret's row one place down (`down`) or up, within the body rows.
5178    pub fn table_move_row(&mut self, down: bool) {
5179        self.table_op("table row", |e, at| e.table_move_row(at, down));
5180    }
5181
5182    /// Move the caret's column one place right (`right`) or left.
5183    pub fn table_move_column(&mut self, right: bool) {
5184        self.table_op("table column", |e, at| e.table_move_column(at, right));
5185    }
5186
5187    /// Settle the caret and document flags after a table op (or report its
5188    /// error). twig re-spells the whole table, so the caret rides its old byte
5189    /// offset and is clamped back into the rebuilt bytes — near enough to where
5190    /// it was, since the op preserves the cells' content and order around it.
5191    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
5192        match result {
5193            Ok(()) => {
5194                self.last_edit_kind = None;
5195                self.refresh();
5196                self.anchor = None;
5197                self.clamp_caret();
5198                self.dirty = self.source != self.clean_source;
5199                self.status = None;
5200                self.record_caret();
5201            }
5202            Err(e) => self.status = Some(format!("{what}: {e}")),
5203        }
5204    }
5205
5206    /// One `toggle_block_container` over the block-level target.
5207    ///
5208    /// leaf says *where*; twig decides everything else — which blocks the range
5209    /// covers, whether that means wrapping, unwrapping, nesting or converting,
5210    /// and how this document's format spells the prefix. The rule that a
5211    /// container only comes off when the range covers every block it holds is
5212    /// what the re-anchoring below is built around.
5213    fn toggle_container(&mut self, kind: BlockContainerKind) {
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(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
5219            return;
5220        }
5221        let selected = self.selection();
5222        // A blank line holds no block, and twig opens an *empty* container on one
5223        // — since 3.2.0; it used to decline the range with `NotFound`, which is
5224        // why this used to lend it a scratch paragraph to wrap. Worth knowing
5225        // here because the line-for-line caret mapping below cannot describe it:
5226        // opening one under a paragraph writes the blank line the format needs
5227        // above the marker too, so the rewritten region has a line the old one
5228        // didn't, and "the same line, the same distance from its end" lands on
5229        // that new blank instead of in the container.
5230        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
5231        // Without a selection the target is the caret's own block, resolved the
5232        // way `set_block` resolves it — a caret at a line end sits at the doc
5233        // level and has to be nudged back onto the block it looks like it's in.
5234        // An empty range is enough: twig widens to the whole lines it touches.
5235        let (start, end) = match selected {
5236            Some(range) => range,
5237            None => {
5238                let off = self.block_offset_for_caret().unwrap_or(self.caret);
5239                (off, off)
5240            }
5241        };
5242        self.record_caret();
5243        match self.editor.toggle_block_container(start, end, kind) {
5244            Ok(change) => {
5245                // Read the caret's place out of the *pre-edit* source, before
5246                // `refresh` swaps that source out from under it.
5247                let place = (selected.is_none() && !opened_empty)
5248                    .then(|| self.caret_line_tail(&change.old));
5249                self.last_edit_kind = None; // structural edit is its own undo step
5250                self.refresh();
5251                match place {
5252                    // Both land the caret at the far end of what twig wrote, and
5253                    // differ only in what they leave selected.
5254                    //
5255                    // From a selection: select what the container now holds, the
5256                    // way `toggle` keeps its marked region selected — and for a
5257                    // stronger reason than symmetry: a container comes *off* only
5258                    // a range covering every block it holds, so a selection left
5259                    // on its old bytes (now short by a prefix per line) would nest
5260                    // on the second press instead of reversing the first.
5261                    //
5262                    // From a blank line: nothing to select, and the end of the
5263                    // region is exactly past the bare `> ` / `- ` twig wrote —
5264                    // the caret standing inside the container that was asked for.
5265                    None => {
5266                        self.anchor = (!opened_empty).then_some(change.new.start);
5267                        self.caret = change.new.end;
5268                    }
5269                    Some(place) => {
5270                        self.anchor = None;
5271                        self.caret = self.line_tail_offset(&change.new, place);
5272                    }
5273                }
5274                self.dirty = self.source != self.clean_source;
5275                self.status = None;
5276                self.clamp_caret();
5277                self.record_caret();
5278            }
5279            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
5280        }
5281    }
5282
5283    /// The caret's place inside the region a container toggle is rewriting, in
5284    /// the only terms the rewrite preserves: which of the region's lines it sits
5285    /// on, and how many bytes of that line lie ahead of it.
5286    ///
5287    /// A container's markup goes in at column 0 and never touches what follows
5288    /// on the line, so that pair survives the edit exactly where a byte offset
5289    /// does not — a caret left on its old offset slides back by one prefix per
5290    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
5291    /// `> ` it just asked for.
5292    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
5293        let caret = self.caret.clamp(old.start, old.end);
5294        let line = self.source[old.start..caret].matches('\n').count();
5295        let end = self.source[caret..old.end]
5296            .find('\n')
5297            .map_or(old.end, |i| caret + i);
5298        (line, end - caret)
5299    }
5300
5301    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
5302    /// region: the offset `tail` bytes back from the end of the region's `line`.
5303    ///
5304    /// Both walks are clamped rather than trusted, because the one op that does
5305    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
5306    /// the items back apart with blank lines between them — and a caret landing
5307    /// on the nearest line of the right item beats one landing out of the region
5308    /// entirely.
5309    fn line_tail_offset(
5310        &self,
5311        new: &std::ops::Range<usize>,
5312        (line, tail): (usize, usize),
5313    ) -> usize {
5314        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
5315        let mut start = 0;
5316        for _ in 0..line {
5317            match region[start..].find('\n') {
5318                Some(i) => start += i + 1,
5319                None => break,
5320            }
5321        }
5322        let end = region[start..]
5323            .find('\n')
5324            .map_or(region.len(), |i| start + i);
5325        new.start + end.saturating_sub(tail).max(start)
5326    }
5327
5328    /// Link the selection to `destination` — the toolbar's Link button. With no
5329    /// selection it acts at the caret, which re-points a link the caret is
5330    /// already standing in (twig replaces an existing link's destination and
5331    /// keeps its text) and otherwise spells a link that has no text of its own:
5332    /// an autolink (`<https://x.dev>`) where the destination is one, and
5333    /// `[destination](destination)` where it isn't.
5334    ///
5335    /// `destination` reaches twig raw. Escaping it is format knowledge and the
5336    /// two formats genuinely disagree — Markdown ends a destination at the first
5337    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
5338    /// itself — so the side holding the document is the side that gets to spell
5339    /// it. A destination twig can't carry at all (one with a newline) comes back
5340    /// as an error rather than a quietly rewritten URL.
5341    pub fn insert_link(&mut self, destination: &str) {
5342        if self.read_only || self.refuse_unsupported("link", Gesture::InsertLink) {
5343            return;
5344        }
5345        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
5346        self.record_caret();
5347        match self.editor.insert_link(start, end, destination) {
5348            Ok(change) => {
5349                self.last_edit_kind = None;
5350                self.refresh();
5351                match self.link_text_span(change.new.start) {
5352                    // A link with text of its own: select it, so typing replaces
5353                    // a `[dest](dest)`'s stand-in label and a second press
5354                    // re-points what the first one linked.
5355                    Some(text) => {
5356                        self.anchor = (text.start != text.end).then_some(text.start);
5357                        self.caret = text.end;
5358                    }
5359                    // An autolink is finished the moment it's written — its text
5360                    // *is* the URL. Leaving it selected would aim the next press
5361                    // at the one shape twig still wraps instead of re-points.
5362                    None => {
5363                        self.anchor = None;
5364                        self.caret = change.new.end;
5365                    }
5366                }
5367                self.dirty = self.source != self.clean_source;
5368                self.status = None;
5369                self.clamp_caret();
5370                self.record_caret();
5371            }
5372            Err(e) => self.status = Some(format!("link: {e}")),
5373        }
5374    }
5375
5376    /// Insert a block-level image at the caret: `![alt](destination)`. Any
5377    /// selection becomes the alt text (so "select a caption, insert image" labels
5378    /// it); with no selection, `alt` is used — empty for none. The caret lands
5379    /// just past the inserted image.
5380    ///
5381    /// Both halves go through twig (`insert_literal` for the alt text,
5382    /// `insert_image` for the image), so neither is spelled here. That used to be a
5383    /// `format!`, and it was wrong the first time an app inserted a real filename:
5384    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
5385    /// not an image at all — and the fix is per-format, since moving into the
5386    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
5387    pub fn insert_image(&mut self, destination: &str, alt: &str) {
5388        if self.read_only || self.refuse_unsupported("image", Gesture::InsertImage) {
5389            return;
5390        }
5391        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
5392        self.record_caret();
5393        // With no selection and an explicit `alt`, the alt text has to exist in the
5394        // document before it can be the image's — and it is raw caller input, so
5395        // it goes in through `insert_literal`, which escapes it for the format
5396        // rather than letting a `]` in someone's caption close the image early.
5397        let (start, end) = if start == end && !alt.is_empty() {
5398            match self.editor.insert_literal(start, alt) {
5399                Ok(change) => (change.new.start, change.new.end),
5400                Err(e) => {
5401                    self.status = Some(format!("image: {e}"));
5402                    return;
5403                }
5404            }
5405        } else {
5406            (start, end)
5407        };
5408        match self.editor.insert_image(start, end, destination) {
5409            Ok(change) => {
5410                self.last_edit_kind = None;
5411                self.refresh();
5412                // Just past the image, nothing selected — where a caret belongs
5413                // after inserting one.
5414                self.anchor = None;
5415                self.caret = change.new.end;
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!("image: {e}")),
5422        }
5423    }
5424
5425    /// Insert a block-level image, video, or audio at the caret. The image case
5426    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
5427    /// HTML elements, which is the only spelling Markdown and Djot have for them:
5428    ///
5429    /// ```text
5430    /// <video src="clip.mp4" controls>alt</video>
5431    /// <audio src="take.mp3" controls>alt</audio>
5432    /// ```
5433    ///
5434    /// HTML rather than a `::video{…}` directive deliberately. A directive means
5435    /// something only to an app that knows the vocabulary, so the document would
5436    /// read as literal punctuation everywhere else; `<video>` is what every other
5437    /// renderer already understands, and what leaf's own reader picks back up
5438    /// through `html_elements` promotion (see [`parse_extensions`]).
5439    ///
5440    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
5441    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
5442    /// `html_elements`. Before that only the multi-line form parsed as a block at
5443    /// all, and this wrote three lines to work around it.
5444    ///
5445    /// `controls` is always written: a player with no transport is a still frame
5446    /// the reader can't do anything with. Any selection becomes the element's
5447    /// fallback text, exactly as it becomes an image's alt.
5448    ///
5449    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
5450    /// applies, and bites harder here: a `"` in `destination` closes the
5451    /// attribute. A frontend taking these from a file picker is fine; one taking
5452    /// them from free text should keep them tame.
5453    ///
5454    /// [`MediaInfo`]: crate::MediaInfo
5455    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
5456        if kind == MediaKind::Image {
5457            return self.insert_image(destination, alt);
5458        }
5459        // Gated on the *image* gesture, not on one of its own — there isn't one,
5460        // since the bytes below are spelled here rather than by twig, and an HTML
5461        // document would in fact parse them. The button is one control with three
5462        // kinds behind it, and two of them working in a format where the third
5463        // cannot is a worse surface than three that agree — especially as
5464        // `insert_image` is the kind anyone reaches for first.
5465        if self.refuse_unsupported("media", Gesture::InsertImage) {
5466            return;
5467        }
5468        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
5469        let alt_text = self
5470            .selected_text()
5471            .map(str::to_string)
5472            .unwrap_or_else(|| alt.to_string());
5473        let tag = match kind {
5474            MediaKind::Audio => "audio",
5475            _ => "video",
5476        };
5477        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
5478        self.edit(start, end, &markup);
5479    }
5480
5481    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
5482    /// button. Spelling and placement are both twig's; leaf used to write `---`
5483    /// itself, which was the Markdown spelling in a djot document too.
5484    ///
5485    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
5486    /// mid-paragraph and lands it after the caret's whole block. To get a rule
5487    /// *at* the caret — the paragraph parted in two around it, which is what a
5488    /// rule button is understood to do — the paragraph is first divided with
5489    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
5490    /// the offset `split_block` returns puts the rule after the *second* half
5491    /// instead, which is a rule in the right document and the wrong place.
5492    ///
5493    /// Only a plain paragraph is split, and only where there is something to
5494    /// part: at the paragraph's end the split has no second half to mint and
5495    /// would write the separator anyway — a blank line and the empty slot Enter
5496    /// leaves for the next paragraph, which the rule then lands above and
5497    /// nothing fills — so there the rule goes straight after the paragraph,
5498    /// which is where the split-and-aim was sending it regardless. At the
5499    /// paragraph's *start* the split is kept, though it parts nothing either:
5500    /// `|para` becomes `\npara` with the caret on the new blank line, and a
5501    /// rule aimed at a blank line is written on it (twig ≥ 3.5.2), which is how
5502    /// "before the paragraph" is said through a gesture that only knows
5503    /// "after" — `---\n\npara`, and `prev\n\n---\n\npara` mid-document. Everywhere
5504    /// else the rule simply lands after the block, which is both twig's own
5505    /// answer and the better one: splitting a fenced code block would leave two
5506    /// fences with a rule between them, and splitting a list item would mint an
5507    /// item nobody asked for on the way to a rule that lands after the list
5508    /// regardless. A table and a setext heading refuse the split outright, so
5509    /// they take the same path by themselves.
5510    pub fn insert_thematic_break(&mut self) {
5511        if self.read_only || self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak)
5512        {
5513            return;
5514        }
5515        self.caret = self.skip_trailing_close_delims(self.caret);
5516        // A selection is replaced by the rule, so collapse it first and let the
5517        // split-and-rule below run from the caret it leaves behind.
5518        if let Some((s, e)) = self.selection() {
5519            self.splice(s, e, "", EditKind::Other);
5520        }
5521        self.anchor = None;
5522        self.record_caret();
5523        let at = self.caret;
5524        if self.caret_parts_bare_paragraph() {
5525            // A failure here is not fatal: the rule still lands after the block,
5526            // which is exactly what this call was trying to improve on.
5527            let _ = self.editor.split_block(at);
5528        }
5529        match self.editor.insert_thematic_break(at) {
5530            Ok(change) => {
5531                self.last_edit_kind = None;
5532                self.refresh();
5533                self.anchor = None;
5534                self.caret = change.new.end;
5535                self.dirty = self.source != self.clean_source;
5536                self.status = None;
5537                self.clamp_caret();
5538                self.record_caret();
5539            }
5540            Err(e) => self.status = Some(format!("thematic break: {e}")),
5541        }
5542    }
5543
5544    /// Insert a fresh table at the caret — the toolbar's Table button. One
5545    /// header row, `rows` empty body rows, `cols` columns, spelled by twig in
5546    /// the document's own dialect and placed the way its thematic break is:
5547    /// after the caret's block, blank-separated. A bare paragraph is parted
5548    /// around the caret first, exactly as
5549    /// [`insert_thematic_break`](Self::insert_thematic_break) parts it, so the
5550    /// table lands *at* the caret rather than after everything the caret's
5551    /// paragraph says.
5552    ///
5553    /// The caret ends in the first header cell, selected the way Tab selects
5554    /// a cell — the natural next act is to type the heading, and Tab then
5555    /// walks the grid. That cell is read back from the rebuilt table map
5556    /// rather than computed from the splice, because twig's blank line and
5557    /// quote prefix put the first bar at an offset only the reparse knows.
5558    ///
5559    /// The shape is the caller's: a menu offers a few, a dialog asks. Zero
5560    /// rows or columns is twig's refusal (a header with nothing under it is
5561    /// what its row delete refuses to leave), reported through `status`.
5562    pub fn insert_table(&mut self, rows: usize, cols: usize) {
5563        if self.read_only || self.refuse_unsupported("table", Gesture::InsertTable) {
5564            return;
5565        }
5566        self.caret = self.skip_trailing_close_delims(self.caret);
5567        if let Some((s, e)) = self.selection() {
5568            self.splice(s, e, "", EditKind::Other);
5569        }
5570        self.anchor = None;
5571        self.record_caret();
5572        let at = self.caret;
5573        if self.caret_parts_bare_paragraph() {
5574            let _ = self.editor.split_block(at);
5575        }
5576        match self.editor.insert_table(at, rows, cols) {
5577            Ok(change) => {
5578                self.last_edit_kind = None;
5579                self.refresh();
5580                self.anchor = None;
5581                self.caret = change.new.end;
5582                self.dirty = self.source != self.clean_source;
5583                self.status = None;
5584                self.clamp_caret();
5585                // Into the first header cell of the table just written: the
5586                // first table whose grid begins inside the splice.
5587                self.rebuild_map();
5588                let first_cell = self
5589                    .vmap
5590                    .tables
5591                    .iter()
5592                    .filter_map(|t| t.grid.first().and_then(|row| row.cells.first()))
5593                    .find(|cell| cell.start >= change.new.start && cell.start < change.new.end)
5594                    .map(|cell| (cell.start, cell.end));
5595                if let Some((start, end)) = first_cell {
5596                    self.select_cell(start, end);
5597                }
5598                self.record_caret();
5599            }
5600            Err(e) => self.status = Some(format!("table: {e}")),
5601        }
5602    }
5603
5604    /// Whether the caret sits in a paragraph and nothing else — no list item, no
5605    /// quote, no fence, no table — with paragraph text still ahead of it. The
5606    /// one shape where parting the block around the caret is unambiguously what
5607    /// a rule button means; see
5608    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
5609    /// container is left to take the rule after itself.
5610    ///
5611    /// The "text ahead" half is what keeps `split_block` from running at the
5612    /// one edge where its output composes badly. At a paragraph's end twig
5613    /// cannot mint the empty second half (no format spells an empty
5614    /// paragraph), so it writes only the separator — a blank line and the
5615    /// slot Enter leaves for the paragraph to come — and a block then aimed at
5616    /// the first half lands above a slot that nothing fills: `para\n` with the
5617    /// caret at 4 came out as `para\n\n* * *\n\n\n`. Trailing whitespace counts
5618    /// as nothing ahead, since the split would shed it as the second half's
5619    /// leading indent and leave the same slot. Which end of the newline a
5620    /// paragraph's span stops at differs between the formats (Markdown before
5621    /// it, djot after), which is why this reads the remaining bytes rather
5622    /// than comparing offsets. The paragraph's
5623    /// start is deliberately not the same case — see
5624    /// [`insert_thematic_break`](Self::insert_thematic_break) for why that
5625    /// split is kept.
5626    fn caret_parts_bare_paragraph(&mut self) -> bool {
5627        let caret = self.caret.min(self.source.len());
5628        let Ok(chain) = self.editor.ancestors_at(caret) else {
5629            return false;
5630        };
5631        let mut para_end = None;
5632        for m in chain {
5633            match m.kind {
5634                Kind::Para => para_end = Some(m.span.end.min(self.source.len())),
5635                Kind::ListItem
5636                | Kind::TaskListItem
5637                | Kind::BlockQuote
5638                | Kind::CodeBlock
5639                | Kind::Table => return false,
5640                _ => {}
5641            }
5642        }
5643        match para_end {
5644            Some(end) if end > caret => !self.source[caret..end].trim().is_empty(),
5645            _ => false,
5646        }
5647    }
5648
5649    /// The destination of the link under the caret — what a Link prompt shows so
5650    /// ⌘K on an existing link edits its URL instead of asking for it again.
5651    /// `None` when the caret stands in no link.
5652    ///
5653    /// An autolink carries no separate destination: its text *is* the URL, so
5654    /// that's what comes back for one.
5655    pub fn link_destination_at_caret(&mut self) -> Option<String> {
5656        self.link_destination_at(self.caret)
5657    }
5658
5659    /// The destination of the link at `off`.
5660    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
5661    /// the caret isn't.
5662    ///
5663    /// The offset form exists for the same reason
5664    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
5665    /// the document somewhere else — a footnote's text in a popover, say — has
5666    /// rows and runs but no caret in them, and still needs to know which of those
5667    /// runs a reader can follow.
5668    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
5669        self.nodes()
5670            .into_iter()
5671            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
5672            .filter(|n| n.span.start <= off && off < n.span.end)
5673            .max_by_key(|n| n.span.start)
5674            .and_then(|n| n.destination.or(n.text))
5675    }
5676
5677    /// Where the locator `id` lands in this document — the `#v2` half of a
5678    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
5679    /// answers to it.
5680    ///
5681    /// The other end of a link, and the reason this exists: without it a
5682    /// destination has only file granularity, so following a citation into a
5683    /// chapter drops the reader at the top of it to hunt for the verse. Which is
5684    /// also why it is a *document* query rather than a caret one — the document
5685    /// being asked is usually not the one the reader is in.
5686    ///
5687    /// Three readings, tried in order, because the same `#some-heading` is
5688    /// written three ways across the formats leaf opens:
5689    ///
5690    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
5691    ///    the auto-ids djot mints for its headings. The only exact answer, so it
5692    ///    goes first — a document that says `{#v1}` has settled the question.
5693    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
5694    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
5695    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
5696    ///    authored anywhere land on a djot heading.
5697    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
5698    ///    none and `{#custom}` is literal text in a Markdown heading — so for
5699    ///    the format most vaults are written in, the heading's own words are the
5700    ///    only thing a fragment can name. This is the rule every Markdown
5701    ///    renderer already follows, which is what makes `#a-heading` mean in
5702    ///    diaryx what it means on the web.
5703    ///
5704    /// Ties go to the earliest match, then to the widest: a duplicated id is the
5705    /// document's mistake and the first one is the answer every anchor
5706    /// implementation gives, while preferring the wider span picks the section
5707    /// over the heading that opens it — more for a peek to show, same place to
5708    /// land.
5709    pub fn locate(&mut self, id: &str) -> Option<Landing> {
5710        let id = id.trim();
5711        if id.is_empty() {
5712            return None;
5713        }
5714        let nodes = self.nodes();
5715
5716        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
5717        // is picking, among nodes that start together, the one that ends last.
5718        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
5719            matches
5720                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
5721                .map(|n| Landing {
5722                    start: n.span.start,
5723                    end: n.span.end,
5724                })
5725        };
5726
5727        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
5728            return Some(landing);
5729        }
5730        let want = slug(id);
5731        if want.is_empty() {
5732            return None;
5733        }
5734        if let Some(landing) = pick(
5735            &mut nodes
5736                .iter()
5737                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
5738        ) {
5739            return Some(landing);
5740        }
5741
5742        // A heading by its words. Its span is one line, so the end comes from
5743        // where the *section* it opens gives out — the next heading that is not
5744        // under it, or the end of the document. A Markdown heading has no
5745        // section node to ask (twig only builds those for djot), and a peek that
5746        // showed the heading alone would answer "what does that say" with the
5747        // title of the thing it says.
5748        let heading = nodes
5749            .iter()
5750            .filter(|n| n.kind == Kind::Heading)
5751            .filter(|n| {
5752                n.content_span
5753                    .clone()
5754                    .and_then(|s| self.source.get(s))
5755                    .is_some_and(|text| slug(text) == want)
5756            })
5757            .min_by_key(|n| n.span.start)?;
5758        let level = heading.level.unwrap_or(u32::MAX);
5759        let end = nodes
5760            .iter()
5761            .filter(|n| n.kind == Kind::Heading)
5762            .filter(|n| n.span.start > heading.span.start)
5763            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
5764            .map(|n| n.span.start)
5765            .min()
5766            .unwrap_or(self.source.len());
5767        Some(Landing {
5768            start: heading.span.start,
5769            end,
5770        })
5771    }
5772
5773    /// Write a footnote at the caret — the toolbar's Footnote button, and the
5774    /// one gesture in the footnote story that *authors* rather than follows.
5775    ///
5776    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
5777    /// the `[^1]:` definition at the end of the document. Half a footnote is not
5778    /// a footnote — a bare reference with nothing defining it renders as literal
5779    /// brackets — so a single button that wrote only the reference would leave
5780    /// the author to hand-spell the other half in a document that had just
5781    /// stopped showing them what the first half meant. One edit also means one
5782    /// undo takes both back.
5783    ///
5784    /// The definition's body is left empty and **the caret lands in it**, which
5785    /// is the whole point of pressing the button: nobody wants a reference to a
5786    /// note they have not written yet. Getting back to where they were writing
5787    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
5788    /// the same return leg a reader following a reference already uses, so the
5789    /// author is left standing on the near end of a round trip that works.
5790    ///
5791    /// A selection collapses to its *end* rather than being replaced: a
5792    /// reference annotates the words before it, so "select the claim, add a
5793    /// footnote" should mark that claim, not consume it.
5794    pub fn insert_footnote(&mut self) {
5795        if self.read_only || self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
5796            return;
5797        }
5798        let at = self.selection().map_or(self.caret, |(_, end)| end);
5799        self.anchor = None;
5800        self.caret = at;
5801        self.record_caret();
5802        let label = self.next_footnote_label();
5803        match self.editor.insert_footnote(at, &label) {
5804            Ok(change) => {
5805                self.last_edit_kind = None;
5806                self.refresh();
5807                self.anchor = None;
5808                // `change.new` runs from the reference to the end of the
5809                // document, so its start is the `[^1]` just written and
5810                // `footnote_at` resolves it to the note the same way a reader's
5811                // tap does — and to the note's *body*, which is already a caret
5812                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
5813                // and has none), so this needs no snap on top. The fallback is
5814                // the reference's own offset: a format that spelled the pair some
5815                // way leaf can't read back should still leave the caret on the
5816                // edit rather than at the far end of a document it just grew.
5817                self.caret = self
5818                    .footnote_at(change.new.start)
5819                    .and_then(|note| note.offset)
5820                    .unwrap_or(change.new.start);
5821                self.dirty = self.source != self.clean_source;
5822                self.status = None;
5823                self.clamp_caret();
5824                self.record_caret();
5825            }
5826            Err(e) => self.status = Some(format!("footnote: {e}")),
5827        }
5828    }
5829
5830    /// The label to give a footnote the author has not named: the lowest counting
5831    /// number no footnote in the document is already wearing.
5832    ///
5833    /// twig takes the label rather than minting one, because it holds no opinion
5834    /// about what a document's footnotes should be called — and it is right not
5835    /// to. Numbering them is what every author of a numbered note expects, and
5836    /// re-using a taken number would silently point the new reference at somebody
5837    /// else's note (twig reuses an existing definition rather than appending a
5838    /// second one, which is the right rule for citing a note twice on purpose and
5839    /// exactly the wrong accident to have by default).
5840    ///
5841    /// *References* are counted alongside definitions, not just definitions: a
5842    /// document carrying a dangling `[^2]` has a 2 that means something to
5843    /// whoever wrote it, and minting a definition for it here would answer a
5844    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
5845    /// count entirely — they take no number, so they block none.
5846    fn next_footnote_label(&mut self) -> String {
5847        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
5848            .into_iter()
5849            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
5850            .filter_map(|label| label.parse().ok())
5851            .collect();
5852        taken.extend(
5853            self.nodes()
5854                .into_iter()
5855                .filter(|n| n.kind == Kind::FootnoteReference)
5856                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
5857                .filter_map(|label| label.parse::<u32>().ok()),
5858        );
5859        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
5860    }
5861
5862    /// The footnote reference under the caret, resolved to the note it names.
5863    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
5864    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
5865        self.footnote_at(self.caret)
5866    }
5867
5868    /// The footnote reference at `off`, resolved to the note it names — what a
5869    /// frontend shows when a reader activates a `[^1]`.
5870    ///
5871    /// A reference is not a link node, so
5872    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
5873    /// (and should not) answer for one: a link names a destination to leave for,
5874    /// a reference names a note that is already in this document. Following one
5875    /// is a move within the page, which is why this hands back an `offset`
5876    /// rather than something to open.
5877    ///
5878    /// Offset-based rather than caret-only because the gesture that wants this
5879    /// most is the one that must not move the caret: a pointer hovering a `[1]`
5880    /// asks what note it names without disturbing where the reader was typing.
5881    /// The caret is just the offset a click already placed —
5882    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
5883    ///
5884    /// `None` when `off` stands in no reference. A reference whose note the
5885    /// document never defines is *not* `None` — it answers with the label it
5886    /// looked for and no text, which is what lets a frontend say so instead of
5887    /// silently doing nothing.
5888    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
5889        // Innermost-wins by latest start, the rule its link sibling uses.
5890        let span = self
5891            .nodes()
5892            .into_iter()
5893            .filter(|n| n.kind == Kind::FootnoteReference)
5894            .filter(|n| n.span.start <= off && off < n.span.end)
5895            .max_by_key(|n| n.span.start)?
5896            .span;
5897        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();
5898
5899        // The note itself. Definitions are roots beside `doc` rather than
5900        // children of it, so they're asked for directly — see
5901        // `wysiwyg::footnote_definitions`.
5902        let note = wysiwyg::footnote_definitions(&mut self.editor)
5903            .into_iter()
5904            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
5905        let Some(note) = note else {
5906            return Some(FootnoteRef {
5907                label,
5908                text: None,
5909                offset: None,
5910                end: None,
5911            });
5912        };
5913        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
5914        Some(FootnoteRef {
5915            label,
5916            text: body
5917                .clone()
5918                .and_then(|b| self.source.get(b))
5919                .map(str::to_string),
5920            // The body's start, not the definition's — see `FootnoteRef::offset`.
5921            offset: body.clone().map(|b| b.start),
5922            end: body.map(|b| b.end),
5923        })
5924    }
5925
5926    /// The footnote *definition* the caret stands in, and where the reference
5927    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
5928    /// at the caret's offset.
5929    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
5930        self.footnote_definition_at(self.caret)
5931    }
5932
5933    /// The footnote definition spanning `off`, and where the reference that
5934    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
5935    ///
5936    /// The mirror image, deliberately: the same gesture that takes a reader from
5937    /// `[1]` down to the note takes them from the note back up to `[1]`, so
5938    /// following a footnote is a round trip rather than a fall. It needs no
5939    /// memory of how the reader arrived — the document says where the reference
5940    /// is — which is what makes it work for a reader who scrolled to the notes
5941    /// themselves, and what keeps it right after an edit moves either end.
5942    ///
5943    /// `None` when `off` stands in no definition. A definition nothing cites is
5944    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
5945    /// its label and no offset, so a frontend can say "nothing refers to this"
5946    /// rather than offer a jump that goes nowhere.
5947    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
5948        // Definitions are roots beside `doc`, so `nodes()` — which walks the
5949        // document body — never reports one. They're asked for directly, the way
5950        // `footnote_at` asks for the note it resolves to.
5951        //
5952        // Closed at the end, unlike the half-open test its neighbours use. A
5953        // definition's span stops at its last content byte — the newline ending
5954        // the line is outside it — so `span.end` is the caret stop at the end of
5955        // the note's own row, not the first byte of anything after. Excluding it
5956        // meant the one caret an author is guaranteed to have, the one left
5957        // sitting at the end of the note they just typed, was in no definition at
5958        // all: writing a note and then asking to go back to its reference
5959        // answered nothing. Two definitions in a row still can't both match —
5960        // there is a blank line between them — and `max_by_key` decides anyway.
5961        let note = wysiwyg::footnote_definitions(&mut self.editor)
5962            .into_iter()
5963            .filter(|m| m.span.start <= off && off <= m.span.end)
5964            .max_by_key(|m| m.span.start)?;
5965        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();
5966
5967        // The earliest reference carrying this label. `min` rather than a `find`,
5968        // because `nodes()` reports a flattened walk whose order is twig's
5969        // business, not document order. Bound first: the walk needs `&mut self`
5970        // and reading the labels back out needs `&self.source`.
5971        let nodes = self.nodes();
5972        let offset = nodes
5973            .into_iter()
5974            .filter(|n| n.kind == Kind::FootnoteReference)
5975            .filter(|n| {
5976                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
5977            })
5978            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
5979            .map(|n| n.span.start + 2)
5980            .min();
5981        Some(FootnoteDef { label, offset })
5982    }
5983
5984    /// The destination of the image under the caret — what an image prompt shows
5985    /// so editing an existing image starts from its current URL instead of blank,
5986    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
5987    /// `None` when the caret stands in no image. A caret resting just after a
5988    /// block image (its trailing stop) is still "in" it — the half-open span test
5989    /// excludes that offset, which is the intended precision: past the image is
5990    /// past it.
5991    pub fn image_destination_at_caret(&mut self) -> Option<String> {
5992        let off = self.caret;
5993        self.nodes()
5994            .into_iter()
5995            .filter(|n| n.kind == Kind::Image)
5996            .filter(|n| n.span.start <= off && off < n.span.end)
5997            .max_by_key(|n| n.span.start)
5998            .and_then(|n| n.destination)
5999    }
6000
6001    /// The language of the fenced code block the caret stands in — what a
6002    /// language prompt shows so editing it starts from the current value rather
6003    /// than blank. `None` when the caret is in no code block, or in one whose
6004    /// fence carries no language (or an indented block, which has no fence).
6005    pub fn code_language_at_caret(&mut self) -> Option<String> {
6006        let start = self.code_block_start_at_caret()?;
6007        wysiwyg::code_language(&self.source, start)
6008    }
6009
6010    /// Whether the caret stands in a fenced code block — the one a language
6011    /// prompt could edit. A frontend gates its "set language" affordance on this
6012    /// (an indented block, which can't carry a language, reports `false`).
6013    pub fn caret_in_fenced_code(&mut self) -> bool {
6014        self.code_block_start_at_caret()
6015            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
6016    }
6017
6018    /// Set (or clear, with `""`) the language of the fenced code block the caret
6019    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
6020    /// block, and a reported error for a language the format's fence cannot
6021    /// carry.
6022    ///
6023    /// twig rewrites the info string, so the fence's own width — measured
6024    /// against a body neither side touches — is kept, and a language holding a
6025    /// space, a line end or the fence character is refused rather than written
6026    /// out to reparse as something else. Leaf used to splice over the info span
6027    /// itself and `trim()` the input, which handled the one bad case it had
6028    /// thought of.
6029    pub fn set_code_language(&mut self, lang: &str) {
6030        // The read-only gate — this door reaches twig without the splice.
6031        if self.read_only {
6032            return;
6033        }
6034        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
6035            return;
6036        }
6037        if self.code_block_start_at_caret().is_none() {
6038            return;
6039        }
6040        let lang = lang.trim();
6041        // `None` clears the info string; `Some("")` asks for an empty one. Both
6042        // write a bare fence, and the prompt's empty value means "clear".
6043        let want = (!lang.is_empty()).then_some(lang);
6044        self.record_caret();
6045        match self.editor.set_code_language(self.caret, want) {
6046            Ok(_) => {
6047                self.last_edit_kind = None;
6048                self.refresh();
6049                self.anchor = None;
6050                self.dirty = self.source != self.clean_source;
6051                self.status = None;
6052                self.clamp_caret();
6053                self.record_caret();
6054            }
6055            Err(e) => self.status = Some(format!("code language: {e}")),
6056        }
6057    }
6058
6059    /// The `span.start` of the code block covering the caret — the anchor
6060    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
6061    /// in none.
6062    fn code_block_start_at_caret(&mut self) -> Option<usize> {
6063        let off = self.caret;
6064        self.nodes()
6065            .into_iter()
6066            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
6067            .max_by_key(|n| n.span.start)
6068            .map(|n| n.span.start)
6069    }
6070
6071    /// The source range of the text inside the link covering `off` — what sits
6072    /// between its `[` and `]`. `None` when twig reports no link there.
6073    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
6074        self.nodes()
6075            .into_iter()
6076            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
6077            // the other's `span.start`; the link that starts latest at or before
6078            // `off` is the one `off` is actually in.
6079            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
6080            .max_by_key(|n| n.span.start)
6081            .and_then(|n| n.content_span)
6082    }
6083
6084    // ── undo / redo ───────────────────────────────────────────────────────────
6085    // twig owns the history of *bytes* (it owns the buffer) and now carries the
6086    // caret through it too: `record_caret` stashes each state's caret in twig's
6087    // opaque per-step blob, and undo/redo hand it back with the source they
6088    // restore. So leaf keeps no history of its own — no parallel stacks to march
6089    // in lockstep and silently drift out of it.
6090
6091    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
6092    /// where they were when that step began.
6093    pub fn undo(&mut self) {
6094        if self.read_only {
6095            return;
6096        }
6097        let (undone, redoable) = (self.undo_steps, self.redo_steps);
6098        match self.editor.undo() {
6099            Ok(Some(change)) => {
6100                self.after_history(change);
6101                // `refresh` counted the restore as an edit; it was a step back.
6102                self.undo_steps = undone.saturating_sub(1);
6103                self.redo_steps = redoable + 1;
6104            }
6105            Ok(None) => {
6106                self.undo_steps = 0;
6107                self.status = Some("nothing to undo".into());
6108            }
6109            Err(e) => self.status = Some(format!("undo: {e}")),
6110        }
6111    }
6112
6113    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
6114    /// selection back where that step originally left them.
6115    pub fn redo(&mut self) {
6116        if self.read_only {
6117            return;
6118        }
6119        let (undone, redoable) = (self.undo_steps, self.redo_steps);
6120        match self.editor.redo() {
6121            Ok(Some(change)) => {
6122                self.after_history(change);
6123                // `refresh` counted the restore as an edit; it was a step forward.
6124                self.undo_steps = undone + 1;
6125                self.redo_steps = redoable.saturating_sub(1);
6126            }
6127            Ok(None) => {
6128                self.redo_steps = 0;
6129                self.status = Some("nothing to redo".into());
6130            }
6131            Err(e) => self.status = Some(format!("redo: {e}")),
6132        }
6133    }
6134
6135    /// Refresh the cached source and put the caret back where the step being
6136    /// undone/redone had it, clearing any active run.
6137    ///
6138    /// The caret comes from twig's blob for the restored state (what
6139    /// `record_caret` stored). `change` is only the fallback for a state with no
6140    /// blob — a caret at the end of the restored text, which is where this always
6141    /// landed before the blobs were kept. It is the edit site, not where the user
6142    /// was standing, so it's a floor and not the behaviour: undoing should hand
6143    /// back the document *and* the place you were working, which for an edit made
6144    /// anywhere but under the caret are two different places.
6145    fn after_history(&mut self, change: Change) {
6146        self.refresh();
6147        match self
6148            .editor
6149            .caret_blob()
6150            .ok()
6151            .and_then(|b| CaretState::from_blob(&b))
6152        {
6153            Some(state) => {
6154                self.caret = state.caret.min(self.source.len());
6155                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
6156            }
6157            None => {
6158                self.caret = change.new.end.min(self.source.len());
6159                self.anchor = None;
6160            }
6161        }
6162        self.goal_col = None;
6163        self.last_edit_kind = None;
6164        self.dirty = self.source != self.clean_source;
6165        self.status = None;
6166        self.clamp_caret();
6167    }
6168
6169    // ── the file ──────────────────────────────────────────────────────────────
6170
6171    #[cfg(feature = "fs")]
6172    pub fn save(&mut self) {
6173        if self.is_untitled() {
6174            // No path to write and no name to invent: ⌘S on an untitled document
6175            // is a Save As, and only a frontend has a picker to ask with. Say so
6176            // rather than failing at the filesystem with an empty path.
6177            self.status = Some("untitled — save as…".into());
6178            return;
6179        }
6180        let path = self.path.clone();
6181        if self.write(&path) {
6182            self.mark_saved();
6183        }
6184    }
6185
6186    /// Save As: write the document to `path` and *move* it there — `self.path`
6187    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
6188    /// what Save As means; a copy would leave the user editing a document whose
6189    /// name is no longer where their keystrokes go.
6190    ///
6191    /// The move only happens if the bytes actually landed. A failed write leaves
6192    /// the path, `dirty`, and the disk watermark exactly as they were, with the
6193    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
6194    /// must never come away believing it was saved.
6195    ///
6196    /// An existing `path` is overwritten, and the caller is the one that knows
6197    /// whether to ask first: a Save As picker has already run that prompt, and a
6198    /// second confirmation from down here would be the same question twice.
6199    ///
6200    /// `format` does **not** follow the new extension. The buffer is parsed as
6201    /// the format it was opened with, and re-reading it as another one is a
6202    /// conversion — a different, lossy operation that would throw away the undo
6203    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
6204    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
6205    /// until it's reopened.
6206    #[cfg(feature = "fs")]
6207    pub fn save_as(&mut self, path: PathBuf) {
6208        if !self.write(&path) {
6209            return;
6210        }
6211        self.path = path;
6212        self.mark_saved();
6213    }
6214
6215    /// Put `source` on disk at `path`, reporting whether it got there. The one
6216    /// place leaf writes a document, so a save and a Save As can't disagree
6217    /// about what a failure looks like.
6218    #[cfg(feature = "fs")]
6219    fn write(&mut self, path: &Path) -> bool {
6220        match std::fs::write(path, self.source.as_bytes()) {
6221            Ok(()) => true,
6222            Err(e) => {
6223                self.status = Some(format!("save failed: {e}"));
6224                false
6225            }
6226        }
6227    }
6228
6229    /// Re-base the document's saved watermark to the current bytes: clears
6230    /// `dirty`, records `source` as the new clean state (so undoing back to here
6231    /// clears the flag again), and re-stamps the on-disk hash.
6232    ///
6233    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
6234    /// the hook a **filesystem-free host** calls itself once it has persisted
6235    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
6236    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
6237    /// are already where that host wants them, and this just tells the model they
6238    /// are safe.
6239    pub fn mark_saved(&mut self) {
6240        self.clean_source = self.source.clone();
6241        self.dirty = false;
6242        // The bytes on disk are now ours, so this is the new watermark: without
6243        // re-stamping it, every save would report its own work as an external
6244        // change forever after.
6245        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
6246        self.status = Some(format!("saved {}", self.file_name()));
6247    }
6248
6249    /// What the file looks like now against the bytes leaf last read or wrote.
6250    ///
6251    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
6252    /// so this is a filesystem round-trip, not a per-frame question — ask it
6253    /// when a window regains focus, on a timer, or before a save.
6254    ///
6255    /// This *only* reports the file. Whether the document also has unsaved edits
6256    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
6257    /// [`DiskState::Changed`] means a save overwrites someone's work and a
6258    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
6259    /// it has no way to ask — so it hands a frontend both halves and lets it put
6260    /// the question to the person who can answer it.
6261    #[cfg(feature = "fs")]
6262    pub fn disk_state(&self) -> DiskState {
6263        let Some(want) = self.disk_hash else {
6264            return DiskState::Untitled;
6265        };
6266        match std::fs::read(&self.path) {
6267            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
6268            Ok(_) => DiskState::Changed,
6269            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
6270            Err(_) => DiskState::Unreadable,
6271        }
6272    }
6273
6274    /// Re-read the file and replace the document with what's there — the other
6275    /// answer to a [`DiskState::Changed`].
6276    ///
6277    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
6278    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
6279    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
6280    /// document shouldn't have to argue with a guard.
6281    ///
6282    /// **The undo history survives, and the reload is one step in it.** The
6283    /// whole buffer is spliced with the file's bytes through the same door every
6284    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
6285    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
6286    /// swapped the document out from under a reader gives them back what they
6287    /// were looking at, marked dirty, and ^Z again carries on into whatever they
6288    /// had done before it. This used to build a fresh parse and drop the stack,
6289    /// on the reasoning that twig's history belongs to the buffer and these are
6290    /// different bytes; that is true of *rebasing* a step onto them and not of
6291    /// recording the swap itself as one, which is all this is. A splice twig
6292    /// won't take falls back to the fresh parse, and only that path still costs
6293    /// the history.
6294    ///
6295    /// The caret keeps its byte offset, clamped to the new length; the selection
6296    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
6297    /// file changed, so it can't know where the caret "still" is. Clamping keeps
6298    /// it where the user left it in the common case (a change further down the
6299    /// file, or none in the text they're sitting in), and never puts it
6300    /// somewhere invalid. A selection has two such offsets and no such excuse —
6301    /// silently reinterpreting one over changed bytes would arm the *next*
6302    /// keystroke to delete something the user never selected.
6303    ///
6304    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
6305    /// document alone with a status.
6306    #[cfg(feature = "fs")]
6307    pub fn reload(&mut self) {
6308        if self.is_untitled() {
6309            self.status = Some("no file to reload".into());
6310            return;
6311        }
6312        let bytes = match std::fs::read(&self.path) {
6313            Ok(b) => b,
6314            Err(e) => {
6315                self.status = Some(format!("reload failed: {e}"));
6316                return;
6317            }
6318        };
6319        let Ok(source) = String::from_utf8(bytes) else {
6320            self.status = Some("reload failed: file is not UTF-8".into());
6321            return;
6322        };
6323        // Already these bytes — someone saved a file back unchanged, or leaf's
6324        // own write is being read back. Re-baseline against it and stop: a
6325        // splice of the text onto itself would put an undo step on the stack for
6326        // something nobody did.
6327        if source == self.source {
6328            self.disk_hash = Some(hash_bytes(source.as_bytes()));
6329            self.clean_source = source;
6330            self.dirty = false;
6331            self.status = Some(format!("reloaded {}", self.file_name()));
6332            return;
6333        }
6334        let caret = self.caret;
6335        // The pre-reload caret, so undoing the swap puts it back where the
6336        // reader was standing — the same bracketing `splice_exact` does.
6337        self.record_caret();
6338        if self
6339            .editor
6340            .edit_range(0, self.source.len(), &source)
6341            .is_ok()
6342        {
6343            self.refresh();
6344        } else {
6345            // twig wouldn't take the splice. Start over from the bytes, which is
6346            // what this always did, and is the one path that still costs the
6347            // history — `format` is the format this document *is*, not what the
6348            // (unchanged) name now says, see `save_as`.
6349            match new_editor(source.as_bytes(), self.format) {
6350                Ok(editor) => {
6351                    self.editor = editor;
6352                    self.source = source.clone();
6353                    // Not going through `refresh`, so the revision has to move
6354                    // here or every frontend keeps painting the old file from
6355                    // cache.
6356                    self.revision += 1;
6357                }
6358                Err(e) => {
6359                    self.status = Some(format!("reload failed: {e}"));
6360                    return;
6361                }
6362            }
6363        }
6364        self.disk_hash = Some(hash_bytes(source.as_bytes()));
6365        self.clean_source = self.source.clone();
6366        self.caret = caret.min(self.source.len());
6367        self.anchor = None;
6368        self.goal_col = None;
6369        self.last_edit_kind = None;
6370        self.dirty = false;
6371        self.status = Some(format!("reloaded {}", self.file_name()));
6372        self.clamp_caret();
6373        // And the post-reload caret, so a redo restores it.
6374        self.record_caret();
6375    }
6376
6377    /// Re-read the source from twig after it has changed the document. The one
6378    /// funnel every edit, undo, and redo comes through — so it's where the
6379    /// revision moves, and anything cached against the text dies here.
6380    fn refresh(&mut self) {
6381        if let Ok(s) = self.editor.source_str() {
6382            self.source = s;
6383        }
6384        self.revision += 1;
6385        // An edit is a step onto the history and the end of anything undone;
6386        // `undo`/`redo` come through here too and correct this after.
6387        self.undo_steps += 1;
6388        self.redo_steps = 0;
6389        self.clamp_caret();
6390    }
6391
6392    /// Whether [`undo`](Self::undo) has a step to take back — for a native
6393    /// Edit menu to enable its item by. See the note on `undo_steps` for what
6394    /// "has" means here.
6395    pub fn can_undo(&self) -> bool {
6396        !self.read_only && self.undo_steps > 0
6397    }
6398
6399    /// Whether [`redo`](Self::redo) has an undone step to restore.
6400    pub fn can_redo(&self) -> bool {
6401        !self.read_only && self.redo_steps > 0
6402    }
6403
6404    // ── caret movement ─────────────────────────────────────────────────────────
6405    // `extend` grows the selection (Shift+motion): it pins the anchor on the
6406    // first extended step and moves only the caret; an un-extended motion drops
6407    // the selection.
6408
6409    /// Place the caret at byte `offset` (clamped to a char boundary), extending
6410    /// the selection when `extend` is set. The public form of `move_to`, for a
6411    /// frontend that hit-tests pixels straight to a source offset.
6412    pub fn place_caret(&mut self, offset: usize, extend: bool) {
6413        self.goal_col = None;
6414        let before = self.caret;
6415        // A pixel hit-test can land between the visible caret stops — in the
6416        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
6417        // Snap to the nearest real stop so the caret can't come to rest where it
6418        // would draw in one place and type in another. The `(row, col)` click
6419        // path (`click`) already snaps this way through `offset_of_pos`; the
6420        // source view reaches every byte, so it snaps to nothing.
6421        let target = match self.view {
6422            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
6423            // The source view reaches every byte, so there is no stop to snap
6424            // to — but "every byte" still means every *character* boundary. A
6425            // caret resting inside a multi-byte character draws nowhere real
6426            // and panics the next time anything slices there.
6427            View::Source => self.char_boundary_at_or_before(offset),
6428        };
6429        self.move_to(target, extend);
6430        self.clamp_caret();
6431        self.debug_assert_on_a_stop(before);
6432    }
6433
6434    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
6435    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
6436    /// grab the metadata) while the source view still selects the literal whole.
6437    pub fn select_all(&mut self) {
6438        self.anchor = Some(self.caret_floor());
6439        self.caret = self.source.len();
6440        self.goal_col = None;
6441        self.last_edit_kind = None;
6442        self.status = None;
6443    }
6444
6445    /// Select the word (or whitespace / punctuation run) at `offset` — the
6446    /// double-click gesture. Anchors on the run's start with the caret at its
6447    /// end so a following Shift-motion extends from the far edge.
6448    pub fn select_word_at(&mut self, offset: usize) {
6449        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
6450        self.anchor = Some(s);
6451        self.caret = e;
6452        self.goal_col = None;
6453        self.last_edit_kind = None;
6454        self.status = None;
6455        self.clamp_caret();
6456    }
6457
6458    /// Select the whole enclosing text block (paragraph, heading, list item's
6459    /// text…) at `offset` — the triple-click gesture. Reads the range straight
6460    /// from the AST (twig's `content_span`), so it selects the entire *logical*
6461    /// paragraph even when that paragraph soft-wraps across several visual rows —
6462    /// where a visual-row-based select breaks down, because one source offset at
6463    /// a wrap boundary belongs to two rows at once.
6464    pub fn select_block_at(&mut self, offset: usize) {
6465        let off = offset.min(self.source.len());
6466        let range = self
6467            .editor
6468            .ancestors_at(off)
6469            .ok()
6470            .and_then(|chain| {
6471                // Ancestors run root → deepest; the deepest node that is neither
6472                // an inline span nor a multi-block container is the text block
6473                // the caret sits in (a paragraph, a heading, a code block…).
6474                chain
6475                    .into_iter()
6476                    .rev()
6477                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
6478                    .map(|m| m.content_span.unwrap_or(m.span))
6479            })
6480            .unwrap_or_else(|| source_line_range(&self.source, off));
6481        self.anchor = Some(range.start.min(self.source.len()));
6482        self.caret = range.end.min(self.source.len());
6483        self.goal_col = None;
6484        self.last_edit_kind = None;
6485        self.status = None;
6486        self.clamp_caret();
6487    }
6488
6489    /// Select the exact source range `[start, end)` — anchor at `start`, caret
6490    /// at `end` — without snapping either end to a visible caret stop.
6491    ///
6492    /// The one caret verb that takes a range it was *handed* rather than one it
6493    /// worked out, for a host that already knows the bytes it means: a search
6494    /// hit, an annotation's footprint, a quote re-anchored through
6495    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
6496    /// wrong tool for that, and not by a little — it snaps to the nearest
6497    /// *visible* stop, and where a range butts up against a hidden delimiter
6498    /// the nearest stop is the one before it, so selecting the "needle" of
6499    /// `**needle**` comes back with "needl" and an edit against it strands the
6500    /// "e".
6501    ///
6502    /// What `place_caret` does that is bookkeeping rather than snapping still
6503    /// happens here, because a host handing in a range is not asking to opt out
6504    /// of the invariants:
6505    ///
6506    /// - both ends are clamped into the document and up to
6507    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
6508    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
6509    ///   types into the metadata;
6510    /// - both land on character boundaries, so nothing slices a `é` in half;
6511    /// - the sticky vertical goal column is dropped, and any armed inline mark
6512    ///   disarmed, since a range from outside inherits neither.
6513    ///
6514    /// An empty range is a caret rather than a selection —
6515    /// [`selection`](Self::selection) reports `None` for it, as it does for any
6516    /// anchor that has met the caret.
6517    pub fn select_range(&mut self, start: usize, end: usize) {
6518        let floor = self.caret_floor();
6519        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
6520        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
6521        self.anchor = Some(anchor);
6522        self.caret = caret;
6523        self.goal_col = None;
6524        self.status = None;
6525        self.last_edit_kind = None;
6526        self.clear_pending();
6527    }
6528
6529    /// `offset` itself if it is a character boundary, else the boundary before
6530    /// it. An offset that isn't one draws nowhere real and panics the next time
6531    /// anything slices there.
6532    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
6533        let mut o = offset.min(self.source.len());
6534        while o > 0 && !self.source.is_char_boundary(o) {
6535            o -= 1;
6536        }
6537        o
6538    }
6539
6540    /// The lowest source offset the caret may occupy in the active view. In
6541    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
6542    /// the first rendered offset; the source view reaches everything, so it's 0.
6543    fn caret_floor(&self) -> usize {
6544        match self.view {
6545            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
6546            View::Source => 0,
6547        }
6548    }
6549
6550    /// Land in a table cell with its whole content selected — the anchor at the
6551    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
6552    /// like tabbing into a form field: the text comes up selected, so typing
6553    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
6554    /// end`) collapses to a plain caret home (an empty selection is no selection).
6555    fn select_cell(&mut self, start: usize, end: usize) {
6556        self.select_range(start, end);
6557    }
6558
6559    fn move_to(&mut self, offset: usize, extend: bool) {
6560        if extend {
6561            if self.anchor.is_none() {
6562                self.anchor = Some(self.caret);
6563            }
6564        } else {
6565            self.anchor = None;
6566        }
6567        self.caret = offset.min(self.source.len()).max(self.caret_floor());
6568        self.status = None;
6569        // A caret move ends the current typing/deletion run, so the next edit
6570        // starts a fresh undo group rather than coalescing across the gap.
6571        self.last_edit_kind = None;
6572        // Moving away disarms any sticky mark — "start bold" applies only where
6573        // it was asked for, not wherever the caret next lands.
6574        self.clear_pending();
6575    }
6576
6577    // In the source view, motion walks source bytes / source lines. In the
6578    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
6579    // what steps the caret cleanly over hidden delimiters.
6580
6581    pub fn move_left(&mut self, extend: bool) {
6582        self.goal_col = None;
6583        if !extend && let Some((s, _e)) = self.selection() {
6584            self.move_to(s, false);
6585            return;
6586        }
6587        let target = match self.view {
6588            View::Source => {
6589                if self.caret > 0 {
6590                    prev_boundary(&self.source, self.caret)
6591                } else {
6592                    0
6593                }
6594            }
6595            // Walks caret *stops*, not columns: decoration (a table border, a
6596            // cell's padding) is stepped over in one press, and a hidden
6597            // delimiter never holds the caret up — though the end of a mark's
6598            // content is a stop of its own (`VisualMap::mark_ends`), so
6599            // leaving `**bold**` from past its `**` is a press onto the end of
6600            // the bold and another onto the `d`.
6601            View::Wysiwyg => self
6602                .vmap
6603                .caret_stop_before(self.caret)
6604                .unwrap_or(self.caret),
6605        };
6606        let before = self.caret;
6607        self.move_to(target, extend);
6608        self.debug_assert_on_a_stop(before);
6609    }
6610
6611    pub fn move_right(&mut self, extend: bool) {
6612        self.goal_col = None;
6613        if !extend && let Some((_s, e)) = self.selection() {
6614            self.move_to(e, false);
6615            return;
6616        }
6617        let target = match self.view {
6618            View::Source => {
6619                if self.caret < self.source.len() {
6620                    next_boundary(&self.source, self.caret)
6621                } else {
6622                    self.caret
6623                }
6624            }
6625            View::Wysiwyg => self.vmap.caret_stop_after(self.caret).unwrap_or(self.caret),
6626        };
6627        let before = self.caret;
6628        self.move_to(target, extend);
6629        self.debug_assert_on_a_stop(before);
6630    }
6631
6632    /// Move to the start of the previous word (⌥← / Ctrl+←).
6633    pub fn move_word_left(&mut self, extend: bool) {
6634        self.goal_col = None;
6635        let before = self.caret;
6636        let target = self.word_left_from(self.caret);
6637        self.move_to(target, extend);
6638        self.debug_assert_on_a_stop(before);
6639    }
6640
6641    /// Move to the end of the next word (⌥→ / Ctrl+→).
6642    pub fn move_word_right(&mut self, extend: bool) {
6643        self.goal_col = None;
6644        let before = self.caret;
6645        let target = self.word_right_from(self.caret);
6646        self.move_to(target, extend);
6647        self.debug_assert_on_a_stop(before);
6648    }
6649
6650    // Word boundaries are found in the space the *view* is in. The source view
6651    // walks the source, because there the source is what's rendered. WYSIWYG
6652    // walks the rendered text instead: `**` is invisible to the user, so it has
6653    // to be invisible to word motion too — a caret parked inside one draws in
6654    // the column after `bold` and types two bytes earlier, and a word-delete
6655    // that stops there shreds the markup into `a ** c`.
6656
6657    /// The word boundary to the left of `off` in the active view's space.
6658    fn word_left_from(&self, off: usize) -> usize {
6659        match self.view {
6660            View::Source => prev_word(&self.source, off),
6661            View::Wysiwyg => self.glyph_word_left(off),
6662        }
6663    }
6664
6665    /// The word boundary to the right of `off` in the active view's space.
6666    fn word_right_from(&self, off: usize) -> usize {
6667        match self.view {
6668            View::Source => next_word(&self.source, off),
6669            View::Wysiwyg => self.glyph_word_right(off),
6670        }
6671    }
6672
6673    /// The character class of the glyph drawn at stop `off`.
6674    ///
6675    /// Read from the source, because a stop points at the source byte its glyph
6676    /// came from — the source *is* where the rendered character is written. What
6677    /// makes the walk glyph space rather than source space is that it only ever
6678    /// visits stops, and the hidden bytes between them have none.
6679    fn class_at(&self, off: usize) -> Class {
6680        self.source
6681            .get(off..)
6682            .and_then(|s| s.chars().next())
6683            .map_or(Class::Space, classify)
6684    }
6685
6686    /// [`next_word`] in glyph space: skip any leading separators, then consume
6687    /// the following word run, with the stop table standing in for the source's
6688    /// characters.
6689    fn glyph_word_right(&self, from: usize) -> usize {
6690        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
6691            return from;
6692        };
6693        let mut in_word = false;
6694        loop {
6695            match self.class_at(off) {
6696                Class::Word => in_word = true,
6697                _ if in_word => return off,
6698                _ => {}
6699            }
6700            match self.vmap.stop_after(off) {
6701                Some(next) => off = next,
6702                None => return off,
6703            }
6704        }
6705    }
6706
6707    /// [`prev_word`] in glyph space: skip separators walking left, then consume
6708    /// the preceding word run.
6709    fn glyph_word_left(&self, from: usize) -> usize {
6710        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
6711            return from;
6712        };
6713        let mut in_word = false;
6714        while let Some(prev) = self.vmap.stop_before(off) {
6715            match self.class_at(prev) {
6716                Class::Word => in_word = true,
6717                _ if in_word => return off,
6718                _ => {}
6719            }
6720            off = prev;
6721        }
6722        off
6723    }
6724
6725    /// After a motion that walks the visual map, the caret must be *on* the map.
6726    /// A stop is the only offset where the caret draws and edits in the same
6727    /// place, and it's the invariant both a caret parked inside an emoji and one
6728    /// parked inside a `**` were quietly breaking.
6729    ///
6730    /// Only when the caret actually moved: a walk with nowhere to go leaves it
6731    /// where it was, which is wherever the floor or a frontend put it rather
6732    /// than somewhere this motion chose.
6733    fn debug_assert_on_a_stop(&self, before: usize) {
6734        debug_assert!(
6735            self.view != View::Wysiwyg
6736                || self.vmap.num_rows() == 0
6737                || self.caret == before
6738                || self.vmap.is_stop(self.caret),
6739            "motion left the caret at {}, which is not a caret stop: it would draw in \
6740             one place and type in another",
6741            self.caret
6742        );
6743    }
6744
6745    // Up and Down run off the ends of the document rather than stopping dead at
6746    // them: Up from the first row lands at the document's start, Down from the
6747    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
6748    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
6749    // reaching the end of the text is what a reader means by it.
6750    //
6751    // The views used to disagree here by accident rather than by decision: the
6752    // source view fell into the edge behaviour through `row_col_to_offset`
6753    // clamping an out-of-range row to the end of the string, while WYSIWYG had
6754    // no row below to walk to and did nothing at all. They share the rule now,
6755    // each in its own space — the source view reaches every byte, WYSIWYG only
6756    // the offsets it draws.
6757
6758    pub fn move_up(&mut self, extend: bool) {
6759        let (row, col) = self.caret_pos();
6760        let goal = self.goal_col.unwrap_or(col);
6761        let target = match self.view {
6762            View::Source => match row.checked_sub(1) {
6763                Some(r) => row_col_to_offset(&self.source, r, goal),
6764                None => self.reachable_start(),
6765            },
6766            // A table's border rules are drawn but hold no caret, so Up steps
6767            // over them to the row that does.
6768            View::Wysiwyg => match self.vmap.navigable_above(row) {
6769                Some(r) => self.row_target(r, goal),
6770                None => self.reachable_start(),
6771            },
6772        };
6773        self.step_vertical(target, goal, extend);
6774    }
6775
6776    pub fn move_down(&mut self, extend: bool) {
6777        let (row, col) = self.caret_pos();
6778        let goal = self.goal_col.unwrap_or(col);
6779        let target = match self.view {
6780            View::Source => match self.source_row_below(row) {
6781                Some(r) => row_col_to_offset(&self.source, r, goal),
6782                None => self.reachable_end(),
6783            },
6784            View::Wysiwyg => match self.vmap.navigable_below(row) {
6785                Some(r) => self.row_target(r, goal),
6786                None => self.reachable_end(),
6787            },
6788        };
6789        self.step_vertical(target, goal, extend);
6790    }
6791
6792    /// Land a vertical motion at `target`, latching the `goal` column it aimed
6793    /// with so the rest of the run keeps aiming there.
6794    ///
6795    /// A motion with nowhere to go changes *nothing*, the goal column included:
6796    /// the latch used to run before the early return at the top of the document,
6797    /// so an Up that did nothing still armed a column, and the next Down aimed
6798    /// at one the caret had never been in.
6799    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
6800        let before = self.caret;
6801        if target == before {
6802            return;
6803        }
6804        self.goal_col = Some(goal);
6805        self.move_to(target, extend);
6806        self.debug_assert_on_a_stop(before);
6807    }
6808
6809    /// The source line below `row`, or `None` when `row` is the last one. Lines
6810    /// are counted by newline, so a trailing one leaves a real, empty last line
6811    /// for the caret to sit on — the document ends below it, not on it.
6812    fn source_row_below(&self, row: usize) -> Option<usize> {
6813        let last = self.source.bytes().filter(|&b| b == b'\n').count();
6814        (row < last).then_some(row + 1)
6815    }
6816
6817    /// Where a vertical motion aiming at the `goal` column lands on visual row
6818    /// `r`: the column clamped to the row, mapped to its offset, then held
6819    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
6820    /// column belongs to the row below, and a gutter's column 0 points at the
6821    /// block rather than at this row.
6822    fn row_target(&self, r: usize, goal: usize) -> usize {
6823        let (start, end) = self.row_bounds(r);
6824        self.vmap
6825            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
6826            .clamp(start, end)
6827    }
6828
6829    /// The first and last offsets the caret can reach in the active view.
6830    ///
6831    /// Not the same span in both: the source view shows every byte, so it can
6832    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
6833    /// sits below the first stop, and a document's trailing newline is drawn
6834    /// nowhere and so sits past the last.
6835    fn reachable_start(&self) -> usize {
6836        match self.view {
6837            View::Source => 0,
6838            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
6839        }
6840    }
6841
6842    fn reachable_end(&self) -> usize {
6843        match self.view {
6844            View::Source => self.source.len(),
6845            View::Wysiwyg => self
6846                .vmap
6847                .stop_at_or_before(self.source.len())
6848                .unwrap_or(self.caret),
6849        }
6850    }
6851
6852    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
6853    /// including the space a soft wrap ate off its end, which is drawn on this
6854    /// row however much the offset past it belongs to the next one.
6855    fn row_span(&self, r: usize) -> (usize, usize) {
6856        let start = self
6857            .vmap
6858            .row_start(r)
6859            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
6860        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
6861        (start.min(end), end)
6862    }
6863
6864    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
6865    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
6866    /// this row's last position is the one before it — the offset before the
6867    /// space the wrap ate, where the caret draws just past the row's last word
6868    /// and types there too.
6869    ///
6870    /// Aiming at the shared offset instead is what stalled End: it is the row's
6871    /// last *column*, so End pressed on the row reached it and then read back as
6872    /// the row below's start, where a second press ran on to that row's end and
6873    /// the next to the one after — End walking down the paragraph a row a press.
6874    fn row_bounds(&self, r: usize) -> (usize, usize) {
6875        let (start, end) = self.row_span(r);
6876        let wraps = self
6877            .vmap
6878            .navigable_below(r)
6879            .and_then(|b| self.vmap.row_start(b))
6880            .is_some_and(|off| off == end);
6881        match wraps {
6882            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
6883            false => (start, end),
6884        }
6885    }
6886
6887    /// The `[start, end]` of the line Home and End aim at: the visual row in
6888    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
6889    ///
6890    /// A soft-wrapped row is a line here, because it is one to the eye and the
6891    /// eye is what these keys are aimed by — a reader pressing End means the end
6892    /// of the line they can see. (`select_block_at` wants the opposite and reads
6893    /// the AST for it: a triple-click grabs the whole paragraph, however many
6894    /// rows it folds into.)
6895    fn line_bounds(&self) -> (usize, usize) {
6896        let (row, _) = self.caret_pos();
6897        match self.view {
6898            View::Source => {
6899                let start = line_start(&self.source, row);
6900                (start, line_end_from(&self.source, start))
6901            }
6902            View::Wysiwyg => self.row_bounds(row),
6903        }
6904    }
6905
6906    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
6907    /// *drawn* — what a kill takes.
6908    ///
6909    /// The two part only at a soft wrap, over the space the wrap ate: the caret
6910    /// can't stand after it (that offset opens the row below, and End stopping
6911    /// there would walk), but it is on this row, and a kill that spared it would
6912    /// leave a double space behind where the row's text had been. Deleting it
6913    /// joins nothing — a wrap is drawn, not written.
6914    fn line_span(&self) -> (usize, usize) {
6915        let (row, _) = self.caret_pos();
6916        match self.view {
6917            View::Source => self.line_bounds(),
6918            View::Wysiwyg => self.row_span(row),
6919        }
6920    }
6921
6922    /// The first offset in `[start, end]` holding something other than
6923    /// whitespace, or `end` when the line holds nothing else — where Home aims.
6924    ///
6925    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
6926    /// so a hidden delimiter is never taken for the line's first character (nor
6927    /// landed on), and the source view steps the source it is showing.
6928    fn first_non_space(&self, start: usize, end: usize) -> usize {
6929        let mut off = start;
6930        while off < end {
6931            if self.class_at(off) != Class::Space {
6932                return off;
6933            }
6934            off = match self.view {
6935                View::Source => next_boundary(&self.source, off),
6936                View::Wysiwyg => match self.vmap.stop_after(off) {
6937                    Some(next) => next,
6938                    None => return end,
6939                },
6940            };
6941        }
6942        end
6943    }
6944
6945    /// Home: to the first character on the line, or to column 0 when the caret
6946    /// is already on it — the two-press toggle every editor spells this way.
6947    /// The indentation is somewhere the caret has to be able to reach and almost
6948    /// never where a reader is headed, so it costs the second press.
6949    pub fn move_home(&mut self, extend: bool) {
6950        self.goal_col = None;
6951        let (start, end) = self.line_bounds();
6952        let text = self.first_non_space(start, end);
6953        let target = if self.caret == text { start } else { text };
6954        let before = self.caret;
6955        self.move_to(target, extend);
6956        self.debug_assert_on_a_stop(before);
6957    }
6958
6959    /// End: to the end of the line.
6960    pub fn move_end(&mut self, extend: bool) {
6961        self.goal_col = None;
6962        let (_, end) = self.line_bounds();
6963        let before = self.caret;
6964        self.move_to(end, extend);
6965        self.debug_assert_on_a_stop(before);
6966    }
6967
6968    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
6969    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
6970    /// when the caret isn't in a table, or is already in the last/first cell — the
6971    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
6972    /// meaning everywhere else.
6973    pub fn cell_hop(&mut self, forward: bool) -> bool {
6974        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
6975            return false;
6976        };
6977        // Flatten to document (row-major) order and step one cell either way.
6978        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
6979        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
6980        let next = if forward {
6981            i.checked_add(1)
6982        } else {
6983            i.checked_sub(1)
6984        };
6985        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
6986            return false; // at the table's edge; leave Tab to the frontend
6987        };
6988        self.select_cell(start, end);
6989        true
6990    }
6991
6992    /// Move the caret to the cell directly above (`down == false`) or below in
6993    /// the same column, landing with the cell's whole content selected (see
6994    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
6995    /// when the caret isn't in a table), so the frontend can fall through — the
6996    /// vertical counterpart of [`Self::cell_hop`].
6997    ///
6998    /// A ragged row that is short a column clamps to its last cell, so Down never
6999    /// falls out of the table over a gap the row above happened to have.
7000    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
7001        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
7002            return false;
7003        };
7004        let target = match down {
7005            true => r + 1,
7006            false if r == 0 => return false,
7007            false => r - 1,
7008        };
7009        let Some(row) = grid.get(target) else {
7010            return false;
7011        };
7012        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
7013            return false;
7014        };
7015        self.select_cell(start, end);
7016        true
7017    }
7018
7019    /// The table containing `off` as a row-major grid of `(start, end)` cell
7020    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
7021    /// isn't in a table. Read straight off the visual map's laid-out grid, so
7022    /// every cell (an empty one included, whose derived home twig gives no
7023    /// `content_span` for) is present and in the order Tab walks them.
7024    // Grid, row, column — three returns that only ever travel together, and a
7025    // named type for the pair of them would be read at one call site.
7026    #[allow(clippy::type_complexity)]
7027    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
7028        for t in &self.vmap.tables {
7029            let mut pos = None;
7030            let grid: Vec<Vec<(usize, usize)>> = t
7031                .grid
7032                .iter()
7033                .enumerate()
7034                .map(|(r, row)| {
7035                    row.cells
7036                        .iter()
7037                        .enumerate()
7038                        .map(|(c, cell)| {
7039                            if pos.is_none() && off >= cell.start && off <= cell.end {
7040                                pos = Some((r, c));
7041                            }
7042                            (cell.start, cell.end)
7043                        })
7044                        .collect()
7045                })
7046                .collect();
7047            if let Some((r, c)) = pos {
7048                return Some((grid, r, c));
7049            }
7050        }
7051        None
7052    }
7053
7054    // ── table key policy ──────────────────────────────────────────────────────
7055    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
7056    // as one policy every frontend shares, rather than each re-deriving it. Each
7057    // reports whether it acted *as a table key*; a `false` hands the key back to
7058    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
7059    // everywhere else.
7060
7061    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
7062    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
7063    /// back and simply stays put at the very first cell. `false` when the caret
7064    /// isn't in a table.
7065    pub fn cell_tab(&mut self, forward: bool) -> bool {
7066        if !self.caret_in_table() {
7067            return false;
7068        }
7069        if self.cell_hop(forward) {
7070            return true;
7071        }
7072        // Off the last cell: grow the table by a row and step into its first
7073        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
7074        if forward {
7075            self.append_row_and_enter(0);
7076        }
7077        true
7078    }
7079
7080    /// Return inside a table: drop to the cell below in the same column,
7081    /// appending a new row when the caret is already in the last one. `false`
7082    /// when the caret isn't in a table, so the frontend inserts a newline.
7083    pub fn cell_return(&mut self) -> bool {
7084        if !self.caret_in_table() {
7085            return false;
7086        }
7087        if self.cell_move_vertical(true) {
7088            return true;
7089        }
7090        // Already on the last row: grow one below and drop into the same column.
7091        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
7092        self.append_row_and_enter(col);
7093        true
7094    }
7095
7096    /// Append a row below the caret's (last) row and land in `col` of it. The
7097    /// caret is in the last row, so twig's "insert below" makes the fresh row the
7098    /// table's new last — but twig re-spells the whole table, moving every byte,
7099    /// so the destination is read back from the rebuilt grid by the table's
7100    /// position (stable across a row insert), not from the pre-edit caret.
7101    fn append_row_and_enter(&mut self, col: usize) {
7102        let table = self.caret_table_index();
7103        self.table_insert_row(true);
7104        self.rebuild_map();
7105        let Some((start, end)) = table
7106            .and_then(|ti| self.vmap.tables.get(ti))
7107            .and_then(|t| t.grid.last())
7108            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
7109            .map(|cell| (cell.start, cell.end))
7110        else {
7111            return;
7112        };
7113        self.select_cell(start, end);
7114    }
7115
7116    /// The index, among the document's tables, of the one the caret sits in —
7117    /// `None` when it's in none. Used to re-find a table after an edit re-spells
7118    /// it (a row insert leaves the table order unchanged).
7119    fn caret_table_index(&self) -> Option<usize> {
7120        let off = self.caret;
7121        self.vmap.tables.iter().position(|t| {
7122            t.grid
7123                .iter()
7124                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
7125        })
7126    }
7127
7128    /// Shift+Return inside a table: insert a hard line break *within* the current
7129    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
7130    /// table, so the frontend inserts an ordinary line break.
7131    ///
7132    /// A table row is a single source line, so the newline-spelled hard break
7133    /// can't live in a cell. twig spells the in-cell break the format's way
7134    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
7135    /// break round-trips as structure the renderer reads back as a line — not the
7136    /// opaque raw HTML the old raw-splice left behind.
7137    ///
7138    /// Djot has no idiomatic in-cell break, so twig refuses it
7139    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
7140    /// would render as the literal text `<br>`. The gesture is still *consumed*
7141    /// there — returning `false` would let the frontend insert a real newline,
7142    /// which splits the one-line row — it just leaves the cell unchanged and says
7143    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
7144    ///
7145    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
7146    /// have to be read together: djot is not the only `false`, and naming it in
7147    /// the message was already a guess that HTML — which spells the break as its
7148    /// own `<br>` — would have made wrong.
7149    pub fn cell_line_break(&mut self) -> bool {
7150        if self.read_only || !self.caret_in_table() {
7151            return false;
7152        }
7153        self.record_caret();
7154        match self.editor.insert_line_break(self.caret) {
7155            Ok(change) => {
7156                self.last_edit_kind = None;
7157                self.refresh();
7158                self.caret = change.new.end;
7159                self.anchor = None;
7160                self.goal_col = None;
7161                self.clamp_caret();
7162                self.dirty = self.source != self.clean_source;
7163                self.status = None;
7164                self.record_caret();
7165            }
7166            Err(twig::Error::UnsupportedFormat) => {
7167                self.status = Some(format!(
7168                    "in-cell line breaks aren't supported in {}",
7169                    self.format_name()
7170                ));
7171            }
7172            Err(_) => {}
7173        }
7174        true
7175    }
7176
7177    /// Rebuild the visual map at the width the last build used. A structural edit
7178    /// bumps the revision and swaps the source in, but leaves the *map* stale;
7179    /// when a single gesture edits and then moves over the result (Tab appending
7180    /// a row, then stepping into it), the move needs the map to already show the
7181    /// edit rather than waiting for the frontend's next frame.
7182    fn rebuild_map(&mut self) {
7183        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
7184        self.build_map(wrap);
7185    }
7186
7187    /// Move the caret to the very start of the document (⌘↑ on macOS,
7188    /// Ctrl+Home on Windows/Linux).
7189    pub fn move_doc_start(&mut self, extend: bool) {
7190        self.goal_col = None;
7191        self.move_to(0, extend);
7192    }
7193
7194    /// Move the caret to the very end of the document (⌘↓ on macOS,
7195    /// Ctrl+End on Windows/Linux).
7196    pub fn move_doc_end(&mut self, extend: bool) {
7197        self.goal_col = None;
7198        let end = self.source.len();
7199        self.move_to(end, extend);
7200    }
7201
7202    /// Point the caret at the body cell `(row, col)` the mouse landed on —
7203    /// `col` being a cell of the terminal grid, which is what a display column
7204    /// is. A click on the far cell of a wide character lands at that
7205    /// character's start; the mapping's own doc-comments carry the rule.
7206    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
7207        self.goal_col = None;
7208        let target = match self.view {
7209            View::Source => row_col_to_offset(&self.source, row, col),
7210            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
7211        };
7212        let before = self.caret;
7213        self.move_to(target, extend);
7214        self.debug_assert_on_a_stop(before);
7215    }
7216
7217    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
7218    /// screen if it has moved since the last frame, and never scroll past the
7219    /// last of `rows`.
7220    ///
7221    /// Only if it has *moved* — that's the whole point. Revealing the caret on
7222    /// every frame ties the viewport to it, and a scroll wheel that fights the
7223    /// caret for the viewport loses: the view snaps back the instant it tries to
7224    /// pass the caret's row, so the document can't be scrolled beyond what's
7225    /// already on screen. A caret move is the frontend's cue to follow; a scroll
7226    /// with the caret sitting still is the reader's cue to leave it alone.
7227    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
7228        if self.drawn_caret != Some(self.caret) {
7229            if caret_row < self.scroll {
7230                self.scroll = caret_row;
7231            } else if height > 0 && caret_row >= self.scroll + height {
7232                self.scroll = caret_row + 1 - height;
7233            }
7234            self.drawn_caret = Some(self.caret);
7235        }
7236        self.scroll = self.scroll.min(rows.saturating_sub(1));
7237    }
7238
7239    /// The caret's screen position `(row, col)` in the active view's grid, with
7240    /// `col` a display column: the cell to draw the caret in, which on a line of
7241    /// `你好` or emoji is not the count of characters before it.
7242    pub fn caret_pos(&self) -> (usize, usize) {
7243        match self.view {
7244            View::Source => offset_to_row_col(&self.source, self.caret),
7245            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
7246        }
7247    }
7248
7249    fn clamp_caret(&mut self) {
7250        if self.caret > self.source.len() {
7251            self.caret = self.source.len();
7252        }
7253        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
7254        // any selection anchor) to the first rendered offset.
7255        let floor = self.caret_floor();
7256        if self.caret < floor {
7257            self.caret = floor;
7258        }
7259        if let Some(a) = self.anchor
7260            && a < floor
7261        {
7262            self.anchor = Some(floor);
7263        }
7264        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
7265            self.caret -= 1;
7266        }
7267    }
7268}
7269
7270// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
7271
7272// Left/right motion and backspace/delete step by *grapheme cluster*, not
7273// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
7274// marks moves and deletes as the single character a user sees. Grapheme
7275// boundaries are a superset of char boundaries, so the caret stays valid for twig.
7276
7277/// How an insert of `text` groups for undo: a single typed character folds into
7278/// the run of typing around it, while a newline or a multi-character insert is a
7279/// step of its own.
7280fn typed_edit_kind(text: &str) -> EditKind {
7281    if text.chars().take(2).count() == 1 && text != "\n" {
7282        EditKind::Insert
7283    } else {
7284        EditKind::Other
7285    }
7286}
7287
7288fn prev_boundary(s: &str, i: usize) -> usize {
7289    let mut cursor = GraphemeCursor::new(i, s.len(), true);
7290    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
7291}
7292
7293fn next_boundary(s: &str, i: usize) -> usize {
7294    let mut cursor = GraphemeCursor::new(i, s.len(), true);
7295    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
7296}
7297
7298// ── word boundaries ──────────────────────────────────────────────────────────
7299// The shared primitive behind word-wise motion, word deletion, and
7300// double-click-to-select-a-word. A "word" is a maximal run of one character
7301// class; whitespace and punctuation are their own classes, so motion skips
7302// cleanly between them the way native text fields do.
7303
7304#[derive(PartialEq, Eq, Clone, Copy)]
7305enum Class {
7306    Word,
7307    Space,
7308    Other,
7309}
7310
7311/// The source range of an inline node's own visible text — the part of it a
7312/// WYSIWYG caret can reach, as against the delimiters that only spell it.
7313/// `None` for a node with no interior to empty (a `str`, a break).
7314///
7315/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
7316/// one delimiter in from the span — the same place the renderer maps it to. A
7317/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
7318/// against the source rather than trusted: a range guessed wrong here is text
7319/// deleted wrong.
7320fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
7321    if let Some(span) = n.content_span.clone() {
7322        return Some(span);
7323    }
7324    match n.kind.as_str() {
7325        "verbatim" | "inline_math" => {
7326            let text = n.text.as_ref()?;
7327            let start = n.span.start + 1;
7328            let range = start..start + text.len();
7329            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
7330        }
7331        _ => None,
7332    }
7333}
7334
7335/// The `id` a node declares, or `None` for one that declares none — the
7336/// attribute djot writes for a `{#v1}` and mints for a heading.
7337///
7338/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
7339/// names nothing, so it reads as absent rather than as the empty string.
7340fn declared_id(n: &FlatNode) -> Option<&str> {
7341    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
7342}
7343
7344/// A heading's words reduced to the form a link fragment spells them in:
7345/// lowercase, runs of anything else collapsed to a single `-`, with none left
7346/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
7347///
7348/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
7349/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
7350/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
7351/// any other language is still a heading someone will link to. Underscores
7352/// survive for the same reason they do on the web: they are word characters
7353/// wherever identifiers are written.
7354fn slug(text: &str) -> String {
7355    let mut out = String::new();
7356    let mut pending = false;
7357    for c in text.chars() {
7358        if c.is_alphanumeric() || c == '_' {
7359            if pending && !out.is_empty() {
7360                out.push('-');
7361            }
7362            pending = false;
7363            out.extend(c.to_lowercase());
7364        } else {
7365            pending = true;
7366        }
7367    }
7368    out
7369}
7370
7371fn is_block_container(kind: &Kind) -> bool {
7372    matches!(
7373        kind,
7374        Kind::Doc
7375            | Kind::Section
7376            | Kind::BlockQuote
7377            | Kind::BulletList
7378            | Kind::OrderedList
7379            | Kind::TaskList
7380            | Kind::ListItem
7381            | Kind::TaskListItem
7382            // Every `container` — a directive in any of its three forms, or a
7383            // promoted HTML element. A *text* directive is really inline, so
7384            // claiming it here is a small overreach, and the deliberate one this
7385            // function's kind-only peer `is_inline_kind` documents: the pair is
7386            // consulted together, and answering "block container" for something
7387            // inline is what keeps an ancestor walk from stopping short of the
7388            // paragraph that actually holds it.
7389            | Kind::Container
7390    )
7391}
7392
7393/// The `[start, end)` byte range of the source line containing `off` (newline
7394/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
7395/// line between paragraphs).
7396fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
7397    let off = off.min(s.len());
7398    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
7399    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
7400    start..end
7401}
7402
7403/// How many leading bytes an outdent takes off `line`: a whole indent level
7404/// where the line has one, and whatever it has where it has less.
7405///
7406/// A leading tab counts as a level on its own. It's indentation some other
7407/// editor wrote, and one tab is one level everywhere it came from — measuring it
7408/// in spaces it doesn't contain would leave it untouchable.
7409fn outdent_width(line: &str, unit: usize) -> usize {
7410    if line.starts_with('\t') {
7411        return 1;
7412    }
7413    line.bytes().take(unit).take_while(|b| *b == b' ').count()
7414}
7415
7416/// A list marker found at the head of a line, together with everything before it
7417/// that a sibling line has to repeat.
7418///
7419/// The three offsets differ only inside a block quote, where `>   - b` opens with
7420/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
7421/// `line_start == marker_start`, and `text` is the plain `"  - "`.
7422#[derive(Clone, Debug)]
7423struct ListMarker {
7424    /// The line's first byte.
7425    line_start: usize,
7426    /// Where the marker proper begins, past any quote prefix. The offset to hand
7427    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
7428    marker_start: usize,
7429    /// `line_start` through the marker's trailing space — quote prefix, indent
7430    /// and bullet together, which is what the next item's line opens with.
7431    text: String,
7432}
7433
7434impl ListMarker {
7435    /// Where the item's content starts — one past the marker's trailing space.
7436    fn content_start(&self) -> usize {
7437        self.line_start + self.text.len()
7438    }
7439}
7440
7441fn classify(c: char) -> Class {
7442    if c == '_' || c.is_alphanumeric() {
7443        Class::Word
7444    } else if c.is_whitespace() {
7445        Class::Space
7446    } else {
7447        Class::Other
7448    }
7449}
7450
7451/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
7452/// skip any leading separators, then consume the following word run.
7453fn next_word(s: &str, i: usize) -> usize {
7454    let mut off = i;
7455    let mut in_word = false;
7456    for c in s[i..].chars() {
7457        if classify(c) == Class::Word {
7458            in_word = true;
7459        } else if in_word {
7460            break;
7461        }
7462        off += c.len_utf8();
7463    }
7464    off
7465}
7466
7467/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
7468/// skip separators walking left, then consume the preceding word run.
7469fn prev_word(s: &str, i: usize) -> usize {
7470    let mut off = i;
7471    let mut in_word = false;
7472    for c in s[..i].chars().rev() {
7473        if classify(c) == Class::Word {
7474            in_word = true;
7475        } else if in_word {
7476            break;
7477        }
7478        off -= c.len_utf8();
7479    }
7480    off
7481}
7482
7483/// The `[start, end)` run of same-class characters surrounding `off` — the
7484/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
7485/// the run ending there is used.
7486fn word_range_at(s: &str, off: usize) -> (usize, usize) {
7487    if s.is_empty() {
7488        return (0, 0);
7489    }
7490    let off = off.min(s.len());
7491    let reference = if off < s.len() {
7492        s[off..].chars().next()
7493    } else {
7494        s[..off].chars().next_back()
7495    };
7496    let Some(rc) = reference else {
7497        return (off, off);
7498    };
7499    let class = classify(rc);
7500
7501    let mut start = off;
7502    for c in s[..start].chars().rev() {
7503        if classify(c) == class {
7504            start -= c.len_utf8();
7505        } else {
7506            break;
7507        }
7508    }
7509    let mut end = off;
7510    for c in s[end..].chars() {
7511        if classify(c) == class {
7512            end += c.len_utf8();
7513        } else {
7514            break;
7515        }
7516    }
7517    (start, end)
7518}
7519
7520/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
7521/// the line's start — terminal cells, not characters, so the column names the
7522/// cell the caret is drawn in even on a line of `你好` or emoji.
7523fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
7524    let off = off.min(s.len());
7525    let mut row = 0;
7526    let mut line_start = 0;
7527    for (i, &b) in s.as_bytes().iter().enumerate() {
7528        if i >= off {
7529            break;
7530        }
7531        if b == b'\n' {
7532            row += 1;
7533            line_start = i + 1;
7534        }
7535    }
7536    (row, wysiwyg::text_width(&s[line_start..off]))
7537}
7538
7539/// The byte offset at display column `col` of `row` (clamped to that line's
7540/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
7541///
7542/// A column landing *inside* a character — the second cell of `你`, or any cell
7543/// but the first of an emoji — resolves to that character's start, which is the
7544/// column the caret would have been drawn at to begin with. So both cells of a
7545/// wide character mean the character, and every offset survives the round trip
7546/// out to a column and back. The walk steps by grapheme cluster for the same
7547/// reason the caret does: a cluster is the character, and the cells belong to it
7548/// rather than to the codepoints spelling it.
7549fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
7550    let start = line_start(s, row);
7551    let end = line_end_from(s, start);
7552    let mut off = start;
7553    let mut at = 0; // the display column `off` sits at
7554    while off < end {
7555        let next = next_boundary(s, off).min(end);
7556        let cells = wysiwyg::text_width(&s[off..next]);
7557        if at + cells > col {
7558            break; // `col` is one of this cluster's own cells
7559        }
7560        at += cells;
7561        off = next;
7562    }
7563    off
7564}
7565
7566fn line_start(s: &str, row: usize) -> usize {
7567    if row == 0 {
7568        return 0;
7569    }
7570    let mut r = 0;
7571    for (i, &b) in s.as_bytes().iter().enumerate() {
7572        if b == b'\n' {
7573            r += 1;
7574            if r == row {
7575                return i + 1;
7576            }
7577        }
7578    }
7579    s.len()
7580}
7581
7582fn line_end_from(s: &str, start: usize) -> usize {
7583    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
7584}
7585
7586/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
7587/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
7588/// twig applies writing the mark out, so the toolbar can light the same button
7589/// that made the node.
7590///
7591/// `None` for every other kind, including the inline nodes that aren't marks at
7592/// all (`str`, `link`, `image`, the math and break kinds): they're things a
7593/// caret stands in, not formatting a button toggles.
7594/// Whether a match from an ancestor chain is an inline run whose delimiters
7595/// the rich view draws nothing for — a mark (`**`, `_`, `==`), or an
7596/// attributed span: `<span data-size="large">…</span>`, djot's `[…]{…}`. The
7597/// span is a [`Kind::Container`], which the kind alone cannot tell from a
7598/// block `<div>`, so the chain's caller passes [`Doc::run_span_ids`] and the
7599/// answer is the node's own. Every delete and caret step that walks over a
7600/// `**` walks over a span's tags by this test; without it Backspace after
7601/// `</span>` took the `>` and left the paragraph unparseable.
7602fn hides_delims(m: &QueryMatch, run_spans: &[NodeId]) -> bool {
7603    inline_kind(&m.kind).is_some() || run_spans.contains(&NodeId(m.node_id))
7604}
7605
7606fn inline_kind(kind: &Kind) -> Option<InlineKind> {
7607    Some(match kind {
7608        Kind::Strong => InlineKind::Strong,
7609        Kind::Emph => InlineKind::Emph,
7610        Kind::Verbatim => InlineKind::Verbatim,
7611        Kind::Mark => InlineKind::Mark,
7612        Kind::Superscript => InlineKind::Superscript,
7613        Kind::Subscript => InlineKind::Subscript,
7614        Kind::Insert => InlineKind::Insert,
7615        Kind::Delete => InlineKind::Delete,
7616        _ => return None,
7617    })
7618}
7619
7620/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
7621/// a highlight's opening `==`.
7622///
7623/// Two enums for one closed vocabulary, and the duplication is the boundary
7624/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
7625/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
7626/// the editor writes. Spelled as a match rather than routed through the two
7627/// crates' name strings so that a colour added on either side is a compile
7628/// error here, where the pairing is decided, rather than a runtime `None` that
7629/// would read as "clear the colour".
7630fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
7631    match color {
7632        MarkColor::Red => twig::MarkColor::Red,
7633        MarkColor::Orange => twig::MarkColor::Orange,
7634        MarkColor::Yellow => twig::MarkColor::Yellow,
7635        MarkColor::Green => twig::MarkColor::Green,
7636        MarkColor::Blue => twig::MarkColor::Blue,
7637        MarkColor::Purple => twig::MarkColor::Purple,
7638        MarkColor::Brown => twig::MarkColor::Brown,
7639    }
7640}
7641
7642/// Where an offset lands after a splice it didn't make — twig's own rule, from
7643/// [`Change`]: shift anything at or past the replaced range's end by the length
7644/// the replacement gained or lost, and leave anything before it alone.
7645///
7646/// An offset *inside* the replaced range has no text of its own to ride any
7647/// more, and lands at the end of what replaced it: for
7648/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
7649/// the prefix is cleared, which then sits where the highlighted text begins.
7650/// One node's attribute list, twig's own `(key, value)` pairs owned — what
7651/// every presentation gesture reads, edits one key of, and passes back whole.
7652type Attrs = Vec<(String, Option<String>)>;
7653
7654/// The name of the leaf directive a page break is — [`Doc::insert_page_break`]
7655/// writes it and the walker draws it, and a frontend that paginates matches a
7656/// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) against it. One spelling,
7657/// stated once.
7658pub const PAGE_BREAK: &str = "page-break";
7659
7660/// `attrs` with `key` set to `value`, or removed when `value` is `None`, and
7661/// every other attribute kept in its place — the read-edit-write half of twig's
7662/// replace-not-merge contract for a `data-` key.
7663///
7664/// **A key that is already there is rewritten where it stands**, and only a key
7665/// the node did not have goes on the end. That is what makes the proposal's
7666/// worked example true: `class="lead center" id="intro"
7667/// data-line-height="1.5"`, right-aligned, is `class="lead right" id="intro"
7668/// data-line-height="1.5"` — the same document with one token changed, and a
7669/// one-line diff. Removing the key and pushing it back would reorder the
7670/// author's attributes on every press, so a document that passed through the
7671/// editor came out shuffled even where nothing about it had changed.
7672///
7673/// A duplicate key — which no format leaf opens can spell, but twig reports
7674/// verbatim — collapses onto the first of its copies, since twig is handed one
7675/// value for one key either way.
7676fn with_attr(attrs: &[(String, Option<String>)], key: &str, value: Option<&str>) -> Attrs {
7677    let mut out: Attrs = Vec::with_capacity(attrs.len() + 1);
7678    let mut written = false;
7679    for (k, v) in attrs {
7680        if k != key {
7681            out.push((k.clone(), v.clone()));
7682            continue;
7683        }
7684        if let Some(new) = value.filter(|_| !written) {
7685            out.push((k.clone(), Some(new.to_string())));
7686            written = true;
7687        }
7688    }
7689    if let Some(new) = value.filter(|_| !written) {
7690        out.push((key.to_string(), Some(new.to_string())));
7691    }
7692    out
7693}
7694
7695/// [`with_attr`] for a `class` token: every token `mine` claims is removed, and
7696/// `token` added, with the rest of the list kept in order.
7697///
7698/// `class` is a space-separated token list, and leaf owns three of the tokens in
7699/// it. A paragraph that arrives as `class="lead center"` and is right-aligned
7700/// goes out as `class="lead right"`; one whose last owned token goes and which
7701/// carried nothing else loses the key, so a block that has lost its whole
7702/// vocabulary is spelled bare again. `class` itself keeps its place among the
7703/// attributes, because [`with_attr`] does the writing.
7704fn with_class_token(
7705    attrs: &[(String, Option<String>)],
7706    mine: impl Fn(&str) -> bool,
7707    token: Option<&str>,
7708) -> Attrs {
7709    let kept: Vec<&str> = attrs
7710        .iter()
7711        .find(|(k, _)| k == "class")
7712        .and_then(|(_, v)| v.as_deref())
7713        .unwrap_or_default()
7714        .split_whitespace()
7715        .filter(|t| !mine(t))
7716        .collect();
7717    let class = kept.into_iter().chain(token).collect::<Vec<_>>().join(" ");
7718    with_attr(
7719        attrs,
7720        "class",
7721        (!class.is_empty()).then_some(class.as_str()),
7722    )
7723}
7724
7725/// An owned attribute list as the borrowed pairs twig's two attribute ops take.
7726///
7727/// A **bare** attribute — one twig reports with no value, such as HTML's `<p
7728/// hidden>` — is passed back as an empty one. Twig refuses a `None` outright
7729/// (djot has no bare attribute, so no format reads one back everywhere), and
7730/// `hidden=""` is the same document where `hidden` is; dropping it instead
7731/// would lose what the author wrote, which is the one thing these gestures
7732/// promise not to do.
7733fn attr_pairs(attrs: &[(String, Option<String>)]) -> Vec<(&str, Option<&str>)> {
7734    attrs
7735        .iter()
7736        .map(|(k, v)| (k.as_str(), Some(v.as_deref().unwrap_or_default())))
7737        .collect()
7738}
7739
7740fn reanchor(off: usize, change: &Change) -> usize {
7741    if off < change.old.start {
7742        return off;
7743    }
7744    if off < change.old.end {
7745        return change.new.end;
7746    }
7747    (off + change.new.end).saturating_sub(change.old.end)
7748}
7749
7750/// [`reanchor`] for an edit that respells the markup *around* a block and
7751/// leaves the block's own bytes alone — which is every attribute gesture.
7752///
7753/// `block` is that block's content span before and after the splice, so an
7754/// offset standing in the text keeps its distance from the text's start and how
7755/// many bytes twig wrote above it never enters the arithmetic. That is the whole
7756/// rule, and it is why nothing here knows how long a `<div …>` is: a second key
7757/// on the same div lengthens the attribute line, clearing the last one takes the
7758/// div away entirely, and both are the same sum. `None` where the splice named
7759/// no block at either end, which is every djot case — the `{…}` line is written
7760/// above the block, and the block itself only shifts past it.
7761///
7762/// Anywhere else it is `reanchor`'s own answer: untouched before the splice,
7763/// shifted by its delta after it, and at the splice's end for an offset that
7764/// stood in markup being rewritten — a caret inside djot's `{…}` line has no
7765/// text to keep.
7766fn reanchor_in_block(
7767    off: usize,
7768    change: &Change,
7769    block: Option<(&Range<usize>, &Range<usize>)>,
7770) -> usize {
7771    if let Some((was, now)) = block
7772        && was.start <= off
7773        && off <= was.end
7774    {
7775        return now.start + (off - was.start).min(now.end - now.start);
7776    }
7777    reanchor(off, change)
7778}
7779
7780/// A watermark for a file's contents (see `Doc::disk_hash`).
7781///
7782/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
7783/// watermark is compared only against one taken by the same process moments
7784/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
7785/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
7786fn hash_bytes(bytes: &[u8]) -> u64 {
7787    use std::hash::{Hash, Hasher};
7788    let mut h = std::collections::hash_map::DefaultHasher::new();
7789    bytes.hash(&mut h);
7790    h.finish()
7791}
7792
7793#[cfg(feature = "fs")]
7794fn detect_format(path: &Path) -> Result<Format> {
7795    let ext = path
7796        .extension()
7797        .and_then(|e| e.to_str())
7798        .unwrap_or("")
7799        .to_ascii_lowercase();
7800    Ok(match ext.as_str() {
7801        "dj" | "djot" => Format::Djot,
7802        "md" | "markdown" => Format::Markdown,
7803        "xml" => Format::Xml,
7804        "html" | "htm" => Format::Html,
7805        other => return Err(anyhow!("unknown document extension: .{other}")),
7806    })
7807}
7808
7809#[cfg(test)]
7810mod tests {
7811    use super::*;
7812
7813    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
7814    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
7815    /// without one is a view no user is ever in.
7816    fn doc_in(view: View, name: &str, body: &str) -> Doc {
7817        // The fixture name doubles as the temp file's, so two tests picking the
7818        // same one raced under the parallel runner and read each other's body —
7819        // a green suite proving the wrong thing. The counter makes that
7820        // unreachable rather than asking every future caller to notice.
7821        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7822        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7823        let mut p = std::env::temp_dir();
7824        p.push(format!("leaf_test_{name}_{seq}.md"));
7825        std::fs::write(&p, body).unwrap();
7826        let mut d = Doc::open(p).unwrap();
7827        d.view = view;
7828        if view == View::Wysiwyg {
7829            d.build_visual(80);
7830        }
7831        d
7832    }
7833
7834    // Source-view document for the source-behaviour tests. `Doc::open` now
7835    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
7836    // `wysiwyg_doc` builds the rich-text variant on top of this.
7837    fn doc_with(name: &str, body: &str) -> Doc {
7838        doc_in(View::Source, name, body)
7839    }
7840
7841    /// Every visual row's drawn text — what the reader actually sees, which is
7842    /// the only thing the reveal preference is supposed to change.
7843    fn drawn_rows(d: &Doc) -> Vec<String> {
7844        d.vmap
7845            .rows
7846            .iter()
7847            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7848            .collect()
7849    }
7850
7851    /// Put the caret at the first byte of `needle` and rebuild, so the row under
7852    /// it becomes the revealed line.
7853    fn caret_at(d: &mut Doc, needle: &str) {
7854        d.caret = d.source.find(needle).expect("needle in source");
7855        d.build_visual(80);
7856    }
7857
7858    #[test]
7859    fn blockquote_after_a_list_is_not_bulleted() {
7860        // twig nests a following top-level block quote under the `bullet_list`
7861        // (a direct child, not a `list_item`). The map must render it de-nested —
7862        // `│ quote`, never `• │ quote` — with a blank separator, like any block
7863        // that follows a list. Regression for the "combined list + blockquote" bug.
7864        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
7865        d.build_visual(80);
7866        let rows: Vec<String> = d
7867            .vmap
7868            .rows
7869            .iter()
7870            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
7871            .collect();
7872        assert!(
7873            rows.iter().any(|r| r == "│ quote"),
7874            "block quote should render on its own gutter, got rows: {rows:?}"
7875        );
7876        assert!(
7877            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
7878            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
7879        );
7880    }
7881
7882    // ── the map is built at most once per (revision, wrap) ───────────────────
7883    //
7884    // A frontend repaints for reasons that have nothing to do with the text — a
7885    // blinking caret, a scroll — and rebuilding the map is O(document). These
7886    // pin *that the cache fires*, which a passing suite can't tell you: a cache
7887    // that never hits is invisible to every other test in this file.
7888    //
7889    // The probe is to wreck the built map and ask for it again. A rebuild
7890    // repairs it; a cache hit hands the wreckage straight back. Nothing else
7891    // can distinguish the two from outside.
7892
7893    #[test]
7894    fn a_rebuild_with_nothing_changed_reuses_the_map() {
7895        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
7896        d.build_visual(80);
7897        assert!(!d.vmap.rows.is_empty());
7898        d.vmap.rows.clear(); // wreck it
7899        d.build_visual(80);
7900        assert!(
7901            d.vmap.rows.is_empty(),
7902            "the map was rebuilt though nothing changed — the cache never fired"
7903        );
7904    }
7905
7906    #[test]
7907    fn an_edit_rebuilds_the_map() {
7908        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
7909        d.build_visual(80);
7910        let before = d.revision();
7911        d.vmap.rows.clear();
7912        d.insert("x");
7913        d.build_visual(80);
7914        assert!(d.revision() > before, "an edit must move the revision");
7915        assert!(
7916            !d.vmap.rows.is_empty(),
7917            "an edited document must not paint from a stale map"
7918        );
7919    }
7920
7921    #[test]
7922    fn a_width_change_rebuilds_the_map() {
7923        // The map is a function of the wrap width too, so a resize is a miss
7924        // even though the text is untouched.
7925        let mut d = doc_in(
7926            View::Wysiwyg,
7927            "cache_width",
7928            "one two three four five six\n",
7929        );
7930        d.build_visual(80);
7931        d.vmap.rows.clear();
7932        d.build_visual(12);
7933        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
7934        // And the unwrapped map is its own key, not the same as any width.
7935        d.vmap.rows.clear();
7936        d.build_visual_unwrapped();
7937        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
7938    }
7939
7940    #[test]
7941    fn a_motion_does_not_rebuild_the_map() {
7942        // The whole point: moving the caret changes nothing the map is built
7943        // from. If a motion bumped the revision, every arrow key would cost a
7944        // full rebuild and the cache would be worthless.
7945        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
7946        d.build_visual(80);
7947        let rev = d.revision();
7948        d.move_right(false);
7949        d.move_right(true);
7950        d.move_down(false);
7951        assert_eq!(d.revision(), rev, "a motion must not move the revision");
7952        d.vmap.rows.clear();
7953        d.build_visual(80);
7954        assert!(
7955            d.vmap.rows.is_empty(),
7956            "a motion should not rebuild the map"
7957        );
7958    }
7959
7960    #[test]
7961    fn saving_does_not_rebuild_the_map() {
7962        // Saving changes `dirty`, not the text.
7963        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
7964        d.insert("x");
7965        d.build_visual(80);
7966        let rev = d.revision();
7967        d.save();
7968        assert_eq!(d.revision(), rev, "a save must not move the revision");
7969        assert!(!d.dirty, "the save should have cleaned the document");
7970    }
7971
7972    #[test]
7973    fn a_reload_rebuilds_the_map() {
7974        // Reload replaces the text without going through `refresh`, so it has to
7975        // move the revision itself — else the editor paints the old file.
7976        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
7977        d.build_visual(80);
7978        let rev = d.revision();
7979        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
7980        d.reload();
7981        assert!(d.revision() > rev, "a reload must move the revision");
7982        d.build_visual(80);
7983        let text: String = d
7984            .vmap
7985            .rows
7986            .iter()
7987            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
7988            .collect();
7989        assert!(
7990            text.contains("wholly new"),
7991            "the reloaded text should be on screen, got {text:?}"
7992        );
7993    }
7994
7995    // ── golden-case harness ──────────────────────────────────────────────────
7996    // The pattern the whole parity suite can reuse: write a fixture with the
7997    // caret marked by `|`, run one action, and compare the rendered result —
7998    // also caret-marked — against the expected string. One readable line per
7999    // behavior, and it exercises the exact `Doc` ops both frontends call.
8000
8001    /// Split a `|`-marked fixture into `(source, caret_offset)`.
8002    fn parse_caret(marked: &str) -> (String, usize) {
8003        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
8004        (marked.replacen('|', "", 1), caret)
8005    }
8006
8007    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
8008    /// selection) so a result reads like the fixtures.
8009    fn render_caret(d: &Doc) -> String {
8010        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
8011        // so the caret always renders inside its own selection.
8012        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
8013        if let Some((s, e)) = d.selection() {
8014            marks.push((s, 0, '['));
8015            marks.push((e, 2, ']'));
8016        }
8017        // Insert right-to-left: descending offset, then descending rank.
8018        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
8019        let mut out = d.source.clone();
8020        for (at, _, ch) in marks {
8021            out.insert(at, ch);
8022        }
8023        out
8024    }
8025
8026    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
8027    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
8028        golden_in(View::Source, name, marked, action)
8029    }
8030
8031    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
8032    /// the same fixture has to read the same way in both.
8033    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
8034        let (src, caret) = parse_caret(marked);
8035        let mut d = doc_in(view, name, &src);
8036        d.caret = caret;
8037        action(&mut d);
8038        render_caret(&d)
8039    }
8040
8041    #[test]
8042    fn word_motion_walks_word_by_word() {
8043        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
8044        assert_eq!(
8045            g("hello wor|ld", |d| d.move_word_left(false)),
8046            "hello |world"
8047        );
8048        assert_eq!(
8049            g("hello| world", |d| d.move_word_left(false)),
8050            "|hello world"
8051        );
8052        assert_eq!(
8053            g("hel|lo world", |d| d.move_word_right(false)),
8054            "hello| world"
8055        );
8056        assert_eq!(
8057            g("hello| world", |d| d.move_word_right(false)),
8058            "hello world|"
8059        );
8060        // Punctuation is its own class, so motion stops at the boundary.
8061        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
8062    }
8063
8064    #[test]
8065    fn word_motion_extends_the_selection_when_asked() {
8066        assert_eq!(
8067            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
8068            "hello [world|]"
8069        );
8070    }
8071
8072    #[test]
8073    fn delete_word_removes_a_whole_word() {
8074        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
8075        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
8076        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
8077        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
8078    }
8079
8080    // ── Home / End ───────────────────────────────────────────────────────────
8081
8082    #[test]
8083    fn home_toggles_between_the_line_s_text_and_its_margin() {
8084        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
8085        // indent to the markup it spells everywhere it means one, so the fixture
8086        // with whitespace left to walk is a code block, which is verbatim.
8087        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
8088        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
8089        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
8090        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
8091        // A line with no indentation has one place to go, so the toggle is a
8092        // no-op rather than a trip to nowhere.
8093        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
8094        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
8095
8096        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
8097        let indent = d.source.find("    indented").unwrap();
8098        d.caret = indent + 6; // inside "indented"
8099        d.move_home(false);
8100        assert_eq!(
8101            d.caret,
8102            indent + 4,
8103            "wysiwyg: Home aims at the code line's text"
8104        );
8105        d.move_home(false);
8106        assert_eq!(
8107            d.caret, indent,
8108            "wysiwyg: the second press takes the indent"
8109        );
8110        d.move_home(false);
8111        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
8112    }
8113
8114    #[test]
8115    fn end_takes_the_line_the_view_is_showing() {
8116        // The line differs by view for the same document, and that is the point:
8117        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
8118        // as a space on one row and the source view as two lines.
8119        let mut d = doc_with("end_src", "one two\nthree\n");
8120        d.caret = 1;
8121        d.move_end(false);
8122        assert_eq!(d.caret, 7, "source: the end of the source line");
8123
8124        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
8125        d.caret = 1;
8126        d.move_end(false);
8127        assert_eq!(
8128            d.caret, 13,
8129            "wysiwyg: the end of the row, soft break and all"
8130        );
8131    }
8132
8133    #[test]
8134    fn home_and_end_extend_the_selection_when_asked() {
8135        for (view, tag) in VIEWS {
8136            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
8137            d.caret = 6;
8138            d.move_end(true);
8139            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
8140            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
8141            d.caret = 6;
8142            d.move_home(true);
8143            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
8144        }
8145    }
8146
8147    // ── kill to the line's start / end ───────────────────────────────────────
8148
8149    #[test]
8150    fn kill_to_the_line_start_and_end_in_both_views() {
8151        for (view, tag) in VIEWS {
8152            // The gap that reads as a paragraph break in each view: the source
8153            // view's lines are the renderer's rows only where the source says so.
8154            let gap = if view == View::Source { "\n" } else { "\n\n" };
8155            let mut d = doc_in(
8156                view,
8157                &format!("kill_end_{tag}"),
8158                &format!("one two{gap}three\n"),
8159            );
8160            d.caret = 3;
8161            d.delete_to_line_end();
8162            assert_eq!(
8163                d.source,
8164                format!("one{gap}three\n"),
8165                "{tag}: ^K to the line's end"
8166            );
8167            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
8168
8169            let mut d = doc_in(
8170                view,
8171                &format!("kill_start_{tag}"),
8172                &format!("one two{gap}three\n"),
8173            );
8174            d.caret = 7; // the end of the first line
8175            d.delete_to_line_start();
8176            assert_eq!(
8177                d.source,
8178                format!("{gap}three\n"),
8179                "{tag}: ⌘⌫ to the line's start"
8180            );
8181            assert_eq!(d.caret, 0, "{tag}");
8182        }
8183    }
8184
8185    #[test]
8186    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
8187        // The decision: at the boundary both kills do nothing, rather than
8188        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
8189        // at a soft wrap as often as at a newline, where there is nothing
8190        // written to delete — and a source newline is only half of the blank
8191        // line between two paragraphs, so taking it leaves a soft break rather
8192        // than the join it looks like. Backspace and Delete are the keys for it.
8193        for (view, tag) in VIEWS {
8194            let gap = if view == View::Source { "\n" } else { "\n\n" };
8195            let src = format!("one{gap}three\n");
8196            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
8197            d.caret = 3; // the end of "one"
8198            d.delete_to_line_end();
8199            assert_eq!(
8200                d.source, src,
8201                "{tag}: ^K at the line's end joined it to the next"
8202            );
8203
8204            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
8205            d.caret = 3 + gap.len(); // the start of "three"
8206            d.delete_to_line_start();
8207            assert_eq!(
8208                d.source, src,
8209                "{tag}: ⌘⌫ at the line's start joined it to the last"
8210            );
8211        }
8212    }
8213
8214    #[test]
8215    fn a_kill_takes_the_selection_when_there_is_one() {
8216        // What every other delete here does with one, so these two as well.
8217        for (view, tag) in VIEWS {
8218            for (name, kill) in [
8219                (
8220                    "end",
8221                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
8222                ),
8223                ("start", |d: &mut Doc| d.delete_to_line_start()),
8224            ] {
8225                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
8226                d.anchor = Some(4);
8227                d.caret = 7; // "two"
8228                kill(&mut d);
8229                assert_eq!(
8230                    d.source, "one  three\n",
8231                    "{tag}: {name} ignored the selection"
8232                );
8233                assert_eq!(d.selection(), None, "{tag}: {name}");
8234            }
8235        }
8236    }
8237
8238    #[test]
8239    fn a_kill_takes_the_markup_it_empties_with_it() {
8240        // The same hazard a word-delete has: a WYSIWYG range covers what the
8241        // user can see, which for `**bold**` is the word and never the
8242        // delimiters, so a kill that stopped at the text would leave `a ****` —
8243        // markup wrapped around nothing.
8244        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
8245        d.caret = d.source.find("bold").unwrap();
8246        d.delete_to_line_end();
8247        assert_eq!(d.source, "a \n");
8248    }
8249
8250    #[test]
8251    fn a_kill_is_undone_in_one_step() {
8252        for (view, tag) in VIEWS {
8253            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
8254            d.caret = 3;
8255            d.delete_to_line_end();
8256            assert_eq!(d.source, "one\n", "{tag}");
8257            d.undo();
8258            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
8259        }
8260    }
8261
8262    #[test]
8263    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
8264        // Regression: triple-click used move_home/move_end over visual rows, so
8265        // it only worked on a paragraph's first row (a wrap-boundary offset maps
8266        // to the earlier row). select_block_at reads the AST, so every offset in
8267        // the paragraph selects the whole thing.
8268        let body = "one two three four five six seven eight\n";
8269        let mut d = doc_with("sel_block", body);
8270        d.view = View::Wysiwyg;
8271        d.build_visual(12); // force the paragraph to wrap into several rows
8272        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
8273        let para = (0, "one two three four five six seven eight".len());
8274        for off in [0usize, 8, 19, 28, 38] {
8275            d.caret = 0;
8276            d.anchor = None;
8277            d.select_block_at(off);
8278            assert_eq!(
8279                d.selection(),
8280                Some(para),
8281                "offset {off} should select the paragraph"
8282            );
8283        }
8284    }
8285
8286    #[test]
8287    fn select_block_uses_content_span_for_a_heading() {
8288        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
8289        d.select_block_at(4); // inside "Title"
8290        // content_span excludes the "# " marker.
8291        assert_eq!(d.selected_text(), Some("Title"));
8292        d.select_block_at(10); // inside "body"
8293        assert_eq!(d.selected_text(), Some("body"));
8294    }
8295
8296    #[test]
8297    fn select_all_spans_the_document() {
8298        let mut d = doc_with("sel_all", "abc\n\ndef\n");
8299        d.select_all();
8300        assert_eq!(d.selection(), Some((0, d.source.len())));
8301    }
8302
8303    #[test]
8304    fn select_word_at_picks_the_surrounding_word() {
8305        let mut d = doc_with("sel_word", "hello world\n");
8306        d.select_word_at(8); // inside "world"
8307        assert_eq!(d.selection(), Some((6, 11)));
8308        // Double-clicking at end-of-word still grabs the word to its left.
8309        d.select_word_at(5); // the space between the words
8310        assert_eq!(d.selection(), Some((5, 6)));
8311    }
8312
8313    #[test]
8314    fn word_helpers_respect_utf8_boundaries() {
8315        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
8316        assert_eq!(
8317            golden("utf8", "|café ok", |d| d.move_word_right(false)),
8318            "café| ok"
8319        );
8320        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
8321    }
8322
8323    #[test]
8324    fn typing_inserts_at_the_caret_and_advances_it() {
8325        let mut d = doc_with("type", "hello\n");
8326        d.insert("Hi ");
8327        assert_eq!(d.source, "Hi hello\n");
8328        assert_eq!(d.caret, 3);
8329        assert!(d.dirty);
8330    }
8331
8332    #[test]
8333    fn backspace_deletes_the_char_before_the_caret() {
8334        let mut d = doc_with("bs", "hello\n");
8335        d.caret = 3; // after "hel"
8336        d.backspace();
8337        assert_eq!(d.source, "helo\n");
8338        assert_eq!(d.caret, 2);
8339    }
8340
8341    #[test]
8342    fn typing_replaces_the_selection() {
8343        let mut d = doc_with("replace", "a word b\n");
8344        d.anchor = Some(2);
8345        d.caret = 6; // "word" selected
8346        d.insert("X");
8347        assert_eq!(d.source, "a X b\n");
8348        assert_eq!(d.caret, 3);
8349        assert_eq!(d.anchor, None);
8350    }
8351
8352    #[test]
8353    fn toggle_bold_wraps_then_unwraps_the_selection() {
8354        let mut d = doc_with("bold", "a word b\n");
8355        d.anchor = Some(2);
8356        d.caret = 6;
8357        d.toggle(InlineKind::Strong);
8358        assert_eq!(d.source, "a **word** b\n");
8359        // The toggled region stays selected, so a second toggle reverses it.
8360        d.toggle(InlineKind::Strong);
8361        assert_eq!(d.source, "a word b\n");
8362        d.toggle(InlineKind::Strong);
8363        assert_eq!(d.source, "a **word** b\n");
8364    }
8365
8366    #[test]
8367    fn toggle_code_wraps_then_unwraps_the_selection() {
8368        let mut d = doc_with("code_rt", "a word b\n");
8369        d.anchor = Some(2);
8370        d.caret = 6;
8371        d.toggle(InlineKind::Verbatim);
8372        assert_eq!(d.source, "a `word` b\n");
8373        d.toggle(InlineKind::Verbatim);
8374        assert_eq!(d.source, "a word b\n");
8375    }
8376
8377    #[test]
8378    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
8379        // ⌘b at a bare caret, then type: the text comes out bold with no
8380        // selection ever made — the word-processor "start bold here" gesture.
8381        let mut d = doc_with("sticky_wrap", "xy\n");
8382        d.caret = 1; // between x and y
8383        d.toggle(InlineKind::Strong);
8384        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
8385        d.insert("A");
8386        assert_eq!(d.source, "x**A**y\n");
8387    }
8388
8389    #[test]
8390    fn sticky_bold_lights_the_toolbar_before_any_typing() {
8391        // The button must light the instant ⌘b is pressed, or the mode is
8392        // invisible until the first character lands.
8393        let mut d = doc_with("sticky_light", "xy\n");
8394        d.caret = 1;
8395        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
8396        d.toggle(InlineKind::Strong);
8397        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8398    }
8399
8400    #[test]
8401    fn sticky_bold_toggled_off_types_normally_again() {
8402        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
8403        // in the flow of typing, the exact sequence the user described.
8404        let mut d = doc_with("sticky_off", "\n");
8405        d.caret = 0;
8406        d.toggle(InlineKind::Strong);
8407        d.insert("a");
8408        d.insert("b"); // continues inside the run, no re-arming
8409        assert_eq!(d.source, "**ab**\n");
8410        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
8411        d.insert("c");
8412        assert_eq!(d.source, "**ab**c\n");
8413    }
8414
8415    #[test]
8416    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
8417        // Once a mark is realised the caret sits inside the run, so plain typing
8418        // extends it rather than starting a second, adjacent bold span.
8419        let mut d = doc_with("sticky_cont", "\n");
8420        d.caret = 0;
8421        d.toggle(InlineKind::Emph);
8422        d.insert("h");
8423        d.insert("i");
8424        assert_eq!(d.source, "*hi*\n");
8425    }
8426
8427    #[test]
8428    fn moving_the_caret_disarms_a_sticky_mark() {
8429        // Arming a mark and then moving away must not style text elsewhere.
8430        let mut d = doc_with("sticky_disarm", "xy\n");
8431        d.caret = 0;
8432        d.toggle(InlineKind::Strong);
8433        d.move_right(false); // caret 0 → 1, disarms
8434        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
8435        d.insert("A");
8436        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
8437    }
8438
8439    #[test]
8440    fn stacked_sticky_marks_apply_together() {
8441        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
8442        let mut d = doc_with("sticky_stack", "\n");
8443        d.caret = 0;
8444        d.toggle(InlineKind::Strong);
8445        d.toggle(InlineKind::Emph);
8446        d.insert("x");
8447        // Land the caret on the styled character and confirm both marks are live.
8448        d.anchor = Some(d.source.find('x').unwrap());
8449        d.caret = d.anchor.unwrap() + 1;
8450        let marks = d.active_inline_marks();
8451        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
8452        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
8453    }
8454
8455    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
8456
8457    #[test]
8458    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
8459        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
8460        // The space inside the run made `**bold **`, which is *not* bold — four
8461        // literal asterisks — so the rich view drew them, correctly and
8462        // uselessly, until the next character happened to close the run again.
8463        let mut d = wysiwyg_doc("edge_typing", "a \n");
8464        d.caret = 2;
8465        d.toggle(InlineKind::Strong);
8466        for c in "bold".chars() {
8467            d.insert(&c.to_string());
8468        }
8469        assert_eq!(d.source, "a **bold**\n");
8470        d.insert(" ");
8471        assert_eq!(
8472            d.source, "a **bold** \n",
8473            "the space belongs outside the run"
8474        );
8475        assert!(
8476            d.active_inline_marks().contains(InlineKind::Strong),
8477            "bold is still what's being typed, so the button stays lit"
8478        );
8479        // What the writer is looking at while all this happens: their words.
8480        d.build_visual(80);
8481        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
8482        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
8483        for c in "hey".chars() {
8484            d.insert(&c.to_string());
8485        }
8486        assert_eq!(
8487            d.source, "a **bold hey**\n",
8488            "one bold phrase, not two runs"
8489        );
8490    }
8491
8492    #[test]
8493    fn typing_past_a_space_can_still_leave_the_bold_behind() {
8494        // The other half: the marks stay armed across the space, so ⌘b turns
8495        // them off again there and the next word is plain — the run isn't
8496        // rejoined by a caret that was told not to.
8497        let mut d = wysiwyg_doc("edge_shed", "\n");
8498        d.caret = 0;
8499        d.toggle(InlineKind::Strong);
8500        for c in "bold ".chars() {
8501            d.insert(&c.to_string());
8502        }
8503        assert_eq!(d.source, "**bold** \n");
8504        d.toggle(InlineKind::Strong);
8505        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
8506        d.insert("x");
8507        assert_eq!(d.source, "**bold** x\n");
8508    }
8509
8510    #[test]
8511    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
8512        // ⌘b and then a space before any word: the space is not marked (nothing
8513        // is), and the word after it is.
8514        let mut d = wysiwyg_doc("edge_space_first", "a\n");
8515        d.caret = 1;
8516        d.toggle(InlineKind::Strong);
8517        d.insert(" ");
8518        assert_eq!(d.source, "a \n");
8519        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8520        d.insert("b");
8521        assert_eq!(d.source, "a **b**\n");
8522    }
8523
8524    #[test]
8525    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
8526        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
8527        d.caret = 8; // the caret's home at the end of the run's text
8528        d.insert(" ");
8529        assert_eq!(
8530            d.source, "x **bold** \n",
8531            "the space lands past the delimiters"
8532        );
8533        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
8534
8535        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
8536        d.caret = 4; // in front of the "b"
8537        d.insert(" ");
8538        assert_eq!(d.source, "x  **bold** y\n");
8539        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
8540    }
8541
8542    #[test]
8543    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
8544        // Backspace over the last letter of a bold phrase.
8545        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
8546        d.caret = 10; // past the "h"
8547        d.backspace();
8548        assert_eq!(d.source, "a **bold** \n");
8549        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
8550        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8551        d.insert("x");
8552        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
8553    }
8554
8555    #[test]
8556    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
8557        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
8558        // mark, which is only text. The marks live on in the caret instead.
8559        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
8560        d.caret = 5;
8561        d.backspace();
8562        assert_eq!(d.source, "a  c\n");
8563        assert!(d.active_inline_marks().contains(InlineKind::Strong));
8564        d.insert("x");
8565        assert_eq!(d.source, "a **x** c\n");
8566    }
8567
8568    #[test]
8569    fn typing_over_a_whole_bold_word_keeps_it_bold() {
8570        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
8571        d.anchor = Some(4);
8572        d.caret = 8; // the word, not its delimiters
8573        d.insert("x");
8574        assert_eq!(d.source, "a **x** c\n");
8575    }
8576
8577    #[test]
8578    fn a_code_span_keeps_the_space_it_is_given() {
8579        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
8580        // is still verbatim, so nothing is re-spelt. The repair asks the parser
8581        // rather than a table of kinds, and this is the answer it gets.
8582        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
8583        d.caret = 7;
8584        d.insert(" ");
8585        assert_eq!(d.source, "a `code ` c\n");
8586    }
8587
8588    #[test]
8589    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
8590        // A run's closing delimiter has a caret home on each side of it, one
8591        // column apart on screen — and a plain ← off the space after a bold word
8592        // lands on the outer one. The character drawn behind the caret there is
8593        // still the last letter of the phrase, so that is what Backspace takes;
8594        // the byte behind it is a `*` nobody can see.
8595        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
8596        d.caret = 9;
8597        d.move_left(false);
8598        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
8599        d.backspace();
8600        assert_eq!(
8601            d.source, "**bol** x\n",
8602            "a letter of the phrase, not its `*`"
8603        );
8604        assert_eq!(d.caret, 5);
8605
8606        // And the mirror in front of the opening delimiter, where Delete's
8607        // character is the first letter of the run.
8608        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
8609        d.caret = 1;
8610        d.delete_forward();
8611        assert_eq!(d.source, "x**old**\n");
8612        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
8613    }
8614
8615    #[test]
8616    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
8617        // The byte beside the caret at either edge of a bold word is a `*` the
8618        // rich view draws nothing for. Taking it is not the character delete the
8619        // key was pressed for — it unspells the run and puts a literal asterisk
8620        // on screen (`a *bold** c`). The visible character is the one that goes.
8621        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
8622        d.caret = 4; // in front of the "b"
8623        d.backspace();
8624        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
8625
8626        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
8627        d.caret = 8; // past the "d"
8628        d.delete_forward();
8629        assert_eq!(d.source, "a **bold**c\n");
8630        assert_eq!(d.caret, 8, "and the caret stays inside the run");
8631        d.insert("x");
8632        assert_eq!(d.source, "a **boldx**c\n");
8633
8634        // A code span's backticks are hidden the same way, so they are covered
8635        // by the same rule and not by a list of kinds.
8636        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
8637        d.caret = 3;
8638        d.backspace();
8639        assert_eq!(d.source, "a`code` c\n");
8640    }
8641
8642    #[test]
8643    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
8644        // The asterisks are on the screen there and the caret can stand between
8645        // them, so a delete takes exactly the byte it is aimed at.
8646        let mut d = doc_with("edge_open_src", "a **bold** c\n");
8647        d.caret = 4;
8648        d.backspace();
8649        assert_eq!(d.source, "a *bold** c\n");
8650
8651        let mut d = doc_with("edge_close_src", "a **bold** c\n");
8652        d.caret = 8;
8653        d.delete_forward();
8654        assert_eq!(d.source, "a **bold* c\n");
8655    }
8656
8657    #[test]
8658    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
8659        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
8660        // The space had stepped outside the run (the mark-edge rule), taking the
8661        // caret with it, so the delete put it back down on the far side of the
8662        // closing `**` — one place on screen, and the wrong side of it. Typing
8663        // came out plain and the toolbar went dark, with nothing to see.
8664        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
8665        d.caret = 0;
8666        d.toggle(InlineKind::Strong);
8667        for c in "bold".chars() {
8668            d.insert(&c.to_string());
8669        }
8670        d.insert(" ");
8671        assert_eq!(d.source, "**bold** \n");
8672        d.backspace();
8673        assert_eq!(
8674            d.source, "**bold**\n",
8675            "the space goes, the delimiters stay"
8676        );
8677        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
8678        assert!(
8679            d.active_inline_marks().contains(InlineKind::Strong),
8680            "so the button is still lit"
8681        );
8682        d.insert("x");
8683        assert_eq!(
8684            d.source, "**boldx**\n",
8685            "and the next character is still bold"
8686        );
8687    }
8688
8689    #[test]
8690    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
8691        // What the stranded caret did next: the byte behind it was the closing
8692        // `*`, so a second press took that instead of a letter — `**bold*`, the
8693        // styling gone and an asterisk on the screen where the word had been.
8694        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
8695        d.caret = 0;
8696        d.toggle(InlineKind::Strong);
8697        for c in "bold ".chars() {
8698            d.insert(&c.to_string());
8699        }
8700        assert_eq!(d.source, "**bold** \n");
8701        d.backspace();
8702        d.backspace();
8703        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
8704        assert_eq!(d.caret, 5);
8705    }
8706
8707    #[test]
8708    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
8709        // `***both***` closes two runs with one stack of asterisks: the caret has
8710        // to walk in through all of them, or it lands between the emph and the
8711        // strong and types half-marked.
8712        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
8713        d.caret = 11;
8714        d.backspace();
8715        assert_eq!(d.source, "***both***\n");
8716        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
8717        d.insert("x");
8718        assert_eq!(d.source, "***bothx***\n");
8719    }
8720
8721    #[test]
8722    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
8723        // The settle only moves a caret a run actually closed over. Ordinary
8724        // deletes — inside a run, or in plain prose — are untouched.
8725        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
8726        d.caret = 8;
8727        d.backspace();
8728        assert_eq!(d.source, "a **bol** c\n");
8729        assert_eq!(d.caret, 7);
8730
8731        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
8732        d.caret = 5;
8733        d.backspace();
8734        assert_eq!(d.source, "plai\n");
8735        assert_eq!(d.caret, 4);
8736    }
8737
8738    #[test]
8739    fn the_source_view_leaves_a_delete_where_it_landed() {
8740        // The delimiters are on the screen there, so the offset past them is a
8741        // place the caret can be seen to be — nothing to settle.
8742        let mut d = doc_with("edge_bksp_src", "**bold** \n");
8743        d.caret = 9;
8744        d.backspace();
8745        assert_eq!(d.source, "**bold**\n");
8746        assert_eq!(d.caret, 8);
8747    }
8748
8749    #[test]
8750    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
8751        // `***both***` closes two runs with one stack of asterisks; a space that
8752        // clears only the inner one lands against the outer's and breaks that
8753        // instead.
8754        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
8755        d.caret = 9;
8756        d.insert(" ");
8757        assert_eq!(d.source, "a ***both*** \n");
8758        assert_eq!(d.caret, 13);
8759        d.insert("x");
8760        assert_eq!(d.source, "a ***both x***\n");
8761    }
8762
8763    #[test]
8764    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
8765        // The delimiter shuffle is not an edit the writer made, so it is not a
8766        // step they have to undo past.
8767        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
8768        d.caret = 8;
8769        d.insert(" ");
8770        assert_eq!(d.source, "a **bold** \n");
8771        d.undo();
8772        assert_eq!(d.source, "a **bold**\n");
8773    }
8774
8775    #[test]
8776    fn the_source_view_types_the_space_where_it_was_asked_to() {
8777        // The rule is a rich-view courtesy. In the source view the delimiters are
8778        // on the screen and the user is editing the bytes they can see.
8779        let mut d = doc_with("edge_src", "a **bold** c\n");
8780        d.caret = 8;
8781        d.insert(" ");
8782        assert_eq!(d.source, "a **bold ** c\n");
8783    }
8784
8785    #[test]
8786    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
8787        // Double-clicking a word takes the space after it; bolding that must not
8788        // spell `**word **`, which is not bold at all.
8789        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
8790        d.anchor = Some(2);
8791        d.caret = 7; // "word "
8792        d.toggle(InlineKind::Strong);
8793        assert_eq!(d.source, "a **word** b\n");
8794        d.toggle(InlineKind::Strong);
8795        assert_eq!(d.source, "a word b\n");
8796        d.toggle(InlineKind::Strong);
8797        assert_eq!(
8798            d.source, "a **word** b\n",
8799            "reapplying the mark must not wrap stale delimiter offsets"
8800        );
8801        // And a selection of nothing but whitespace has no word to mark.
8802        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
8803        d.anchor = Some(6);
8804        d.caret = 7;
8805        d.toggle(InlineKind::Strong);
8806        assert_eq!(d.source, "a word b\n");
8807        assert!(d.status.is_some());
8808    }
8809
8810    #[test]
8811    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
8812        let mut d = doc_with("head_set", "hello\n");
8813        d.caret = 2; // caret inside the paragraph, no selection
8814        d.set_block(BlockKind::Heading(1));
8815        assert_eq!(d.source, "# hello\n");
8816    }
8817
8818    #[test]
8819    fn set_block_heading_works_in_wysiwyg_view() {
8820        // The app defaults to WYSIWYG; the caret is a source offset either way.
8821        let mut d = wysiwyg_doc("head_wys", "hello\n");
8822        d.caret = 2;
8823        d.set_block(BlockKind::Heading(1));
8824        assert_eq!(d.source, "# hello\n");
8825    }
8826
8827    #[test]
8828    fn toggle_heading_applies_switches_and_reverts() {
8829        let mut d = doc_with("head_toggle", "hello\n");
8830        d.caret = 2;
8831        d.toggle_heading(1);
8832        assert_eq!(d.source, "# hello\n"); // paragraph → H1
8833        d.toggle_heading(2);
8834        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
8835        d.toggle_heading(2);
8836        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
8837    }
8838
8839    #[test]
8840    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
8841        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
8842        // the blank line but the caret rendered on the *next* line, because the
8843        // separator was a non-navigable decoration row. In Preserve flow that
8844        // blank line is a real caret home — the caret must resolve onto it, and
8845        // typing there makes the soft break that continues the paragraph.
8846        let src = "line one:\nsecond line\n";
8847        let mut d = wysiwyg_doc("pre_enter_lineend", src);
8848        d.set_line_flow(LineFlow::Preserve);
8849        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
8850        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
8851        d.newline();
8852        d.build_visual_unwrapped();
8853        assert_eq!(d.source, "line one:\n\nsecond line\n");
8854        assert_eq!(
8855            d.caret, 10,
8856            "caret sits on the new blank line, not the next line"
8857        );
8858        // The blank line is row 1, and the caret resolves onto it — not row 2.
8859        assert_eq!(
8860            d.vmap.pos_of_offset(10),
8861            (1, 0),
8862            "caret renders on the blank row"
8863        );
8864        assert!(
8865            !d.vmap.rows[1].decoration,
8866            "the blank line is navigable in Preserve"
8867        );
8868        // Typing there makes a soft break: one paragraph, three lines.
8869        d.insert("new clause,");
8870        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
8871    }
8872
8873    #[test]
8874    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
8875        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
8876        // that keeps it one paragraph — where Fold would open a second paragraph.
8877        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
8878        d.set_line_flow(LineFlow::Preserve);
8879        d.caret = 3;
8880        d.newline();
8881        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
8882
8883        // End-of-paragraph: Enter then typing continues the same paragraph on a
8884        // new line (a soft break), not a fresh paragraph.
8885        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
8886        d.set_line_flow(LineFlow::Preserve);
8887        d.caret = 3;
8888        d.newline();
8889        d.insert("def");
8890        assert_eq!(
8891            d.source, "abc\ndef\n",
8892            "end-of-line Enter + typing is a soft break"
8893        );
8894    }
8895
8896    #[test]
8897    fn preserve_double_enter_still_makes_a_paragraph() {
8898        // Two Enters in a row promote to a real paragraph break: the second lands
8899        // on the blank line the first opened and takes the empty-line branch.
8900        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
8901        d.set_line_flow(LineFlow::Preserve);
8902        d.caret = 3;
8903        d.newline();
8904        d.newline();
8905        d.insert("def");
8906        assert_eq!(
8907            d.source, "abc\n\ndef\n",
8908            "double Enter is a paragraph break"
8909        );
8910    }
8911
8912    #[test]
8913    fn preserve_backspace_joins_across_a_soft_break() {
8914        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
8915        // soft break it deletes the single newline and joins the two lines.
8916        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
8917        d.set_line_flow(LineFlow::Preserve);
8918        d.build_visual(80);
8919        d.caret = 4; // start of "def", just past the soft break
8920        d.backspace();
8921        assert_eq!(
8922            d.source, "abcdef\n",
8923            "Backspace joins across the soft break"
8924        );
8925        assert_eq!(d.caret, 3, "caret lands where the lines meet");
8926    }
8927
8928    #[test]
8929    fn fold_enter_still_starts_a_new_paragraph() {
8930        // The default flow is unchanged: a lone `\n` would render as an invisible
8931        // space, so Enter keeps opening the paragraph break that actually shows.
8932        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
8933        d.caret = 3;
8934        d.newline();
8935        assert_eq!(
8936            d.source, "abc\n\ndef\n",
8937            "Fold mid-line Enter is a paragraph break"
8938        );
8939    }
8940
8941    #[test]
8942    fn wysiwyg_one_enter_starts_a_new_paragraph() {
8943        // Regression: one Enter left the caret between the two newlines, so typing
8944        // made a soft break (one paragraph) and you needed a second Enter.
8945        let mut d = wysiwyg_doc("wys_enter", "abc\n");
8946        d.caret = 3;
8947        d.newline();
8948        d.insert("def");
8949        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
8950    }
8951
8952    #[test]
8953    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
8954        // Regression: Enter at the caret's natural End-of-line resting place
8955        // after a bold run with nothing following it (on screen: right after
8956        // "bold", before the hidden closing "**") spliced the paragraph break
8957        // at that very byte offset — which sits *before* the closing "**" in
8958        // the source, since the delimiter is hidden and emits no glyph of its
8959        // own for `push_row`'s "end of row" fallback to count. That severed the
8960        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
8961        // "**" alone on the new line instead of leaving "**bold**" intact with
8962        // a fresh empty paragraph after it.
8963        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
8964        d.move_end(false); // the WYSIWYG End key, from caret 0
8965        assert_eq!(
8966            d.caret, 6,
8967            "caret rests right after \"bold\", before the hidden \"**\""
8968        );
8969        d.newline();
8970        assert!(
8971            d.source.starts_with("**bold**"),
8972            "the closing ** must stay attached to \"bold\": got {:?}",
8973            d.source
8974        );
8975        assert_eq!(
8976            d.source, "**bold**\n\n\n",
8977            "a fresh empty paragraph follows the still-intact bold run"
8978        );
8979    }
8980
8981    #[test]
8982    fn source_view_enter_is_a_single_newline() {
8983        let mut d = doc_with("src_enter", "abc\n");
8984        d.caret = 3;
8985        d.newline();
8986        assert_eq!(d.source, "abc\n\n");
8987    }
8988
8989    #[test]
8990    fn heading_applies_at_the_end_of_a_paragraph() {
8991        // The caret at a line end sits at the doc level; set_block must still find
8992        // the block on that line.
8993        let mut d = doc_with("head_end", "abc\n");
8994        d.caret = 3; // end of "abc"
8995        d.toggle_heading(1);
8996        assert_eq!(d.source, "# abc\n");
8997    }
8998
8999    #[test]
9000    fn heading_on_an_empty_new_paragraph_creates_one() {
9001        let mut d = wysiwyg_doc("head_empty", "abc\n");
9002        d.caret = 3;
9003        d.newline(); // caret now on a fresh, empty paragraph
9004        d.toggle_heading(1);
9005        d.insert("Title");
9006        assert!(d.source.contains("# Title"), "got {:?}", d.source);
9007    }
9008
9009    #[test]
9010    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
9011        // The reported bug, end to end: click a blank line with another one under
9012        // it, press H1, type. The text landed in the heading and the caret's
9013        // offset was right (the source view drew it there), but the rich view
9014        // drew it two rows lower, on the trailing blank line — the empty `# `
9015        // heading had left every row below it short by the marker's two bytes,
9016        // and the blank line ended up claiming the heading's own end offset.
9017        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
9018        d.build_visual_unwrapped();
9019        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
9020        d.toggle_heading(1);
9021        for c in "title".chars() {
9022            d.insert(&c.to_string());
9023            d.build_visual_unwrapped(); // as a frontend does, one frame per key
9024        }
9025        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
9026        assert_eq!(
9027            d.caret_pos(),
9028            (4, 5),
9029            "the caret draws at the end of the heading"
9030        );
9031    }
9032
9033    #[test]
9034    fn clicking_an_empty_heading_types_after_its_marker() {
9035        // The same anchor from the other side: the empty heading's row is its own
9036        // caret home, so a click on it must land past the hidden `# `. Landing in
9037        // front of the hashes made the first keystroke un-heading the line.
9038        let mut d = wysiwyg_doc("head_click", "# \n");
9039        d.build_visual_unwrapped();
9040        d.caret = d.vmap.offset_of_pos(0, 0);
9041        d.insert("x");
9042        assert_eq!(d.source, "# x\n");
9043    }
9044
9045    #[test]
9046    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
9047        let mut d = wysiwyg_doc("head_enter", "# Title\n");
9048        d.caret = 7; // end of the heading
9049        d.newline();
9050        d.insert("body");
9051        assert_eq!(d.source, "# Title\n\nbody\n");
9052    }
9053
9054    #[test]
9055    fn wysiwyg_enter_continues_a_bullet_list() {
9056        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
9057        d.caret = 6; // end of "item"
9058        d.newline();
9059        d.insert("two");
9060        assert_eq!(d.source, "- item\n- two\n");
9061    }
9062
9063    #[test]
9064    fn wysiwyg_enter_increments_an_ordered_list() {
9065        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
9066        d.caret = 6; // end of "one"
9067        d.newline();
9068        d.insert("two");
9069        assert_eq!(d.source, "1. one\n2. two\n");
9070    }
9071
9072    #[test]
9073    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
9074        // Regression for the "extra newline" left between a list and the paragraph
9075        // below it. Enter, Enter leaves the list on a fresh empty paragraph
9076        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
9077        // Backspace should then take the caret cleanly back to the end of the list
9078        // item, `- item\n\nnext`, not delete a single newline and strand it on the
9079        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
9080        // no caret can land on. The map is rebuilt between keystrokes exactly as a
9081        // frontend does, since Backspace reads the stop table to place the delete.
9082        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
9083        d.caret = 6; // end of "item"
9084        d.newline();
9085        d.build_visual(80);
9086        d.newline(); // leave the list onto a fresh empty paragraph
9087        d.build_visual(80);
9088        assert_eq!(
9089            d.source, "- item\n\n\n\nnext\n",
9090            "double-Enter opens the empty paragraph"
9091        );
9092        d.backspace();
9093        assert_eq!(
9094            d.source, "- item\n\nnext\n",
9095            "one Backspace collapses the whole gap"
9096        );
9097        assert_eq!(
9098            d.caret, 6,
9099            "and lands the caret back at the end of the list item"
9100        );
9101    }
9102
9103    #[test]
9104    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
9105        // The stop-wise delete must not over-reach when there is no block boundary
9106        // to cross: two blank lines in a row are one caret stop apart, so pressing
9107        // Enter on an empty line and then Backspace removes exactly the one newline
9108        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
9109        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
9110        d.caret = 5; // the empty paragraph the first Enter already opened
9111        d.build_visual(80);
9112        d.newline();
9113        d.build_visual(80);
9114        assert_eq!(
9115            d.source, "abc\n\n\n\n",
9116            "Enter on the blank line adds one newline"
9117        );
9118        d.backspace();
9119        assert_eq!(
9120            d.source, "abc\n\n\n",
9121            "Backspace takes back exactly that one newline"
9122        );
9123    }
9124
9125    #[test]
9126    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
9127        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
9128        d.caret = 6; // end of the empty "- " item
9129        d.newline();
9130        d.insert("p");
9131        assert_eq!(d.source, "- a\n\np\n");
9132    }
9133
9134    #[test]
9135    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
9136        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
9137        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
9138        // not take the list-exit path (which would splice the `- ` away as if
9139        // leaving an empty item); the AST guard sends it to a normal break and
9140        // leaves the underline intact.
9141        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
9142        assert!(
9143            d.nodes().iter().any(|n| n.kind == Kind::Heading),
9144            "precondition: twig parses this as a heading, not a list",
9145        );
9146        d.caret = 7; // on the `- ` underline line
9147        d.newline();
9148        assert!(
9149            d.source.contains("- "),
9150            "the setext underline survives, not spliced away as a list item: {:?}",
9151            d.source,
9152        );
9153    }
9154
9155    #[test]
9156    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
9157        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
9158        d.caret = 7; // end of "abc" inside the fence
9159        d.newline();
9160        d.insert("def");
9161        assert_eq!(d.source, "```\nabc\ndef\n```\n");
9162    }
9163
9164    #[test]
9165    fn wysiwyg_enter_continues_a_block_quote() {
9166        // Enter opens a new *paragraph* inside the quote, not a second line of
9167        // the same one. `> quote\n> more` is a soft break, which under
9168        // `LineFlow::Fold` renders as a space — the keystroke would look like it
9169        // did nothing. The quoted blank line is what makes the break visible, and
9170        // it's the same thing Enter does in running prose.
9171        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
9172        d.caret = 7; // end of "quote"
9173        d.newline();
9174        d.insert("more");
9175        assert_eq!(d.source, "> quote\n>\n> more\n");
9176        // Still one quote, now holding two paragraphs — not a quote and a stray
9177        // line that fell out of it.
9178        let quotes = d
9179            .nodes()
9180            .iter()
9181            .filter(|n| n.kind == Kind::BlockQuote)
9182            .count();
9183        assert_eq!(quotes, 1);
9184    }
9185
9186    #[test]
9187    fn set_block_makes_a_heading_at_the_caret() {
9188        let mut d = doc_with("head", "Title\n\nbody\n");
9189        d.caret = 0;
9190        d.set_block(BlockKind::Heading(2));
9191        assert_eq!(d.source, "## Title\n\nbody\n");
9192        d.set_block(BlockKind::Paragraph);
9193        assert_eq!(d.source, "Title\n\nbody\n");
9194    }
9195
9196    // ── block containers (quote / list) ──────────────────────────────────────
9197
9198    #[test]
9199    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
9200        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
9201        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
9202        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
9203        // A caret at a line end sits at the doc level; the block is still found.
9204        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
9205    }
9206
9207    #[test]
9208    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
9209        // Every source line of the paragraph gets its own `> `, so a caret left
9210        // on its old byte offset falls one prefix per line above it too far
9211        // back — inside the markup it just asked for rather than in its word.
9212        assert_eq!(
9213            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
9214            "> aaa\n> b|bb\n> ccc\n"
9215        );
9216    }
9217
9218    #[test]
9219    fn toggle_blockquote_works_in_wysiwyg_view() {
9220        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
9221        assert_eq!(
9222            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
9223            "> hel|lo\n"
9224        );
9225        assert_eq!(
9226            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
9227            "hel|lo\n"
9228        );
9229    }
9230
9231    #[test]
9232    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
9233        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
9234        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
9235        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
9236        // The *other* kind converts in place instead of nesting, which is what
9237        // makes the two buttons one three-state control.
9238        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
9239        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
9240        // Its own kind, over the only item the list holds, takes it off.
9241        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
9242    }
9243
9244    #[test]
9245    fn toggle_list_works_in_wysiwyg_view() {
9246        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
9247        assert_eq!(
9248            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
9249            "1. hel|lo\n"
9250        );
9251        assert_eq!(
9252            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
9253            "- hel|lo\n"
9254        );
9255        assert_eq!(
9256            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
9257            "hel|lo\n"
9258        );
9259    }
9260
9261    #[test]
9262    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
9263        // The selection has to grow with the markup: twig takes a container off
9264        // only a range covering every block it holds, so the second press can
9265        // reverse the first only if the result is what's selected.
9266        let mut d = doc_with("list_sel", "abc\n\ndef\n");
9267        d.select_all();
9268        d.toggle_list(true);
9269        assert_eq!(d.source, "1. abc\n\n2. def\n");
9270        assert_eq!(d.selection(), Some((0, d.source.len())));
9271        d.toggle_list(true);
9272        assert_eq!(d.source, "abc\n\ndef\n");
9273    }
9274
9275    #[test]
9276    fn toggle_blockquote_nests_a_partly_covered_quote() {
9277        // twig's rule: covering only some of a container's blocks nests, because
9278        // taking the quote off would drag its uncovered siblings out with it.
9279        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
9280        d.caret = 2; // in the first quoted paragraph only
9281        d.toggle_blockquote();
9282        assert_eq!(d.source, "> > a\n>\n> b\n");
9283    }
9284
9285    #[test]
9286    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
9287        // A blank line used to be no block for twig to wrap —
9288        // `toggle_block_container` answered `NotFound` — so Quote and the list
9289        // buttons did nothing on the very line the H1 button works on, and leaf
9290        // lent twig a scratch paragraph to wrap and took it back out again.
9291        // twig 3.2.0 opens an empty container there itself, so what is left here
9292        // is where the caret lands: inside the marker that was just written.
9293        let mut d = doc_with("quote_blank", "\nabc\n");
9294        d.caret = 0;
9295        d.toggle_blockquote();
9296        assert_eq!(d.source, "> \nabc\n");
9297        assert_eq!(
9298            d.caret, 2,
9299            "the caret belongs inside the quote it just opened"
9300        );
9301        assert!(d.status.is_none(), "{:?}", d.status);
9302        assert!(d.dirty);
9303
9304        // And the paragraph below is still its own block: an empty container one
9305        // soft break from `abc` would take that paragraph into the quote with it.
9306        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
9307        d.caret = 0;
9308        d.toggle_blockquote();
9309        d.build_visual(80);
9310        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
9311
9312        // The same from the other side: a blank line directly under a paragraph
9313        // earns the blank line an empty block needs, rather than being read as a
9314        // soft break inside that paragraph.
9315        let mut d = doc_with("list_blank_below", "abc\n");
9316        d.caret = 4;
9317        d.toggle_list(false);
9318        assert_eq!(d.source, "abc\n\n- ");
9319        assert_eq!(d.caret, 7);
9320    }
9321
9322    #[test]
9323    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
9324        // The gesture the rendering fix is for. `newline` inside a quote already
9325        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
9326        // spelling — but the two marker lines it adds belonged to no node until
9327        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
9328        // just made drew as plain prose under the quote.
9329        let mut d = wysiwyg_doc("quote_enter", "> a\n");
9330        d.caret = 3; // past `a`, at the end of the quoted line
9331        d.newline();
9332        assert_eq!(d.source, "> a\n>\n> \n");
9333        d.build_visual(80);
9334        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
9335        // And the caret is on the new line, not stranded on the old one.
9336        assert_eq!(d.caret, 8);
9337    }
9338
9339    #[test]
9340    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
9341        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
9342        // now it is twig's single edit. Either way one ⌘z has to put the blank
9343        // line back rather than undoing into a half-built document.
9344        for open in [
9345            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
9346            &|d: &mut Doc| d.toggle_list(false),
9347            &|d: &mut Doc| d.toggle_list(true),
9348        ] {
9349            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
9350            d.caret = 3;
9351            open(&mut d);
9352            assert_ne!(d.source, "a\n\n\n\nb\n");
9353            d.undo();
9354            assert_eq!(d.source, "a\n\n\n\nb\n");
9355        }
9356    }
9357
9358    #[test]
9359    fn a_container_toggle_is_one_undo_step() {
9360        let mut d = doc_with("quote_undo", "hello\n");
9361        d.caret = 3;
9362        d.insert("X"); // a typing run the structural edit must not fold into
9363        d.toggle_blockquote();
9364        assert_eq!(d.source, "> helXlo\n");
9365        d.undo();
9366        assert_eq!(d.source, "helXlo\n");
9367    }
9368
9369    // ── links ────────────────────────────────────────────────────────────────
9370
9371    #[test]
9372    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
9373        let mut d = doc_with("link_sel", "word here\n");
9374        d.anchor = Some(0);
9375        d.caret = 4;
9376        d.insert_link("http://x.dev");
9377        assert_eq!(d.source, "[word](http://x.dev) here\n");
9378        // The text, not the destination — so a second press re-points the link
9379        // the first one made rather than nesting one inside it.
9380        assert_eq!(d.selected_text(), Some("word"));
9381        d.insert_link("http://y.dev");
9382        assert_eq!(d.source, "[word](http://y.dev) here\n");
9383        assert_eq!(d.selected_text(), Some("word"));
9384    }
9385
9386    #[test]
9387    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
9388        let mut d = doc_with("img_caret", "before after\n");
9389        d.caret = 7; // between "before " and "after"
9390        d.insert_image("cat.png", "a cat");
9391        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
9392        // The caret sits just past the inserted image, nothing selected.
9393        assert_eq!(d.selection(), None);
9394        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
9395    }
9396
9397    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
9398    /// destination at the first space, so the `format!` this used to be wrote
9399    /// something that was not an image at all — and the reader saw the markup as
9400    /// text. twig owns the spelling now, and moves it into the angle form.
9401    #[test]
9402    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
9403        let mut d = doc_with("img_space", "x\n");
9404        d.caret = 0;
9405        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
9406        assert_eq!(
9407            d.source,
9408            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
9409        );
9410        // And it reads back as an image pointing at the unescaped path — the angle
9411        // brackets are spelling, not part of the destination.
9412        d.caret = 2;
9413        assert_eq!(
9414            d.image_destination_at_caret(),
9415            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
9416        );
9417    }
9418
9419    /// A `)` in a caption or a filename must not close the image early.
9420    #[test]
9421    fn insert_image_escapes_a_paren_in_either_half() {
9422        let mut d = doc_with("img_paren", "x\n");
9423        d.caret = 0;
9424        d.insert_image("a)b.png", "");
9425        assert_eq!(d.source, "![](a\\)b.png)x\n");
9426        d.caret = 2;
9427        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
9428    }
9429
9430    #[test]
9431    fn insert_image_uses_the_selection_as_alt_text() {
9432        let mut d = doc_with("img_sel", "caption here\n");
9433        d.anchor = Some(0);
9434        d.caret = 7; // "caption"
9435        d.insert_image("p.png", "ignored fallback");
9436        assert_eq!(d.source, "![caption](p.png) here\n");
9437    }
9438
9439    #[test]
9440    fn insert_image_with_no_alt_leaves_empty_brackets() {
9441        let mut d = doc_with("img_noalt", "\n");
9442        d.caret = 0;
9443        d.insert_image("logo.svg", "");
9444        assert_eq!(d.source, "![](logo.svg)\n");
9445    }
9446
9447    #[test]
9448    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
9449        // The round trip is the point: it's no use writing markup the reader
9450        // can't pick up again. This is the pair that only holds from twig 2.5.1
9451        // on — before it, the one-line form went in fine and came back as a
9452        // paragraph of raw tags, publishing no media at all.
9453        let mut d = doc_with("vid_rt", "\n");
9454        d.caret = 0;
9455        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
9456        assert_eq!(
9457            d.source,
9458            "<video src=\"clip.mp4\" controls>a clip</video>\n"
9459        );
9460
9461        d.build_visual(80);
9462        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
9463        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
9464        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
9465        assert_eq!(d.vmap.media[0].alt, "a clip");
9466    }
9467
9468    #[test]
9469    fn insert_media_spells_audio_with_its_own_tag() {
9470        let mut d = doc_with("aud_rt", "\n");
9471        d.caret = 0;
9472        d.insert_media(MediaKind::Audio, "take.mp3", "");
9473        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
9474        d.build_visual(80);
9475        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
9476    }
9477
9478    #[test]
9479    fn insert_media_uses_the_selection_as_fallback_text() {
9480        // The same courtesy `insert_image` does with alt: select a caption,
9481        // insert, and the caption labels the thing rather than being replaced.
9482        let mut d = doc_with("vid_sel", "the talk here\n");
9483        d.anchor = Some(0);
9484        d.caret = 8; // "the talk"
9485        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
9486        assert_eq!(
9487            d.source,
9488            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
9489        );
9490    }
9491
9492    #[test]
9493    fn insert_media_with_an_image_kind_is_just_insert_image() {
9494        let mut d = doc_with("img_via_media", "\n");
9495        d.caret = 0;
9496        d.insert_media(MediaKind::Image, "logo.svg", "x");
9497        assert_eq!(d.source, "![x](logo.svg)\n");
9498    }
9499
9500    // ── thematic breaks ─────────────────────────────────────────────────────
9501
9502    /// The node the source parses as at `caret` — what confirms an inserted
9503    /// `---` actually reads back as a rule, not stray text or a setext heading.
9504    ///
9505    /// The *narrowest* node covering the offset. Every ancestor covers it too,
9506    /// and since twig 2.8 that includes the `doc` root, which now carries a real
9507    /// span (it reported none before, so taking the first match used to land on
9508    /// the block by luck and now always answers `"doc"`).
9509    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
9510        d.nodes()
9511            .into_iter()
9512            .filter(|n| n.span.start <= caret && caret < n.span.end)
9513            .min_by_key(|n| n.span.end - n.span.start)
9514            .map(|n| n.kind)
9515    }
9516
9517    #[test]
9518    fn a_task_box_toggles_at_the_caret_and_reads_back() {
9519        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
9520        d.caret = 8; // inside "todo"
9521        assert_eq!(d.task_checked_at_caret(), Some(false));
9522        d.toggle_task_checked();
9523        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
9524        assert_eq!(d.task_checked_at_caret(), Some(true));
9525        d.toggle_task_checked();
9526        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
9527    }
9528
9529    #[test]
9530    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
9531        // The whole reason `toggle_task_at` exists apart from the caret form:
9532        // ticking a box elsewhere must not move the cursor out of what's being
9533        // typed.
9534        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
9535        d.caret = 8; // inside "first"
9536        let second = d.source.find("second").unwrap();
9537        d.toggle_task_at(second);
9538        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
9539        assert_eq!(d.caret, 8, "the caret stayed in the first item");
9540    }
9541
9542    #[test]
9543    fn a_plain_item_gains_and_loses_a_box() {
9544        let mut d = doc_with("task_mint", "- plain\n");
9545        d.caret = 4;
9546        assert_eq!(d.task_checked_at_caret(), None);
9547        d.toggle_task_item();
9548        assert_eq!(d.source, "- [ ] plain\n");
9549        assert_eq!(
9550            d.task_checked_at_caret(),
9551            Some(false),
9552            "a new box arrives unticked"
9553        );
9554        d.toggle_task_item();
9555        assert_eq!(d.source, "- plain\n");
9556    }
9557
9558    #[test]
9559    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
9560        // `set checked` must not silently convert a bullet into a task — that is
9561        // `toggle_task_item`'s job, and twig refuses it here.
9562        let mut d = doc_with("task_none", "- plain\n");
9563        d.caret = 4;
9564        d.toggle_task_checked();
9565        assert_eq!(d.source, "- plain\n", "nothing written");
9566        assert!(
9567            d.status.is_some(),
9568            "the refusal should reach the status line"
9569        );
9570    }
9571
9572    #[test]
9573    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
9574        let mut d = doc_with("task_quote", "> - [ ] nested\n");
9575        d.caret = d.source.find("nested").unwrap();
9576        assert_eq!(d.task_checked_at_caret(), Some(false));
9577        d.toggle_task_checked();
9578        assert_eq!(d.source, "> - [x] nested\n");
9579    }
9580
9581    #[test]
9582    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
9583        // A rule is a block, so twig's `insert_thematic_break` alone lands it
9584        // after the whole paragraph. `split_block` parts the paragraph first and
9585        // the rule is aimed at the *first* half, which is what a rule button is
9586        // understood to do — and what leaf spelled by hand until twig grew both
9587        // halves of the gesture.
9588        let mut d = doc_with("hr_mid", "before after\n");
9589        d.caret = 7; // between "before " and "after"
9590        d.insert_thematic_break();
9591        assert_eq!(d.source, "before \n\n---\n\nafter\n");
9592        assert_eq!(d.selection(), None);
9593        assert_eq!(
9594            kind_at(&mut d, "before \n\n".len()),
9595            Some(Kind::ThematicBreak)
9596        );
9597    }
9598
9599    #[test]
9600    fn insert_thematic_break_at_a_paragraph_s_end_splits_nothing() {
9601        // At the end there is nothing to part, and a split there writes the
9602        // separator anyway — a blank line and the empty slot the next paragraph
9603        // would fill — which the rule then landed above: `para\n\n* * *\n\n\n`,
9604        // two blank lines nothing fills. Now the rule lands after the paragraph,
9605        // where the split-and-aim was sending it regardless. Both formats, and
9606        // both shapes of a last line — terminated, and still being typed —
9607        // because the two reach the split through different doors: Markdown's
9608        // paragraph span stops before its newline, so `para\n` at 4 never split
9609        // there, but `para` at 4 did.
9610        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
9611            for src in ["para\n", "para"] {
9612                let mut d = Doc::from_source(src.into(), fmt).unwrap();
9613                d.caret = 4;
9614                d.insert_thematic_break();
9615                assert_eq!(d.source, format!("para\n\n{rule}\n"), "{fmt:?} {src:?}");
9616                assert_eq!(d.caret, d.source.len());
9617            }
9618            // Mid-document the slot sat between the rule and the next block.
9619            let mut d = Doc::from_source("para\n\nnext\n".into(), fmt).unwrap();
9620            d.caret = 4;
9621            d.insert_thematic_break();
9622            assert_eq!(d.source, format!("para\n\n{rule}\n\nnext\n"), "{fmt:?}");
9623            // Trailing whitespace is nothing to part either.
9624            let mut d = Doc::from_source("para  \n".into(), fmt).unwrap();
9625            d.caret = 4;
9626            d.insert_thematic_break();
9627            assert_eq!(d.source, format!("para  \n\n{rule}\n"), "{fmt:?}");
9628        }
9629    }
9630
9631    #[test]
9632    fn insert_thematic_break_at_a_paragraph_s_start_lands_before_it() {
9633        // The split at the start parts nothing, but it is kept on purpose:
9634        // `|para` becomes `\npara` with the caret on a blank line, and twig
9635        // (3.5.2) writes a rule aimed at a blank line ON that line — the only
9636        // way "before the paragraph" is reachable through a gesture that only
9637        // places after. Before 3.5.2 this came out as `\n\n---\n\npara`.
9638        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
9639            let mut d = Doc::from_source("para\n".into(), fmt).unwrap();
9640            d.caret = 0;
9641            d.insert_thematic_break();
9642            assert_eq!(d.source, format!("{rule}\n\npara\n"), "{fmt:?}");
9643            let mut d = Doc::from_source("prev\n\npara\n".into(), fmt).unwrap();
9644            d.caret = 6;
9645            d.insert_thematic_break();
9646            assert_eq!(d.source, format!("prev\n\n{rule}\n\npara\n"), "{fmt:?}");
9647        }
9648    }
9649
9650    #[test]
9651    fn insert_thematic_break_on_a_blank_line_takes_that_line() {
9652        // The gap between two blocks is where a click lands the caret; the
9653        // rule goes on the blank, one blank each side.
9654        let mut d = doc_with("hr_gap", "a\n\nb\n");
9655        d.caret = 2;
9656        d.insert_thematic_break();
9657        assert_eq!(d.source, "a\n\n---\n\nb\n");
9658    }
9659
9660    #[test]
9661    fn insert_table_at_a_paragraph_s_end_splits_nothing() {
9662        // The same door as the rule's, through the placement they share.
9663        let mut d = Doc::from_source("para\n".into(), Format::Djot).unwrap();
9664        d.caret = 4;
9665        d.insert_table(1, 1);
9666        assert_eq!(d.source, "para\n\n|  |\n|---|\n|  |\n");
9667        let mut d = doc_with("table_end_typed", "para");
9668        d.caret = 4;
9669        d.insert_table(1, 1);
9670        assert_eq!(d.source, "para\n\n|  |\n| --- |\n|  |\n");
9671        assert!(d.caret_in_table());
9672    }
9673
9674    #[test]
9675    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
9676        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
9677        // and leaf wrote the first into both until twig started spelling it.
9678        let mut md = doc_with("hr_md", "para\n");
9679        md.caret = 2;
9680        md.insert_thematic_break();
9681        assert_eq!(md.source, "pa\n\n---\n\nra\n");
9682
9683        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
9684        dj.caret = 2;
9685        dj.insert_thematic_break();
9686        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
9687    }
9688
9689    #[test]
9690    fn insert_table_parts_the_paragraph_and_lands_in_the_first_header_cell() {
9691        // The table goes *at* the caret the way the rule does: the paragraph is
9692        // parted first, and twig writes the grid after its first half. The
9693        // caret then sits in the first header cell — selected, as Tab would
9694        // leave it — so the next keystroke is the heading.
9695        let mut d = doc_with("table_mid", "before after\n");
9696        d.caret = 7;
9697        d.insert_table(2, 3);
9698        assert_eq!(
9699            d.source,
9700            "before \n\n|  |  |  |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |\n\nafter\n"
9701        );
9702        assert!(d.caret_in_table());
9703        let first_bar = d.source.find('|').unwrap();
9704        assert!(
9705            d.caret > first_bar && d.caret < d.source.find("| ---").unwrap(),
9706            "caret {} is not in the header row",
9707            d.caret
9708        );
9709        d.insert("Name");
9710        assert!(d.source.starts_with("before \n\n| Name |  |  |\n"));
9711        // And the grid the table was written into is one the table keys walk
9712        // (over the map a frontend rebuilds after every edit).
9713        d.build_visual(80);
9714        assert!(d.cell_tab(true));
9715        d.insert("Qty");
9716        assert!(d.source.starts_with("before \n\n| Name | Qty |  |\n"));
9717    }
9718
9719    #[test]
9720    fn insert_table_spells_the_grid_the_format_s_own_way() {
9721        // Djot's delimiter row is unpadded, and leaf never has to know that.
9722        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
9723        dj.caret = 2;
9724        dj.insert_table(1, 2);
9725        assert_eq!(dj.source, "pa\n\n|  |  |\n|---|---|\n|  |  |\n\nra\n");
9726        assert!(dj.caret_in_table());
9727    }
9728
9729    #[test]
9730    fn insert_table_refuses_where_the_format_spells_no_table() {
9731        let mut d = Doc::from_source("<p>ab</p>\n".into(), Format::Html).unwrap();
9732        d.caret = 4;
9733        d.insert_table(1, 1);
9734        assert_eq!(d.source, "<p>ab</p>\n");
9735        assert!(d.status.as_deref().unwrap_or("").contains("not supported"));
9736        assert!(!d.capabilities().table);
9737    }
9738
9739    #[test]
9740    fn insert_table_reports_a_zero_shape_and_writes_nothing() {
9741        let mut d = doc_with("table_zero", "para\n");
9742        d.caret = 2;
9743        d.insert_table(0, 2);
9744        assert_eq!(d.source, "para\n");
9745        assert!(d.status.as_deref().unwrap_or("").starts_with("table:"));
9746    }
9747
9748    #[test]
9749    fn clicking_below_a_final_thematic_break_can_type_after_it() {
9750        let mut d = wysiwyg_doc("hr_final_click", "---\n");
9751        d.build_visual(80);
9752        d.click(d.vmap.num_rows() + 2, 0, false);
9753        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
9754        d.insert("after");
9755        assert_eq!(d.source, "---\nafter");
9756    }
9757
9758    #[test]
9759    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
9760        // The same bytes are two documents. In Markdown `  - b` is a nested item
9761        // and the next one belongs beside it, at its indent. In Djot a list
9762        // marker can't interrupt a paragraph, so those bytes are literal text in
9763        // item `a` and there is only one item — writing `  - ` under it would add
9764        // no item at all, just more text, and the new sibling has to go to
9765        // column zero. Both spellings come out of the *enclosing item's* line.
9766        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
9767        md.caret = "- a\n  - b".len();
9768        md.newline();
9769        assert_eq!(md.source, "- a\n  - b\n  - \n");
9770        assert_eq!(list_items(&mut md), 3);
9771
9772        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
9773        dj.view = View::Wysiwyg;
9774        dj.build_visual(80);
9775        dj.caret = "- a\n  - b".len();
9776        dj.newline();
9777        assert_eq!(dj.source, "- a\n  - b\n- \n");
9778        assert_eq!(list_items(&mut dj), 2);
9779
9780        // Where Djot's nesting is real — opened by a blank line — the indent is
9781        // reproduced there too, and the two formats agree again.
9782        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
9783        dj.view = View::Wysiwyg;
9784        dj.build_visual(80);
9785        dj.caret = "- a\n\n  - b".len();
9786        dj.newline();
9787        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
9788        assert_eq!(list_items(&mut dj), 3);
9789    }
9790
9791    #[test]
9792    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
9793        // Tab replaces the line's whole prefix with the one twig spells, so the
9794        // quote markers, the parent's indent and an ordered marker's extra
9795        // column are all its answer rather than leaf's arithmetic.
9796        for (name, body, caret, want) in [
9797            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
9798            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
9799            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
9800            // A checkbox is markup the item's own text wraps past, but a nested
9801            // list may only open at the *list* marker's column — four in from
9802            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
9803            // parses as one item, not two.
9804            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
9805            (
9806                "quoted task",
9807                "> - [ ] a\n> - [ ] b\n",
9808                18,
9809                "> - [ ] a\n>   - [ ] b\n",
9810            ),
9811        ] {
9812            let mut doc = wysiwyg_doc(name, body);
9813            doc.caret = caret;
9814            doc.indent();
9815            assert_eq!(doc.source, want, "{name}");
9816            // The nesting is real, not just indented text.
9817            assert_eq!(list_items(&mut doc), 2, "{name}");
9818        }
9819    }
9820
9821    #[test]
9822    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
9823        // The same bytes, the two formats disagreeing, and a gesture that used
9824        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
9825        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
9826        // so those bytes are literal text inside item `a` — there is nothing to
9827        // outdent, and treating them as a marker turned one item into two, a
9828        // structural edit from a keystroke that should delete one character.
9829        //
9830        // twig's `line_prefix` is what tells them apart: it reports the marker
9831        // on the Markdown line and nothing on the Djot one, which is a
9832        // continuation. No byte scan can reach that answer.
9833        let src = "- a\n  - b\n";
9834        let at = "- a\n  - ".len();
9835
9836        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
9837        md.view = View::Wysiwyg;
9838        md.build_visual(80);
9839        md.caret = at;
9840        md.backspace();
9841        assert_eq!(md.source, "- a\n- b\n");
9842        assert_eq!(list_items(&mut md), 2);
9843
9844        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
9845        dj.view = View::Wysiwyg;
9846        dj.build_visual(80);
9847        dj.caret = at;
9848        dj.backspace();
9849        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
9850        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
9851    }
9852
9853    #[test]
9854    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
9855        // Leaf used to spell the next item from the marker bytes it scanned, and
9856        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
9857        // and dropped out of the checklist. twig reproduces the whole
9858        // continuation, and a fresh item is always unticked however the one above
9859        // it stands.
9860        for (name, body, want) in [
9861            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
9862            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
9863        ] {
9864            let mut doc = wysiwyg_doc(name, body);
9865            doc.caret = body.trim_end_matches('\n').len();
9866            doc.newline();
9867            assert_eq!(doc.source, want, "{name}");
9868            // Both items are checklist items — the new one is a box, not the
9869            // plain bullet the old marker scan left behind — and it is unticked
9870            // whichever way the one above it faces.
9871            let boxes: Vec<Option<bool>> = doc
9872                .nodes()
9873                .iter()
9874                .filter(|n| n.kind == Kind::TaskListItem)
9875                .map(|n| n.checked)
9876                .collect();
9877            assert_eq!(boxes.len(), 2, "{name}");
9878            assert_eq!(boxes[1], Some(false), "{name}");
9879        }
9880    }
9881
9882    #[test]
9883    fn a_split_takes_the_space_the_caret_was_in_front_of() {
9884        // Splicing a break at the caret strands the space the words were parted
9885        // at on the head of the second block, where it reads as an indent nobody
9886        // typed. twig's split consumes it.
9887        for (name, body, caret, want) in [
9888            ("para", "one two\n", 3, "one\n\ntwo\n"),
9889            ("item", "- one two\n", 5, "- one\n- two\n"),
9890            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
9891            // A heading takes leaf's own path, which has to match.
9892            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
9893        ] {
9894            let mut doc = wysiwyg_doc(name, body);
9895            doc.caret = caret;
9896            doc.newline();
9897            assert_eq!(doc.source, want, "{name}");
9898        }
9899    }
9900
9901    #[test]
9902    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
9903        // The one place leaf keeps its own break: `split_block` repeats the `#`,
9904        // and Enter after a title is how the body under it is asked for.
9905        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
9906        doc.caret = "# Title".len();
9907        doc.newline();
9908        doc.insert("body");
9909        assert_eq!(doc.source, "# Title\n\nbody\n");
9910        assert_eq!(
9911            doc.nodes()
9912                .iter()
9913                .filter(|n| n.kind == Kind::Heading)
9914                .count(),
9915            1
9916        );
9917    }
9918
9919    #[test]
9920    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
9921        // A quoted item's marker doesn't open its line, so a scan that starts at
9922        // column zero finds a `>` where it wanted a bullet, calls the line "not a
9923        // list" and hands Enter to the plain-quote branch — which writes `> ` and
9924        // drops the list. The next item has to carry the whole prefix.
9925        for (name, body, want) in [
9926            ("flat", "> - a\n", "> - a\n> - \n"),
9927            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
9928            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
9929            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
9930            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
9931        ] {
9932            let mut doc = wysiwyg_doc(name, body);
9933            doc.caret = body.trim_end_matches('\n').len();
9934            doc.newline();
9935            assert_eq!(doc.source, want, "{name}");
9936            // The marker isn't just spelled right, it parses as an item.
9937            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
9938        }
9939    }
9940
9941    #[test]
9942    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
9943        // Double-Enter exits the list. Unquoted that means a blank line, but a
9944        // *bare* blank line would end the quote too and drop the caret out of it,
9945        // so the separator keeps its `>` and the caret's line keeps its `> `.
9946        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
9947        doc.caret = "> - a\n> - ".len();
9948        doc.newline();
9949        assert_eq!(doc.source, "> - a\n>\n> \n");
9950        assert_eq!(list_items(&mut doc), 1);
9951        // What "still in the quote" means for the next keystroke: the caret sits
9952        // behind the prefix, and what's typed there lands inside the quote as a
9953        // paragraph of its own — not as more of item `a`.
9954        doc.insert("x");
9955        assert_eq!(doc.source, "> - a\n>\n> x\n");
9956        assert!(
9957            doc.editor
9958                .ancestors_at(doc.caret - 1)
9959                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
9960        );
9961    }
9962
9963    #[test]
9964    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
9965        // The marker is hidden block markup, so Backspace over it is structural —
9966        // but only the marker is the list's. Splicing from the line start would
9967        // take the `>` with it and silently unquote the line.
9968        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
9969        doc.caret = "> - ".len();
9970        doc.backspace();
9971        assert_eq!(doc.source, "> a\n");
9972        assert_eq!(list_items(&mut doc), 0);
9973
9974        // A nested one outdents instead, moving the bullet within the quote
9975        // rather than moving the quote.
9976        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
9977        doc.caret = "> - a\n>   - ".len();
9978        doc.backspace();
9979        assert_eq!(doc.source, "> - a\n> - b\n");
9980        assert_eq!(list_items(&mut doc), 2);
9981    }
9982
9983    #[test]
9984    fn only_a_bare_paragraph_is_parted_around_the_caret() {
9985        // The split is deliberately narrow. Parting a fenced block would leave
9986        // two fences with a rule between them, and parting a list item would
9987        // mint an item nobody asked for on the way to a rule that lands after
9988        // the list either way — so both keep the whole block intact and take the
9989        // rule after it. A caret in a quote is likewise left alone.
9990        for (name, body, caret, want) in [
9991            (
9992                "code",
9993                "```\nfn x() {}\n```\n",
9994                8,
9995                "```\nfn x() {}\n```\n\n---\n",
9996            ),
9997            ("list", "- one two\n", 6, "- one two\n\n---\n"),
9998            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n"),
9999        ] {
10000            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
10001            d.caret = caret;
10002            d.insert_thematic_break();
10003            assert_eq!(d.source, want, "{name}: the block should stay whole");
10004        }
10005    }
10006
10007    #[test]
10008    fn insert_thematic_break_replaces_the_selection() {
10009        // Now that the rule lands *at* the caret again, replacing the selection
10010        // is coherent once more: the text goes, and the rule takes its place.
10011        // The space the deletion left leading the second half is consumed by the
10012        // split rather than opening the new paragraph with it.
10013        let mut d = doc_with("hr_sel", "one two three\n");
10014        d.anchor = Some(4);
10015        d.caret = 7; // "two"
10016        d.insert_thematic_break();
10017        assert_eq!(d.source, "one \n\n---\n\nthree\n");
10018        assert_eq!(d.selection(), None);
10019    }
10020
10021    #[test]
10022    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
10023        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
10024        // because writing `---` into one is code, not a rule — twig now walks out
10025        // to the block that owns the caret's line, so there is nothing to refuse.
10026        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
10027        code.caret = 5; // inside the fenced code
10028        code.insert_thematic_break();
10029        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n");
10030        assert_eq!(code.status, None, "no refusal to report any more");
10031
10032        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
10033        table.caret = 3; // in the header row
10034        table.insert_thematic_break();
10035        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n");
10036    }
10037
10038    #[test]
10039    fn insert_thematic_break_in_a_list_item_ends_the_list() {
10040        // The un-indented rule cannot continue the list, so it closes the list
10041        // and lands at the top level rather than nested inside it.
10042        let mut d = doc_with("hr_list", "- one\n- two\n");
10043        d.caret = "- one\n- tw".len(); // mid "two"
10044        d.insert_thematic_break();
10045        d.build_visual(80);
10046        let rule_at = d.source.find("---").unwrap();
10047        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
10048        assert!(
10049            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
10050                && n.span.start <= rule_at
10051                && rule_at < n.span.end),
10052            "the rule must not be nested inside the list"
10053        );
10054    }
10055
10056    #[test]
10057    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
10058        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
10059        // which is the document the gesture was actually asked for.
10060        let mut d = doc_with("hr_quote", "> hello\n");
10061        d.caret = 4; // inside the quoted text
10062        d.insert_thematic_break();
10063        assert_eq!(d.source, "> hello\n>\n> ---\n");
10064        d.build_visual(80);
10065        let rule_at = d.source.find("---").unwrap();
10066        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
10067        assert!(
10068            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
10069                && n.span.start <= rule_at
10070                && rule_at < n.span.end),
10071            "the rule belongs to the quote it was asked for"
10072        );
10073    }
10074
10075    // ── typing against a block picture ────────────────────────────────────────
10076
10077    /// A rendered-view document with the caret parked on one of the picture's two
10078    /// stops, and the map already built — the state a frontend is in between
10079    /// drawing a frame and the next keystroke.
10080    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
10081        let mut d = doc_in(View::Wysiwyg, name, src);
10082        d.build_visual_unwrapped();
10083        let start = src.find("![").unwrap();
10084        d.caret = match side {
10085            MediaStop::Before => start,
10086            MediaStop::After => start + "![](p.png)".len(),
10087        };
10088        d
10089    }
10090
10091    /// The block media the map publishes, after rebuilding it — "is this still a
10092    /// picture, or has it become a line of text with an image in it?"
10093    fn media_count(d: &mut Doc) -> usize {
10094        d.build_visual_unwrapped();
10095        d.vmap.media.len()
10096    }
10097
10098    #[test]
10099    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
10100        // The accident this prevents: tap the blank page under a photo (which
10101        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
10102        // paragraph with an *inline* image — the photo stops being drawn.
10103        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
10104        d.insert("xy");
10105        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
10106        assert_eq!(media_count(&mut d), 1, "still a picture");
10107    }
10108
10109    #[test]
10110    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
10111        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
10112        d.insert("xy");
10113        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
10114        assert_eq!(media_count(&mut d), 1);
10115    }
10116
10117    #[test]
10118    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
10119        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
10120        d.insert("x");
10121        assert_eq!(d.source, "x\n\n![](p.png)\n");
10122        assert_eq!(media_count(&mut d), 1);
10123    }
10124
10125    #[test]
10126    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
10127        // The opened paragraph is part of the keystroke, not an edit the writer
10128        // made — so it undoes with the character, not a step later.
10129        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
10130        d.insert("x");
10131        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
10132        d.undo();
10133        assert_eq!(d.source, "hi\n\n![](p.png)\n");
10134    }
10135
10136    #[test]
10137    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
10138        // ⌘V dissolves the picture exactly as a keystroke does.
10139        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
10140        d.paste("pasted");
10141        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
10142        assert_eq!(media_count(&mut d), 1);
10143    }
10144
10145    #[test]
10146    fn typing_beside_an_inline_image_is_ordinary_editing() {
10147        // An inline image has no placeholder row and no stops of its own. Opening
10148        // a paragraph mid-sentence would be the bug, not the fix.
10149        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
10150        d.build_visual_unwrapped();
10151        d.caret = "see ![](p.png)".len();
10152        d.insert("!");
10153        assert_eq!(d.source, "see ![](p.png)! here\n");
10154    }
10155
10156    #[test]
10157    fn source_view_types_raw_markup_against_an_image_untouched() {
10158        // Source view is for writing the markup itself; a break inserted behind
10159        // the writer's back there would be the editor arguing with them.
10160        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
10161        d.caret = "![](p.png)".len();
10162        d.insert("x");
10163        assert_eq!(d.source, "![](p.png)x\n");
10164    }
10165
10166    #[test]
10167    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
10168        // A selection is replaced, not joined into, so there is nothing to
10169        // protect: the range takes the picture with it.
10170        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
10171        d.anchor = Some(d.caret);
10172        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
10173        d.insert("x");
10174        assert_eq!(d.source, "hi\n\nx\n");
10175    }
10176
10177    #[test]
10178    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
10179        // What this actually cost: a real vault's photo, to one stray Backspace.
10180        // The caret past `![](p.png)` was deleting the closing paren — invisible
10181        // in the rendered view — and the photo became the text `![](p.png`.
10182        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
10183        d.backspace();
10184        assert_eq!(d.source, "hi\n");
10185        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
10186        d.undo();
10187        assert_eq!(
10188            d.source, "hi\n\n![](p.png)\n",
10189            "and comes back in one piece"
10190        );
10191    }
10192
10193    #[test]
10194    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
10195        // Deleting the break here would join the picture to the paragraph above,
10196        // where it is an *inline* image and stops being drawn. Step over the
10197        // boundary; the next press deletes in the paragraph the caret reached.
10198        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
10199        d.backspace();
10200        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
10201        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
10202        d.backspace();
10203        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
10204        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
10205    }
10206
10207    #[test]
10208    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
10209        // The mirror. A byte-step here eats the `!` and leaves a link.
10210        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
10211        d.delete_forward();
10212        assert_eq!(d.source, "hi\n\nbye\n");
10213        assert_eq!(media_count(&mut d), 0);
10214    }
10215
10216    #[test]
10217    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
10218        let mut d = doc_at_picture(
10219            "pic_del_after",
10220            "hi\n\n![](p.png)\n\nbye\n",
10221            MediaStop::After,
10222        );
10223        d.delete_forward();
10224        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
10225        assert_eq!(
10226            d.caret,
10227            d.source.find("bye").unwrap(),
10228            "the caret stepped down to `bye`"
10229        );
10230    }
10231
10232    #[test]
10233    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
10234        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
10235        d.backspace();
10236        assert_eq!(d.source, "\n");
10237        assert_eq!(media_count(&mut d), 0);
10238    }
10239
10240    #[test]
10241    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
10242        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
10243        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
10244        d.delete_word_back();
10245        assert_eq!(d.source, "hi there\n");
10246
10247        // And in front of one it runs *through* the paragraph break into the
10248        // prose above, which merges the picture inline — so it steps out first,
10249        // and the second press deletes the word it was aimed at.
10250        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
10251        d.delete_word_back();
10252        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
10253        d.delete_word_back();
10254        assert_eq!(
10255            d.source, "hi \n\n![](p.png)\n",
10256            "the word above went, the picture stayed"
10257        );
10258        assert_eq!(media_count(&mut d), 1);
10259    }
10260
10261    #[test]
10262    fn source_view_deletes_raw_markup_against_an_image_untouched() {
10263        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
10264        d.caret = "![](p.png)".len();
10265        d.backspace();
10266        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
10267    }
10268
10269    #[test]
10270    fn image_destination_at_caret_reads_the_image_under_the_caret() {
10271        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
10272        d.caret = 3; // inside the image markup
10273        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
10274        // Past the image, the caret is in no image.
10275        d.caret = "![a cat](cat.png)".len();
10276        assert_eq!(d.image_destination_at_caret(), None);
10277    }
10278
10279    #[test]
10280    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
10281        // The image is one placeholder row by default, and `set_media_rows` grows
10282        // it to the height the frontend measured: the label row plus blank
10283        // `decoration` fillers that hold the vertical space a raster is drawn into.
10284        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
10285        assert_eq!(d.vmap.media.len(), 1);
10286        let img_row = d.vmap.media[0].rows_span.start;
10287        assert_eq!(
10288            d.vmap.media[0].rows_span,
10289            img_row..img_row + 1,
10290            "default is one row"
10291        );
10292
10293        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
10294        d.build_visual(80);
10295        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
10296        let span = d.vmap.media[0].rows_span.clone();
10297        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
10298        // The label row carries the mark and its glyphs; the three below are blank
10299        // decoration — drawn, but no caret and no text.
10300        assert!(
10301            d.vmap.rows[span.start].media.is_some(),
10302            "mark rides the first row"
10303        );
10304        for r in (span.start + 1)..span.end {
10305            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
10306            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
10307            assert!(
10308                d.vmap.rows[r].media.is_none(),
10309                "only the first row is marked"
10310            );
10311        }
10312    }
10313
10314    #[test]
10315    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
10316        // The extra rows are pure spacers: the caret's only homes stay the stop in
10317        // front of the image and the one just past it, so walking the document top
10318        // to bottom visits the same offsets whether the image is 1 row or 5.
10319        let body = "ab\n\n![x](p.png)\n\ncd\n";
10320        let stops_at = |rows: usize| -> Vec<usize> {
10321            let mut d = wysiwyg_doc("img_stops", body);
10322            if rows > 1 {
10323                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
10324                d.build_visual(80);
10325            }
10326            d.caret = 0;
10327            let mut seen = vec![d.caret];
10328            loop {
10329                d.move_right(false);
10330                if *seen.last().unwrap() == d.caret {
10331                    break;
10332                }
10333                seen.push(d.caret);
10334            }
10335            seen
10336        };
10337        assert_eq!(
10338            stops_at(1),
10339            stops_at(5),
10340            "reserving rows must not add stops"
10341        );
10342    }
10343
10344    #[test]
10345    fn insert_link_repoints_the_link_at_a_bare_caret() {
10346        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
10347        d.caret = 3; // in the link's text, nothing selected
10348        d.insert_link("http://y.dev");
10349        assert_eq!(d.source, "[word](http://y.dev)\n");
10350        assert_eq!(d.selected_text(), Some("word"));
10351    }
10352
10353    #[test]
10354    fn insert_link_on_an_empty_range_autolinks_a_url() {
10355        // A link with no text of its own is an autolink, and twig spells it —
10356        // `<…>` is the canonical form and needs no text typed into it, so the
10357        // caret lands after it rather than selecting a finished link.
10358        let mut d = doc_with("link_empty", "\n");
10359        d.caret = 0;
10360        d.insert_link("http://x.dev");
10361        assert_eq!(d.source, "<http://x.dev>\n");
10362        assert_eq!(d.selection(), None);
10363        assert_eq!(d.caret, 14);
10364    }
10365
10366    #[test]
10367    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
10368        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
10369        // in Markdown, so a destination that can't autolink doubles as the text
10370        // instead — which is then selected, ready to be typed over.
10371        let mut d = doc_with("link_rel", "\n");
10372        d.caret = 0;
10373        d.insert_link("./notes.md");
10374        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
10375        assert_eq!(d.selection(), Some((1, 11)));
10376        d.insert("Notes");
10377        assert_eq!(d.source, "[Notes](./notes.md)\n");
10378    }
10379
10380    #[test]
10381    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
10382        // The autolink's text is its URL, so re-pointing replaces the whole
10383        // node — the caret must not splice a second link inside the first.
10384        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
10385        d.caret = 10;
10386        d.insert_link("https://y.dev");
10387        assert_eq!(d.source, "see <https://y.dev> ok\n");
10388    }
10389
10390    #[test]
10391    fn code_language_reads_and_edits_through_the_fence() {
10392        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
10393        d.caret = 10; // inside the code body
10394        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
10395        assert!(d.caret_in_fenced_code());
10396
10397        d.set_code_language("python");
10398        assert!(
10399            d.source.starts_with("```python\n"),
10400            "source: {:?}",
10401            d.source
10402        );
10403        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
10404
10405        // Clearing it leaves a bare fence and no label.
10406        d.set_code_language("");
10407        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
10408        assert_eq!(d.code_language_at_caret(), None);
10409
10410        // A caret outside any code block edits nothing.
10411        let mut p = doc_with("code_lang_none", "just prose\n");
10412        assert!(!p.caret_in_fenced_code());
10413        p.set_code_language("rust");
10414        assert_eq!(p.source, "just prose\n");
10415    }
10416
10417    #[test]
10418    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
10419        // Markdown's info string ends at whitespace, so `two words` would write
10420        // a fence that reads back with a different language than the one asked
10421        // for. twig refuses it; leaf reports that and leaves the source alone.
10422        // The old splice trimmed the ends and wrote whatever was left.
10423        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
10424        d.caret = 10;
10425        d.set_code_language("two words");
10426        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
10427        assert!(d.status.is_some(), "the refusal should be reported");
10428        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
10429    }
10430
10431    #[test]
10432    fn link_destination_at_caret_reads_both_spellings() {
10433        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
10434        d.caret = 5;
10435        assert_eq!(
10436            d.link_destination_at_caret().as_deref(),
10437            Some("https://x.dev")
10438        );
10439        d.caret = 0;
10440        assert_eq!(d.link_destination_at_caret(), None);
10441
10442        // An autolink has no `destination`; its text is the URL.
10443        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
10444        a.caret = 10;
10445        assert_eq!(
10446            a.link_destination_at_caret().as_deref(),
10447            Some("https://x.dev")
10448        );
10449        a.caret = 21;
10450        assert_eq!(a.link_destination_at_caret(), None);
10451    }
10452
10453    #[test]
10454    fn locate_finds_the_block_a_declared_id_names() {
10455        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
10456        // verse. The locator has to land on the *verse*, which is the whole
10457        // reason a link carries one.
10458        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
10459                   {#v2}\nYea, I make a record in the language of my father.\n";
10460        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10461        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
10462        assert_eq!(
10463            d.source[v2.start..v2.end].trim_end(),
10464            "Yea, I make a record in the language of my father."
10465        );
10466        // The attribute line is not part of it: `start` is a place to put a
10467        // caret, and `{#v2}` is markup the caret has no business landing in.
10468        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
10469        assert_eq!(d.locate("v99"), None);
10470    }
10471
10472    #[test]
10473    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
10474        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
10475        // Markdown heading is literal text. So `#the-second-part` can only be
10476        // the heading's own words, which is the rule every Markdown renderer
10477        // already follows and therefore the one a link was authored against.
10478        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
10479        let mut d = doc_with("locate_md", src);
10480        let hit = d.locate("the-second-part").expect("the heading's slug");
10481        assert!(d.source[hit.start..].starts_with("## The Second Part"));
10482        // Bounded by the next heading that isn't under it, so a peek shows the
10483        // section rather than only its title.
10484        assert_eq!(
10485            &d.source[hit.start..hit.end],
10486            "## The Second Part\n\nbody\n\n"
10487        );
10488
10489        // A subsection does not end its parent: `# Title` runs to `## Third`'s
10490        // sibling only because there is no other `#`, so it covers the lot.
10491        let title = d.locate("title").expect("the top heading");
10492        assert_eq!(title.end, d.source.len());
10493    }
10494
10495    #[test]
10496    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
10497        // djot mints `Some-Heading-Here`; a link to it is written
10498        // `#some-heading-here` by nearly everything that writes links. Both
10499        // spellings are one question.
10500        let src = "## Some Heading Here\n\nbody\n";
10501        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10502        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
10503        let slugged = d.locate("some-heading-here").expect("the link's spelling");
10504        assert_eq!(exact, slugged);
10505        // The section, not the heading line — there is more to show than a title.
10506        assert_eq!(&d.source[exact.start..exact.end], src);
10507    }
10508
10509    #[test]
10510    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
10511        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
10512        assert_eq!(d.locate(""), None);
10513        assert_eq!(d.locate("   "), None);
10514        // All punctuation: it names nothing, and must not be read as "match the
10515        // first heading whose slug is also empty".
10516        assert_eq!(d.locate("!!!"), None);
10517    }
10518
10519    #[test]
10520    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
10521        // The document's mistake, and the answer every other anchor
10522        // implementation gives — the alternative is for a link to mean whichever
10523        // of the two a walk happened to reach first.
10524        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
10525        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10526        let hit = d.locate("dup").expect("the first `{#dup}`");
10527        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
10528    }
10529
10530    #[test]
10531    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
10532        // The button's whole job: a reference where the caret was, a definition
10533        // to give it meaning, and the caret waiting in the empty note so the
10534        // next keystroke is the note's first word.
10535        let mut d = doc_with("fn_insert", "A claim and more.\n");
10536        d.caret = 7; // just past "A claim"
10537        d.insert_footnote();
10538        assert!(
10539            d.source.starts_with("A claim[^1] and more."),
10540            "{:?}",
10541            d.source
10542        );
10543        assert!(
10544            d.source.contains("[^1]:"),
10545            "the definition too: {:?}",
10546            d.source
10547        );
10548        assert_eq!(d.status, None);
10549
10550        let reference = d.source.find("[^1]").unwrap();
10551        let note = d
10552            .footnote_at(reference + 2)
10553            .expect("the reference just written");
10554        assert_eq!(note.label, "1");
10555        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
10556        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
10557        // …and typing there is typing into the note, not near it.
10558        d.insert("the note");
10559        assert_eq!(
10560            d.footnote_at(reference + 2).and_then(|f| f.text),
10561            Some("the note".to_string())
10562        );
10563    }
10564
10565    #[test]
10566    fn insert_footnote_numbers_past_the_notes_already_written() {
10567        // A second press must not hand back a label somebody else is using: twig
10568        // reuses a defined label rather than appending a rival definition, so a
10569        // repeat of `1` would quietly point the new reference at the old note.
10570        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
10571        d.caret = 7; // past `[^1]`, before " two."
10572        d.insert_footnote();
10573        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
10574        assert_eq!(d.source.matches("[^2]:").count(), 1);
10575    }
10576
10577    #[test]
10578    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
10579        // `[^2]` with no definition is still a 2 that means something to whoever
10580        // wrote it — stepping over it would mint a note for their reference. A
10581        // word label takes no number, so it blocks none.
10582        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
10583        d.caret = d.source.find(" c").unwrap();
10584        d.insert_footnote();
10585        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
10586        assert!(
10587            d.source.starts_with("a[^2] b[^why][^1] c"),
10588            "{:?}",
10589            d.source
10590        );
10591    }
10592
10593    #[test]
10594    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
10595        // A reference annotates the words before it. Consuming the selection —
10596        // which is what an insert normally does — would delete the very claim
10597        // the author selected in order to footnote.
10598        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
10599        d.anchor = Some(2);
10600        d.caret = 7; // "claim" selected
10601        d.insert_footnote();
10602        assert!(
10603            d.source.starts_with("A claim[^1] and more."),
10604            "{:?}",
10605            d.source
10606        );
10607    }
10608
10609    #[test]
10610    fn a_note_just_written_still_knows_where_its_reference_is() {
10611        // The authoring loop in one test: press the button, type the note, ask to
10612        // go back. The caret ends at the note's last byte — which is the *end* of
10613        // the definition's span, the one offset the query used to exclude — so
10614        // this is where the round trip either works or doesn't.
10615        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
10616        d.caret = 7;
10617        d.insert_footnote();
10618        d.insert("the note");
10619        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
10620        let back = d
10621            .footnote_definition_at_caret()
10622            .expect("still in the note we just typed");
10623        assert_eq!(back.label, "1");
10624        // …and following it lands on the reference's label, where a reader's
10625        // return leg lands.
10626        assert_eq!(back.offset, Some(9));
10627        assert_eq!(&d.source[9..10], "1");
10628    }
10629
10630    #[test]
10631    fn insert_footnote_takes_one_undo_for_both_halves() {
10632        // twig writes the pair as a single edit; the point of that is here.
10633        let before = "A claim and more.\n";
10634        let mut d = doc_with("fn_insert_undo", before);
10635        d.caret = 7;
10636        d.insert_footnote();
10637        assert_ne!(d.source, before);
10638        d.undo();
10639        assert_eq!(d.source, before, "one undo takes back both halves");
10640    }
10641
10642    #[test]
10643    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
10644        // HTML is authorable — it spells the inline marks — and has no footnote.
10645        // The refusal says so rather than writing brackets that would render as
10646        // brackets.
10647        let src = "<p>A claim.</p>\n";
10648        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
10649        assert!(!Capabilities::of(Format::Html).footnote);
10650        d.caret = 5;
10651        d.insert_footnote();
10652        assert_eq!(d.source, src, "nothing written");
10653        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
10654    }
10655
10656    #[test]
10657    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
10658        // The empty body is the one place this could go wrong: the definition
10659        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
10660        // byte early would draw up in the paragraph above the note it belongs to.
10661        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
10662        d.place_caret(7, false);
10663        d.insert_footnote();
10664        d.build_visual(80); // the frame a frontend draws after the edit
10665        assert_eq!(
10666            d.vmap.snap_to_stop(d.caret),
10667            d.caret,
10668            "the caret sits on a stop"
10669        );
10670        let (row, _) = d.caret_pos();
10671        assert!(
10672            drawn_rows(&d)[row].contains("[1]"),
10673            "the caret is on the note's row, not above it: {:?}",
10674            drawn_rows(&d)
10675        );
10676    }
10677
10678    #[test]
10679    fn footnote_at_caret_resolves_a_reference_to_its_note() {
10680        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
10681        // blank line, as one has to.
10682        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
10683        d.caret = 9;
10684        let f = d
10685            .footnote_at_caret()
10686            .expect("the caret stands in a reference");
10687        assert_eq!(f.label, "1");
10688        assert_eq!(f.text.as_deref(), Some("the note"));
10689        // The offset points at the note's first word, not at the definition's
10690        // `[` — the marker is decoration with no caret stop on it.
10691        assert_eq!(f.offset, Some(29));
10692        assert_eq!(&d.source[29..37], "the note");
10693        // …and `end` closes the range, so a frontend can ask which rendered rows
10694        // the note occupies rather than re-deriving them from the text.
10695        assert_eq!(f.end, Some(37));
10696        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
10697    }
10698
10699    /// Two definitions in a row: each is its own note, and neither reaches into
10700    /// the other.
10701    ///
10702    /// A djot definition's span used to run past the blank line into the first
10703    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
10704    /// offsets named the *next* note's rows too, showing a reader two footnotes
10705    /// when they had asked about one. twig 3.1 ends the span after the block's
10706    /// own last line; the test outlives the workaround leaf carried for it.
10707    #[test]
10708    fn footnote_at_stops_a_note_at_the_definition_after_it() {
10709        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
10710        for format in [Format::Markdown, Format::Djot] {
10711            let mut d = Doc::from_source(src.to_string(), format).unwrap();
10712            d.caret = 7;
10713            let f = d.footnote_at_caret().expect("a reference");
10714            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
10715            assert_eq!(
10716                &src[f.offset.unwrap()..f.end.unwrap()],
10717                "first note.",
10718                "in {format:?}"
10719            );
10720        }
10721    }
10722
10723    /// The other side of that boundary: a blank line *inside* a definition is
10724    /// interior to it, and the note keeps its second paragraph.
10725    ///
10726    /// This is what the old body scan cost. It stopped at the first line not
10727    /// indented under the note — a blank line is not — so a two-paragraph note
10728    /// came back as its first paragraph, and "go to note" framed half of it.
10729    /// Reading the span twig gives is both simpler and right.
10730    #[test]
10731    fn footnote_at_keeps_a_notes_second_paragraph() {
10732        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
10733        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
10734        d.caret = 7;
10735        let f = d.footnote_at_caret().expect("a reference");
10736        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
10737        // And it stops there — `After.` is the next block, not more note.
10738        assert_eq!(
10739            &src[f.offset.unwrap()..f.end.unwrap()],
10740            f.text.as_deref().unwrap()
10741        );
10742        assert!(!f.text.as_deref().unwrap().contains("After"));
10743    }
10744
10745    #[test]
10746    fn footnote_at_bounds_a_note_whose_body_is_empty() {
10747        // `[^1]:` with nothing after it. The range is empty rather than
10748        // inverted, and still points inside the definition — which is what keeps
10749        // a frontend's row lookup from walking off into the block above.
10750        let src = "A claim[^1].\n\n[^1]:\n";
10751        let mut d = doc_with("fn_empty_body", src);
10752        d.caret = 9;
10753        let f = d.footnote_at_caret().expect("a reference");
10754        assert_eq!(f.text.as_deref(), Some(""));
10755        assert_eq!(f.offset, f.end, "an empty note is an empty range");
10756        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
10757    }
10758
10759    #[test]
10760    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
10761        let mut d = doc_with(
10762            "fn_at_caret_none",
10763            "A claim[^1] and more.\n\n[^1]: the note\n",
10764        );
10765        d.caret = 2; // in the prose
10766        assert_eq!(d.footnote_at_caret(), None);
10767    }
10768
10769    #[test]
10770    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
10771        // The two are deliberately separate: a reference names a note in this
10772        // document, a link names somewhere to leave for, and answering one with
10773        // the other is what made a reference click do nothing at all.
10774        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
10775        d.caret = 3; // the `1` of `[^1]`
10776        assert!(d.footnote_at_caret().is_some());
10777        assert_eq!(
10778            d.link_destination_at_caret(),
10779            None,
10780            "a reference is not a link"
10781        );
10782
10783        d.caret = 10; // inside the link's label
10784        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
10785        assert_eq!(
10786            d.link_destination_at_caret().as_deref(),
10787            Some("https://x.dev")
10788        );
10789    }
10790
10791    #[test]
10792    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
10793        // A `[^99]` the document never defines is a real state — a note deleted
10794        // out from under its reference — and the label is what lets a frontend
10795        // say so. `None` here would be indistinguishable from "not on a
10796        // reference", which is the wrong thing to tell a reader.
10797        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
10798        d.caret = 9;
10799        let f = d
10800            .footnote_at_caret()
10801            .expect("the reference is still a reference");
10802        assert_eq!(f.label, "99");
10803        assert_eq!(f.text, None);
10804        assert_eq!(f.offset, None);
10805    }
10806
10807    #[test]
10808    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
10809        // Labels are not always numbers, and a note's body runs past its first
10810        // line — the indented continuation belongs to the note, so it comes back
10811        // with it (source bytes, verbatim, as documented).
10812        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
10813        let mut d = doc_with("fn_word_label", src);
10814        d.caret = 6;
10815        let f = d
10816            .footnote_at_caret()
10817            .expect("the caret stands in a reference");
10818        assert_eq!(f.label, "note");
10819        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
10820    }
10821
10822    #[test]
10823    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
10824        // The point of the offset form: a pointer hovering a reference asks what
10825        // note it names, and must not drag the caret along to ask.
10826        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
10827        d.caret = 0;
10828        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
10829        assert_eq!(f.label, "1");
10830        assert_eq!(f.text.as_deref(), Some("the note"));
10831        assert_eq!(d.caret, 0, "asking must not move the caret");
10832        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
10833    }
10834
10835    #[test]
10836    fn footnote_definition_at_caret_points_back_at_the_reference() {
10837        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
10838        // the caret can rest on — is at 9.
10839        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
10840        d.caret = 30; // inside the note's body
10841        let f = d
10842            .footnote_definition_at_caret()
10843            .expect("the caret stands in a definition");
10844        assert_eq!(f.label, "1");
10845        assert_eq!(f.offset, Some(9));
10846        assert_eq!(&d.source[7..11], "[^1]");
10847    }
10848
10849    #[test]
10850    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
10851        // The two legs have to meet: wherever `footnote_at` sends the caret, the
10852        // definition query must answer for — otherwise arriving at a note leaves
10853        // the reader somewhere the way back isn't offered.
10854        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
10855        let mut d = doc_with("fn_def_marker", src);
10856        let landed = d.footnote_at(9).unwrap().offset.unwrap();
10857        assert_eq!(
10858            d.footnote_definition_at(landed).and_then(|f| f.offset),
10859            Some(9),
10860            "the note a reference sends you to offers the way back"
10861        );
10862    }
10863
10864    #[test]
10865    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
10866        // The two queries answer for disjoint places, which is what lets one
10867        // gesture mean "down to the note" in one and "back up" in the other
10868        // without either having to remember which way the reader is going.
10869        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
10870        d.caret = 2; // prose
10871        assert_eq!(d.footnote_definition_at_caret(), None);
10872        d.caret = 9; // the reference
10873        assert_eq!(d.footnote_definition_at_caret(), None);
10874        assert!(
10875            d.footnote_at_caret().is_some(),
10876            "which is the reference's own query"
10877        );
10878    }
10879
10880    #[test]
10881    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
10882        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
10883        // note", which is false and leaves a frontend unable to explain why the
10884        // way back is missing.
10885        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
10886        let mut d = doc_with("fn_def_orphan", src);
10887        d.caret = src.find("orphan").unwrap();
10888        let f = d
10889            .footnote_definition_at_caret()
10890            .expect("an orphan is still a definition");
10891        assert_eq!(f.label, "2");
10892        assert_eq!(f.offset, None);
10893    }
10894
10895    #[test]
10896    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
10897        // One label, cited twice. The first is where the reader most likely came
10898        // from, and the only answer that doesn't depend on how they got here.
10899        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
10900        let mut d = doc_with("fn_def_repeat", src);
10901        d.caret = src.find("the note").unwrap();
10902        let f = d.footnote_definition_at_caret().expect("a definition");
10903        assert_eq!(
10904            f.offset,
10905            Some(5),
10906            "the first `[^a]`'s label, not the second's"
10907        );
10908        assert_eq!(&src[3..7], "[^a]");
10909    }
10910
10911    #[test]
10912    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
10913        // Down and back up, each leg found from the document rather than from a
10914        // memory of the other — so it still works for a reader who scrolled to
10915        // the notes instead of jumping there.
10916        //
10917        // `place_caret` rather than assigning `caret`, because that is what a
10918        // frontend calls: it snaps to a real caret stop, and a jump that lands
10919        // on a byte the caret can't rest on would arrive somewhere the return
10920        // leg no longer answers for. `build_map` first, since snapping is a
10921        // no-op until the map exists — which is exactly how this went unnoticed
10922        // when the offsets pointed at the `[^` markers.
10923        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
10924        d.build_map(None);
10925        d.place_caret(9, false);
10926        let down = d
10927            .footnote_at_caret()
10928            .expect("a reference")
10929            .offset
10930            .expect("a note");
10931        d.place_caret(down, false);
10932        let up = d
10933            .footnote_definition_at_caret()
10934            .expect("a definition")
10935            .offset
10936            .expect("a reference");
10937        d.place_caret(up, false);
10938        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
10939        assert_eq!(
10940            d.footnote_at_caret().expect("back on the reference").label,
10941            "1"
10942        );
10943    }
10944
10945    #[test]
10946    fn insert_link_hands_the_destination_to_twig_raw() {
10947        // Escaping is twig's, and format-specific: Markdown ends a destination
10948        // at the first space and needs the `<…>` form, where djot would read
10949        // those angle brackets as part of the URL.
10950        let mut d = doc_with("link_space", "word\n");
10951        d.anchor = Some(0);
10952        d.caret = 4;
10953        d.insert_link("a b");
10954        assert_eq!(d.source, "[word](<a b>)\n");
10955    }
10956
10957    #[test]
10958    fn insert_link_reports_a_destination_no_format_can_carry() {
10959        let mut d = doc_with("link_bad", "word\n");
10960        d.anchor = Some(0);
10961        d.caret = 4;
10962        d.insert_link("a\nb");
10963        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
10964        assert!(
10965            d.status.is_some(),
10966            "InvalidArgument should reach the status line"
10967        );
10968        assert!(!d.dirty);
10969    }
10970
10971    #[test]
10972    fn insert_link_works_in_wysiwyg_view() {
10973        let mut d = wysiwyg_doc("link_wys", "word here\n");
10974        d.anchor = Some(0);
10975        d.caret = 4;
10976        d.insert_link("http://x.dev");
10977        assert_eq!(d.source, "[word](http://x.dev) here\n");
10978        assert_eq!(d.selected_text(), Some("word"));
10979        // The map the caret has to keep riding is rebuilt each frame; motion
10980        // over the fresh one must still land on a real stop (the debug_assert).
10981        d.build_visual(80);
10982        d.move_right(false);
10983        d.move_left(false);
10984    }
10985
10986    #[test]
10987    fn click_maps_a_row_col_to_a_byte_offset() {
10988        let mut d = doc_with("click", "ab\ncd\n");
10989        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
10990        assert_eq!(d.caret, 4);
10991    }
10992
10993    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
10994    // stop just as the `(row, col)` click path does, so the caret can never come
10995    // to rest in the blank gap between two paragraphs — where it would draw in one
10996    // place and type in another.
10997    #[test]
10998    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
10999        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
11000        // caret stop (stops are 0,1,3,4).
11001        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
11002        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
11003        d.place_caret(2, false);
11004        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
11005        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
11006    }
11007
11008    #[test]
11009    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
11010        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
11011        d.place_caret(0, false); // anchor at the start of "A"
11012        d.place_caret(2, true); // drag into the gap
11013        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
11014        let (s, e) = d.selection().expect("a selection");
11015        assert!(
11016            d.vmap.is_stop(s) && d.vmap.is_stop(e),
11017            "selection {s}..{e} off a stop"
11018        );
11019    }
11020
11021    #[test]
11022    fn place_caret_on_a_real_stop_is_left_untouched() {
11023        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
11024        d.place_caret(3, false); // the start of "B" — a genuine stop
11025        assert_eq!(d.caret, 3);
11026    }
11027
11028    // An *empty paragraph* (two blank lines, an intentional blank line the user
11029    // opened) is a real caret stop, unlike the gap — a click into it must stay.
11030    #[test]
11031    fn place_caret_rests_in_an_empty_paragraph() {
11032        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
11033        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
11034        assert!(d.vmap.is_stop(empty));
11035        d.place_caret(empty, false);
11036        assert_eq!(d.caret, empty);
11037    }
11038
11039    // The content end of a hidden mark is a home too (`VisualMap::mark_ends`):
11040    // a drag over the word `bold` ends there, and a caret placed there stays.
11041    #[test]
11042    fn place_caret_rests_at_the_end_of_a_hidden_marks_content() {
11043        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
11044        let mut d = wysiwyg_doc("place_mark_end", src);
11045        let start = src.find("bold").unwrap();
11046        d.place_caret(start, false);
11047        d.place_caret(start + 4, true);
11048        assert_eq!(d.selection(), Some((start, start + 4)), "the whole word");
11049        d.toggle(InlineKind::Strong);
11050        assert_eq!(d.source, src.replace("**bold**", "bold"));
11051    }
11052
11053    #[test]
11054    fn right_steps_onto_the_end_of_a_mark_and_then_past_its_delimiter() {
11055        let mut d = wysiwyg_doc("right_mark_end", "a **bold** b");
11056        d.caret = 7; // before the `d`
11057        d.move_right(false);
11058        assert_eq!(d.caret, 8, "onto the end of the bold");
11059        assert!(d.active_inline_marks().contains(InlineKind::Strong));
11060        d.move_right(false);
11061        assert_eq!(d.caret, 10, "past the closing `**`");
11062        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
11063        d.move_left(false);
11064        assert_eq!(d.caret, 8);
11065        d.move_left(false);
11066        assert_eq!(d.caret, 7);
11067        // Typing at the inner home extends the bold.
11068        d.caret = 8;
11069        d.insert("!");
11070        assert_eq!(d.source, "a **bold!** b");
11071    }
11072
11073    #[test]
11074    fn a_marks_end_home_follows_an_edit_through_the_incremental_map() {
11075        // The splice path shifts the home with the block it is in, and the
11076        // re-rendered block finds its own again.
11077        let mut d = wysiwyg_doc("mark_end_splice", "x\n\na **bold** b\n\ny\n");
11078        d.build_visual_unwrapped();
11079        d.edit(0, 0, "zz");
11080        d.build_visual_unwrapped();
11081        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a shift");
11082        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
11083        let at = d.source.find("bold").unwrap();
11084        d.edit(at, at, "very ");
11085        d.build_visual_unwrapped();
11086        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a re-render");
11087        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
11088    }
11089
11090    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
11091        doc_in(View::Wysiwyg, name, body)
11092    }
11093
11094    /// How many list items the source actually parses into — the check that a
11095    /// marker Leaf wrote is a marker the format agrees is one.
11096    fn list_items(doc: &mut Doc) -> usize {
11097        doc.editor
11098            .nodes()
11099            .unwrap()
11100            .iter()
11101            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
11102            .count()
11103    }
11104
11105    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
11106    /// incremental (`build_spliced` / `build_cached`) path must always match.
11107    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
11108        reference_map_revealing(source, None)
11109    }
11110
11111    /// [`reference_map`] with a reveal line — the ground truth for the
11112    /// `MarkupMode::Full` builds, where the map is a function of the caret's
11113    /// line as well as the text.
11114    fn reference_map_revealing(
11115        source: &str,
11116        reveal: Option<Range<usize>>,
11117    ) -> crate::wysiwyg::VisualMap {
11118        // The same parse `Doc` uses. With twig's plain defaults instead, the two
11119        // sides disagree on what the *document* is before the renderer is even
11120        // reached — a bare `:word` is a text directive to one and prose to the
11121        // other — and the mismatch reads as a splice bug that isn't one.
11122        let mut ed =
11123            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
11124        let nodes = ed.nodes().unwrap();
11125        crate::wysiwyg::build(
11126            &nodes,
11127            source,
11128            None,
11129            false,
11130            &std::collections::HashMap::new(),
11131            reveal,
11132        )
11133    }
11134
11135    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
11136        if a.rows.len() != b.rows.len() {
11137            return true;
11138        }
11139        for (ra, rb) in a.rows.iter().zip(&b.rows) {
11140            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
11141                return true;
11142            }
11143            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
11144                if ga.ch != gb.ch || ga.src != gb.src {
11145                    return true;
11146                }
11147            }
11148        }
11149        false
11150    }
11151
11152    #[test]
11153    fn incremental_build_matches_a_fresh_build_across_edits() {
11154        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
11155        // fast path, gated on twig's `dirty_range`) or falls back to
11156        // `build_cached`. After each edit the map must be byte-identical to a
11157        // from-scratch build — this is the correctness net under the splice.
11158        let docs = [
11159            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
11160            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
11161            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
11162            // A footnote definition is a root beside `doc`, merged back into the
11163            // top-level list by `wysiwyg::top_blocks`. The random edits below
11164            // make and unmake definitions as they go (a deleted `:` turns one
11165            // back into a paragraph, and vice versa), which is exactly the
11166            // structural churn the splice path has to notice and bail out of.
11167            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
11168            // A comment is a top-level block that draws no rows — a layout entry
11169            // at zero rows either side of blocks that do. The edits below type
11170            // into the blocks around it (a splice past a hidden block), and
11171            // break the comment open into prose and back (a structural change).
11172            "intro\n\n<!-- exec -->\n```\ncode\n```\n\nafter the comment\n\n<!-- trail -->\n",
11173            // Link reference definitions: a hidden block that an edit can turn
11174            // into a paragraph (a deleted `:`) and back, and whose own bytes an
11175            // edit can land in.
11176            "see [a] and [b]\n\n[a]: /a\n\nmid text\n\n[b]: /b\n",
11177        ];
11178        // A deterministic mix: mostly single characters (which stay inside one
11179        // block → splice), plus edits that reshape structure (a paragraph break,
11180        // a heading marker, a code fence → fallback), so both paths are exercised.
11181        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
11182        for src in docs {
11183            let mut d = wysiwyg_doc("diff", src);
11184            d.build_visual_unwrapped();
11185            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
11186
11187            for step in 0..60usize {
11188                let len = d.source.len();
11189                let raw = (step * 13 + 5) % (len + 1);
11190                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
11191                let pre = d.source.clone();
11192                let action;
11193                if step % 3 == 0 && pos < len {
11194                    let end = (pos + 1..=len)
11195                        .find(|&i| d.source.is_char_boundary(i))
11196                        .unwrap();
11197                    action = format!("delete [{pos},{end})");
11198                    d.edit(pos, end, "");
11199                } else {
11200                    let ins = inserts[step % inserts.len()];
11201                    action = format!("insert {ins:?} @ {pos}");
11202                    d.edit(pos, pos, ins);
11203                }
11204                d.build_visual_unwrapped();
11205                if maps_differ(&d.vmap, &reference_map(&d.source)) {
11206                    panic!(
11207                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
11208                        d.source
11209                    );
11210                }
11211            }
11212        }
11213    }
11214
11215    /// A frontend is handed [`Doc::vmap`] and may present it differently:
11216    /// leaf-ratatui splices blank filler rows under an oversized heading so the
11217    /// raster it paints there has somewhere to stand, and leaves them in the map
11218    /// because the caret and the mouse both read it between frames. The splice
11219    /// path addresses that map by *row index*, against the block layout the last
11220    /// build recorded — so handed a map with rows in it that no block owns, it
11221    /// laid the re-rendered block over one of the fillers and carried the rows
11222    /// the block really occupied into the suffix. One stranded copy of the
11223    /// edited line, and everything below it a row further down, per keystroke.
11224    ///
11225    /// A map that isn't the one the layout describes is a map this path can't
11226    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
11227    #[test]
11228    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
11229        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
11230        d.build_visual_unwrapped();
11231
11232        // Stand in for the heading filler rows: two blank rows past the heading
11233        // that no block accounts for. Cloning a real row keeps every field
11234        // plausible — it is the row *count* the splice can't survive.
11235        let filler = d.vmap.rows[0].clone();
11236        d.vmap.rows.insert(1, filler.clone());
11237        d.vmap.rows.insert(1, filler);
11238
11239        // An edit inside the last block: the single-block case the splice path
11240        // is for, and the one the frontend hits on every keystroke.
11241        let at = d.source.len() - 1;
11242        d.edit(at, at, "!");
11243        d.build_visual_unwrapped();
11244
11245        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
11246    }
11247
11248    #[test]
11249    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
11250        // The same correctness net as `incremental_build_matches_a_fresh_build_
11251        // across_edits`, under `MarkupMode::Full` — where the map depends on
11252        // the caret's *line* as well as the text, so the two caches have a new
11253        // way to be wrong. Both are exercised: the block cache can hand back
11254        // rows built for a line that is no longer the revealed one, and the
11255        // splice path can reuse a suffix that still has yesterday's line raw.
11256        //
11257        // Caret motion is interleaved with the edits deliberately, because a
11258        // caret that only ever moved with the edit would never cross a line
11259        // without also dirtying it — the case where a stale reveal survives.
11260        let docs = [
11261            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
11262            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
11263        ];
11264        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
11265        for src in docs {
11266            let mut d = wysiwyg_doc("reveal_diff", src);
11267            d.set_markup_mode(MarkupMode::Full);
11268
11269            for step in 0..60usize {
11270                let len = d.source.len();
11271                let raw = (step * 13 + 5) % (len + 1);
11272                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
11273                let pre = d.source.clone();
11274                let action;
11275                if step % 3 == 0 && pos < len {
11276                    let end = (pos + 1..=len)
11277                        .find(|&i| d.source.is_char_boundary(i))
11278                        .unwrap();
11279                    action = format!("delete [{pos},{end})");
11280                    d.edit(pos, end, "");
11281                } else {
11282                    let ins = inserts[step % inserts.len()];
11283                    action = format!("insert {ins:?} @ {pos}");
11284                    d.edit(pos, pos, ins);
11285                }
11286                // Walk the caret somewhere else in the document, independently
11287                // of where the edit landed.
11288                let want = (step * 29 + 11) % (d.source.len() + 1);
11289                d.caret = (want..=d.source.len())
11290                    .find(|&i| d.source.is_char_boundary(i))
11291                    .unwrap();
11292                d.build_visual_unwrapped();
11293
11294                let want = reference_map_revealing(&d.source, d.reveal_line());
11295                if maps_differ(&d.vmap, &want) {
11296                    panic!(
11297                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
11298                        d.caret, d.source
11299                    );
11300                }
11301            }
11302        }
11303    }
11304
11305    #[test]
11306    fn caret_motion_across_lines_rebuilds_only_under_full() {
11307        // The cache-key change has to earn its keep in both directions: `Full`
11308        // must rebuild when the caret changes line (or the reveal would never
11309        // move), and the hidden modes must *not* (or every arrow key would pay
11310        // for a feature they don't use). The existing `cache_motion` test pins
11311        // the second for the default mode; this pins the pair against a mode
11312        // change alone.
11313        let body = "*one* here\n\n*two* there\n";
11314
11315        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
11316        full.set_markup_mode(MarkupMode::Full);
11317        caret_at(&mut full, "one");
11318        let before = full.revision();
11319        caret_at(&mut full, "two");
11320        assert_eq!(full.revision(), before, "motion is not an edit");
11321        assert!(
11322            drawn_rows(&full).iter().any(|r| r == "*two* there"),
11323            "the map followed the caret: {:?}",
11324            drawn_rows(&full)
11325        );
11326
11327        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
11328        caret_at(&mut hidden, "one");
11329        let key = hidden.vmap_key.clone();
11330        caret_at(&mut hidden, "two");
11331        assert_eq!(
11332            hidden.vmap_key, key,
11333            "a hidden mode rebuilds nothing on motion"
11334        );
11335    }
11336
11337    #[test]
11338    fn wysiwyg_down_crosses_a_paragraph_boundary() {
11339        // Regression: the blank separator row used to share the previous
11340        // paragraph's end offset, so Down got pinned at the boundary (while Up
11341        // still crossed). Both directions must step through it symmetrically.
11342        //
11343        // It's now stepped *over* rather than onto: the blank line between two
11344        // paragraphs is the boundary being drawn, not a line of the document, so
11345        // one press of Down crosses it. The goal column survives the crossing —
11346        // col 3 at the end of "abc" is col 3 at the end of "def".
11347        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
11348        d.caret = 3; // end of "abc" (row 0)
11349        d.move_down(false);
11350        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
11351        assert_eq!(d.caret, 8); // end of "def", col 3 kept
11352        d.move_up(false);
11353        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
11354        assert_eq!(d.caret, 3);
11355    }
11356
11357    #[test]
11358    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
11359        // The second Up and the second Down here run off the ends of the
11360        // document, which is no longer a place a press is swallowed: they carry
11361        // the caret to the start and the end of the text. The claim in the
11362        // middle — that a Down retraces the Up that crossed the paragraph gap —
11363        // is the one this test is for, and it is asserted where it is made.
11364        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
11365        d.caret = 5; // start of "def"
11366        let start = d.caret_pos();
11367        d.move_up(false);
11368        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
11369        d.move_up(false);
11370        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
11371        d.move_down(false);
11372        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
11373        d.move_down(false);
11374        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
11375    }
11376
11377    #[test]
11378    fn wysiwyg_new_paragraph_shows_before_typing() {
11379        // Regression: two Enters at the end of a paragraph produced trailing
11380        // newlines with no AST node, so the caret appeared stuck on the old line
11381        // until a character was typed. It must ride down onto the new line now.
11382        let mut d = doc_with("wys_newpara", "abc\n");
11383        d.view = View::Wysiwyg;
11384        d.caret = 3;
11385        d.insert("\n");
11386        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
11387        assert_eq!(d.source, "abc\n\n\n");
11388        d.build_visual(80);
11389        let (row, _) = d.caret_pos();
11390        assert!(
11391            row >= 2,
11392            "caret should have moved down to the new line, got row {row}"
11393        );
11394        assert!(
11395            d.vmap.num_rows() >= 3,
11396            "the blank lines should render as rows"
11397        );
11398    }
11399
11400    #[test]
11401    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
11402        // The reported bug: Enter at the end of a paragraph that has another
11403        // paragraph below put the caret at the *start of the next paragraph* —
11404        // the empty paragraph it opened had no row, so the caret snapped onto
11405        // "World". It must now sit on its own empty line, with a blank spacer
11406        // above it (the paragraph gap).
11407        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
11408        d.caret = 5; // end of "Hello"
11409        d.newline();
11410        d.build_visual(80);
11411        let (row, col) = d.caret_pos();
11412        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
11413        assert_eq!(
11414            d.vmap.row_width(row),
11415            0,
11416            "caret's row must be empty, not 'World'"
11417        );
11418        assert!(
11419            row >= 2,
11420            "a blank spacer row should sit above the caret, got row {row}"
11421        );
11422        // The row above the caret is a real (empty) gap, and "Hello" stays put.
11423        assert_eq!(
11424            d.vmap.row_width(row - 1),
11425            0,
11426            "the row above the caret is a gap"
11427        );
11428        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
11429        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
11430    }
11431
11432    #[test]
11433    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
11434        // At the document end a single Enter must also show the paragraph gap —
11435        // a blank spacer row above the caret — so the layout already matches how
11436        // it will look once the new paragraph has text.
11437        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
11438        d.caret = 5; // end of "Hello", no trailing newline
11439        d.newline(); // source becomes "Hello\n\n"
11440        d.build_visual(80);
11441        let (row, col) = d.caret_pos();
11442        assert_eq!(col, 0);
11443        assert!(
11444            row >= 2,
11445            "caret should sit below a blank spacer, got row {row}"
11446        );
11447        assert_eq!(
11448            d.vmap.row_width(row - 1),
11449            0,
11450            "the row above the caret is a gap"
11451        );
11452    }
11453
11454    #[test]
11455    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
11456        // The spacer is view-only: typing the new paragraph must not reflow the
11457        // caret onto a different row — the transient view already matched the
11458        // settled one.
11459        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
11460        d.caret = 5;
11461        d.newline();
11462        d.build_visual(80);
11463        let before = d.caret_pos();
11464        d.insert("New");
11465        d.build_visual(80);
11466        let after = d.caret_pos();
11467        assert_eq!(
11468            after.0, before.0,
11469            "typing must not move the caret to another row ({before:?} -> {after:?})"
11470        );
11471    }
11472
11473    #[test]
11474    fn wysiwyg_return_on_the_last_code_line_keeps_the_caret_in_the_block() {
11475        // Return at the end of the block's last line writes an empty line the
11476        // map used to drop, so the caret landed on `after` and the next
11477        // keystroke went into the paragraph below instead of into the code.
11478        let mut d = wysiwyg_doc("code_return", "prose\n\n```\nalpha\nbeta\n```\n\nafter\n");
11479        d.caret = d.source.find("beta").unwrap() + "beta".len();
11480        d.build_visual(80);
11481        let before = d.caret_pos().0;
11482
11483        d.newline();
11484        d.build_visual(80);
11485        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n");
11486
11487        let (row, col) = d.caret_pos();
11488        assert_eq!(row, before + 1, "the caret moves down one row");
11489        assert_eq!(col, 0, "onto the head of the empty line");
11490        let span = d.vmap.code_blocks[0].rows_span.clone();
11491        assert!(
11492            span.contains(&row),
11493            "caret row {row} is outside the block's rows {span:?}"
11494        );
11495
11496        // The whole point: what is typed next is code.
11497        d.insert("gamma");
11498        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\ngamma\n```\n\nafter\n");
11499    }
11500
11501    #[test]
11502    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
11503        let fm = "---\ntitle: hi\n---\n";
11504        let body = format!("{fm}# leaf\n\nbody\n");
11505        let mut d = wysiwyg_doc("wys_fm", &body);
11506        // Opening lifts the caret out of the now-hidden frontmatter.
11507        assert_eq!(
11508            d.caret,
11509            fm.len(),
11510            "caret should start at the first real block"
11511        );
11512        // Left at the content start can't step back into frontmatter.
11513        d.move_left(false);
11514        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
11515        // Doc-start lands on the content floor, not offset 0.
11516        d.move_doc_start(false);
11517        assert_eq!(d.caret, fm.len());
11518        // Select-all + copy never include the frontmatter bytes.
11519        d.select_all();
11520        let sel = d.selected_text().unwrap().to_string();
11521        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
11522        assert!(
11523            sel.starts_with("# leaf"),
11524            "selection should begin at content: {sel:?}"
11525        );
11526    }
11527
11528    #[test]
11529    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
11530        // A fresh note is frontmatter and nothing else. With no rendered block
11531        // to floor the caret it opened at offset 0 — before the opening `---` —
11532        // so the first keystroke wrote itself in front of the metadata and the
11533        // file came out as `This---\ntitle: …`.
11534        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
11535        let mut d = wysiwyg_doc("wys_fm_only", fm);
11536        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
11537        // Nothing is rendered, so the caret draws at the origin of an empty view
11538        // — the same place an empty document puts it.
11539        assert_eq!(d.caret_pos(), (0, 0));
11540        d.insert("This");
11541        assert_eq!(d.source, format!("{fm}This"));
11542    }
11543
11544    /// `select_range` is the verb for a range a host already knows the bytes of,
11545    /// so it must not snap — and must still hold every invariant `place_caret`
11546    /// holds, the frontmatter floor above all.
11547    #[test]
11548    fn select_range_takes_the_range_as_given_but_still_floors_it() {
11549        let fm = "---\ntitle: foo\n---\n\n";
11550        let body = format!("{fm}body foo here\n");
11551        let mut d = wysiwyg_doc("wys_select_range", &body);
11552
11553        // The `foo` in the body: taken exactly, not snapped to a caret stop.
11554        let at = body.rfind("foo").unwrap();
11555        d.select_range(at, at + 3);
11556        assert_eq!(d.selection(), Some((at, at + 3)));
11557        assert_eq!(d.selected_text(), Some("foo"));
11558
11559        // The `foo` in the hidden frontmatter: below the floor, so both ends
11560        // come up to it rather than parking the caret in the metadata, where a
11561        // later keystroke would rewrite `title:`.
11562        let hidden = body.find("foo").unwrap();
11563        assert!(hidden < d.vmap.content_start);
11564        d.select_range(hidden, hidden + 3);
11565        assert!(
11566            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
11567            "a range under the floor must not leave the caret in the frontmatter"
11568        );
11569
11570        // Past the end, and mid-character, are both brought back to something
11571        // sliceable rather than panicking the next reader of the range.
11572        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
11573        let mut d = multi;
11574        d.select_range(2, 9_999);
11575        assert_eq!(d.caret, d.source.len());
11576        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
11577        assert!(d.source.is_char_boundary(d.caret));
11578    }
11579
11580    /// The bug `select_range` exists for: a match butting up against a hidden
11581    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
11582    /// the one before the `**`.
11583    #[test]
11584    fn select_range_does_not_snap_off_a_hidden_delimiter() {
11585        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
11586        let at = d.source.find("needle").unwrap();
11587        d.select_range(at, at + 6);
11588        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
11589    }
11590
11591    #[test]
11592    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
11593        // Backspace deletes `prev_boundary..caret` directly; at the first real
11594        // block that boundary is inside the hidden frontmatter, so it must be a
11595        // no-op rather than eating the closing `---`.
11596        let fm = "---\ntitle: hi\n---\n";
11597        let body = format!("{fm}leaf\n");
11598        let mut d = wysiwyg_doc("wys_fm_bs", &body);
11599        assert_eq!(d.caret, fm.len());
11600        d.backspace();
11601        assert_eq!(d.source, body, "backspace must not touch frontmatter");
11602        d.delete_word_back();
11603        assert_eq!(
11604            d.source, body,
11605            "word-delete must not touch frontmatter either"
11606        );
11607    }
11608
11609    #[test]
11610    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
11611        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
11612        // fenced div, really, since core parses these on for every document
11613        // now (`parse_extensions`). The container is a `directive` node, an
11614        // `is_block_container` kind like `block_quote`, so the caret works
11615        // inside its child paragraph exactly as it would inside a quote: typing
11616        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
11617        // untouched.
11618        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
11619        let mut d = wysiwyg_doc("wys_vis", body);
11620        d.caret = body.find("hello").unwrap() + "hello".len();
11621        d.insert("!");
11622        assert_eq!(
11623            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
11624            "typing inside the block edits its content in place"
11625        );
11626        assert!(
11627            d.source.contains(":::vis{.public .family}"),
11628            "opening fence survives"
11629        );
11630        assert!(d.source.contains(":::\nafter"), "closing fence survives");
11631    }
11632
11633    #[test]
11634    fn source_view_still_reaches_frontmatter() {
11635        // The metadata is only *hidden*, never lost: the source view edits and
11636        // selects it in full, and it's always preserved on save.
11637        let fm = "---\ntitle: hi\n---\n";
11638        let body = format!("{fm}# leaf\n");
11639        let mut d = doc_with("src_fm", &body);
11640        d.select_all();
11641        let sel = d.selected_text().unwrap();
11642        assert!(
11643            sel.contains("title"),
11644            "source view should select everything"
11645        );
11646        d.move_doc_start(false);
11647        assert_eq!(d.caret, 0, "source view can reach offset 0");
11648    }
11649
11650    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
11651
11652    #[test]
11653    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
11654        // The border and padding between two cells all share one source offset,
11655        // so a column-stepping caret would sit on `│` and then stall there
11656        // forever. Right must step: end of "Name" -> start of "Qty".
11657        let mut d = wysiwyg_doc("tbl_right", TABLE);
11658        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
11659        d.move_right(false);
11660        assert_eq!(
11661            d.caret,
11662            TABLE.find("Qty").unwrap(),
11663            "should land in the next cell"
11664        );
11665        let (r, c) = d.caret_pos();
11666        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
11667    }
11668
11669    #[test]
11670    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
11671        let mut d = wysiwyg_doc("tbl_left", TABLE);
11672        d.caret = TABLE.find("Qty").unwrap();
11673        d.move_left(false);
11674        assert_eq!(
11675            d.caret,
11676            TABLE.find("Name").unwrap() + 4,
11677            "end of the previous cell"
11678        );
11679    }
11680
11681    #[test]
11682    fn wysiwyg_down_steps_over_a_table_rule() {
11683        // Between the header and the first body row sits a `├───┼───┤` rule.
11684        // It's drawn but holds no caret, so one Down must reach "Pear".
11685        let mut d = wysiwyg_doc("tbl_down", TABLE);
11686        d.caret = TABLE.find("Name").unwrap();
11687        d.move_down(false);
11688        assert_eq!(
11689            d.caret,
11690            TABLE.find("Pear").unwrap(),
11691            "one Down reaches the body row"
11692        );
11693        d.move_down(false);
11694        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
11695    }
11696
11697    #[test]
11698    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
11699        let mut d = wysiwyg_doc("tbl_tab", TABLE);
11700        d.caret = TABLE.find("Name").unwrap();
11701        // A hop lands with the destination cell's whole content selected, the
11702        // caret at its end — so typing replaces the cell like a form field.
11703        assert!(d.cell_hop(true));
11704        assert_eq!(
11705            d.selected_text(),
11706            Some("Qty"),
11707            "the target cell comes up selected"
11708        );
11709        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
11710        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
11711        assert_eq!(d.selected_text(), Some("Pear"));
11712        assert!(d.cell_hop(false));
11713        assert_eq!(d.selected_text(), Some("Qty"));
11714    }
11715
11716    #[test]
11717    fn tab_outside_a_table_is_not_a_cell_hop() {
11718        // `cell_hop` reports false so the frontend can indent as usual.
11719        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
11720        d.caret = 4;
11721        assert!(!d.cell_hop(true));
11722        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
11723    }
11724
11725    #[test]
11726    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
11727        let mut d = wysiwyg_doc("tbl_edge", TABLE);
11728        d.caret = TABLE.rfind("12").unwrap(); // the final cell
11729        assert!(!d.cell_hop(true), "no cell after the last one");
11730        d.caret = TABLE.find("Name").unwrap();
11731        assert!(!d.cell_hop(false), "no cell before the first one");
11732    }
11733
11734    #[test]
11735    fn wysiwyg_vertical_cell_motion_holds_the_column() {
11736        // Down/Up step to the cell above/below in the *same column*, not back to
11737        // the top-left the way a naive row/col motion over the picture would.
11738        let mut d = wysiwyg_doc("tbl_vert", TABLE);
11739        d.caret = TABLE.find("Qty").unwrap();
11740        // Each vertical hop selects the destination cell, holding the column.
11741        assert!(d.cell_move_vertical(true));
11742        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
11743        assert!(d.cell_move_vertical(true));
11744        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
11745        assert!(!d.cell_move_vertical(true), "no row below the last");
11746        assert!(d.cell_move_vertical(false));
11747        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
11748        assert!(d.cell_move_vertical(false));
11749        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
11750        assert!(!d.cell_move_vertical(false), "no row above the header");
11751    }
11752
11753    #[test]
11754    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
11755        let mut d = wysiwyg_doc("tbl_grow", TABLE);
11756        d.caret = TABLE.rfind("12").unwrap();
11757        let rows_before = d.source.matches('\n').count();
11758        assert!(d.cell_tab(true), "acts as a table key");
11759        assert_eq!(
11760            d.source.matches('\n').count(),
11761            rows_before + 1,
11762            "a fresh row was appended"
11763        );
11764        assert!(d.caret_in_table(), "the caret entered the new row");
11765        // The caret sits in the new row's first cell — past the old last cell.
11766        assert!(d.caret > TABLE.rfind("12").unwrap());
11767    }
11768
11769    #[test]
11770    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
11771        let mut d = wysiwyg_doc("tbl_ret", TABLE);
11772        d.caret = TABLE.find("Name").unwrap();
11773        assert!(d.cell_return(), "acts as a table key");
11774        assert_eq!(
11775            d.selected_text(),
11776            Some("Pear"),
11777            "Return drops one cell, selecting it"
11778        );
11779        // From the last row, Return appends a row and enters it.
11780        d.caret = TABLE.rfind("Fig").unwrap();
11781        let rows_before = d.source.matches('\n').count();
11782        assert!(d.cell_return());
11783        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
11784        assert!(d.caret_in_table());
11785    }
11786
11787    #[test]
11788    fn return_and_tab_outside_a_table_decline() {
11789        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
11790        d.caret = 4;
11791        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
11792        assert!(!d.cell_tab(true), "no table: the frontend indents");
11793        assert!(
11794            !d.cell_line_break(),
11795            "no table: the frontend breaks the line"
11796        );
11797    }
11798
11799    #[test]
11800    fn a_click_under_a_trailing_table_lands_past_it_and_enter_opens_a_line() {
11801        // A document that ends in a table used to end *inside* it: nothing
11802        // past the last cell was a caret stop, so a click in the blank space
11803        // under the grid snapped back into the table and there was no way to
11804        // write a line after it. The bottom border's end is that stop now.
11805        let mut d = wysiwyg_doc("tbl_trail", TABLE);
11806        let rows = d.vmap.num_rows();
11807        d.click(rows + 3, 0, false);
11808        let end = TABLE.trim_end_matches('\n').len();
11809        assert_eq!(d.caret, end, "the caret stands just past the table");
11810        assert!(!d.caret_in_table(), "past the table is outside it");
11811        assert!(!d.cell_return(), "Return there is the frontend's newline");
11812        d.newline();
11813        d.insert("after");
11814        assert_eq!(
11815            d.source,
11816            format!("{TABLE}\nafter\n"),
11817            "Enter opens a paragraph under the table"
11818        );
11819    }
11820
11821    #[test]
11822    fn typing_at_a_table_s_trailing_stop_opens_a_paragraph_first() {
11823        // The stop sits at the end of the table's last source line, and a
11824        // line glued under a table is a row of it — `| Fig | 12 |x` would be a
11825        // three-cell row. So the text gets a paragraph of its own, as it does
11826        // beside a block picture.
11827        let mut d = wysiwyg_doc("tbl_type", TABLE);
11828        d.caret = TABLE.trim_end_matches('\n').len();
11829        d.insert("x");
11830        assert_eq!(d.source, format!("{TABLE}\nx\n"));
11831        assert_eq!(d.caret, TABLE.len() + 2, "the caret follows the text");
11832        // And a paste, which joins the block exactly as typing would.
11833        let mut d = wysiwyg_doc("tbl_paste", TABLE);
11834        d.caret = TABLE.trim_end_matches('\n').len();
11835        d.paste("pasted");
11836        assert_eq!(d.source, format!("{TABLE}\npasted\n"));
11837    }
11838
11839    #[test]
11840    fn right_leaves_a_table_by_its_trailing_stop_and_backspace_steps_back_in() {
11841        let mut d = wysiwyg_doc("tbl_edge", TABLE);
11842        let last_cell_end = TABLE.rfind("12").unwrap() + 2;
11843        let end = TABLE.trim_end_matches('\n').len();
11844        d.caret = last_cell_end;
11845        d.move_right(false);
11846        assert_eq!(d.caret, end, "Right from the last cell leaves the table");
11847        // Backspace there takes no byte: the one behind the caret is the row's
11848        // closing `|`, which the rich view never drew. It steps back instead.
11849        d.backspace();
11850        assert_eq!(d.source, TABLE, "nothing deleted");
11851        assert_eq!(d.caret, last_cell_end, "back into the last cell");
11852        // Down from the last row lands on the same stop, and Up returns.
11853        d.move_down(false);
11854        assert_eq!(d.caret, end, "Down from the last row leaves the table");
11855        d.move_up(false);
11856        assert_eq!(d.caret, last_cell_end);
11857    }
11858
11859    #[test]
11860    fn a_table_s_trailing_stop_sits_between_it_and_the_text_below() {
11861        // With prose under the table, the stop is one hop between the last
11862        // cell and the paragraph — the shape a block picture's second stop has.
11863        let src = format!("{TABLE}\nafter\n");
11864        let mut d = wysiwyg_doc("tbl_mid", &src);
11865        d.caret = TABLE.rfind("12").unwrap() + 2;
11866        d.move_right(false);
11867        assert_eq!(d.caret, TABLE.trim_end_matches('\n').len());
11868        d.move_right(false);
11869        assert_eq!(d.caret, src.find("after").unwrap());
11870        // Typing at the stop still opens a paragraph, and the text below keeps
11871        // its own.
11872        d.move_left(false);
11873        d.insert("x");
11874        assert_eq!(d.source, format!("{TABLE}\nx\n\nafter\n"));
11875    }
11876
11877    #[test]
11878    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
11879        let mut d = wysiwyg_doc("tbl_break", TABLE);
11880        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
11881        assert!(d.cell_line_break(), "acts as a table key");
11882        assert!(
11883            d.source.contains("Pear<br>"),
11884            "spelled as an inline <br>: {}",
11885            d.source
11886        );
11887        assert!(d.caret_in_table(), "still in the cell, past the break");
11888        // The break renders as a real line: the "Pear" cell now draws two lines,
11889        // so the table's picture is one row taller than a single-line table.
11890        d.build_visual(80);
11891        let table = &d.vmap.tables[0];
11892        let cell = &table.grid[1].cells[0]; // first body row, first column
11893        assert!(
11894            cell.glyphs.iter().any(|g| g.ch == '\n'),
11895            "the cell carries the break as a newline glyph for the frontend to split"
11896        );
11897    }
11898
11899    #[test]
11900    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
11901        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
11902        // back as structure — the whole point of routing through insert_line_break
11903        // instead of splicing raw `<br>` bytes.
11904        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
11905        d.caret = TABLE.find("Pear").unwrap() + 4;
11906        assert!(d.cell_line_break());
11907        let kinds: Vec<Kind> = d
11908            .editor
11909            .nodes()
11910            .unwrap()
11911            .iter()
11912            .map(|n| n.kind.clone())
11913            .collect();
11914        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
11915        assert!(
11916            !kinds.contains(&Kind::RawInline),
11917            "still raw HTML: {kinds:?}"
11918        );
11919    }
11920
11921    #[test]
11922    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
11923        // The `<br>` draws as one newline glyph, so Backspace over it must take
11924        // all four bytes — a one-byte delete would strand a visible `<br` in the
11925        // cell (the reported bug).
11926        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
11927        d.caret = TABLE.find("Pear").unwrap() + 4;
11928        assert!(d.cell_line_break());
11929        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
11930        d.backspace(); // caret sits just past the break
11931        assert!(
11932            !d.source.contains("<br"),
11933            "no half-deleted <br left: {}",
11934            d.source
11935        );
11936        assert!(
11937            d.source.contains("| Pear |"),
11938            "the cell is back to one line: {}",
11939            d.source
11940        );
11941    }
11942
11943    #[test]
11944    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
11945        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
11946        d.caret = TABLE.find("Pear").unwrap() + 4;
11947        assert!(d.cell_line_break());
11948        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
11949        d.delete_forward();
11950        assert!(
11951            !d.source.contains("<br"),
11952            "no half-deleted <br: {}",
11953            d.source
11954        );
11955        assert!(
11956            d.source.contains("| Pear |"),
11957            "cell back to one line: {}",
11958            d.source
11959        );
11960    }
11961
11962    #[test]
11963    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
11964        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
11965        // still consumed (a real newline would split the one-line row), but the
11966        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
11967        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
11968        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
11969        d.caret = src.find("Pear").unwrap() + 4;
11970        assert!(d.caret_in_table(), "caret should be inside the djot table");
11971        assert!(
11972            d.cell_line_break(),
11973            "the key is consumed, not passed to the frontend"
11974        );
11975        assert_eq!(d.source, src, "the djot cell is left untouched");
11976        assert!(
11977            !d.source.contains("<br>"),
11978            "no non-idiomatic <br> spliced into djot"
11979        );
11980        assert!(
11981            d.status.is_some(),
11982            "the refusal is surfaced on the status line"
11983        );
11984    }
11985
11986    #[test]
11987    fn typing_in_a_cell_edits_that_cell() {
11988        // Editing comes free once offsets map correctly: the caret is a source
11989        // offset, so a normal splice lands inside the pipe table.
11990        let mut d = wysiwyg_doc("tbl_type", TABLE);
11991        d.caret = TABLE.find("Pear").unwrap() + 4;
11992        d.insert("s");
11993        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
11994    }
11995
11996    #[test]
11997    fn motion_and_delete_treat_an_emoji_as_one_character() {
11998        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
11999        // bytes, several codepoints. Right-arrow must clear it in one step, and
12000        // backspace must remove the whole cluster, not a stray joiner.
12001        let family = "👨‍👩‍👧";
12002        let mut d = doc_with("emoji", &format!("a{family}b\n"));
12003        d.caret = 1; // just after 'a', before the emoji
12004        d.move_right(false);
12005        assert_eq!(
12006            d.caret,
12007            1 + family.len(),
12008            "one step clears the whole cluster"
12009        );
12010        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
12011
12012        d.backspace(); // delete the emoji as a unit
12013        assert_eq!(d.source, "ab\n");
12014        assert_eq!(d.caret, 1);
12015    }
12016
12017    #[test]
12018    fn motion_handles_a_combining_accent_as_one_character() {
12019        // "e" + U+0301 (combining acute) renders as one é.
12020        let mut d = doc_with("combining", "e\u{0301}x\n");
12021        d.caret = 0;
12022        d.move_right(false);
12023        assert_eq!(
12024            d.caret,
12025            "e\u{0301}".len(),
12026            "steps past base + combining mark"
12027        );
12028    }
12029
12030    #[test]
12031    fn undo_then_redo_round_trips_an_edit() {
12032        let mut d = doc_with("undo", "hello\n");
12033        d.caret = 5;
12034        d.insert("!");
12035        assert_eq!(d.source, "hello!\n");
12036        d.undo();
12037        assert_eq!(d.source, "hello\n");
12038        assert_eq!(d.caret, 5, "undo restores the caret");
12039        d.redo();
12040        assert_eq!(d.source, "hello!\n");
12041    }
12042
12043    #[test]
12044    fn a_run_of_typing_undoes_as_one_step() {
12045        let mut d = doc_with("coalesce", "\n");
12046        d.caret = 0;
12047        d.insert("a");
12048        d.insert("b");
12049        d.insert("c");
12050        assert_eq!(d.source, "abc\n");
12051        d.undo(); // the whole typed run, not just "c"
12052        assert_eq!(d.source, "\n");
12053        d.undo(); // nothing left — the run was one step
12054        assert_eq!(d.source, "\n");
12055        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
12056    }
12057
12058    // ── IME composition ──────────────────────────────────────────────────────
12059
12060    #[test]
12061    fn a_composition_run_undoes_as_one_step() {
12062        let mut d = doc_with("compose", "\n");
12063        d.caret = 0;
12064        // What an IME does: each step replaces the last one's provisional bytes.
12065        d.edit_composing(0, 0, "k");
12066        d.edit_composing(0, 1, "か");
12067        d.edit_composing(0, 3, "かん");
12068        d.edit_composing(0, 6, "感"); // the commit
12069        d.end_composition();
12070        assert_eq!(d.source, "感\n");
12071        d.undo(); // the whole composition, not its last keystroke
12072        assert_eq!(d.source, "\n");
12073        assert_eq!(d.status.as_deref(), None, "the run was a single step");
12074    }
12075
12076    #[test]
12077    fn two_compositions_are_two_undo_steps() {
12078        let mut d = doc_with("compose_two", "\n");
12079        d.caret = 0;
12080        d.edit_composing(0, 0, "か");
12081        d.edit_composing(0, 3, "蚊");
12082        d.end_composition();
12083        d.edit_composing(3, 3, "き");
12084        d.edit_composing(3, 6, "木");
12085        d.end_composition();
12086        assert_eq!(d.source, "蚊木\n");
12087        d.undo();
12088        assert_eq!(d.source, "蚊\n", "only the second composition");
12089        d.undo();
12090        assert_eq!(d.source, "\n");
12091    }
12092
12093    #[test]
12094    fn a_composition_does_not_fold_into_the_typing_around_it() {
12095        let mut d = doc_with("compose_typing", "\n");
12096        d.caret = 0;
12097        d.insert("a");
12098        d.insert("b");
12099        d.edit_composing(2, 2, "か");
12100        d.edit_composing(2, 5, "蚊");
12101        d.end_composition();
12102        d.insert("c");
12103        assert_eq!(d.source, "ab蚊c\n");
12104        d.undo();
12105        assert_eq!(d.source, "ab蚊\n");
12106        d.undo();
12107        assert_eq!(d.source, "ab\n");
12108        d.undo();
12109        assert_eq!(d.source, "\n");
12110    }
12111
12112    #[test]
12113    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
12114        let mut d = doc_with("compose_spurious", "\n");
12115        d.caret = 0;
12116        d.insert("a");
12117        d.end_composition(); // an IME unmarking unprompted
12118        d.insert("b");
12119        assert_eq!(d.source, "ab\n");
12120        d.undo();
12121        assert_eq!(d.source, "\n", "still one typed run");
12122    }
12123
12124    // ── the clipboard's rich flavor ──────────────────────────────────────────
12125
12126    #[test]
12127    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
12128        let mut d = doc_with("sel_inline", "a **bold** c\n");
12129        d.anchor = Some(2);
12130        d.caret = 10; // `**bold**`, inside the paragraph
12131        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
12132    }
12133
12134    #[test]
12135    fn a_whole_block_selection_keeps_its_paragraph() {
12136        let mut d = doc_with("sel_block", "a **bold** c\n");
12137        d.anchor = Some(0);
12138        d.caret = 12; // the entire paragraph
12139        assert_eq!(
12140            d.selection_html().as_deref(),
12141            Some("<p>a <strong>bold</strong> c</p>")
12142        );
12143    }
12144
12145    #[test]
12146    fn a_multi_block_selection_keeps_its_structure() {
12147        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
12148        d.select_all();
12149        let html = d.selection_html().expect("renders");
12150        assert!(html.contains("<p>para</p>"), "{html:?}");
12151        assert!(html.contains("<li>one</li>"), "{html:?}");
12152    }
12153
12154    #[test]
12155    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
12156        // The fragment `Head` is a paragraph standalone; the *document* says it
12157        // sits inside one block, so the wrapper is an artifact either way.
12158        let mut d = doc_with("sel_heading", "# Head line\n");
12159        d.anchor = Some(2);
12160        d.caret = 6;
12161        assert_eq!(d.selection_html().as_deref(), Some("Head"));
12162    }
12163
12164    #[test]
12165    fn no_selection_publishes_no_html() {
12166        let mut d = doc_with("sel_none", "a b\n");
12167        d.caret = 1;
12168        assert_eq!(d.selection_html(), None);
12169    }
12170
12171    #[test]
12172    fn pasting_html_converts_it_and_is_one_undo_step() {
12173        let mut d = doc_with("paste_html", "x\n");
12174        d.caret = 1;
12175        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
12176        assert_eq!(d.source, "xa **b** c\n");
12177        d.undo();
12178        assert_eq!(d.source, "x\n", "the whole paste, in one step");
12179    }
12180
12181    #[test]
12182    fn pasting_html_replaces_the_selection() {
12183        let mut d = doc_with("paste_html_sel", "keep drop\n");
12184        d.anchor = Some(5);
12185        d.caret = 9;
12186        assert!(d.paste_html("<em>new</em>"));
12187        assert_eq!(d.source, "keep *new*\n");
12188    }
12189
12190    #[test]
12191    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
12192        let mut d = doc_with("paste_html_bad", "x\n");
12193        d.caret = 1;
12194        // twig builds no table from HTML; raw `<table>` in prose is worse than
12195        // the plain flavor the caller still holds.
12196        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
12197        assert_eq!(d.source, "x\n", "declined edits nothing");
12198    }
12199
12200    #[test]
12201    fn copy_then_paste_round_trips_through_the_html_flavor() {
12202        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
12203        d.select_all();
12204        let html = d.selection_html().expect("renders");
12205        let mut into = doc_with("clip_round_dst", "\n");
12206        into.caret = 0;
12207        assert!(into.paste_html(&html));
12208        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
12209    }
12210
12211    #[test]
12212    fn moving_the_caret_starts_a_new_undo_group() {
12213        let mut d = doc_with("break", "\n");
12214        d.caret = 0;
12215        d.insert("a");
12216        d.insert("b"); // "ab\n", caret at 2
12217        d.move_left(false); // breaks the run
12218        d.insert("X"); // "aXb\n"
12219        assert_eq!(d.source, "aXb\n");
12220        d.undo();
12221        assert_eq!(
12222            d.source, "ab\n",
12223            "first undo removes only the post-move insert"
12224        );
12225        d.undo();
12226        assert_eq!(d.source, "\n", "second undo removes the earlier run");
12227    }
12228
12229    #[test]
12230    fn undo_reverses_a_format_toggle() {
12231        let mut d = doc_with("fmt_undo", "a word b\n");
12232        d.anchor = Some(2);
12233        d.caret = 6;
12234        d.toggle(InlineKind::Strong);
12235        assert_eq!(d.source, "a **word** b\n");
12236        d.undo();
12237        assert_eq!(d.source, "a word b\n");
12238    }
12239
12240    #[test]
12241    fn undo_back_to_the_saved_state_clears_dirty() {
12242        let mut d = doc_with("dirty_undo", "hello\n");
12243        assert!(!d.dirty);
12244        d.caret = 5;
12245        d.insert("!");
12246        assert!(d.dirty);
12247        d.undo();
12248        assert!(
12249            !d.dirty,
12250            "undoing to the saved source is not a modification"
12251        );
12252    }
12253
12254    #[test]
12255    fn a_new_edit_invalidates_redo() {
12256        let mut d = doc_with("redo_inv", "\n");
12257        d.caret = 0;
12258        d.insert("a");
12259        d.undo();
12260        d.insert("b"); // diverges — the redo of "a" is now gone
12261        d.redo();
12262        assert_eq!(d.source, "b\n");
12263    }
12264
12265    #[test]
12266    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
12267        let mut d = doc_with("can_undo", "hello\n");
12268        assert!(
12269            !d.can_undo() && !d.can_redo(),
12270            "a fresh document has no history"
12271        );
12272        d.caret = 5;
12273        d.insert("!");
12274        assert!(
12275            d.can_undo() && !d.can_redo(),
12276            "an edit is a step to take back"
12277        );
12278        d.undo();
12279        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
12280        d.redo();
12281        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
12282        d.undo();
12283        d.insert("?");
12284        assert!(
12285            d.can_undo() && !d.can_redo(),
12286            "a fresh edit ends the redo chain"
12287        );
12288        // A coalesced run over-counts steps — the bound is what a menu needs,
12289        // and it reconciles the moment twig reports the history empty.
12290        d.insert("a");
12291        d.insert("b");
12292        while d.can_undo() {
12293            d.undo();
12294        }
12295        assert_eq!(d.source, "hello\n");
12296        assert!(!d.can_undo());
12297        // A reading surface has nothing to undo, whatever the history holds.
12298        d.redo();
12299        d.set_read_only(true);
12300        assert!(!d.can_undo() && !d.can_redo());
12301    }
12302
12303    #[test]
12304    fn undo_on_empty_history_is_a_no_op() {
12305        let mut d = doc_with("undo_empty", "hi\n");
12306        d.undo();
12307        assert_eq!(d.source, "hi\n");
12308        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
12309    }
12310
12311    #[test]
12312    fn a_one_character_paste_is_its_own_undo_step() {
12313        for view in [View::Source, View::Wysiwyg] {
12314            let mut d = doc_in(view, "paste_step", "ab\n");
12315            d.caret = 0;
12316            d.insert("x");
12317            d.insert("y"); // a run of typing
12318            d.paste("z"); // one character, but pasted — not part of that run
12319            assert_eq!(d.source, "xyzab\n");
12320            d.undo();
12321            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
12322            assert_eq!(d.caret, 2, "and hands back the caret it found");
12323            d.undo();
12324            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
12325        }
12326    }
12327
12328    #[test]
12329    fn the_same_character_typed_still_joins_the_run() {
12330        // The other half of the pair: `z` is a keystroke here and a paste above,
12331        // and the two undo differently. Nothing about the *string* says which —
12332        // which is why provenance has to come from the door the caller uses.
12333        for view in [View::Source, View::Wysiwyg] {
12334            let mut d = doc_in(view, "typed_run", "ab\n");
12335            d.caret = 0;
12336            d.insert("x");
12337            d.insert("y");
12338            d.insert("z");
12339            d.undo();
12340            assert_eq!(d.source, "ab\n", "one run, one step");
12341        }
12342    }
12343
12344    #[test]
12345    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
12346        for view in [View::Source, View::Wysiwyg] {
12347            let mut d = doc_in(view, "undo_caret", "hello world\n");
12348            d.caret = 11; // standing at the end of "world", away from the edit
12349            d.edit(0, 5, "goodbye");
12350            assert_eq!(d.source, "goodbye world\n");
12351            d.undo();
12352            assert_eq!(d.source, "hello world\n");
12353            // The undone edit ends at offset 5; the user was at 11.
12354            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
12355        }
12356    }
12357
12358    #[test]
12359    fn undo_restores_the_selection_the_edit_replaced() {
12360        for view in [View::Source, View::Wysiwyg] {
12361            let mut d = doc_in(view, "undo_sel", "a word b\n");
12362            d.anchor = Some(2);
12363            d.caret = 6; // "word" selected
12364            d.insert("X");
12365            assert_eq!(d.source, "a X b\n");
12366            d.undo();
12367            assert_eq!(d.source, "a word b\n");
12368            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
12369        }
12370    }
12371
12372    #[test]
12373    fn redo_restores_the_caret_the_edit_left_behind() {
12374        for view in [View::Source, View::Wysiwyg] {
12375            let mut d = doc_in(view, "redo_caret", "hello world\n");
12376            d.caret = 11;
12377            d.edit(0, 5, "goodbye");
12378            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
12379            d.undo();
12380            d.redo();
12381            assert_eq!(d.source, "goodbye world\n");
12382            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
12383        }
12384    }
12385
12386    #[test]
12387    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
12388        for view in [View::Source, View::Wysiwyg] {
12389            let mut d = doc_in(view, "run_caret", "hi\n");
12390            d.caret = 2;
12391            d.insert("a");
12392            d.insert("b");
12393            d.insert("c");
12394            assert_eq!(d.source, "hiabc\n");
12395            d.undo();
12396            assert_eq!(d.source, "hi\n");
12397            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
12398            d.redo();
12399            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
12400        }
12401    }
12402
12403    #[test]
12404    fn undo_restores_the_caret_across_a_format_toggle() {
12405        // A toggle reaches twig without going through `splice`, so it has to
12406        // record its own step — miss it and every stack depth below it is off by
12407        // one, and undo starts handing back another edit's caret.
12408        for view in [View::Source, View::Wysiwyg] {
12409            let mut d = doc_in(view, "fmt_caret", "a word b\n");
12410            d.caret = 8;
12411            d.anchor = Some(2);
12412            d.caret = 6;
12413            d.toggle(InlineKind::Strong);
12414            assert_eq!(d.source, "a **word** b\n");
12415            d.undo();
12416            assert_eq!(d.source, "a word b\n");
12417            assert_eq!(
12418                d.selection(),
12419                Some((2, 6)),
12420                "the toggled selection comes back"
12421            );
12422        }
12423    }
12424
12425    #[test]
12426    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
12427        // The drift that would never announce itself: twig drops its redo stack
12428        // on any fresh edit, so a leaf redo entry that outlives it would restore
12429        // a caret from the timeline that edit abandoned.
12430        for view in [View::Source, View::Wysiwyg] {
12431            let mut d = doc_in(view, "redo_trunc", "hello world\n");
12432            d.caret = 11;
12433            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
12434            d.undo();
12435            assert_eq!(d.caret, 11);
12436            d.caret = 0;
12437            d.insert("X"); // diverges: A's redo is gone from twig
12438            assert_eq!(d.source, "Xhello world\n");
12439
12440            d.redo();
12441            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
12442            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
12443            d.undo();
12444            assert_eq!(d.source, "hello world\n");
12445            assert_eq!(
12446                d.caret, 0,
12447                "the surviving step's caret, not the dropped one"
12448            );
12449        }
12450    }
12451
12452    #[test]
12453    fn indent_and_outdent_move_the_caret_line_with_its_text() {
12454        for view in [View::Source, View::Wysiwyg] {
12455            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
12456            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
12457            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
12458            // Indentation the caret is standing *in* collapses to the line start
12459            // rather than dragging the caret into the text.
12460            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
12461            // A line with none to give back is left exactly as it was.
12462            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
12463            // Less than a full level gives back what it has.
12464            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
12465            // A tab is one level however many spaces it isn't.
12466            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
12467        }
12468    }
12469
12470    #[test]
12471    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
12472        // Why the level is two spaces and not the four both frontends type
12473        // today. Four is markdown's indented-code-block marker, so a Tab on a
12474        // paragraph would silently restyle it as code — a width that changes
12475        // what the document *means* isn't an indent. Pinned because the number
12476        // is the kind of thing a later list-aware pass would reach for.
12477        let mut d = doc_with("indent_kind", "hello\n");
12478        d.caret = 2;
12479        d.indent();
12480        assert_eq!(d.source, "  hello\n");
12481        assert!(
12482            d.nodes().iter().any(|n| n.kind == Kind::Para),
12483            "still prose after a Tab"
12484        );
12485        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
12486
12487        // The four-space level this replaces, for contrast: same text, and twig
12488        // reparses the paragraph into a code block.
12489        let mut wide = doc_with("indent_kind_4", "    hello\n");
12490        wide.build_visual(80);
12491        assert!(
12492            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
12493            "four spaces is a code block, not an indented paragraph"
12494        );
12495    }
12496
12497    #[test]
12498    fn indent_nests_a_list_item_under_its_parent() {
12499        // Tab indents a list item by its own marker width, landing its marker at
12500        // the parent's content column so twig reparses it as a nested list.
12501        for view in [View::Source, View::Wysiwyg] {
12502            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
12503            d.caret = 6; // on the second item
12504            d.indent();
12505            assert_eq!(d.source, "- a\n  - b\n");
12506            let lists = d
12507                .nodes()
12508                .iter()
12509                .filter(|n| n.kind == Kind::BulletList)
12510                .count();
12511            assert_eq!(lists, 2, "the indented item is a nested list");
12512        }
12513    }
12514
12515    #[test]
12516    fn indent_nests_an_ordered_item_at_its_marker_width() {
12517        // An ordered marker `1. ` is three columns wide, so a two-space step
12518        // (which nests a bullet) leaves it flat. Regression: Tab must use the
12519        // marker width, three, so the item actually nests — and the source
12520        // renumbers so the sub-list restarts at 1 and the outer list resumes.
12521        for view in [View::Source, View::Wysiwyg] {
12522            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
12523            d.caret = d.source.find('b').unwrap();
12524            d.indent();
12525            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
12526            let lists = d
12527                .nodes()
12528                .iter()
12529                .filter(|n| n.kind == Kind::OrderedList)
12530                .count();
12531            assert_eq!(lists, 2, "the indented item is a nested ordered list");
12532        }
12533    }
12534
12535    #[test]
12536    fn indent_leaves_a_lists_first_item_put() {
12537        // The first item of a list has no sibling above it to nest under, so Tab
12538        // is a no-op there — the marker stays at column zero rather than being
12539        // shoved into indentation twig can't read as a sub-list.
12540        for view in [View::Source, View::Wysiwyg] {
12541            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
12542            d.caret = 1; // on the FIRST item
12543            d.indent();
12544            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
12545            // The sibling below still nests, proving the guard is per-item.
12546            d.caret = d.source.find('b').unwrap();
12547            d.indent();
12548            assert_eq!(d.source, "- a\n  - b\n");
12549        }
12550    }
12551
12552    #[test]
12553    fn hidden_mode_keeps_typed_markup_literal() {
12554        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
12555        // twig escapes what would open markup, so the source is `\*hi\*` and the
12556        // AST is a plain string. Formatting is the commands' job in this mode.
12557        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
12558        d.insert("*hi*");
12559        assert_eq!(d.source, "\\*hi\\*");
12560        assert!(
12561            d.nodes()
12562                .iter()
12563                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
12564        );
12565    }
12566
12567    #[test]
12568    fn hidden_mode_escapes_a_line_start_block_marker() {
12569        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
12570        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
12571        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
12572        d.insert("# hi");
12573        assert_eq!(d.source, "\\# hi");
12574        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
12575    }
12576
12577    #[test]
12578    fn authoring_modes_keep_typed_markup_live() {
12579        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
12580        // (no escape), the same as source view — escaping is `None`'s alone, and
12581        // it's the axis, not the reveal, that decides.
12582        for (view, mode) in [
12583            (View::Wysiwyg, MarkupMode::Shortcuts),
12584            (View::Wysiwyg, MarkupMode::Full),
12585            (View::Source, MarkupMode::None),
12586        ] {
12587            let mut d = doc_in(view, "live_markup", "");
12588            d.set_markup_mode(mode);
12589            d.insert("*hi*");
12590            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
12591        }
12592    }
12593
12594    #[test]
12595    fn hidden_mode_overwrite_undoes_in_one_step() {
12596        // Typing over a selection escapes the replacement *and* stays a single
12597        // undo — the selection-delete and the literal insert fold together, so
12598        // one undo brings the whole selection back, like a plain overwrite.
12599        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
12600        d.anchor = Some(2);
12601        d.caret = 6; // "word"
12602        d.insert("*");
12603        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
12604        d.undo();
12605        assert_eq!(d.source, "a word b\n");
12606        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
12607    }
12608
12609    #[test]
12610    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
12611        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
12612        // the whole visual character, never stranding the hidden `\`.
12613        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
12614        d.insert("*");
12615        assert_eq!(d.source, "\\*");
12616        d.backspace();
12617        assert_eq!(d.source, "", "the escape backslash went with the *");
12618        // A *literal* backslash (source view, no escape) is an ordinary char.
12619        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
12620        s.caret = 3; // after `b`
12621        s.backspace();
12622        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
12623    }
12624
12625    #[test]
12626    fn hidden_mode_leaves_structural_markup_alone() {
12627        // Enter continues a bullet list by writing a real `- ` marker (an
12628        // `insert_raw`, not the typing path), so Hidden mode's escaping never
12629        // touches it — the list keeps working.
12630        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
12631        d.caret = 6;
12632        d.newline();
12633        d.insert("two");
12634        assert_eq!(d.source, "- item\n- two\n");
12635    }
12636
12637    #[test]
12638    fn markup_mode_defaults_to_none_and_round_trips() {
12639        // Diaryx's default is the clean `None` surface; a markup-fluent
12640        // frontend can climb the ladder, and the choice sticks.
12641        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
12642        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
12643        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
12644            d.set_markup_mode(mode);
12645            assert_eq!(d.markup_mode(), mode);
12646        }
12647    }
12648
12649    #[test]
12650    fn full_mode_reveals_only_the_caret_line() {
12651        // The mode's whole claim: the caret's line shows its raw delimiters and
12652        // every other line stays resolved. Two paragraphs with identical markup
12653        // so the only difference between the rows is where the caret is.
12654        let mut d = doc_in(
12655            View::Wysiwyg,
12656            "reveal_caret_line",
12657            "*one* here\n\n*two* there\n",
12658        );
12659        d.set_markup_mode(MarkupMode::Full);
12660
12661        caret_at(&mut d, "one");
12662        let rows = drawn_rows(&d);
12663        assert!(
12664            rows.iter().any(|r| r == "*one* here"),
12665            "caret's line raw: {rows:?}"
12666        );
12667        assert!(
12668            rows.iter().any(|r| r == "two there"),
12669            "other line resolved: {rows:?}"
12670        );
12671
12672        // Move to the other paragraph: the reveal follows, and the line just
12673        // left goes back to being resolved.
12674        caret_at(&mut d, "two");
12675        let rows = drawn_rows(&d);
12676        assert!(
12677            rows.iter().any(|r| r == "*two* there"),
12678            "caret's line raw: {rows:?}"
12679        );
12680        assert!(
12681            rows.iter().any(|r| r == "one here"),
12682            "left line resolved: {rows:?}"
12683        );
12684    }
12685
12686    #[test]
12687    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
12688        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
12689        // the same treatment as an emphasis's `*`: hidden while the caret is
12690        // elsewhere, shown in full where the caret lands. That falls out of
12691        // `delims` reading the bytes between the mark's span and its content
12692        // span, which is exactly `==🔴 ` and `==`, rather than from a table
12693        // of spellings — so the no-space form `==🟢green==` reveals right too.
12694        let mut d = doc_in(
12695            View::Wysiwyg,
12696            "reveal_coloured_mark",
12697            "a ==🔴 red== one\n\nb ==plain== two\n",
12698        );
12699        d.set_markup_mode(MarkupMode::Full);
12700
12701        caret_at(&mut d, "red");
12702        let rows = drawn_rows(&d);
12703        assert!(
12704            rows.iter().any(|r| r == "a ==🔴 red== one"),
12705            "the caret's line shows the colour it was written with: {rows:?}"
12706        );
12707        assert!(
12708            rows.iter().any(|r| r == "b plain two"),
12709            "and every other line stays resolved: {rows:?}"
12710        );
12711
12712        // Away from it, the emoji goes back to being markup — the reader sees
12713        // the words and the wash.
12714        caret_at(&mut d, "two");
12715        let rows = drawn_rows(&d);
12716        assert!(
12717            rows.iter().any(|r| r == "a red one"),
12718            "resolved again: {rows:?}"
12719        );
12720    }
12721
12722    #[test]
12723    fn hidden_modes_never_reveal_wherever_the_caret_is() {
12724        // The two rungs below `Full` share a rendering: delimiters stay hidden
12725        // even under the caret. `Shortcuts` differing from `None` only in what
12726        // typing does is exactly the point of splitting the axes.
12727        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
12728            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
12729            d.set_markup_mode(mode);
12730            caret_at(&mut d, "one");
12731            let rows = drawn_rows(&d);
12732            assert!(
12733                rows.iter().any(|r| r == "one here"),
12734                "{mode:?} hides: {rows:?}"
12735            );
12736            assert!(
12737                !rows.iter().any(|r| r.contains('*')),
12738                "{mode:?} shows no `*`: {rows:?}"
12739            );
12740        }
12741    }
12742
12743    #[test]
12744    fn revealed_delimiters_are_the_authors_own_spelling() {
12745        // Delimiters are re-read from the source rather than synthesized per
12746        // kind, so a line comes back spelled the way it was written: `_em_` does
12747        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
12748        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
12749        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
12750        d.set_markup_mode(MarkupMode::Full);
12751        caret_at(&mut d, "em");
12752        let rows = drawn_rows(&d);
12753        assert!(
12754            rows.iter().any(|r| r == body.trim_end()),
12755            "the revealed line is its own source: {rows:?}"
12756        );
12757    }
12758
12759    #[test]
12760    fn revealed_heading_shows_its_hashes() {
12761        // The `# ` marker is a block-level prefix, not an inline delimiter, so
12762        // it takes its own path — but it reveals on the same rule.
12763        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
12764        d.set_markup_mode(MarkupMode::Full);
12765
12766        caret_at(&mut d, "Title");
12767        assert!(
12768            drawn_rows(&d).iter().any(|r| r == "# Title"),
12769            "{:?}",
12770            drawn_rows(&d)
12771        );
12772
12773        caret_at(&mut d, "body");
12774        let rows = drawn_rows(&d);
12775        assert!(
12776            rows.iter().any(|r| r == "Title"),
12777            "hashes hidden again: {rows:?}"
12778        );
12779    }
12780
12781    #[test]
12782    fn revealed_delimiters_are_caret_stops() {
12783        // A delimiter that is drawn but can't be reached is worse than one
12784        // that's hidden: the mode exists so the markup can be *edited*. Every
12785        // revealed byte must be somewhere the caret can stand.
12786        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
12787        d.set_markup_mode(MarkupMode::Full);
12788        caret_at(&mut d, "em");
12789        let opener = d.source.find('*').unwrap();
12790        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
12791        assert!(
12792            d.vmap.is_stop(opener + 3),
12793            "the closing `*` is a caret stop"
12794        );
12795    }
12796
12797    #[test]
12798    fn setext_heading_reveals_nothing_across_its_newline() {
12799        // A setext heading's underline is on another line, so it is not the
12800        // caret line's to reveal — and emitting it would inject a `\n` glyph
12801        // that splits the row where the author wrote no break.
12802        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
12803        d.set_markup_mode(MarkupMode::Full);
12804        caret_at(&mut d, "Title");
12805        let rows = drawn_rows(&d);
12806        assert!(
12807            rows.iter().any(|r| r == "Title"),
12808            "title renders alone: {rows:?}"
12809        );
12810        assert!(
12811            !rows.iter().any(|r| r.contains('=')),
12812            "no underline leaks in: {rows:?}"
12813        );
12814    }
12815
12816    #[test]
12817    fn markup_mode_axes_split_the_ladder() {
12818        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
12819        // that authors markup but still hides it, and it's the only rung where
12820        // the two axes disagree.
12821        assert!(!MarkupMode::None.authors());
12822        assert!(!MarkupMode::None.reveals_caret_line());
12823        assert!(MarkupMode::Shortcuts.authors());
12824        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
12825        assert!(MarkupMode::Full.authors());
12826        assert!(MarkupMode::Full.reveals_caret_line());
12827    }
12828
12829    #[test]
12830    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
12831        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
12832        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
12833        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
12834        // nested bullet and `hello` stays prose: the file round-trips instead of
12835        // hiding a heading the user never asked for.
12836        for view in [View::Source, View::Wysiwyg] {
12837            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
12838            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
12839            d.indent();
12840            assert_eq!(d.source, "- hello\n  * \n");
12841            assert!(
12842                d.nodes().iter().all(|n| n.kind != Kind::Heading),
12843                "no heading"
12844            );
12845            // And it's genuinely a nested list, not a flat one.
12846            assert_eq!(
12847                d.nodes()
12848                    .iter()
12849                    .filter(|n| n.kind == Kind::BulletList)
12850                    .count(),
12851                2
12852            );
12853        }
12854    }
12855
12856    #[test]
12857    fn indenting_a_dash_item_with_content_keeps_its_dash() {
12858        // With content, `- x` can't be a setext underline, so there's nothing to
12859        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
12860        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
12861        d.caret = d.source.find('x').unwrap();
12862        d.indent();
12863        assert_eq!(d.source, "- hello\n  - x\n");
12864    }
12865
12866    #[test]
12867    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
12868        // The dash→`*` repair coalesces into the Tab, so a single undo restores
12869        // the whole pre-Tab state rather than stranding a half-collapsed doc.
12870        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
12871        d.caret = d.source.find("- \n").unwrap() + 2;
12872        d.indent();
12873        assert_eq!(d.source, "- hello\n  * \n");
12874        d.undo();
12875        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
12876    }
12877
12878    #[test]
12879    fn indent_leaves_a_nested_lists_first_item_put_too() {
12880        // The guard is about siblings, not depth: the first item of an *inner*
12881        // list (already nested under `a`) still has nothing before it at its own
12882        // level, so Tab can't take it deeper.
12883        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
12884        d.caret = d.source.find('b').unwrap();
12885        d.indent();
12886        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
12887        // But `c` (a sibling of `b`) nests under `b`.
12888        d.caret = d.source.find('c').unwrap();
12889        d.indent();
12890        assert_eq!(d.source, "- a\n  - b\n    - c\n");
12891    }
12892
12893    #[test]
12894    fn backspace_at_a_nested_item_start_outdents_it() {
12895        // Backspace with the caret right after a nested item's marker gives back
12896        // one level of nesting, the mirror of Tab — and renumbers the flattened
12897        // ordered list back to a clean run.
12898        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
12899        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
12900        d.backspace();
12901        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
12902    }
12903
12904    #[test]
12905    fn backspace_at_a_top_level_item_start_strips_the_marker() {
12906        // At the outermost level there's no nesting left to give back, so the same
12907        // keystroke drops the bullet and leaves a plain paragraph.
12908        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
12909        d.caret = d.source.find('b').unwrap(); // right after `- `
12910        d.backspace();
12911        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
12912    }
12913
12914    #[test]
12915    fn backspace_mid_item_still_deletes_a_character() {
12916        // The list behaviour is armed only at the item's content start; anywhere
12917        // else Backspace is the ordinary character delete.
12918        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
12919        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
12920        d.backspace();
12921        assert_eq!(d.source, "- b\n");
12922    }
12923
12924    #[test]
12925    fn backspace_at_a_heading_start_strips_the_marker() {
12926        // The `# ` is markup the rich view hides, so Backspace over it takes the
12927        // whole marker and leaves a paragraph. Deleting a byte of it instead left
12928        // `#Title` — no longer a heading, with the hash now literal text the user
12929        // never typed and has to delete again.
12930        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
12931        d.caret = d.source.find('T').unwrap(); // right after `## `
12932        d.backspace();
12933        assert_eq!(d.source, "Title\n");
12934        assert_eq!(
12935            d.caret, 0,
12936            "the caret stays with the text it was in front of"
12937        );
12938    }
12939
12940    #[test]
12941    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
12942        // Only the heading's own marker goes — the quote (or list) it sits in is
12943        // untouched, exactly as un-heading it should be.
12944        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
12945        d.caret = d.source.find('T').unwrap();
12946        d.backspace();
12947        assert_eq!(d.source, "> Title\n");
12948    }
12949
12950    #[test]
12951    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
12952        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
12953        // behind would surface the same stray hash the marker delete just avoided.
12954        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
12955        d.caret = d.source.find('T').unwrap();
12956        d.backspace();
12957        assert_eq!(d.source, "Title\n");
12958        // And it's one edit: a single undo puts the whole heading back.
12959        d.undo();
12960        assert_eq!(d.source, "# Title #\n");
12961    }
12962
12963    #[test]
12964    fn backspace_mid_heading_still_deletes_a_character() {
12965        // The heading behaviour is armed only at the content's start; anywhere
12966        // else Backspace is the ordinary character delete.
12967        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
12968        d.caret = d.source.find('b').unwrap();
12969        d.backspace();
12970        assert_eq!(d.source, "# b\n");
12971    }
12972
12973    #[test]
12974    fn source_view_backspace_still_edits_the_heading_marker_literally() {
12975        // In source view the `# ` is text on the screen the user is deleting a
12976        // byte of, so it keeps its literal meaning — the same split the list
12977        // ladder and Enter draw between the two views.
12978        let mut d = doc_with("bsp_head_src", "# Title\n");
12979        d.caret = d.source.find('T').unwrap();
12980        d.backspace();
12981        assert_eq!(d.source, "#Title\n");
12982    }
12983
12984    #[test]
12985    fn outdent_unnests_an_ordered_item_in_one_press() {
12986        // Shift+Tab gives back exactly the marker width the indent added, so a
12987        // nested ordered item unnests in a single press, and the flattened list
12988        // renumbers back to a clean 1, 2, 3.
12989        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
12990        d.caret = d.source.find('b').unwrap();
12991        d.outdent();
12992        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
12993        let lists = d
12994            .nodes()
12995            .iter()
12996            .filter(|n| n.kind == Kind::OrderedList)
12997            .count();
12998        assert_eq!(lists, 1, "back to one flat list");
12999    }
13000
13001    #[test]
13002    fn table_insert_row_adds_a_row_below_the_caret() {
13003        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
13004        d.caret = d.source.find('1').unwrap(); // in the body row
13005        d.table_insert_row(true);
13006        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
13007    }
13008
13009    #[test]
13010    fn table_insert_and_delete_column_at_the_caret() {
13011        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
13012        d.caret = d.source.find('a').unwrap(); // column 0
13013        d.table_insert_column(true); // add a column to the right of `a`
13014        assert_eq!(
13015            d.source,
13016            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
13017        );
13018        d.caret = d.source.find('b').unwrap(); // now the third column
13019        d.table_delete_column();
13020        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
13021    }
13022
13023    // ── ragged formats ───────────────────────────────────────────────────────
13024    // No format spells every gesture. HTML writes the inline marks as a tag pair
13025    // and no heading, list, quote or link; Markdown spells five of the eight
13026    // marks — the highlight only because leaf parses with `highlight`, which is
13027    // why the question is asked with the extensions; djot spells all eight and
13028    // no in-cell break. leaf asks twig per
13029    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
13030    // op discover the fact on its own — one of them didn't.
13031
13032    /// An HTML document in the rich view, ready for a gesture.
13033    fn html_doc(body: &str) -> Doc {
13034        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
13035        d.view = View::Wysiwyg;
13036        d.build_visual(80);
13037        d
13038    }
13039
13040    #[test]
13041    fn a_table_gesture_leaves_an_html_table_alone() {
13042        // The regression this guard exists for. twig's table editor consults no
13043        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
13044        // HTML `<table>` as a *pipe table* and reported success: the whole
13045        // element replaced by `| a | b |`, silently, on one press of a toolbar
13046        // button. Every grid op went the same way.
13047        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
13048        // A table of named operations, which is what it looks like.
13049        #[allow(clippy::type_complexity)]
13050        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
13051            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
13052            ("delete row", &|d: &mut Doc| d.table_delete_row()),
13053            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
13054            ("delete column", &|d: &mut Doc| d.table_delete_column()),
13055            ("align", &|d: &mut Doc| {
13056                d.table_set_alignment(Alignment::Right)
13057            }),
13058            ("move row", &|d: &mut Doc| d.table_move_row(true)),
13059            ("move column", &|d: &mut Doc| d.table_move_column(true)),
13060        ];
13061        for (name, op) in ops {
13062            let mut d = html_doc(src);
13063            d.caret = d.source.find('a').unwrap();
13064            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
13065            op(&mut d);
13066            assert_eq!(d.source, src, "{name} rewrote an HTML table");
13067            assert!(
13068                !d.dirty,
13069                "{name} marked the document dirty without editing it"
13070            );
13071            assert!(d.status.is_some(), "{name} refused without saying why");
13072        }
13073    }
13074
13075    #[test]
13076    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
13077        // A task box is a form control in HTML and a footnote has no native
13078        // spelling at all — the two gestures twig 3.5 still spells nothing
13079        // for, now that a quote, a list, a link and an image print through
13080        // its renderer (see the test below).
13081        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
13082        // A table of named operations, which is what it looks like.
13083        #[allow(clippy::type_complexity)]
13084        let ops: [(&str, &dyn Fn(&mut Doc)); 3] = [
13085            ("task item", &|d: &mut Doc| d.toggle_task_item()),
13086            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
13087            ("footnote", &|d: &mut Doc| d.insert_footnote()),
13088        ];
13089        for (name, op) in ops {
13090            let mut d = html_doc(src);
13091            let at = d.source.find("Hello").unwrap();
13092            d.caret = at;
13093            d.anchor = Some(at + 5); // a selection, for the ops that want one
13094            op(&mut d);
13095            assert_eq!(d.source, src, "{name} edited an HTML document");
13096            assert!(
13097                !d.dirty,
13098                "{name} marked the document dirty without editing it"
13099            );
13100            let status = d.status.as_deref().unwrap_or("");
13101            assert!(
13102                status.contains("html"),
13103                "{name}: the refusal should name the format, got {status:?}"
13104            );
13105        }
13106    }
13107
13108    #[test]
13109    fn html_spells_a_quote_a_list_a_link_and_an_image_through_the_renderer() {
13110        // twig 3.5: where HTML has no marker alphabet it prints the fresh
13111        // node — a `<blockquote>` around the paragraph, a `<ul>`/`<ol>` with
13112        // the paragraph as its item, an `<a>` or `<img>` over the selection.
13113        // Until then every one of these was a refusal; now each is a real
13114        // edit, which is what the toolbar's capability flags say too.
13115        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
13116        #[allow(clippy::type_complexity)]
13117        let ops: [(&str, &dyn Fn(&mut Doc), &str); 5] = [
13118            (
13119                "quote",
13120                &|d: &mut Doc| d.toggle_blockquote(),
13121                "<blockquote>",
13122            ),
13123            ("list", &|d: &mut Doc| d.toggle_list(false), "<ul>\n<li>"),
13124            (
13125                "ordered list",
13126                &|d: &mut Doc| d.toggle_list(true),
13127                "<ol>\n<li>",
13128            ),
13129            (
13130                "link",
13131                &|d: &mut Doc| d.insert_link("https://example.dev"),
13132                "<a href=\"https://example.dev\">Hello</a>",
13133            ),
13134            (
13135                "image",
13136                &|d: &mut Doc| d.insert_image("pic.png", "alt"),
13137                "<img alt=\"Hello\" src=\"pic.png\">",
13138            ),
13139        ];
13140        for (name, op, expect) in ops {
13141            let mut d = html_doc(src);
13142            let at = d.source.find("Hello").unwrap();
13143            d.caret = at;
13144            d.anchor = Some(at + 5);
13145            op(&mut d);
13146            assert!(d.source.contains(expect), "{name}: got {:?}", d.source);
13147            assert!(d.dirty, "{name}: a real edit");
13148            assert_eq!(
13149                d.status, None,
13150                "{name}: a supported gesture reports nothing"
13151            );
13152        }
13153    }
13154
13155    #[test]
13156    fn html_spells_a_heading_as_its_tag_pair() {
13157        // twig 3.4 rebuilds a heading or paragraph as its tag pair, attributes
13158        // along — the one block gesture whose HTML shape it can write. So ⌘2
13159        // in an HTML document is a real edit, and ⌘0 takes it back.
13160        let src = "<h1>Title</h1>\n<p>Hello world</p>\n";
13161        let mut d = html_doc(src);
13162        d.caret = d.source.find("Hello").unwrap();
13163        d.toggle_heading(2);
13164        assert_eq!(d.source, "<h1>Title</h1>\n<h2>Hello world</h2>\n");
13165        assert!(d.dirty);
13166        assert_eq!(d.status, None, "a supported gesture reports nothing");
13167        d.toggle_heading(2);
13168        assert_eq!(d.source, src, "the same level again is back to a paragraph");
13169    }
13170
13171    #[test]
13172    fn html_spells_the_inline_marks_and_the_rule() {
13173        // The other half, and why one per-document flag stopped being enough:
13174        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
13175        // already emits and the parser reads straight back as the same mark —
13176        // and the rule button writes an `<hr>`. Refusing these on the old
13177        // "HTML is parse-only" reading would now be leaf's own limitation.
13178        let mut d = html_doc("<p>Hello world</p>\n");
13179        let at = d.source.find("world").unwrap();
13180        d.caret = at;
13181        d.anchor = Some(at + 5);
13182        d.toggle(InlineKind::Strong);
13183        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
13184        assert!(d.dirty);
13185        assert_eq!(d.status, None, "a supported gesture reports nothing");
13186
13187        // And off again — the toggle reverses, which is the property that makes
13188        // authoring in HTML worth offering rather than a one-way trip.
13189        d.toggle(InlineKind::Strong);
13190        assert_eq!(d.source, "<p>Hello world</p>\n");
13191
13192        let mut d = html_doc("<p>Hello world</p>\n");
13193        d.caret = d.source.find("world").unwrap();
13194        d.insert_thematic_break();
13195        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
13196    }
13197
13198    #[test]
13199    fn a_mark_the_format_cannot_spell_arms_nothing() {
13200        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
13201        // sticky mark for the next text typed. Guarding only the twig call
13202        // leaves that path live, promising a mark the gesture will not write and
13203        // then swallowing the error inside `insert`.
13204        //
13205        // Markdown carries this, on the superscript now rather than on the
13206        // highlight: `^x^` is text there in any configuration, whereas twig
13207        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
13208        // which every leaf document does.
13209        let mut d = doc_with("mark", "Hello world\n");
13210        d.view = View::Wysiwyg;
13211        d.build_visual(80);
13212        d.caret = d.source.find("world").unwrap();
13213        d.toggle(InlineKind::Superscript);
13214        assert!(d.pending_marks.is_empty(), "no mark should be armed");
13215        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
13216        d.insert("X");
13217        assert_eq!(d.source, "Hello Xworld\n");
13218    }
13219
13220    #[test]
13221    fn markdown_authors_a_highlight_and_a_strikethrough() {
13222        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
13223        // write. `==x==` is authorable because leaf's own `parse_extensions`
13224        // turns `highlight` on — twig will only mint bytes this editor's reparse
13225        // reads back — and `~~x~~` because GFM strikethrough is parsed by
13226        // default, so the refusal there was never right for any leaf document.
13227        for (kind, marked) in [
13228            (InlineKind::Mark, "a ==word== b\n"),
13229            (InlineKind::Delete, "a ~~word~~ b\n"),
13230        ] {
13231            let mut d = doc_with("author_mark", "a word b\n");
13232            d.anchor = Some(2);
13233            d.caret = 6;
13234            d.toggle(kind);
13235            assert_eq!(d.source, marked, "{kind:?}");
13236            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
13237            assert!(d.dirty, "{kind:?}");
13238            // The region stays selected, so the second press reverses it — the
13239            // property that separates authoring from a one-way trip.
13240            d.toggle(kind);
13241            assert_eq!(d.source, "a word b\n", "{kind:?}");
13242        }
13243    }
13244
13245    #[test]
13246    fn an_authored_highlight_reads_back_as_a_mark() {
13247        // The round trip the extension gate exists to protect: what the toggle
13248        // writes, the reparse must read back as a `mark` rather than as two
13249        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
13250        // rebuilt map rather than from the source text.
13251        let mut d = doc_with("mark_roundtrip", "a word b\n");
13252        d.view = View::Wysiwyg;
13253        d.build_visual(80);
13254        d.anchor = Some(2);
13255        d.caret = 6;
13256        d.toggle(InlineKind::Mark);
13257        assert_eq!(d.source, "a ==word== b\n");
13258        d.build_visual(80);
13259        let w = d
13260            .vmap
13261            .rows
13262            .iter()
13263            .flat_map(|r| r.glyphs.iter())
13264            .find(|g| g.ch == 'w')
13265            .expect("the highlighted word");
13266        assert_eq!(w.style.role, crate::Role::Mark(None));
13267    }
13268
13269    #[test]
13270    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
13271        // The three states of one gesture, in the order a palette is pressed:
13272        // an uncoloured highlight takes the prefix, a coloured one has it
13273        // replaced, and `None` takes it away with the space that was part of the
13274        // spelling.
13275        let mut d = doc_with("mark_colour", "a ==word== b\n");
13276        d.caret = d.source.find("word").unwrap();
13277        d.set_mark_color(Some(MarkColor::Red));
13278        assert_eq!(d.source, "a ==🔴 word== b\n");
13279        assert_eq!(d.status, None);
13280        assert!(d.dirty);
13281
13282        d.set_mark_color(Some(MarkColor::Blue));
13283        assert_eq!(d.source, "a ==🔵 word== b\n");
13284
13285        d.set_mark_color(None);
13286        assert_eq!(d.source, "a ==word== b\n");
13287    }
13288
13289    #[test]
13290    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
13291        // The prefix is written *before* the word, so an offset in the word has
13292        // to ride its width — a caret that stayed put would be a caret that
13293        // walked backwards through the text it was standing in.
13294        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
13295        let word = d.source.find("word").unwrap();
13296        d.caret = word + 2; // between `wo` and `rd`
13297        d.set_mark_color(Some(MarkColor::Red));
13298        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
13299
13300        // And back the other way when the prefix goes.
13301        d.set_mark_color(None);
13302        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
13303    }
13304
13305    #[test]
13306    fn the_colour_at_the_caret_is_what_the_palette_lights() {
13307        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
13308        d.caret = d.source.find("red").unwrap();
13309        assert!(d.caret_in_mark());
13310        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
13311
13312        d.caret = d.source.find("plain").unwrap();
13313        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
13314        assert_eq!(d.mark_color_at_caret(), None);
13315
13316        d.caret = d.source.find(" and ").unwrap() + 2;
13317        assert!(!d.caret_in_mark());
13318        assert_eq!(d.mark_color_at_caret(), None);
13319    }
13320
13321    #[test]
13322    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
13323        // The gesture colours a highlight that exists; it does not make one.
13324        // Two presses is the price of a coloured highlight from bare text, and
13325        // the reason is undo — one press that spliced twice would take two
13326        // presses to take back.
13327        let mut d = doc_with("mark_colour_none", "a word b\n");
13328        d.caret = d.source.find("word").unwrap();
13329        d.set_mark_color(Some(MarkColor::Red));
13330        assert_eq!(d.source, "a word b\n");
13331        assert!(d.status.is_some(), "it should say why");
13332        assert!(!d.dirty);
13333
13334        // Clearing where there is nothing to clear is the same refusal, not a
13335        // quiet success — the caret is in no highlight either way.
13336        d.status = None;
13337        d.set_mark_color(None);
13338        assert_eq!(d.source, "a word b\n");
13339        assert!(d.status.is_some());
13340    }
13341
13342    #[test]
13343    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
13344        // twig answers this one *successfully* with a `Change` describing some
13345        // earlier edit, so a caller that trusted the change would jump the caret
13346        // to wherever that was. Core answers it before asking.
13347        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
13348        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
13349        d.caret = d.source.find("word").unwrap();
13350        let (source, caret) = (d.source.clone(), d.caret);
13351        d.set_mark_color(None);
13352        assert_eq!(d.source, source);
13353        assert_eq!(
13354            d.caret, caret,
13355            "the caret must not ride a change that isn't one"
13356        );
13357        assert_eq!(d.status, None, "and it is not an error either");
13358    }
13359
13360    #[test]
13361    fn djot_spells_the_highlight_and_not_its_colour() {
13362        // The reason the palette is its own capability rather than the Highlight
13363        // button's: `{=word=}` is a highlight djot writes happily, and there is
13364        // no djot spelling for a colour on it.
13365        assert!(Capabilities::of(Format::Djot).mark);
13366        assert!(!Capabilities::of(Format::Djot).mark_color);
13367        assert!(Capabilities::of(Format::Markdown).mark_color);
13368
13369        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
13370        d.caret = d.source.find("word").unwrap();
13371        assert!(
13372            d.caret_in_mark(),
13373            "the caret is in a highlight all the same"
13374        );
13375        d.set_mark_color(Some(MarkColor::Red));
13376        assert_eq!(d.source, "a {=word=} b\n");
13377        assert!(
13378            d.status.as_deref().unwrap_or("").contains("djot"),
13379            "and the refusal names the document's format: {:?}",
13380            d.status
13381        );
13382    }
13383
13384    #[test]
13385    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
13386        // The round trip that matters for a palette: the bytes twig writes are
13387        // bytes its own reparse reads back as a colour, so the swatch that was
13388        // pressed is the swatch that lights afterwards.
13389        let mut d = doc_with("mark_colour_undo", "a word b\n");
13390        d.anchor = Some(2);
13391        d.caret = 6;
13392        d.toggle(InlineKind::Mark);
13393        d.caret = d.source.find("word").unwrap();
13394        d.set_mark_color(Some(MarkColor::Green));
13395        assert_eq!(d.source, "a ==🟢 word== b\n");
13396        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
13397
13398        // One splice, one step: the colour comes off and the highlight stays.
13399        d.undo();
13400        assert_eq!(d.source, "a ==word== b\n");
13401        d.undo();
13402        assert_eq!(d.source, "a word b\n");
13403    }
13404
13405    #[test]
13406    fn every_colour_leaf_names_is_one_twig_writes() {
13407        // The two enums are one vocabulary, and this is what says so: each of
13408        // leaf's colours writes an emoji twig's reparse reads back as *that*
13409        // colour, so `twig_mark_color`'s table cannot quietly pair red with
13410        // orange.
13411        for color in MarkColor::ALL {
13412            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
13413            d.caret = d.source.find("word").unwrap();
13414            d.set_mark_color(Some(color));
13415            assert_eq!(d.status, None, "{color:?}");
13416            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
13417        }
13418    }
13419
13420    #[test]
13421    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
13422        // The two presses a coloured highlight is made of, in the state the
13423        // first one leaves: `toggle` selects the whole `==word==` and puts the
13424        // caret one past the closing `==`, which is *not* in the mark. Asking at
13425        // the caret alone would refuse to colour the highlight just written —
13426        // the selection's start is what answers.
13427        let mut d = doc_with("mark_colour_fresh", "a word b\n");
13428        d.anchor = Some(2);
13429        d.caret = 6;
13430        d.toggle(InlineKind::Mark);
13431        assert_eq!(d.source, "a ==word== b\n");
13432        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
13433
13434        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
13435        d.set_mark_color(Some(MarkColor::Yellow));
13436        assert_eq!(d.source, "a ==🟡 word== b\n");
13437        assert_eq!(d.status, None);
13438    }
13439
13440    #[test]
13441    fn one_press_highlights_a_selection_and_colours_it() {
13442        // What a toolbar swatch means over a plain selection, and the undo it
13443        // has to have: one press, one step. Two steps would leave an uncoloured
13444        // highlight behind on the way back, which is a state the author never
13445        // asked for and never saw.
13446        let mut d = doc_with("highlight_one", "a word b\n");
13447        d.anchor = Some(2);
13448        d.caret = 6;
13449        d.highlight(Some(MarkColor::Purple));
13450        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
13451        assert_eq!(d.status, None);
13452
13453        d.undo();
13454        assert_eq!(d.source, "a word b\n", "one press, one undo");
13455    }
13456
13457    #[test]
13458    fn one_press_on_an_existing_highlight_only_recolours_it() {
13459        // The other half: inside a highlight there is nothing to make, so the
13460        // compound is the plain gesture and the text is untouched.
13461        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
13462        d.caret = d.source.find("word").unwrap();
13463        d.highlight(Some(MarkColor::Blue));
13464        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
13465        d.undo();
13466        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
13467    }
13468
13469    #[test]
13470    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
13471        // `None` means "no colour", and over bare text that is the Highlight
13472        // button's own job. The fold must not happen here — there is no second
13473        // splice, and folding would take the *previous* edit into this one.
13474        let mut d = doc_with("highlight_none", "a word b and more\n");
13475        d.caret = d.source.find("more").unwrap() + 4; // after "more"
13476        d.insert("!"); // an earlier edit for a wrong fold to swallow
13477        d.anchor = Some(2);
13478        d.caret = 6;
13479        d.highlight(None);
13480        assert_eq!(d.source, "a ==word== b and more!\n");
13481
13482        d.undo();
13483        assert_eq!(
13484            d.source, "a word b and more!\n",
13485            "only the highlight came off"
13486        );
13487        d.undo();
13488        assert_eq!(
13489            d.source, "a word b and more\n",
13490            "and the edit before it survived"
13491        );
13492    }
13493
13494    #[test]
13495    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
13496        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
13497        // a colour cannot be armed with it — so the compound declines rather
13498        // than leaving half a promise.
13499        let mut d = doc_with("highlight_bare", "a word b\n");
13500        d.caret = 4;
13501        d.highlight(Some(MarkColor::Red));
13502        assert_eq!(d.source, "a word b\n");
13503        assert!(d.pending_marks.is_empty(), "and nothing armed");
13504        assert!(d.status.is_some());
13505    }
13506
13507    #[test]
13508    fn a_read_only_document_takes_no_colour() {
13509        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
13510        d.caret = d.source.find("word").unwrap();
13511        d.set_read_only(true);
13512        d.set_mark_color(Some(MarkColor::Red));
13513        assert_eq!(d.source, "a ==word== b\n");
13514    }
13515
13516    #[test]
13517    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
13518        // The other door into `toggle`: no selection, so nothing reaches twig
13519        // until `insert` realises the armed mark. It is armed now — the guard
13520        // above asks `Doc::supports`, which asks with the extensions — and what
13521        // it writes is the same `==…==`.
13522        let mut d = doc_with("sticky_mark", "xy\n");
13523        d.caret = 1;
13524        d.toggle(InlineKind::Mark);
13525        assert!(d.pending_marks.contains(InlineKind::Mark));
13526        d.insert("Z");
13527        assert_eq!(d.source, "x==Z==y\n");
13528    }
13529
13530    #[test]
13531    fn html_documents_still_take_typed_text() {
13532        // The guard covers *markup* gestures and must not touch plain editing:
13533        // twig's splicer is language-neutral, and typing into an HTML document
13534        // is the thing that does work today.
13535        let mut d = html_doc("<p>Hello world</p>\n");
13536        d.caret = d.source.find("world").unwrap();
13537        d.insert("big ");
13538        assert_eq!(d.source, "<p>Hello big world</p>\n");
13539        assert!(d.dirty);
13540        d.backspace();
13541        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
13542        d.undo();
13543        d.undo();
13544        assert_eq!(d.source, "<p>Hello world</p>\n");
13545    }
13546
13547    #[test]
13548    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
13549        // `authorable` only separates "there is a door in" from "there is not",
13550        // and HTML is on the near side of that line — which is exactly why a
13551        // toolbar must not be built from it.
13552        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
13553        assert!(html.authorable());
13554        assert!(
13555            !Doc::from_source("<r>x</r>".into(), Format::Xml)
13556                .unwrap()
13557                .authorable()
13558        );
13559
13560        let caps = html.capabilities();
13561        assert!(caps.bold && caps.italic && caps.code && caps.mark);
13562        assert!(caps.thematic_break && caps.cell_line_break);
13563        // A heading is a tag pair twig rebuilds (3.4), and since 3.5 so are a
13564        // quote, a list, a code block's language, a link and an image — each
13565        // printed as a fresh node where HTML has no marker to rewrite. A task
13566        // box is a form control and a footnote has no spelling, so those two
13567        // are what keeps the record ragged.
13568        assert!(caps.heading && caps.blockquote && caps.bullet_list);
13569        assert!(caps.link && caps.image && caps.code_language);
13570        assert!(!caps.task && !caps.footnote);
13571        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
13572        // twig's table editor would happily re-emit as `| a | b |`.
13573        assert!(!caps.table);
13574
13575        // The two lightweight formats spell everything leaf offers — and still
13576        // differ from each other, which is the other half of why one boolean
13577        // can't serve.
13578        for fmt in [Format::Markdown, Format::Djot] {
13579            let caps = Capabilities::of(fmt);
13580            assert!(
13581                caps.heading && caps.blockquote && caps.ordered_list,
13582                "{fmt:?}"
13583            );
13584            assert!(
13585                caps.task && caps.link && caps.image && caps.table,
13586                "{fmt:?}"
13587            );
13588        }
13589        // Both spell the highlight and the strikethrough: djot natively, and
13590        // Markdown because `Capabilities` asks with `parse_extensions` rather
13591        // than with twig's defaults — `==x==` is text under those, and a mark
13592        // under the `highlight` leaf always parses with.
13593        for fmt in [Format::Markdown, Format::Djot] {
13594            let caps = Capabilities::of(fmt);
13595            assert!(caps.mark && caps.strike, "{fmt:?}");
13596        }
13597        // What still separates them, now that the highlight doesn't: djot has
13598        // no in-cell break, and Markdown spells neither of the scripts.
13599        assert!(Capabilities::of(Format::Djot).superscript);
13600        assert!(!Capabilities::of(Format::Markdown).superscript);
13601        assert!(Capabilities::of(Format::Markdown).cell_line_break);
13602        assert!(!Capabilities::of(Format::Djot).cell_line_break);
13603
13604        // A parse-only format answers no to every one of them, so the coarse
13605        // predicate and the record agree there.
13606        let caps = Capabilities::of(Format::Xml);
13607        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
13608    }
13609
13610    #[test]
13611    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
13612        // The guard exists to name the *document's* format rather than twig's
13613        // internals, so the message has to survive being one leaf writes itself.
13614        // Checked against a gesture twig also refuses, since that is the pair
13615        // most at risk of drifting apart — the task box, once the code
13616        // language stopped being one (twig 3.5).
13617        let mut d = html_doc("<p>Hello</p>\n");
13618        d.caret = d.source.find("Hello").unwrap();
13619        d.toggle_task_item();
13620        assert_eq!(d.status.as_deref(), Some("task: not supported in html"));
13621        assert!(!d.dirty);
13622    }
13623
13624    #[test]
13625    fn table_set_alignment_respells_the_delimiter() {
13626        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
13627        d.caret = d.source.find('b').unwrap();
13628        d.table_set_alignment(Alignment::Right);
13629        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
13630    }
13631
13632    #[test]
13633    fn each_empty_table_cell_has_its_own_editable_home() {
13634        // Regression: an empty cell has no twig content_span, so both cells of a
13635        // `|  |  |` row collapsed onto the row's start (before the first `│`).
13636        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
13637        // tell the cells apart. Each empty cell must now have a distinct home
13638        // inside it.
13639        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
13640        let (c0, c1) = {
13641            let cells = &d.vmap.tables[0].grid[1].cells;
13642            (cells[0].start, cells[1].start)
13643        };
13644        assert!(
13645            c0 < c1,
13646            "the two empty cells have distinct homes: {c0} < {c1}"
13647        );
13648        d.caret = c0;
13649        d.insert("x");
13650        assert_eq!(
13651            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
13652            "typed inside the cell"
13653        );
13654    }
13655
13656    #[test]
13657    fn arrows_step_into_each_empty_table_cell() {
13658        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
13659        let (c0, c1) = {
13660            let cells = &d.vmap.tables[0].grid[1].cells;
13661            (cells[0].start, cells[1].start)
13662        };
13663        d.caret = d.source.find('b').unwrap(); // in the header's second cell
13664        let mut seen = std::collections::HashSet::new();
13665        for _ in 0..6 {
13666            d.move_right(false);
13667            seen.insert(d.caret);
13668        }
13669        assert!(
13670            seen.contains(&c0),
13671            "right arrow reaches the first empty cell"
13672        );
13673        assert!(
13674            seen.contains(&c1),
13675            "right arrow reaches the second empty cell"
13676        );
13677    }
13678
13679    #[test]
13680    fn table_op_off_a_table_is_a_no_op_with_a_status() {
13681        let mut d = doc_with("tbl_none", "just text\n");
13682        d.caret = 3;
13683        d.table_insert_row(true);
13684        assert_eq!(d.source, "just text\n", "nothing changed");
13685        assert!(d.status.is_some(), "a status explains why");
13686        assert!(!d.caret_in_table());
13687    }
13688
13689    #[test]
13690    fn enter_in_an_ordered_list_renumbers_the_following_items() {
13691        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
13692        // the renumber pass keeps them sequential, matching what the view draws.
13693        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
13694        d.caret = d.source.find('a').unwrap() + 1; // end of item a
13695        d.newline();
13696        d.insert("x");
13697        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
13698    }
13699
13700    #[test]
13701    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
13702        for view in [View::Source, View::Wysiwyg] {
13703            let mut d = doc_in(view, "outdent_noop", "hello\n");
13704            d.caret = 2;
13705            d.outdent();
13706            assert_eq!(d.source, "hello\n");
13707            assert!(!d.dirty, "a no-op is not a modification");
13708            d.undo();
13709            assert_eq!(
13710                d.status.as_deref(),
13711                Some("nothing to undo"),
13712                "spends no undo step"
13713            );
13714            assert_eq!(d.source, "hello\n");
13715        }
13716    }
13717
13718    #[test]
13719    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
13720        for view in [View::Source, View::Wysiwyg] {
13721            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
13722            d.anchor = Some(0);
13723            d.caret = 7; // through "two"
13724            d.indent();
13725            assert_eq!(
13726                d.source, "  one\n\n  two\n",
13727                "the blank line keeps no trailing pad"
13728            );
13729            // Selected, so a second Tab lands on the same lines rather than on
13730            // whatever the shifted offsets now cover.
13731            assert_eq!(d.selection(), Some((0, 12)));
13732            d.indent();
13733            assert_eq!(d.source, "    one\n\n    two\n");
13734        }
13735    }
13736
13737    #[test]
13738    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
13739        for view in [View::Source, View::Wysiwyg] {
13740            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
13741            d.anchor = Some(0);
13742            d.caret = 15;
13743            d.outdent();
13744            assert_eq!(d.source, "two\none\nnone\n");
13745        }
13746    }
13747
13748    #[test]
13749    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
13750        for view in [View::Source, View::Wysiwyg] {
13751            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
13752            d.anchor = Some(0);
13753            d.caret = 7;
13754            d.indent();
13755            assert_eq!(d.source, "  one\n\n  two\n");
13756            d.undo();
13757            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
13758            assert_eq!(
13759                d.selection(),
13760                Some((0, 7)),
13761                "with the selection it was aimed at"
13762            );
13763            d.redo();
13764            assert_eq!(d.source, "  one\n\n  two\n");
13765            assert_eq!(
13766                d.selection(),
13767                Some((0, 12)),
13768                "redo replays the caret the indent placed, not the one splice left"
13769            );
13770        }
13771    }
13772
13773    #[test]
13774    fn vertical_motion_keeps_the_column() {
13775        let mut d = doc_with("move", "abcd\nef\n");
13776        d.caret = 3; // "abc|d" on row 0, col 3
13777        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
13778        assert_eq!(d.caret, 7); // just after "ef"
13779    }
13780
13781    // ── goal column ──────────────────────────────────────────────────────────
13782
13783    #[test]
13784    fn vertical_motion_goal_column_survives_a_short_line() {
13785        // Regression: re-deriving the column from the clamped position on
13786        // every step permanently forgets it once a short line clamps it.
13787        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
13788        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
13789        assert_eq!(
13790            g("abcd|ef\nxy\nghijkl\n", |d| {
13791                d.move_down(false); // clamps to end of "xy"
13792                d.move_down(false); // restores col 4 on the long line
13793            }),
13794            "abcdef\nxy\nghij|kl\n"
13795        );
13796    }
13797
13798    #[test]
13799    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
13800        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
13801        assert_eq!(d.goal_col, None);
13802        d.caret = 4; // row 0, col 4
13803        d.move_down(false); // clamps into "xy"; goal stays the original col
13804        assert_eq!(d.goal_col, Some(4));
13805        assert_eq!(d.caret_pos(), (1, 2));
13806
13807        // A horizontal motion drops the goal column...
13808        d.move_left(false);
13809        assert_eq!(d.goal_col, None);
13810
13811        // ...so the next vertical motion picks up the *new* column (1), not
13812        // the stale one (4).
13813        d.move_down(false);
13814        assert_eq!(d.goal_col, Some(1));
13815        assert_eq!(d.caret_pos(), (2, 1));
13816    }
13817
13818    #[test]
13819    fn editing_clears_the_goal_column() {
13820        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
13821        d.caret = 4;
13822        d.move_down(false);
13823        assert_eq!(d.goal_col, Some(4));
13824        d.insert("Z");
13825        assert_eq!(d.goal_col, None);
13826    }
13827
13828    #[test]
13829    fn vertical_motion_on_an_empty_document_is_a_no_op() {
13830        let mut d = doc_with("empty_vert", "");
13831        d.move_down(false);
13832        assert_eq!(d.caret, 0);
13833        d.move_up(false);
13834        assert_eq!(d.caret, 0);
13835    }
13836
13837    // ── the document's edges ─────────────────────────────────────────────────
13838
13839    #[test]
13840    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
13841        // The reproduction, and the disagreement: Down on the last line ran to
13842        // the end of the document in the source view — by accident, an
13843        // out-of-range row clamping to the end of the string — and did nothing
13844        // whatever in the view leaf opens in. One rule now, in both.
13845        for (view, tag) in VIEWS {
13846            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
13847            d.caret = 1;
13848            d.move_down(false);
13849            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
13850            d.move_up(false);
13851            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
13852        }
13853    }
13854
13855    #[test]
13856    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
13857        // Down off the bottom is a motion like any other, so it latches a goal
13858        // column — and Up comes back to the column the caret left, not to the
13859        // one the document's end happened to be in.
13860        for (view, tag) in VIEWS {
13861            let gap = if view == View::Source { "\n" } else { "\n\n" };
13862            let src = format!("abcdef{gap}ghijkl");
13863            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
13864            d.caret = 2; // row 0, col 2
13865            d.move_down(false);
13866            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
13867            d.move_down(false);
13868            assert_eq!(
13869                d.caret,
13870                src.len(),
13871                "{tag}: Down off the bottom reaches the end"
13872            );
13873            d.move_up(false);
13874            assert_eq!(
13875                d.caret_pos().1,
13876                2,
13877                "{tag}: Up returns to the column Down left"
13878            );
13879        }
13880    }
13881
13882    #[test]
13883    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
13884        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
13885        // Up that did nothing still armed a goal column, and the next Down aimed
13886        // at a column the caret had never been in.
13887        for (view, tag) in VIEWS {
13888            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
13889            d.caret = 0;
13890            d.move_up(false);
13891            assert_eq!(d.caret, 0, "{tag}: already at the start");
13892            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
13893
13894            d.caret = d.source.len();
13895            d.move_down(false);
13896            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
13897            assert_eq!(
13898                d.goal_col, None,
13899                "{tag}: a no-op Down latched a goal column"
13900            );
13901        }
13902    }
13903
13904    // ── soft wrap ────────────────────────────────────────────────────────────
13905    // Every other test here builds the map at 80 columns, where no fixture is
13906    // long enough to fold. A wrap is where one offset belongs to two rows at
13907    // once, and it broke everything that asks the caret what row it is on.
13908
13909    /// The wrapped fixture these cases share, folded at 12 columns into
13910    /// `one two ` / `three four ` / `five six ` / `seven eight`.
13911    fn wrapped_doc(name: &str) -> Doc {
13912        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
13913        d.build_visual(12);
13914        d
13915    }
13916
13917    #[test]
13918    fn home_and_end_work_from_a_wrapped_row() {
13919        // The reproduction: offset 19 is the `f` of "five", the first character
13920        // of the third row — and also the offset the second row ends at. It
13921        // resolved to the *second* row, so End aimed at a place the caret was
13922        // already in and did nothing, while Home walked backwards onto a row the
13923        // caret had left.
13924        let mut d = wrapped_doc("wrap_home_end");
13925        d.caret = 19;
13926        assert_eq!(
13927            d.caret_pos(),
13928            (2, 0),
13929            "the wrap boundary opens the third row"
13930        );
13931        d.move_end(false);
13932        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
13933        d.move_home(false);
13934        assert_eq!(d.caret, 19, "Home left the row the caret was on");
13935    }
13936
13937    #[test]
13938    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
13939        // The row's end is the last offset that is only ever its own: the offset
13940        // past it opens the row below, and aiming there would send a second
13941        // press on to *that* row's end, and a third to the next — End walking
13942        // down the paragraph rather than sitting where it landed.
13943        let mut d = wrapped_doc("wrap_end_twice");
13944        d.caret = 12; // inside "three", on the second row
13945        d.move_end(false);
13946        assert_eq!(
13947            d.caret, 18,
13948            "the end of `three four`, before the space the wrap ate"
13949        );
13950        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
13951        d.move_end(false);
13952        assert_eq!(d.caret, 18, "a second End moved the caret");
13953        d.move_home(false);
13954        assert_eq!(d.caret, 8, "Home takes the row's own start");
13955    }
13956
13957    #[test]
13958    fn vertical_motion_crosses_a_soft_wrap() {
13959        // Down aimed at the row below's column 0, an offset that resolved *up*
13960        // to the row above's end — so it landed on the offset it already had and
13961        // the caret could never leave a paragraph's first row.
13962        let mut d = wrapped_doc("wrap_down");
13963        d.caret = 0;
13964        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
13965            d.move_down(false);
13966            assert_eq!(d.caret, want, "Down stalled");
13967            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
13968        }
13969        d.move_down(false);
13970        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
13971
13972        // ...and back up, one row per press. The goal column is the end of the
13973        // last row, past every other row's width, so each press clamps to the
13974        // row's own last offset rather than to the one that opens the next.
13975        let mut d = wrapped_doc("wrap_up");
13976        d.caret = 39;
13977        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
13978            d.move_up(false);
13979            assert_eq!(d.caret, want, "Up stalled");
13980            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
13981        }
13982    }
13983
13984    #[test]
13985    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
13986        // The kills take the same line Home and End do, so in WYSIWYG they take
13987        // the visual row — and a soft wrap has no newline in it to delete, so
13988        // nothing is joined by reaching the end of one.
13989        let mut d = wrapped_doc("wrap_kill");
13990        d.caret = 19; // the `f` of "five", opening the third row
13991        d.delete_to_line_end();
13992        // The space the wrap ate goes with the row it was drawn on: sparing it
13993        // would leave "four  seven", two spaces where the row had been.
13994        assert_eq!(d.source, "one two three four seven eight");
13995
13996        // Backwards from the row's last caret position — which is *before* that
13997        // space, so this one survives, being on the far side of the caret.
13998        let mut d = wrapped_doc("wrap_kill_back");
13999        d.caret = 27;
14000        d.delete_to_line_start();
14001        assert_eq!(d.source, "one two three four  seven eight");
14002    }
14003
14004    // ── document start / end ────────────────────────────────────────────────
14005
14006    #[test]
14007    fn move_doc_start_and_end_jump_to_the_edges() {
14008        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
14009        assert_eq!(
14010            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
14011            "|hello\nworld\n"
14012        );
14013        assert_eq!(
14014            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
14015            "hello\nworld\n|"
14016        );
14017        // Already at the edge: a no-op.
14018        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
14019        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
14020    }
14021
14022    #[test]
14023    fn move_doc_start_and_end_extend_the_selection() {
14024        assert_eq!(
14025            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
14026                .move_doc_end(true)),
14027            "hello wor[ld\n|]"
14028        );
14029        assert_eq!(
14030            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
14031                .move_doc_start(true)),
14032            "[|hello wor]ld\n"
14033        );
14034    }
14035
14036    #[test]
14037    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
14038        let mut d = doc_with("empty_edges", "");
14039        d.move_doc_end(false);
14040        assert_eq!(d.caret, 0);
14041        d.move_doc_start(false);
14042        assert_eq!(d.caret, 0);
14043    }
14044
14045    // ── arrow collapses an active selection ─────────────────────────────────
14046
14047    #[test]
14048    fn arrow_collapses_selection_to_its_near_edge() {
14049        let mut d = doc_with("collapse", "hello world\n");
14050
14051        // Forward selection (anchor before caret): Right -> end, Left -> start.
14052        d.anchor = Some(2);
14053        d.caret = 7;
14054        d.move_right(false);
14055        assert_eq!((d.caret, d.anchor), (7, None));
14056
14057        d.anchor = Some(2);
14058        d.caret = 7;
14059        d.move_left(false);
14060        assert_eq!((d.caret, d.anchor), (2, None));
14061
14062        // Backward selection (anchor after caret): edges are the same
14063        // regardless of which end the caret started on.
14064        d.anchor = Some(7);
14065        d.caret = 2;
14066        d.move_right(false);
14067        assert_eq!((d.caret, d.anchor), (7, None));
14068
14069        d.anchor = Some(7);
14070        d.caret = 2;
14071        d.move_left(false);
14072        assert_eq!((d.caret, d.anchor), (2, None));
14073    }
14074
14075    #[test]
14076    fn arrow_with_extend_keeps_growing_the_selection() {
14077        let mut d = doc_with("collapse_extend", "hello world\n");
14078        d.anchor = Some(2);
14079        d.caret = 7;
14080        d.move_right(true); // extend: no collapse, caret steps one further
14081        assert_eq!((d.caret, d.anchor), (8, Some(2)));
14082    }
14083
14084    #[test]
14085    fn arrow_without_a_selection_moves_one_character_as_before() {
14086        let mut d = doc_with("no_collapse", "hello\n");
14087        d.caret = 2;
14088        d.move_right(false);
14089        assert_eq!(d.caret, 3);
14090        d.move_left(false);
14091        assert_eq!(d.caret, 2);
14092    }
14093
14094    /// Press Right until it stops, collecting the offsets walked through. Every
14095    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
14096    /// two stops sharing one source offset can't be moved between, so the caret
14097    /// stalls on the first of them and the walk never reaches the rest.
14098    fn walk_right(d: &mut Doc) -> Vec<usize> {
14099        let mut seen = vec![d.caret];
14100        for _ in 0..2000 {
14101            let before = d.caret;
14102            d.move_right(false);
14103            if d.caret == before {
14104                break;
14105            }
14106            seen.push(d.caret);
14107        }
14108        seen
14109    }
14110
14111    #[test]
14112    fn the_caret_crosses_a_soft_break() {
14113        // A newline inside a paragraph is a `soft_break`, which twig gives no
14114        // span of its own — the space it renders as used to borrow the offset of
14115        // the character before it, and a caret can't move without changing
14116        // offset. Right must walk clean off the end of the first line.
14117        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
14118        d.caret = 0;
14119        let seen = walk_right(&mut d);
14120        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
14121    }
14122
14123    #[test]
14124    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
14125        // The paragraph holds one soft break. Folded (the default) it lays out as
14126        // a single reflowed row; Preserve re-lays it as a row per source line.
14127        // The setter must invalidate the cached map for the change to show, and
14128        // again on the way back — so a round trip returns to the folded layout.
14129        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
14130        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
14131        d.build_visual(80);
14132        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
14133
14134        d.set_line_flow(LineFlow::Preserve);
14135        d.build_visual(80);
14136        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
14137
14138        d.set_line_flow(LineFlow::Fold);
14139        d.build_visual(80);
14140        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
14141    }
14142
14143    #[test]
14144    fn the_caret_still_crosses_a_preserved_soft_break() {
14145        // Preserve renders the soft break as a row boundary rather than a space,
14146        // but the caret must still reach every offset — the break's own offset is
14147        // the first row's end stop, so Right walks clean off the end of line one
14148        // onto line two, exactly as it does when the break is folded.
14149        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
14150        d.set_line_flow(LineFlow::Preserve);
14151        d.build_visual(80);
14152        d.caret = 0;
14153        let seen = walk_right(&mut d);
14154        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
14155    }
14156
14157    #[test]
14158    fn the_caret_walks_a_code_block() {
14159        // Every glyph of a code block used to map to the block's start, so the
14160        // whole block was a single offset and the caret couldn't move inside it.
14161        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
14162        let mut d = wysiwyg_doc("code_walk", src);
14163        d.caret = 0;
14164        let seen = walk_right(&mut d);
14165        // The fences are markup: hidden, and no caret stop. The code between
14166        // them is reached a character at a time.
14167        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
14168        for off in code.clone() {
14169            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
14170        }
14171        assert!(seen.contains(&code.end), "no stop after the last line");
14172    }
14173
14174    #[test]
14175    fn the_caret_walks_an_indented_code_block() {
14176        // An indented block's text has the four-space indent stripped, so it
14177        // isn't a verbatim slice and its lines have to be re-found. The caret
14178        // lands on the code, never in the indent.
14179        let src = "    indented\n    code\n";
14180        let mut d = wysiwyg_doc("indent_code_walk", src);
14181        d.caret = 0;
14182        let seen = walk_right(&mut d);
14183        assert!(seen.contains(&src.find("indented").unwrap()));
14184        assert!(seen.contains(&src.find("code").unwrap()));
14185        assert!(
14186            !seen.contains(&0) || seen[0] == 0,
14187            "the caret starts where it was put"
14188        );
14189        // Nothing in the stripped indent is a stop.
14190        for off in [1, 2, 3] {
14191            assert!(!seen.contains(&off), "landed in the indent at {off}");
14192        }
14193    }
14194
14195    #[test]
14196    fn the_caret_leaves_a_tight_heading() {
14197        // "# H" with text directly under it: the heading row's end and the
14198        // separator row's end are the same offset. Right used to find the
14199        // separator's copy, set the caret to where it already was, and stop.
14200        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
14201        d.caret = 2; // the "H"
14202        let seen = walk_right(&mut d);
14203        assert!(
14204            seen.len() > 2,
14205            "Right stalled at the heading's end: {seen:?}"
14206        );
14207        assert!(
14208            seen.contains(&8),
14209            "never reached the end of \"text\": {seen:?}"
14210        );
14211    }
14212
14213    #[test]
14214    fn the_caret_skips_the_gap_between_two_paragraphs() {
14215        // The blank line between two paragraphs is the boundary itself. The
14216        // caret used to be able to sit on it, and typing there landed in the
14217        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
14218        // soft break, so the text visibly snapped back up.
14219        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
14220        d.caret = 1; // the end of "A"
14221        d.move_right(false);
14222        assert_eq!(d.caret, 3, "Right stopped in the gap");
14223        d.insert("x");
14224        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
14225    }
14226
14227    #[test]
14228    fn down_from_a_paragraph_lands_on_the_next_one() {
14229        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
14230        d.caret = 0;
14231        d.move_down(false);
14232        assert_eq!(d.caret, 3, "Down stopped in the gap");
14233    }
14234
14235    #[test]
14236    fn clicking_the_gap_lands_on_real_text() {
14237        // A click can still *reach* the gap — it's drawn, so it's clickable.
14238        // It has to resolve to somewhere the caret can be.
14239        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
14240        d.click(1, 0, false); // the gap row
14241        assert!(
14242            d.caret == 1 || d.caret == 3,
14243            "click left the caret in the gap at {}",
14244            d.caret
14245        );
14246        d.insert("x");
14247        // Either edge of the boundary is a fair place to land; inside it isn't.
14248        assert!(
14249            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
14250            "click in the gap typed into the boundary: {:?}",
14251            d.source
14252        );
14253    }
14254
14255    #[test]
14256    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
14257        // Enter inserts a paragraph break, which leaves a blank line spare on
14258        // either side of a new one. That middle line is a real empty paragraph:
14259        // the caret lands there, and typing makes a paragraph rather than
14260        // extending a neighbour.
14261        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
14262        d.caret = 1;
14263        d.newline();
14264        assert_eq!(d.source, "A\n\n\n\nB\n");
14265        d.build_visual(80);
14266        let (row, _) = d.caret_pos();
14267        assert!(
14268            d.vmap.row_is_navigable(row),
14269            "the caret landed on a gap row"
14270        );
14271        d.insert("x");
14272        assert_eq!(
14273            d.source, "A\n\nx\n\nB\n",
14274            "the new paragraph merged into a neighbour"
14275        );
14276    }
14277
14278    #[test]
14279    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
14280        let mut d = wysiwyg_doc("gap_eof", "A\n");
14281        d.caret = 1;
14282        d.newline();
14283        d.build_visual(80);
14284        let (row, _) = d.caret_pos();
14285        assert!(
14286            d.vmap.row_is_navigable(row),
14287            "the caret landed on a gap row"
14288        );
14289        d.insert("x");
14290        assert!(
14291            d.source.starts_with("A\n\n") && d.source.contains('x'),
14292            "typing at the end merged into A: {:?}",
14293            d.source
14294        );
14295    }
14296
14297    #[test]
14298    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
14299        // A paragraph broken over two source lines is one paragraph. Selecting
14300        // it must not stop at the newline inside it — that newline is markup the
14301        // rich-text view exists to hide.
14302        let src = "one two\nthree four\n\nnext\n";
14303        let mut d = wysiwyg_doc("triple_para", src);
14304        d.select_block_at(2);
14305        assert_eq!(
14306            d.selected_text(),
14307            Some("one two\nthree four"),
14308            "stopped at the soft break"
14309        );
14310    }
14311
14312    #[test]
14313    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
14314        // The reader scrolls down past the caret's row. Nothing moved the
14315        // caret, so the view must stay where it was put — the old code revealed
14316        // the caret every frame, which dragged the view straight back and made
14317        // the document unscrollable past the caret.
14318        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
14319        d.caret = 0;
14320        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
14321        d.scroll = 4; // the wheel
14322        d.follow_caret(0, 3, 9);
14323        assert_eq!(
14324            d.scroll, 4,
14325            "the wheel was overruled by a caret that never moved"
14326        );
14327    }
14328
14329    #[test]
14330    fn moving_the_caret_brings_the_view_back_to_it() {
14331        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
14332        d.caret = 0;
14333        d.follow_caret(0, 3, 9);
14334        d.scroll = 6; // scrolled away
14335        d.move_right(false); // ...and now the caret moves
14336        let (row, _) = d.caret_pos();
14337        d.follow_caret(row, 3, 9);
14338        assert!(
14339            d.scroll <= row && row < d.scroll + 3,
14340            "caret row {row} off screen at scroll {}",
14341            d.scroll
14342        );
14343    }
14344
14345    #[test]
14346    fn scrolling_stops_at_the_last_row() {
14347        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
14348        d.caret = 0;
14349        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
14350        d.scroll = 999; // the wheel, spun hard
14351        d.follow_caret(0, 3, 3);
14352        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
14353    }
14354
14355    #[test]
14356    fn every_cell_of_a_wide_table_is_reachable() {
14357        // A table whose cells are far wider than the surface: the columns are
14358        // cut to fit and the text wraps inside them, so no cell hangs off the
14359        // right edge where the caret can never go.
14360        let src = "| Ingredient | Notes |\n|---|---|\n\
14361                   | flour milled coarse | sift it twice before folding it in |\n";
14362        let mut d = wysiwyg_doc("wide_table_walk", src);
14363        d.build_visual(30);
14364        d.caret = 0;
14365        let seen = walk_right(&mut d);
14366        for word in ["Ingredient", "Notes", "coarse", "folding"] {
14367            let at = src.find(word).unwrap();
14368            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
14369        }
14370    }
14371
14372    // ── view parity ──────────────────────────────────────────────────────────
14373    // `doc_with` pins the source view, so everything above tests a view users
14374    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
14375    // deletion golden cases through *both*, plus the WYSIWYG cases the two
14376    // can't share: where the source carries markup the rendered text is a
14377    // different string, and the views agreeing would itself be the bug.
14378
14379    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
14380
14381    /// Run `action` in both views on one `|`-marked fixture and assert they
14382    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
14383    /// source verbatim, so the two views are looking at the same text and any
14384    /// disagreement is one of them having lost the plot.
14385    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
14386        let (src, caret) = parse_caret(marked);
14387        let run = |view: View, tag: &str| {
14388            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
14389            d.caret = caret;
14390            action(&mut d);
14391            render_caret(&d)
14392        };
14393        let source = run(VIEWS[0].0, VIEWS[0].1);
14394        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
14395        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
14396        source
14397    }
14398
14399    #[test]
14400    fn word_motion_agrees_across_the_views_on_plain_prose() {
14401        let g = both_views;
14402        assert_eq!(
14403            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
14404            "hello |world"
14405        );
14406        assert_eq!(
14407            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
14408            "|hello world"
14409        );
14410        assert_eq!(
14411            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
14412            "hello| world"
14413        );
14414        assert_eq!(
14415            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
14416            "hello world|"
14417        );
14418        assert_eq!(
14419            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
14420            "foo|.bar"
14421        );
14422        assert_eq!(
14423            g("par_ext", "hello |world", |d| d.move_word_right(true)),
14424            "hello [world|]"
14425        );
14426    }
14427
14428    #[test]
14429    fn word_deletion_agrees_across_the_views_on_plain_prose() {
14430        let g = both_views;
14431        assert_eq!(
14432            g("par_db", "hello world|", |d| d.delete_word_back()),
14433            "hello |"
14434        );
14435        assert_eq!(
14436            g("par_df", "hello |world", |d| d.delete_word_forward()),
14437            "hello |"
14438        );
14439        assert_eq!(
14440            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
14441            "|bar baz"
14442        );
14443        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
14444    }
14445
14446    #[test]
14447    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
14448        let g = both_views;
14449        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
14450        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
14451        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
14452        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
14453    }
14454
14455    #[test]
14456    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
14457        // The reproduction: the stop table was built one stop per `char`, so
14458        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
14459        // source view, which steps by grapheme, can't reach and backspace can't
14460        // survive. The two views must land on the same offset.
14461        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
14462        for (view, tag) in VIEWS {
14463            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
14464            d.caret = 1;
14465            d.move_right(false);
14466            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
14467
14468            // ...and the edit that used to sever a joiner off the front of it.
14469            d.backspace();
14470            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
14471            assert_eq!(d.caret, 1);
14472        }
14473    }
14474
14475    #[test]
14476    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
14477        for (view, tag) in VIEWS {
14478            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
14479            d.caret = 0;
14480            d.move_right(false);
14481            assert_eq!(
14482                d.caret,
14483                "e\u{0301}".len(),
14484                "{tag} stopped on the combining mark"
14485            );
14486        }
14487    }
14488
14489    #[test]
14490    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
14491        // The general form: whatever route the caret takes through a document
14492        // full of clusters, it never lands between the codepoints of one — so no
14493        // motion-then-backspace sequence can leave a dangling joiner behind.
14494        use unicode_segmentation::UnicodeSegmentation;
14495
14496        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
14497        let mut d = wysiwyg_doc("cluster_walk", src);
14498        d.caret = 0;
14499        let boundaries: Vec<usize> = src
14500            .grapheme_indices(true)
14501            .map(|(i, _)| i)
14502            .chain(std::iter::once(src.len()))
14503            .collect();
14504        for off in walk_right(&mut d) {
14505            assert!(
14506                boundaries.contains(&off),
14507                "Right stopped at {off}, inside a grapheme cluster"
14508            );
14509        }
14510    }
14511
14512    #[test]
14513    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
14514        // The reproduction: ⌥→ from inside the opening `**` computed its
14515        // boundary over the raw source and landed on byte 8 — inside the
14516        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
14517        // "bold". The caret drew past the bold word and sat inside it.
14518        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
14519        d.caret = 2;
14520        d.move_word_right(false);
14521        assert!(
14522            d.vmap.is_stop(d.caret),
14523            "landed at {}, not a caret stop",
14524            d.caret
14525        );
14526        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
14527        // The rendered row is "a bold c": column 6 is the space just past "bold",
14528        // and now the caret is really there rather than only drawn there.
14529        assert_eq!(d.caret_pos(), (0, 6));
14530
14531        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
14532        d.move_word_left(false);
14533        assert_eq!(d.caret, 4);
14534        assert_eq!(d.caret_pos(), (0, 2));
14535    }
14536
14537    #[test]
14538    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
14539        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
14540        // inside the closing `**`, and left "a ** c\n" — delimiters with no
14541        // opener. Glyph space covers the word alone, which would leave
14542        // "a **** c": markup wrapped around nothing. The word and the styling
14543        // that was only ever the word's go together.
14544        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
14545        d.caret = 10;
14546        d.delete_word_back();
14547        assert_eq!(d.source, "a  c\n");
14548        assert_eq!(d.caret, 2);
14549
14550        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
14551        d.caret = 4; // the "b"
14552        d.delete_word_forward();
14553        assert_eq!(d.source, "a  c\n");
14554    }
14555
14556    #[test]
14557    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
14558        let src = "a ***bold*** c\n";
14559        let mut d = wysiwyg_doc("wys_word_del_nest", src);
14560        d.caret = src.find(" c").unwrap();
14561        d.delete_word_back();
14562        assert_eq!(
14563            d.source, "a  c\n",
14564            "the emph inside the strong empties it too"
14565        );
14566
14567        let src = "a `code` c\n";
14568        let mut d = wysiwyg_doc("wys_word_del_code", src);
14569        d.caret = src.find(" c").unwrap();
14570        d.delete_word_back();
14571        assert_eq!(d.source, "a  c\n");
14572    }
14573
14574    #[test]
14575    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
14576        // Only an *emptied* node goes. Take one word of two and the `**` still
14577        // has a job to do — over the word that's left, with the space the delete
14578        // pushed against the opening delimiter moved out in front of it, or the
14579        // run would be no run at all (`** words**` is literal asterisks — see
14580        // the mark-edge rule on `splice`).
14581        let src = "a **two words** c\n";
14582        let mut d = wysiwyg_doc("wys_word_del_partial", src);
14583        d.caret = src.find(" words").unwrap();
14584        d.delete_word_back();
14585        assert_eq!(d.source, "a  **words** c\n");
14586    }
14587
14588    #[test]
14589    fn source_view_word_motion_still_walks_the_markup() {
14590        // The other half of the decision: in the source view the `**` are
14591        // characters like any other — they're on the screen, so word motion has
14592        // to stop at them and a word-delete has to leave them behind. Only
14593        // WYSIWYG hides them, so only WYSIWYG steps over them.
14594        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
14595        assert_eq!(
14596            g("src_word_motion", "a |**bold** c\n", |d| d
14597                .move_word_right(false)),
14598            "a **bold|** c\n"
14599        );
14600        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
14601        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
14602        assert_eq!(
14603            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
14604            "a **| c\n"
14605        );
14606    }
14607
14608    #[test]
14609    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
14610        // The single invariant both bugs violated: the caret draws and edits at
14611        // the same place only when it's on a stop. `debug_assert_on_a_stop`
14612        // makes the same claim in-place; this pins it from the outside, over a
14613        // document with every kind of thing the map has to be careful about.
14614        // At two widths: the wide one every other test builds at, where no
14615        // fixture folds, and one narrow enough that they all do. A soft wrap is
14616        // where an offset stops being on exactly one row, and testing only the
14617        // width that never wraps is how the caret came to be pinned at the first
14618        // one Down reached.
14619        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
14620                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
14621        // A table of named operations, which is what it looks like.
14622        #[allow(clippy::type_complexity)]
14623        let motions: [(&str, fn(&mut Doc)); 8] = [
14624            ("right", |d| d.move_right(false)),
14625            ("left", |d| d.move_left(false)),
14626            ("word_right", |d| d.move_word_right(false)),
14627            ("word_left", |d| d.move_word_left(false)),
14628            ("down", |d| d.move_down(false)),
14629            ("up", |d| d.move_up(false)),
14630            ("home", |d| d.move_home(false)),
14631            ("end", |d| d.move_end(false)),
14632        ];
14633        for width in [80, 12] {
14634            let mut d = wysiwyg_doc("stop_invariant", src);
14635            d.build_visual(width);
14636            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
14637            assert!(stops.len() > 20, "fixture should have plenty of stops");
14638            for start in stops {
14639                for (name, motion) in &motions {
14640                    d.caret = start;
14641                    d.anchor = None;
14642                    motion(&mut d);
14643                    assert!(
14644                        d.vmap.is_stop(d.caret),
14645                        "{name} from {start} at width {width} landed at {} — not a caret stop",
14646                        d.caret
14647                    );
14648                }
14649            }
14650        }
14651    }
14652
14653    #[test]
14654    fn no_wysiwyg_motion_is_a_dead_end() {
14655        // Down held to the bottom of a document reaches the bottom, and Up held
14656        // to the top reaches the top — from anywhere, at a width that wraps. The
14657        // invariant above says a motion lands somewhere legal; this one says it
14658        // gets somewhere at all, which is what a caret pinned at a wrap boundary
14659        // was quietly failing to do while every assertion around it held.
14660        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
14661                   - item one two three four five\n\nlast\n";
14662        for width in [80, 12] {
14663            let mut d = wysiwyg_doc("no_dead_end", src);
14664            d.build_visual(width);
14665            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
14666            let (first, last) = (stops[0], stops[stops.len() - 1]);
14667            for &start in &stops {
14668                for (name, motion, want) in [
14669                    (
14670                        "down",
14671                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
14672                        last,
14673                    ),
14674                    ("up", |d: &mut Doc| d.move_up(false), first),
14675                ] {
14676                    d.caret = start;
14677                    d.anchor = None;
14678                    d.goal_col = None;
14679                    // Every row, plus the presses the edges take, plus slack.
14680                    for _ in 0..d.vmap.num_rows() + 4 {
14681                        motion(&mut d);
14682                    }
14683                    assert_eq!(
14684                        d.caret, want,
14685                        "{name} held from {start} at width {width} never arrived"
14686                    );
14687                }
14688            }
14689        }
14690    }
14691    // ── display columns ──────────────────────────────────────────────────────
14692    // A `col` is a terminal cell, not a character. The two are the same number
14693    // for the ASCII the fixtures above are written in, which is how they came
14694    // apart in the first place: `你` is one character drawn in two cells, so a
14695    // column counted in characters names a cell the text isn't in — one earlier
14696    // for every wide character to its left.
14697
14698    #[test]
14699    fn a_wide_character_is_two_columns_wide() {
14700        // The reproduction: `你` is one char and two cells, so the caret just
14701        // past it drew at column 1 — inside the character it had already left.
14702        for (view, tag) in VIEWS {
14703            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
14704            d.caret = "你".len();
14705            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
14706            d.caret = "你好".len();
14707            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
14708        }
14709    }
14710
14711    #[test]
14712    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
14713        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
14714        // two-cell — measuring six cells one at a time, but the character they
14715        // spell is drawn in two. Width belongs to the cluster, not the glyph,
14716        // and the frontends measure it the same way.
14717        let family = "👨‍👩‍👧";
14718        for (view, tag) in VIEWS {
14719            let src = format!("a{family}b\n");
14720            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
14721            d.caret = 1 + family.len();
14722            assert_eq!(
14723                d.caret_pos(),
14724                (0, 3),
14725                "{tag}: 'a' is one cell, the family two"
14726            );
14727        }
14728    }
14729
14730    #[test]
14731    fn both_cells_of_a_wide_character_mean_the_character() {
14732        // Clicking the far half of `好` is still clicking `好`: half a character
14733        // is not a place the caret can be, so it comes to rest at the
14734        // character's start — the column it would have been drawn at anyway.
14735        for (view, tag) in VIEWS {
14736            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
14737            for col in [2, 3] {
14738                d.caret = 0;
14739                d.click(0, col, false);
14740                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
14741                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
14742            }
14743            // Past the last cell is the line's end, as it is for ASCII.
14744            d.click(0, 9, false);
14745            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
14746        }
14747    }
14748
14749    #[test]
14750    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
14751        // The mapping is only a mapping if it inverts: the cell the caret is
14752        // drawn in has to be the cell that brings it back to the same offset.
14753        // Over a fixture where a character may be one cell or two, and one
14754        // codepoint or five.
14755        use unicode_segmentation::UnicodeSegmentation;
14756
14757        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
14758
14759        let mut d = doc_in(View::Source, "roundtrip_source", src);
14760        // Every offset the source view's caret can occupy: it steps by grapheme
14761        // cluster, so those are its boundaries.
14762        for (off, _) in src
14763            .grapheme_indices(true)
14764            .chain(std::iter::once((src.len(), "")))
14765        {
14766            d.caret = off;
14767            let (row, col) = d.caret_pos();
14768            d.click(row, col, false);
14769            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
14770        }
14771
14772        // And in WYSIWYG, where the offsets the caret can occupy are the map's
14773        // stops rather than every boundary.
14774        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
14775        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
14776        assert!(stops.len() > 20, "fixture should have plenty of stops");
14777        for off in stops {
14778            d.caret = off;
14779            let (row, col) = d.caret_pos();
14780            d.click(row, col, false);
14781            assert_eq!(
14782                d.caret, off,
14783                "wysiwyg: {off} → ({row}, {col}) → {}",
14784                d.caret
14785            );
14786        }
14787    }
14788
14789    #[test]
14790    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
14791        // Down from under `世` lands under the glyph in that cell, not two
14792        // characters further along the line. The goal is a column, so a line of
14793        // wide characters and a line of ASCII line up the way they're drawn.
14794        //
14795        // The gap differs by view: a bare newline inside a paragraph is a soft
14796        // break, which WYSIWYG draws as a space on a single row. The views share
14797        // a grid only where the source's lines are the renderer's rows too.
14798        for (view, tag) in VIEWS {
14799            let gap = if view == View::Source { "\n" } else { "\n\n" };
14800            let src = format!("你好世{gap}abcdef\n");
14801            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
14802            d.caret = "你好".len();
14803            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
14804            d.move_down(false);
14805            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
14806            assert!(
14807                d.source[d.caret..].starts_with('e'),
14808                "{tag}: landed on the wrong glyph"
14809            );
14810        }
14811    }
14812
14813    #[test]
14814    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
14815        // Down from column 3 onto `你好`, whose characters start at columns 0
14816        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
14817        // between the cells of one character, so the caret rests on it — and on
14818        // its start, which is the only offset there that is a caret stop.
14819        for (view, tag) in VIEWS {
14820            let gap = if view == View::Source { "\n" } else { "\n\n" };
14821            let src = format!("abcdef{gap}你好\n");
14822            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
14823            let line = src.find('你').unwrap();
14824            d.caret = 3;
14825            d.move_down(false);
14826            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
14827            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
14828        }
14829    }
14830
14831    #[test]
14832    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
14833        // The column the cell's text is laid out in is measured in cells, so the
14834        // caret walking that text has to be too — the two agreeing is the whole
14835        // point of the grid staying square.
14836        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
14837        let at = d.source.find("你").unwrap();
14838        d.caret = at;
14839        let (row, col) = d.caret_pos();
14840        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
14841        // cells further along.
14842        assert_eq!(col, 2, "the cell's first character");
14843        d.move_right(false);
14844        assert_eq!(
14845            d.caret_pos(),
14846            (row, 4),
14847            "`好` is drawn past `你`'s two cells"
14848        );
14849        assert_eq!(d.caret, at + "你".len());
14850    }
14851
14852    // ── active inline marks ───────────────────────────────────────────────────
14853
14854    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
14855    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
14856        let (src, caret) = parse_caret(marked);
14857        let mut d = doc_in(view, name, &src);
14858        d.caret = caret;
14859        d.active_inline_marks().iter().collect()
14860    }
14861
14862    /// The marks over the selection `[start, end)`.
14863    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
14864        let mut d = doc_in(view, name, src);
14865        d.anchor = Some(start);
14866        d.caret = end;
14867        d.active_inline_marks().iter().collect()
14868    }
14869
14870    #[test]
14871    fn a_caret_in_a_mark_reports_it() {
14872        for (view, tag) in VIEWS {
14873            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
14874            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
14875            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
14876            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
14877            // Plain text under no mark lights nothing — the toolbar's resting state.
14878            assert_eq!(m("a| **bold** b"), [], "{tag}");
14879            assert!(m("plain t|ext").is_empty(), "{tag}");
14880        }
14881    }
14882
14883    #[test]
14884    fn nested_marks_all_report() {
14885        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
14886        // the ancestor chain is a chain, and every mark on it is in force.
14887        for (view, tag) in VIEWS {
14888            assert_eq!(
14889                marks(
14890                    view,
14891                    &format!("marks_nested_{tag}"),
14892                    "**bold and *bo|th*** end"
14893                ),
14894                [InlineKind::Strong, InlineKind::Emph],
14895                "{tag}"
14896            );
14897        }
14898    }
14899
14900    #[test]
14901    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
14902        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
14903        // the first byte of its text and the byte after its last — both inside
14904        // the mark's span, both places typing lands inside the bold. The offset
14905        // past the closing delimiter is the next text, and reports nothing.
14906        let src = "a **bold** b";
14907        let inner_start = src.find("bold").unwrap(); // 4
14908        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
14909        for (view, tag) in VIEWS {
14910            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
14911            for off in [2, 3, inner_start, inner_end, 9] {
14912                d.caret = off;
14913                assert!(
14914                    d.active_inline_marks().contains(InlineKind::Strong),
14915                    "{tag}: offset {off} is inside the strong span"
14916                );
14917            }
14918            for off in [0, 1, 10, 11, 12] {
14919                d.caret = off;
14920                assert!(
14921                    !d.active_inline_marks().contains(InlineKind::Strong),
14922                    "{tag}: offset {off} is outside the strong run"
14923                );
14924            }
14925        }
14926    }
14927
14928    #[test]
14929    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
14930        // Regression: twig resolves an offset that is one node's end and the
14931        // next one's start to the node that *starts* there, so `**bold**|\n`
14932        // isn't bold. With nothing following there's no tie to break and the
14933        // chain still ended at the mark, which made a trailing `\n` — not the
14934        // text — decide whether the caret after a bold word reported bold. It's
14935        // the offset past the mark either way, and typing there is plain either
14936        // way. A blank document typed into is exactly this shape.
14937        for (view, tag) in VIEWS {
14938            let m = |name: String, marked| marks(view, &name, marked);
14939            assert_eq!(
14940                m(format!("marks_eob_{tag}"), "**bold**|"),
14941                [],
14942                "{tag}: no trailing newline"
14943            );
14944            assert_eq!(
14945                m(format!("marks_eol_{tag}"), "**bold**|\n"),
14946                [],
14947                "{tag}: with one"
14948            );
14949            // And the last offset that *is* in the mark still is.
14950            assert_eq!(
14951                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
14952                [InlineKind::Strong],
14953                "{tag}"
14954            );
14955        }
14956    }
14957
14958    #[test]
14959    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
14960        let src = "a **bold** b";
14961        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
14962        for (view, tag) in VIEWS {
14963            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
14964            // The whole bold word, and a slice of it.
14965            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
14966            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
14967            // Ending exactly at the closing delimiter's start is still all-bold:
14968            // an exclusive end sits *past* the last selected character, so the
14969            // question is asked of the character, not the boundary.
14970            assert_eq!(
14971                m(b, d_ + 2),
14972                [InlineKind::Strong],
14973                "{tag}: through the close"
14974            );
14975            // Half in, half out: Bold lit here would claim a press turns it off.
14976            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
14977            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
14978        }
14979    }
14980
14981    #[test]
14982    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
14983        // Both ends are bold, but the space between them isn't — two runs are two
14984        // nodes, which is exactly what the node id catches and a kind-only
14985        // comparison would not.
14986        let src = "**one** **two**";
14987        for (view, tag) in VIEWS {
14988            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
14989            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
14990        }
14991    }
14992
14993    #[test]
14994    fn marks_read_the_document_as_it_is_edited() {
14995        // The point of asking twig every frame instead of caching: the answer has
14996        // to follow the toggle that changed it.
14997        let mut d = wysiwyg_doc("marks_live", "one two\n");
14998        d.anchor = Some(0);
14999        d.caret = 3;
15000        assert!(d.active_inline_marks().is_empty(), "plain to start");
15001        d.toggle(InlineKind::Strong);
15002        assert_eq!(d.source, "**one** two\n");
15003        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
15004        assert!(d.active_inline_marks().contains(InlineKind::Strong));
15005        d.toggle(InlineKind::Strong);
15006        assert!(d.active_inline_marks().is_empty(), "and off again");
15007    }
15008
15009    #[test]
15010    fn a_link_is_not_an_inline_mark() {
15011        // `link`/`str` are inline nodes, but nothing on the inline toolbar
15012        // toggles them — a set with a "link mark" in it would have no button.
15013        for (view, tag) in VIEWS {
15014            assert_eq!(
15015                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
15016                [],
15017                "{tag}"
15018            );
15019        }
15020    }
15021
15022    // ── blank documents ───────────────────────────────────────────────────────
15023
15024    #[test]
15025    fn a_blank_document_is_untitled_empty_and_markdown() {
15026        let mut d = Doc::blank().unwrap();
15027        assert!(d.is_untitled());
15028        assert_eq!(d.path, PathBuf::new());
15029        assert_eq!(
15030            d.file_name(),
15031            "untitled",
15032            "the header has to show something"
15033        );
15034        assert_eq!(d.format_name(), "markdown");
15035        assert_eq!(d.source, "");
15036        assert!(!d.dirty, "nothing typed yet is nothing to lose");
15037        assert_eq!(d.disk_state(), DiskState::Untitled);
15038        // And it's a document you can be in: the default view renders it.
15039        d.build_visual(80);
15040        assert_eq!(d.caret, 0);
15041    }
15042
15043    #[test]
15044    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
15045        let mut d = Doc::blank().unwrap();
15046        d.insert("hello");
15047        assert!(d.dirty);
15048        d.save();
15049        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
15050        assert!(d.dirty, "it must not come away believing it saved");
15051        assert!(d.is_untitled(), "and it still has no file");
15052    }
15053
15054    #[test]
15055    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
15056        let p = temp_path("blank_save_as");
15057        let mut d = Doc::blank().unwrap();
15058        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
15059        // be kept literal (`\#`); this test is about save-as, not escaping (which
15060        // has its own test), so it types nothing that escaping would touch.
15061        d.insert("hi");
15062        d.save_as(p.clone());
15063        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
15064        assert!(!d.is_untitled());
15065        assert!(!d.dirty);
15066        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
15067        assert_eq!(
15068            d.disk_state(),
15069            DiskState::Unchanged,
15070            "the watermark is stamped"
15071        );
15072        // And ⌘S is a plain save from here on.
15073        d.insert("!");
15074        d.save();
15075        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
15076        let _ = std::fs::remove_file(&p);
15077    }
15078
15079    // ── a file that isn't there yet ───────────────────────────────────────────
15080
15081    /// A unique path in the temp dir with the given extension, guaranteed not to
15082    /// exist — what `leaf notes.md` is handed when the file has never been made.
15083    fn missing_path(name: &str, ext: &str) -> PathBuf {
15084        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
15085        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15086        let mut p = std::env::temp_dir();
15087        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
15088        let _ = std::fs::remove_file(&p);
15089        p
15090    }
15091
15092    #[test]
15093    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
15094        let p = missing_path("named", "md");
15095        let mut d = Doc::open_or_create(p.clone()).unwrap();
15096
15097        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
15098        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
15099        assert!(
15100            !d.is_untitled(),
15101            "it has the name the user asked for — ^S must not detour to Save As"
15102        );
15103        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
15104        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
15105        assert!(!p.exists(), "and opening it wrote nothing");
15106        // And it's a document you can be in.
15107        d.build_visual(80);
15108        assert_eq!(d.caret, 0);
15109    }
15110
15111    #[test]
15112    fn a_new_file_is_created_by_its_first_save() {
15113        let p = missing_path("first_save", "md");
15114        let mut d = Doc::open_or_create(p.clone()).unwrap();
15115        d.insert("hello\n");
15116        assert!(d.dirty);
15117        d.save();
15118
15119        assert_eq!(
15120            std::fs::read_to_string(&p).unwrap(),
15121            "hello\n",
15122            "a plain ^S wrote it — no Save As, no name to invent"
15123        );
15124        assert!(!d.dirty);
15125        assert_eq!(d.disk_state(), DiskState::Unchanged);
15126        let _ = std::fs::remove_file(&p);
15127    }
15128
15129    #[test]
15130    fn a_new_file_takes_its_format_from_the_extension() {
15131        // The one thing `blank` can't do: with no name it has to assume Markdown,
15132        // and typing djot into a Markdown parse is the wrong buffer.
15133        let dj = missing_path("format", "dj");
15134        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
15135        let md = missing_path("format", "md");
15136        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
15137    }
15138
15139    #[test]
15140    fn a_new_file_reports_itself_missing_until_it_is_saved() {
15141        // Not `Untitled` — that's the answer for a document with no path, and it
15142        // would tell a frontend there is nothing a save could collide with. Here
15143        // there is a path, and the file simply isn't at it yet.
15144        let p = missing_path("disk_state", "md");
15145        let mut d = Doc::open_or_create(p.clone()).unwrap();
15146        assert_eq!(d.disk_state(), DiskState::Missing);
15147
15148        // Somebody else creates it while the buffer is open: that's an overwrite
15149        // the frontend has to be able to prompt about, exactly as for an opened
15150        // file. Their bytes, not ours, so `Changed`.
15151        std::fs::write(&p, "theirs\n").unwrap();
15152        assert_eq!(d.disk_state(), DiskState::Changed);
15153
15154        // Saving makes the file ours and re-stamps the watermark.
15155        d.insert("ours\n");
15156        d.save();
15157        assert_eq!(d.disk_state(), DiskState::Unchanged);
15158        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
15159        let _ = std::fs::remove_file(&p);
15160    }
15161
15162    #[test]
15163    fn open_or_create_still_opens_a_file_that_is_there() {
15164        let d = doc_with("open_or_create_existing", "body\n");
15165        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
15166        assert_eq!(reopened.source, "body\n");
15167        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
15168    }
15169
15170    #[test]
15171    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
15172        // A mistyped flag or a stray argument must not become a buffer promising
15173        // to save somewhere — the same refusal `open` gives a real file.
15174        let mut p = std::env::temp_dir();
15175        p.push("leaf_test_new_bad_ext.wat");
15176        assert!(Doc::open_or_create(p).is_err());
15177        let mut none = std::env::temp_dir();
15178        none.push("leaf_test_new_no_ext");
15179        assert!(Doc::open_or_create(none).is_err());
15180    }
15181
15182    #[test]
15183    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
15184        // Opening reads nothing, so there is nothing to fail on yet; the write is
15185        // where it fails, and it says so rather than claiming a save.
15186        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
15187        let mut d = Doc::open_or_create(p).unwrap();
15188        d.insert("x");
15189        d.save();
15190        assert!(
15191            d.status.as_deref().unwrap().starts_with("save failed:"),
15192            "got {:?}",
15193            d.status
15194        );
15195        assert!(d.dirty, "it must not come away believing it saved");
15196    }
15197
15198    // ── save as ───────────────────────────────────────────────────────────────
15199
15200    /// A unique path in the temp dir that no fixture wrote — a Save As target.
15201    fn temp_path(name: &str) -> PathBuf {
15202        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
15203        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15204        let mut p = std::env::temp_dir();
15205        p.push(format!("leaf_test_target_{name}_{seq}.md"));
15206        let _ = std::fs::remove_file(&p);
15207        p
15208    }
15209
15210    #[test]
15211    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
15212        let mut d = doc_with("save_as_move", "original\n");
15213        let old = d.path.clone();
15214        let new = temp_path("save_as_move");
15215        d.insert("edited: ");
15216        d.save_as(new.clone());
15217
15218        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
15219        assert_eq!(
15220            std::fs::read_to_string(&old).unwrap(),
15221            "original\n",
15222            "Save As doesn't touch the file it came from"
15223        );
15224        assert_eq!(d.path, new, "the document moved");
15225        assert!(!d.dirty);
15226        assert_eq!(
15227            d.status.as_deref(),
15228            Some(&*format!("saved {}", d.file_name()))
15229        );
15230
15231        // Every later save follows it, which is the whole difference from a copy.
15232        d.caret = 0;
15233        d.insert("re-");
15234        d.save();
15235        assert_eq!(
15236            std::fs::read_to_string(&new).unwrap(),
15237            "re-edited: original\n"
15238        );
15239        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
15240        let _ = std::fs::remove_file(&new);
15241    }
15242
15243    #[test]
15244    fn save_as_overwrites_an_existing_target() {
15245        // The picker already asked; asking again down here is the same question
15246        // twice, and the second one has no way to be answered.
15247        let new = temp_path("save_as_over");
15248        std::fs::write(&new, "theirs\n").unwrap();
15249        let mut d = doc_with("save_as_over", "ours\n");
15250        d.save_as(new.clone());
15251        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
15252        let _ = std::fs::remove_file(&new);
15253    }
15254
15255    #[test]
15256    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
15257        let mut d = doc_with("save_as_fail", "body\n");
15258        let old = d.path.clone();
15259        d.insert("x");
15260        // A directory that doesn't exist: the write can't land.
15261        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
15262        d.save_as(bad);
15263
15264        assert_eq!(
15265            d.path, old,
15266            "the document must not move to a file that isn't there"
15267        );
15268        assert!(d.dirty, "and must not believe it saved");
15269        assert!(
15270            d.status.as_deref().unwrap().starts_with("save failed:"),
15271            "the same failure a plain save reports, got {:?}",
15272            d.status
15273        );
15274        // The original is still the document's file, and still saveable.
15275        d.save();
15276        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
15277        assert!(!d.dirty);
15278    }
15279
15280    #[test]
15281    fn save_as_renames_without_reparsing_the_format() {
15282        // `.dj` on the name doesn't make the buffer djot: it was parsed as
15283        // Markdown and still is, and saying otherwise would be a conversion the
15284        // user never asked for (and an undo history thrown away to do it).
15285        let mut d = doc_with("save_as_format", "**b**\n");
15286        let mut new = temp_path("save_as_format");
15287        new.set_extension("dj");
15288        d.save_as(new.clone());
15289        assert_eq!(d.format_name(), "markdown");
15290        let _ = std::fs::remove_file(&new);
15291    }
15292
15293    // ── external change / reload ──────────────────────────────────────────────
15294
15295    #[test]
15296    fn an_untouched_file_reports_unchanged() {
15297        let mut d = doc_with("disk_clean", "body\n");
15298        assert_eq!(d.disk_state(), DiskState::Unchanged);
15299        // Editing the buffer is not editing the file.
15300        d.insert("x");
15301        assert_eq!(d.disk_state(), DiskState::Unchanged);
15302        assert!(d.dirty);
15303        // Saving re-stamps the watermark rather than reporting our own bytes back.
15304        d.save();
15305        assert_eq!(d.disk_state(), DiskState::Unchanged);
15306    }
15307
15308    #[test]
15309    fn a_file_written_underneath_reports_changed() {
15310        let mut d = doc_with("disk_changed", "body\n");
15311        std::fs::write(&d.path, "someone else\n").unwrap();
15312        assert_eq!(d.disk_state(), DiskState::Changed);
15313        // Dirty *and* changed is the clobber: both halves are readable, and
15314        // leaf-core takes neither side.
15315        d.insert("x");
15316        assert!(d.dirty && d.disk_state() == DiskState::Changed);
15317        // Saving anyway is allowed — the frontend asked, or chose not to.
15318        d.save();
15319        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
15320        assert_eq!(d.disk_state(), DiskState::Unchanged);
15321    }
15322
15323    #[test]
15324    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
15325        // The hash is what makes this honest: the file was written (a fresh
15326        // mtime), and nothing about the document is stale.
15327        let d = doc_with("disk_same_bytes", "body\n");
15328        std::fs::write(&d.path, "body\n").unwrap();
15329        assert_eq!(d.disk_state(), DiskState::Unchanged);
15330    }
15331
15332    #[test]
15333    fn a_deleted_file_reports_missing() {
15334        let mut d = doc_with("disk_missing", "body\n");
15335        std::fs::remove_file(&d.path).unwrap();
15336        assert_eq!(d.disk_state(), DiskState::Missing);
15337        // A save recreates it, and the document is whole again.
15338        d.save();
15339        assert_eq!(d.disk_state(), DiskState::Unchanged);
15340        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
15341    }
15342
15343    #[test]
15344    fn reload_replaces_the_document_with_the_file() {
15345        for (view, tag) in VIEWS {
15346            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
15347            d.insert("edited ");
15348            assert!(d.dirty);
15349            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
15350            d.reload();
15351
15352            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
15353            assert!(!d.dirty, "{tag}: the file is what we have");
15354            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
15355            assert_eq!(
15356                d.status.as_deref(),
15357                Some(&*format!("reloaded {}", d.file_name()))
15358            );
15359            // The reloaded tree is live, not the old parse.
15360            d.caret = d.source.find("three").unwrap();
15361            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
15362        }
15363    }
15364
15365    #[test]
15366    fn reload_clamps_the_caret_and_drops_the_selection() {
15367        let mut d = doc_with("reload_caret", "a long first line\n");
15368        d.caret = 12;
15369        d.anchor = Some(4);
15370        std::fs::write(&d.path, "short\n").unwrap();
15371        d.reload();
15372        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
15373        assert_eq!(
15374            d.anchor, None,
15375            "a selection over bytes that changed is a lie"
15376        );
15377        assert!(d.selection().is_none());
15378
15379        // A caret the file still has room for stays put.
15380        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
15381        d.caret = 2;
15382        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
15383        d.reload();
15384        assert_eq!(d.caret, 2);
15385    }
15386
15387    /// A silent reload is something that happened *to* a reader — a formatter,
15388    /// a `git checkout` — so it has to be undoable like anything else that
15389    /// changes the document, and undoable as one step rather than as however
15390    /// many the file happens to differ by.
15391    #[test]
15392    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
15393        let mut d = doc_with("reload_undo", "body\n");
15394        d.insert("x");
15395        assert_eq!(d.source, "xbody\n");
15396        std::fs::write(&d.path, "replaced\n").unwrap();
15397        d.reload();
15398        assert_eq!(d.source, "replaced\n");
15399        assert!(!d.dirty, "a reload lands clean");
15400
15401        // One ^Z takes the whole swap off, and hands back the unsaved work it
15402        // replaced — which is unsaved again, because the file no longer says it.
15403        d.undo();
15404        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
15405        assert!(d.dirty, "and what it comes back to is unsaved");
15406        // …and the history under it is still there.
15407        d.undo();
15408        assert_eq!(
15409            d.source, "body\n",
15410            "the typing before the reload undoes too"
15411        );
15412        // Redo walks back up through the reload.
15413        d.redo();
15414        d.redo();
15415        assert_eq!(d.source, "replaced\n");
15416    }
15417
15418    /// A file rewritten with the bytes it already had is not an edit, so it
15419    /// must not leave an undo step behind for something nobody did.
15420    #[test]
15421    fn reloading_identical_bytes_pushes_no_undo_step() {
15422        let mut d = doc_with("reload_same", "body\n");
15423        d.insert("x");
15424        std::fs::write(&d.path, "xbody\n").unwrap();
15425        d.reload();
15426        assert_eq!(d.source, "xbody\n");
15427        assert!(!d.dirty, "the file now says what the buffer does");
15428        d.undo();
15429        assert_eq!(
15430            d.source, "body\n",
15431            "one step back is the typing, not a no-op"
15432        );
15433    }
15434
15435    #[test]
15436    fn a_reload_that_cant_read_leaves_the_document_alone() {
15437        let mut d = doc_with("reload_gone", "body\n");
15438        d.insert("x");
15439        std::fs::remove_file(&d.path).unwrap();
15440        d.reload();
15441        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
15442        assert!(d.dirty);
15443        assert!(
15444            d.status.as_deref().unwrap().starts_with("reload failed:"),
15445            "{:?}",
15446            d.status
15447        );
15448
15449        // And an untitled document has nothing to reload from.
15450        let mut d = Doc::blank().unwrap();
15451        d.insert("typed");
15452        d.reload();
15453        assert_eq!(d.source, "typed");
15454        assert_eq!(d.status.as_deref(), Some("no file to reload"));
15455    }
15456
15457    #[test]
15458    fn a_read_only_document_refuses_every_door() {
15459        let mut d = doc_with("readonly", "one two three\n");
15460        d.insert("x");
15461        assert!(d.dirty, "writable first, so the undo step exists");
15462        d.set_read_only(true);
15463        let before = d.source.clone();
15464        d.insert("y");
15465        d.backspace();
15466        d.undo();
15467        d.redo();
15468        assert_eq!(d.source, before, "no door moved a byte");
15469        d.set_read_only(false);
15470        d.undo();
15471        assert_ne!(d.source, before, "off again, the same doors work");
15472    }
15473
15474    /// The doors that go to twig's own verbs rather than through the splice.
15475    /// Typed text in the rendered view under the default markup mode is the
15476    /// everyday one — it is what a keystroke in leaf-web or the Apple views
15477    /// becomes — and it walked straight past the gate.
15478    #[test]
15479    fn a_read_only_document_refuses_the_doors_around_the_splice() {
15480        let mut d = wysiwyg_doc(
15481            "readonly-doors",
15482            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
15483        );
15484        d.set_markup_mode(MarkupMode::None);
15485        d.set_read_only(true);
15486        let before = d.source.clone();
15487        d.place_caret(3, false);
15488        d.insert("y");
15489        d.insert_link("https://example.com");
15490        d.insert_image("a.png", "alt");
15491        d.insert_thematic_break();
15492        d.insert_footnote();
15493        d.place_caret(0, false);
15494        d.place_caret(3, true);
15495        d.toggle(InlineKind::Strong);
15496        d.toggle_heading(2);
15497        d.set_block(BlockKind::Paragraph);
15498        d.toggle_list(false);
15499        d.toggle_blockquote();
15500        d.toggle_task_item();
15501        d.newline();
15502        d.indent();
15503        d.set_code_language("rust");
15504        let in_cell = d.source.find("| c").unwrap() + 2;
15505        d.place_caret(in_cell, false);
15506        assert!(d.caret_in_table(), "the caret is in the grid");
15507        assert!(!d.cell_line_break(), "the cell break reports the refusal");
15508        assert_eq!(d.source, before, "no door moved a byte");
15509        assert!(!d.dirty, "nothing to save");
15510        d.set_read_only(false);
15511        d.place_caret(3, false);
15512        d.insert("y");
15513        assert_ne!(d.source, before, "off again, the same doors work");
15514    }
15515
15516    #[test]
15517    fn a_selection_quote_carries_its_context_on_char_boundaries() {
15518        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
15519        let start = d.source.find("exact").unwrap();
15520        d.place_caret(start, false);
15521        d.place_caret(start + "exact".len(), true);
15522        let q = d.selection_quote(3).unwrap();
15523        assert_eq!(q.exact, "exact");
15524        assert_eq!(
15525            q.prefix, "你好 ",
15526            "chars, not bytes — the multibyte pair counts as two"
15527        );
15528        assert_eq!(q.suffix, " 世界");
15529        assert_eq!(&d.source[q.start..q.end], "exact");
15530        // At the edges the context clips rather than erring.
15531        d.place_caret(0, false);
15532        d.place_caret(6, true);
15533        let q = d.selection_quote(40).unwrap();
15534        assert_eq!(q.prefix, "");
15535        assert_eq!(q.exact, "before");
15536        // No selection is no quote.
15537        d.place_caret(0, false);
15538        assert!(d.selection_quote(3).is_none());
15539    }
15540
15541    #[test]
15542    fn highlights_are_kept_sorted_and_answer_point_queries() {
15543        let mut d = doc_with("hl", "one two three\n");
15544        d.set_highlights(vec![
15545            Highlight {
15546                start: 8,
15547                end: 13,
15548                id: "b".into(),
15549                color: None,
15550                marker: None,
15551            },
15552            Highlight {
15553                start: 0,
15554                end: 3,
15555                id: "a".into(),
15556                color: Some("#ffe066".into()),
15557                marker: None,
15558            },
15559            Highlight {
15560                start: 5,
15561                end: 5,
15562                id: "empty".into(),
15563                color: None,
15564                marker: None,
15565            },
15566        ]);
15567        assert_eq!(
15568            d.highlights()
15569                .iter()
15570                .map(|h| h.id.as_str())
15571                .collect::<Vec<_>>(),
15572            ["a", "b"],
15573            "sorted by start, the empty range dropped"
15574        );
15575        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
15576        assert_eq!(d.highlight_at(3), None, "end is exclusive");
15577        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
15578        d.set_highlights(Vec::new());
15579        assert!(d.highlights().is_empty(), "a replace is a replace");
15580    }
15581
15582    /// `Highlight::covering` and the cursor over it are what both painters ask
15583    /// per glyph, so they have to answer the same as the scan they replaced —
15584    /// including in the gaps, which is where most glyphs are.
15585    #[test]
15586    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
15587        let hl = |start: usize, end: usize, id: &str| Highlight {
15588            start,
15589            end,
15590            id: id.into(),
15591            color: None,
15592            marker: None,
15593        };
15594        // Disjoint, as search hits are: in a range, in a gap, and past the end.
15595        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
15596        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
15597        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
15598        assert_eq!(
15599            Highlight::covering(&hits, 105),
15600            None,
15601            "a gap covers nothing"
15602        );
15603        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
15604        assert_eq!(Highlight::covering(&hits, 9_999), None);
15605        assert_eq!(Highlight::covering(&[], 0), None);
15606
15607        // Nested: first by start, so a hit inside an annotation still resolves
15608        // to the annotation — and the range that stops short doesn't mask it.
15609        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
15610        assert_eq!(
15611            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
15612            Some("outer")
15613        );
15614        assert_eq!(
15615            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
15616            Some("outer")
15617        );
15618    }
15619
15620    /// The cursor is an optimisation, so the only thing worth asserting is that
15621    /// it is not also a change of answer — at every offset, over a list with a
15622    /// nest in it, walked forwards and then backwards.
15623    #[test]
15624    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
15625        let hl = |start: usize, end: usize, id: &str| Highlight {
15626            start,
15627            end,
15628            id: id.into(),
15629            color: None,
15630            marker: None,
15631        };
15632        let mut list = vec![
15633            hl(0, 20, "outer"),
15634            hl(5, 10, "inner"),
15635            hl(30, 33, "hit"),
15636            hl(40, 43, "hit"),
15637        ];
15638        list.sort_by_key(|h| (h.start, h.end));
15639
15640        let mut cursor = HighlightCursor::new(&list);
15641        for offset in 0..50 {
15642            assert_eq!(
15643                cursor.at(offset).map(|h| h.id.as_str()),
15644                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
15645                "cursor disagrees at {offset}"
15646            );
15647        }
15648        // Backwards: the cursor re-seats rather than answering from where it
15649        // had got to, so a painter that revisits a row is still told the truth.
15650        for offset in (0..50).rev() {
15651            assert_eq!(
15652                cursor.at(offset).map(|h| h.id.as_str()),
15653                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
15654                "cursor disagrees walking back at {offset}"
15655            );
15656        }
15657    }
15658
15659    // ── the presentation vocabulary ─────────────────────────────────────────
15660
15661    /// A document in `format`, for the gesture tests that want more than the
15662    /// Markdown `doc_with` writes.
15663    fn fmt_doc(body: &str, format: Format) -> Doc {
15664        Doc::from_source(body.to_string(), format).unwrap()
15665    }
15666
15667    /// Alignment is a block property, so the gesture is `set_block_attrs` on
15668    /// the caret's block whatever is selected — and each format spells it its
15669    /// own way: djot's `{…}` line above the block, a `<div>` around it in
15670    /// Markdown (the format has nowhere else to put it), the tag in HTML.
15671    #[test]
15672    fn set_alignment_spells_the_class_the_format_s_own_way() {
15673        let mut dj = fmt_doc("hello\n", Format::Djot);
15674        dj.caret = 1;
15675        dj.set_alignment(Some(Align::Center));
15676        assert_eq!(dj.source, "{.center}\nhello\n");
15677        assert!(dj.dirty);
15678        assert_eq!(dj.status, None);
15679
15680        let mut md = fmt_doc("hello\n", Format::Markdown);
15681        md.caret = 1;
15682        md.set_alignment(Some(Align::Right));
15683        assert_eq!(md.source, "<div class=\"right\">\n\nhello\n\n</div>\n");
15684
15685        let mut html = fmt_doc("<p>hello</p>\n", Format::Html);
15686        html.caret = html.source.find("hello").unwrap();
15687        html.set_alignment(Some(Align::Justify));
15688        assert_eq!(html.source, "<p class=\"justify\">hello</p>\n");
15689    }
15690
15691    /// Each gesture edits **one key and keeps the rest** — twig's contract is
15692    /// replace-not-merge, so leaf reads the node's attributes, edits its own
15693    /// key out of them, and passes the list back whole. A document from
15694    /// elsewhere passes through the editor unharmed.
15695    #[test]
15696    fn a_presentation_gesture_keeps_every_attribute_it_did_not_write() {
15697        let mut d = fmt_doc(
15698            "{.lead .center #intro data-line-height=\"1.5\"}\nhello\n",
15699            Format::Djot,
15700        );
15701        d.caret = d.source.find("hello").unwrap();
15702        d.set_alignment(Some(Align::Right));
15703        // `center` goes, `lead` stays, and neither the id nor the spacing is
15704        // touched.
15705        // The serializer picks the order; what matters is which keys survive.
15706        assert!(d.source.contains(".lead"), "{:?}", d.source);
15707        assert!(d.source.contains(".right"), "{:?}", d.source);
15708        assert!(!d.source.contains(".center"), "{:?}", d.source);
15709        assert!(d.source.contains("#intro"), "{:?}", d.source);
15710        assert!(
15711            d.source.contains("data-line-height=\"1.5\""),
15712            "{:?}",
15713            d.source
15714        );
15715        assert_eq!(d.alignment_at_caret(), Some(Align::Right));
15716        assert_eq!(d.line_spacing_at_caret(), Some(LineSpacing::OneHalf));
15717
15718        // And the other way round: the spacing gesture leaves the classes be.
15719        d.set_line_spacing(Some(LineSpacing::Double));
15720        assert!(d.source.contains(".lead"), "{:?}", d.source);
15721        assert!(d.source.contains(".right"), "{:?}", d.source);
15722        assert_eq!(d.line_spacing_at_caret(), Some(LineSpacing::Double));
15723    }
15724
15725    /// Clearing is the same gesture with `None`: the key goes, the tokens leaf
15726    /// owns go out of `class`, and a block left with nothing at all is spelled
15727    /// bare again — in Markdown by unwrapping the div twig wrapped it in.
15728    #[test]
15729    fn none_clears_a_key_and_an_empty_set_unwraps_the_block() {
15730        let mut dj = fmt_doc("{.lead .center}\nhello\n", Format::Djot);
15731        dj.caret = dj.source.find("hello").unwrap();
15732        dj.set_alignment(None);
15733        assert_eq!(dj.source, "{.lead}\nhello\n", "the foreign class stays");
15734        assert_eq!(dj.alignment_at_caret(), None);
15735
15736        let mut bare = fmt_doc("{.center}\nhello\n", Format::Djot);
15737        bare.caret = bare.source.find("hello").unwrap();
15738        bare.set_alignment(None);
15739        assert_eq!(
15740            bare.source, "hello\n",
15741            "the last key takes the line with it"
15742        );
15743
15744        let mut md = fmt_doc("hello\n", Format::Markdown);
15745        md.caret = 1;
15746        md.set_alignment(Some(Align::Center));
15747        assert_eq!(md.source, "<div class=\"center\">\n\nhello\n\n</div>\n");
15748        md.caret = md.source.find("hello").unwrap();
15749        md.set_line_spacing(Some(LineSpacing::OneFifteen));
15750        assert_eq!(
15751            md.source, "<div class=\"center\" data-line-height=\"1.15\">\n\nhello\n\n</div>\n",
15752            "the second key rewrites the div rather than nesting a second"
15753        );
15754        md.caret = md.source.find("hello").unwrap();
15755        md.set_alignment(None);
15756        md.caret = md.source.find("hello").unwrap();
15757        md.set_line_spacing(None);
15758        assert_eq!(md.source, "hello\n", "an empty set unwraps the div");
15759    }
15760
15761    /// Size, face and colour are the run's over a selection and the block's
15762    /// with none — so "make this paragraph larger" is a click with the caret in
15763    /// it rather than a select-all first.
15764    #[test]
15765    fn a_run_gesture_wraps_a_selection_and_sets_the_block_without_one() {
15766        // With a selection: a span, in each format's own spelling.
15767        let mut dj = fmt_doc("a big b\n", Format::Djot);
15768        dj.anchor = Some(2);
15769        dj.caret = 5;
15770        dj.set_font_size(Some(SizeStep::Large));
15771        assert_eq!(dj.source, "a [big]{data-size=\"large\"} b\n");
15772        assert_eq!(dj.font_size_at_caret(), Some(SizeStep::Large));
15773
15774        let mut md = fmt_doc("a big b\n", Format::Markdown);
15775        md.anchor = Some(2);
15776        md.caret = 5;
15777        md.set_text_color(Some(MarkColor::Blue));
15778        assert_eq!(md.source, "a <span data-color=\"blue\">big</span> b\n");
15779        assert_eq!(md.text_color_at_caret(), Some(MarkColor::Blue));
15780
15781        // Without one: the caret's block, through the block gesture.
15782        let mut block = fmt_doc("a big b\n", Format::Djot);
15783        block.caret = 3;
15784        block.set_font_family(Some(FontFamily::Monospace));
15785        assert_eq!(block.source, "{data-font=\"monospace\"}\na big b\n");
15786        assert_eq!(block.font_family_at_caret(), Some(FontFamily::Monospace));
15787    }
15788
15789    /// twig re-styles the span a range already lies in rather than nesting a
15790    /// second, and an empty set unwraps it — so a second press of the menu
15791    /// fixes the size instead of building `[[big]{.a}]{.b}`, and the entry that
15792    /// means "the theme's own" takes the span away.
15793    #[test]
15794    fn a_second_run_gesture_re_styles_the_span_and_none_unwraps_it() {
15795        let mut d = fmt_doc("a big b\n", Format::Djot);
15796        d.anchor = Some(2);
15797        d.caret = 5;
15798        d.set_font_size(Some(SizeStep::Large));
15799        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
15800
15801        // The selection `wrap_range_attrs` left behind covers the whole span;
15802        // colouring it now keeps the size, because the gesture reads the span's
15803        // attributes before it edits its own key.
15804        d.set_text_color(Some(MarkColor::Red));
15805        assert_eq!(
15806            d.source, "a [big]{data-size=\"large\" data-color=\"red\"} b\n",
15807            "one span, both keys"
15808        );
15809        assert_eq!(d.font_size_at_caret(), Some(SizeStep::Large));
15810        assert_eq!(d.text_color_at_caret(), Some(MarkColor::Red));
15811
15812        d.set_text_color(None);
15813        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
15814        d.set_font_size(None);
15815        assert_eq!(d.source, "a big b\n", "the last key unwraps the span");
15816        assert_eq!(d.font_size_at_caret(), None);
15817    }
15818
15819    /// The queries read the nearest node that names the property: the span the
15820    /// caret is in, then its block, then the `div`s around it.
15821    #[test]
15822    fn a_presentation_query_reads_the_nearest_node_that_names_it() {
15823        let mut d = fmt_doc(
15824            "{.center data-size=\"small\" data-font=\"serif\"}\nx [y]{data-size=\"xx-large\"} z\n",
15825            Format::Djot,
15826        );
15827        // In the span: its own size, the block's face and alignment.
15828        d.caret = d.source.find('y').unwrap();
15829        assert_eq!(d.font_size_at_caret(), Some(SizeStep::XxLarge));
15830        assert_eq!(d.font_family_at_caret(), Some(FontFamily::Serif));
15831        assert_eq!(d.alignment_at_caret(), Some(Align::Center));
15832        assert_eq!(d.line_spacing_at_caret(), None);
15833        assert_eq!(d.text_color_at_caret(), None);
15834
15835        // Outside it: the block's size.
15836        d.caret = d.source.find('x').unwrap();
15837        assert_eq!(d.font_size_at_caret(), Some(SizeStep::Small));
15838
15839        // And through a Markdown div, which is where a Markdown block's
15840        // attributes live.
15841        let mut md = fmt_doc(
15842            "<div class=\"center\" data-size=\"large\">\n\nhello\n\n</div>\n",
15843            Format::Markdown,
15844        );
15845        md.caret = md.source.find("hello").unwrap();
15846        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
15847        assert_eq!(md.font_size_at_caret(), Some(SizeStep::Large));
15848
15849        // A document that names none of it answers `None` everywhere, which is
15850        // "the theme's own" and what every toolbar draws unlit.
15851        let mut plain = doc_with("plain_presentation", "hello\n");
15852        plain.caret = 1;
15853        assert_eq!(plain.alignment_at_caret(), None);
15854        assert_eq!(plain.line_spacing_at_caret(), None);
15855        assert_eq!(plain.font_size_at_caret(), None);
15856        assert_eq!(plain.font_family_at_caret(), None);
15857        assert_eq!(plain.text_color_at_caret(), None);
15858    }
15859
15860    /// A djot fenced div is anonymous the way an attributed span is, and is a
15861    /// block all the same — the *form* is the whole of what tells them apart.
15862    /// Read as a span it poisoned both halves: the run gesture copied the div's
15863    /// entire attribute set onto the span it minted, duplicating the `id`, and
15864    /// the run and block queries answered off a node the walker draws nothing
15865    /// for.
15866    #[test]
15867    fn a_djot_fenced_div_is_not_an_attributed_span() {
15868        let src = "{.center data-size=\"small\" #box}\n:::\nhello world\n:::\n";
15869        let mut d = fmt_doc(src, Format::Djot);
15870        let at = d.source.find("world").unwrap();
15871        d.anchor = Some(at);
15872        d.caret = at + "world".len();
15873        d.set_text_color(Some(MarkColor::Red));
15874        assert_eq!(
15875            d.source,
15876            "{.center data-size=\"small\" #box}\n:::\nhello [world]{data-color=\"red\"}\n:::\n",
15877            "the span carries its own key and nothing of the div's"
15878        );
15879
15880        // And the queries stop at the block: a djot div is not a `<div>`, the
15881        // walker lends its keys to nothing inside it, and a query that said
15882        // otherwise would tick a menu entry no glyph on screen obeys.
15883        assert_eq!(d.text_color_at_caret(), Some(MarkColor::Red));
15884        assert_eq!(d.font_size_at_caret(), None);
15885        assert_eq!(d.alignment_at_caret(), None);
15886    }
15887
15888    /// Clearing a property the block does not name and a `div` around it does
15889    /// would write nothing and change nothing — twig's `set_block_attrs`
15890    /// reaches one node, and the div is not it. The gesture says so instead of
15891    /// leaving the author pressing an entry that never ticks.
15892    #[test]
15893    fn clearing_a_property_an_enclosing_div_names_says_so_and_writes_nothing() {
15894        // Markdown, two paragraphs in one div: not the sole-child shape twig
15895        // writes, so `block_attrs_at_caret` reads the paragraph and the
15896        // paragraph names none of it.
15897        let src = "<div class=\"center\" data-line-height=\"1.5\" data-size=\"large\">\n\nhello\n\nworld\n\n</div>\n";
15898        let mut md = fmt_doc(src, Format::Markdown);
15899        md.caret = md.source.find("hello").unwrap();
15900        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
15901
15902        md.set_alignment(None);
15903        assert_eq!(md.source, src, "nothing written");
15904        assert!(!md.dirty);
15905        assert_eq!(
15906            md.status.as_deref(),
15907            Some("alignment: set on the div around the block")
15908        );
15909        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
15910
15911        // The same for a `data-` key, at both levels — the block pair and the
15912        // run three, the run three at a bare caret being the block gesture.
15913        md.set_line_spacing(None);
15914        assert_eq!(md.source, src);
15915        assert_eq!(
15916            md.status.as_deref(),
15917            Some("line spacing: set on the div around the block")
15918        );
15919        md.set_font_size(None);
15920        assert_eq!(md.source, src);
15921        assert_eq!(
15922            md.status.as_deref(),
15923            Some("size: set on the div around the block")
15924        );
15925
15926        // HTML has no sole-child fold at all: a block's attributes go on the
15927        // block, so the div around one is always out of reach.
15928        let html_src = "<div class=\"center\"><p>hi</p></div>\n";
15929        let mut html = fmt_doc(html_src, Format::Html);
15930        html.caret = html.source.find("hi").unwrap();
15931        assert_eq!(html.alignment_at_caret(), Some(Align::Center));
15932        html.set_alignment(None);
15933        assert_eq!(html.source, html_src);
15934        assert!(!html.dirty);
15935        assert_eq!(
15936            html.status.as_deref(),
15937            Some("alignment: set on the div around the block")
15938        );
15939
15940        // And it is a refusal, not a rule against clearing: a block that names
15941        // the property itself still loses it, div or no div.
15942        let mut own = fmt_doc(
15943            "<div class=\"center\"><p class=\"right\">hi</p></div>\n",
15944            Format::Html,
15945        );
15946        own.caret = own.source.find("hi").unwrap();
15947        own.set_alignment(None);
15948        assert_eq!(own.source, "<div class=\"center\"><p>hi</p></div>\n");
15949        assert_eq!(own.status, None);
15950    }
15951
15952    /// An edited key is rewritten **where it stands**. The proposal's worked
15953    /// example is the test: a paragraph that came in as `id="intro"
15954    /// class="lead center" data-line-height="1.5"` and is right-aligned goes
15955    /// out as the same list with one token changed. Removing the key and
15956    /// pushing it back shuffled a document's attributes on every press.
15957    #[test]
15958    fn an_edited_key_keeps_its_place_among_the_attributes() {
15959        let mut html = fmt_doc(
15960            "<p id=\"intro\" class=\"lead center\" data-line-height=\"1.5\">hello</p>\n",
15961            Format::Html,
15962        );
15963        html.caret = html.source.find("hello").unwrap();
15964        html.set_alignment(Some(Align::Right));
15965        assert_eq!(
15966            html.source,
15967            "<p id=\"intro\" class=\"lead right\" data-line-height=\"1.5\">hello</p>\n"
15968        );
15969
15970        // A `data-` key the same way, and a key the block did not have still
15971        // goes on the end.
15972        html.caret = html.source.find("hello").unwrap();
15973        html.set_line_spacing(Some(LineSpacing::Double));
15974        assert_eq!(
15975            html.source,
15976            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\">hello</p>\n"
15977        );
15978        html.caret = html.source.find("hello").unwrap();
15979        html.set_font_size(Some(SizeStep::Large));
15980        assert_eq!(
15981            html.source,
15982            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\" data-size=\"large\">hello</p>\n"
15983        );
15984
15985        // Djot writes the same list in its own spelling, and the order is the
15986        // author's there too.
15987        let mut dj = fmt_doc(
15988            "{#intro .lead .center data-line-height=\"1.5\"}\nhello\n",
15989            Format::Djot,
15990        );
15991        dj.caret = dj.source.find("hello").unwrap();
15992        dj.set_alignment(Some(Align::Right));
15993        assert_eq!(
15994            dj.source,
15995            "{#intro .lead .right data-line-height=\"1.5\"}\nhello\n"
15996        );
15997    }
15998
15999    /// A page break is a block, so twig alone lands one after the caret's whole
16000    /// block; the paragraph is parted at the caret first, exactly as
16001    /// `insert_thematic_break` parts it, and each format spells the directive
16002    /// its own way.
16003    #[test]
16004    fn insert_page_break_parts_the_paragraph_and_spells_the_directive() {
16005        let mut md = doc_with("page_break_md", "hello world\n");
16006        md.caret = 5;
16007        md.insert_page_break();
16008        assert_eq!(md.source, "hello\n\n::page-break\n\nworld\n");
16009        assert!(md.dirty);
16010        assert_eq!(md.status, None);
16011
16012        let mut dj = fmt_doc("hello world\n", Format::Djot);
16013        dj.caret = 5;
16014        dj.insert_page_break();
16015        assert_eq!(dj.source, "hello\n\n::: page-break\n:::\n\nworld\n");
16016
16017        // At a block's end there is no second half to mint, so the break simply
16018        // follows the block — the rule the rule button already has.
16019        let mut end = doc_with("page_break_end", "hello\n");
16020        end.caret = 5;
16021        end.insert_page_break();
16022        assert_eq!(end.source, "hello\n\n::page-break\n");
16023
16024        // And it reaches the map as the placeholder row a frontend paginates on.
16025        end.view = View::Wysiwyg;
16026        end.build_visual(80);
16027        assert_eq!(
16028            end.vmap
16029                .rows
16030                .iter()
16031                .find_map(|r| r.leaf_directive.as_ref())
16032                .map(|m| m.name.as_str()),
16033            Some(PAGE_BREAK)
16034        );
16035    }
16036
16037    /// The vocabulary's capabilities, per format. The two block properties are
16038    /// `SetBlockAttrs` and the three run ones `WrapRangeAttrs`, which is why
16039    /// AsciiDoc can align a paragraph and not size a run: its `[#id.role]#text#`
16040    /// keeps an id and a role and has no slot for a `data-` key.
16041    #[test]
16042    fn the_presentation_capabilities_are_ragged_per_format() {
16043        for fmt in [Format::Markdown, Format::Djot, Format::Html] {
16044            let c = Capabilities::of(fmt);
16045            assert!(c.alignment, "{fmt:?} alignment");
16046            assert!(c.line_spacing, "{fmt:?} line spacing");
16047            assert!(c.font_size, "{fmt:?} size");
16048            assert!(c.font_family, "{fmt:?} face");
16049            assert!(c.text_color, "{fmt:?} colour");
16050        }
16051        // Markdown spells both only under the extensions leaf parses with — a
16052        // `<div>` and a `<span>` read back as containers under `html_elements`,
16053        // and `::page-break` as a directive under `directives`. Ask twig's own
16054        // defaults and the answer is no, which is why `Capabilities` is built
16055        // with `supports_with`.
16056        assert!(!Format::Markdown.supports(Gesture::SetBlockAttrs));
16057        assert!(!Format::Markdown.supports(Gesture::WrapRangeAttrs));
16058        assert!(!Format::Markdown.supports(Gesture::InsertDirective));
16059
16060        let adoc = Capabilities::of(Format::Asciidoc);
16061        assert!(adoc.alignment && adoc.line_spacing, "AsciiDoc's `[…]` line");
16062        assert!(
16063            !adoc.font_size && !adoc.font_family && !adoc.text_color,
16064            "AsciiDoc has no inline spelling that keeps a data- key"
16065        );
16066
16067        // XML spells none of it, and neither page break.
16068        let xml = Capabilities::of(Format::Xml);
16069        assert!(!xml.alignment && !xml.font_size && !xml.page_break);
16070        assert!(Capabilities::of(Format::Markdown).page_break);
16071        assert!(Capabilities::of(Format::Djot).page_break);
16072
16073        // And those two *only*, though twig spells the gesture in HTML and
16074        // AsciiDoc as well: it spells it differently there —
16075        // `<page-break></page-break>` and `<<<` — and the walker reads neither,
16076        // so the button would write a break that draws as nothing at all in
16077        // HTML and as an empty unlabelled row in AsciiDoc. The flag describes
16078        // what leaf can show, not what twig can write. See
16079        // `docs/tasks/page-break-in-html-and-asciidoc.md`.
16080        let exts = parse_extensions();
16081        assert!(Format::Html.supports_with(exts, Gesture::InsertDirective));
16082        assert!(Format::Asciidoc.supports_with(exts, Gesture::InsertDirective));
16083        assert!(!Capabilities::of(Format::Html).page_break);
16084        assert!(!Capabilities::of(Format::Asciidoc).page_break);
16085    }
16086
16087    /// A format that cannot spell a property refuses in its own words and
16088    /// writes nothing — the guard every other gesture has.
16089    #[test]
16090    fn a_presentation_gesture_a_format_cannot_spell_is_refused_with_a_reason() {
16091        let src = "<doc><p>hello</p></doc>\n";
16092        #[allow(clippy::type_complexity)]
16093        let ops: [(&str, &dyn Fn(&mut Doc)); 6] = [
16094            ("alignment", &|d: &mut Doc| {
16095                d.set_alignment(Some(Align::Center))
16096            }),
16097            ("line spacing", &|d: &mut Doc| {
16098                d.set_line_spacing(Some(LineSpacing::Double))
16099            }),
16100            ("size", &|d: &mut Doc| {
16101                d.set_font_size(Some(SizeStep::Large))
16102            }),
16103            ("face", &|d: &mut Doc| {
16104                d.set_font_family(Some(FontFamily::Serif))
16105            }),
16106            ("colour", &|d: &mut Doc| {
16107                d.set_text_color(Some(MarkColor::Red))
16108            }),
16109            ("page break", &|d: &mut Doc| d.insert_page_break()),
16110        ];
16111        for (name, op) in ops {
16112            let mut d = fmt_doc(src, Format::Xml);
16113            let at = d.source.find("hello").unwrap();
16114            d.caret = at;
16115            d.anchor = Some(at + 5);
16116            op(&mut d);
16117            assert_eq!(d.source, src, "{name} edited an XML document");
16118            assert!(!d.dirty, "{name} marked the document dirty");
16119            let status = d.status.as_deref().unwrap_or("");
16120            assert!(
16121                status.contains("xml"),
16122                "{name}: the refusal should name the format, got {status:?}"
16123            );
16124        }
16125
16126        // AsciiDoc is the ragged one: the block gesture works where the run
16127        // gesture does not, and a *selection* is what tells the two apart.
16128        let mut adoc = fmt_doc("hello world\n", Format::Asciidoc);
16129        adoc.anchor = Some(0);
16130        adoc.caret = 5;
16131        adoc.set_font_size(Some(SizeStep::Large));
16132        assert_eq!(adoc.source, "hello world\n", "no inline spelling");
16133        assert!(adoc.status.is_some());
16134    }
16135
16136    /// A read-only document takes none of it, and a caret on a blank line has
16137    /// no block to carry an attribute — both say so rather than writing.
16138    #[test]
16139    fn a_presentation_gesture_respects_read_only_and_a_blank_line() {
16140        let mut ro = fmt_doc("hello\n", Format::Djot);
16141        ro.read_only = true;
16142        ro.caret = 1;
16143        ro.set_alignment(Some(Align::Center));
16144        assert_eq!(ro.source, "hello\n");
16145
16146        let mut blank = fmt_doc("a\n\n\nb\n", Format::Djot);
16147        blank.caret = 2; // the empty line between the two paragraphs
16148        blank.set_alignment(Some(Align::Center));
16149        assert_eq!(blank.source, "a\n\n\nb\n");
16150        assert!(
16151            blank.status.as_deref().unwrap_or("").contains("no block"),
16152            "got {:?}",
16153            blank.status
16154        );
16155    }
16156
16157    /// A block attribute gesture keeps the caret on the **text** it was on, not
16158    /// on the byte offset it had. Markdown has nowhere to put a paragraph's
16159    /// attributes but a `<div>` around it, and twig splices the div and the
16160    /// block it wraps as one region — so a caret that kept its offset landed in
16161    /// the markup, and every press after the first answered "no block at the
16162    /// caret" with the toolbar's queries reading nothing.
16163    #[test]
16164    fn a_markdown_block_gesture_keeps_the_caret_on_its_text() {
16165        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
16166        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
16167        md.caret = md.source.find("brown").unwrap() + 2; // "br|own"
16168
16169        // Wrapping: the div and two blank lines open above the block.
16170        md.set_alignment(Some(Align::Center));
16171        assert_eq!(
16172            md.source,
16173            "<div class=\"center\">\n\nthe quick brown fox\n\n</div>\n"
16174        );
16175        assert_eq!(word(&md), 2, "the caret left its word: {}", md.caret);
16176        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
16177
16178        // Re-styling: the attribute line changes length under the same caret,
16179        // and the second press reaches the same block rather than nothing.
16180        md.set_alignment(Some(Align::Right));
16181        assert_eq!(
16182            md.source, "<div class=\"right\">\n\nthe quick brown fox\n\n</div>\n",
16183            "a second press re-styles the div"
16184        );
16185        assert_eq!(md.status, None);
16186        assert_eq!(word(&md), 2);
16187
16188        // A second key on the same div — the line grows, the caret rides it.
16189        md.set_line_spacing(Some(LineSpacing::Double));
16190        assert_eq!(
16191            md.source,
16192            "<div class=\"right\" data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
16193        );
16194        assert_eq!(word(&md), 2);
16195        assert_eq!(md.line_spacing_at_caret(), Some(LineSpacing::Double));
16196
16197        // Unwrapping: the line shrinks, and then the div goes altogether.
16198        md.set_alignment(None);
16199        assert_eq!(
16200            md.source,
16201            "<div data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
16202        );
16203        assert_eq!(word(&md), 2);
16204        md.set_line_spacing(None);
16205        assert_eq!(md.source, "the quick brown fox\n", "the last key unwraps");
16206        assert_eq!(word(&md), 2, "the caret came back down with the block");
16207        assert_eq!(md.alignment_at_caret(), None);
16208        assert_eq!(md.status, None);
16209    }
16210
16211    /// The same rule in djot, where the spelling is a `{…}` line *above* the
16212    /// block rather than a wrapper around it: inserting it pushes the block
16213    /// down, re-styling it changes the line's length, and clearing the last key
16214    /// takes the line away again. The caret rides all three.
16215    #[test]
16216    fn a_djot_attribute_line_keeps_the_caret_on_its_text() {
16217        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
16218        let mut dj = fmt_doc("the quick brown fox\n", Format::Djot);
16219        dj.caret = dj.source.find("brown").unwrap() + 2;
16220
16221        dj.set_alignment(Some(Align::Center));
16222        assert_eq!(dj.source, "{.center}\nthe quick brown fox\n");
16223        assert_eq!(word(&dj), 2);
16224        assert_eq!(dj.alignment_at_caret(), Some(Align::Center));
16225
16226        dj.set_line_spacing(Some(LineSpacing::Double));
16227        assert_eq!(
16228            dj.source, "{.center data-line-height=\"2\"}\nthe quick brown fox\n",
16229            "a second press edits the line the first wrote"
16230        );
16231        assert_eq!(word(&dj), 2);
16232
16233        dj.set_alignment(None);
16234        assert_eq!(dj.source, "{data-line-height=\"2\"}\nthe quick brown fox\n");
16235        assert_eq!(word(&dj), 2);
16236
16237        dj.set_line_spacing(None);
16238        assert_eq!(dj.source, "the quick brown fox\n");
16239        assert_eq!(word(&dj), 2);
16240        assert_eq!(dj.status, None);
16241    }
16242
16243    /// The run gestures with no selection are the block gesture, so they keep
16244    /// the caret the same way — and a heading keeps it inside the heading's own
16245    /// text, past the `# ` its content span starts after. A selection rides
16246    /// along whole: a block gesture is not a run gesture, and what was selected
16247    /// before the press is still selected after it.
16248    #[test]
16249    fn a_block_gesture_carries_a_selection_and_a_heading_caret_too() {
16250        // No selection: the run gesture goes through the block door.
16251        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
16252        md.caret = md.source.find("brown").unwrap() + 2;
16253        md.set_font_size(Some(SizeStep::Large));
16254        assert_eq!(
16255            md.source,
16256            "<div data-size=\"large\">\n\nthe quick brown fox\n\n</div>\n"
16257        );
16258        assert_eq!(md.caret - md.source.find("brown").unwrap(), 2);
16259        assert_eq!(md.font_size_at_caret(), Some(SizeStep::Large));
16260        md.set_font_size(Some(SizeStep::Small));
16261        assert_eq!(
16262            md.font_size_at_caret(),
16263            Some(SizeStep::Small),
16264            "the second press reached the same block"
16265        );
16266
16267        // A selection: alignment is the block's whatever is selected, and the
16268        // words stay selected.
16269        let mut sel = fmt_doc("the quick brown fox\n", Format::Markdown);
16270        let at = sel.source.find("brown").unwrap();
16271        sel.anchor = Some(at);
16272        sel.caret = at + 5;
16273        sel.set_alignment(Some(Align::Center));
16274        let now = sel.source.find("brown").unwrap();
16275        assert_eq!(sel.selection(), Some((now, now + 5)), "the words moved out");
16276
16277        // A heading: the content span starts past the `# `.
16278        let mut h = fmt_doc("# hi there\n\nbody\n", Format::Markdown);
16279        h.caret = h.source.find("there").unwrap() + 1;
16280        h.set_alignment(Some(Align::Right));
16281        assert_eq!(
16282            h.source,
16283            "<div class=\"right\">\n\n# hi there\n\n</div>\n\nbody\n"
16284        );
16285        assert_eq!(h.caret, h.source.find("there").unwrap() + 1);
16286        assert_eq!(h.alignment_at_caret(), Some(Align::Right));
16287    }
16288
16289    /// A djot document open in the rich view, with its map built as
16290    /// [`wysiwyg_doc`] builds a Markdown one's.
16291    fn wysiwyg_djot(body: &str) -> Doc {
16292        let mut d = fmt_doc(body, Format::Djot);
16293        d.view = View::Wysiwyg;
16294        d.build_visual(80);
16295        d
16296    }
16297
16298    /// Backspace at the start of a block whose presentation is spelled as
16299    /// hidden markup before it strips that presentation, the way Backspace at
16300    /// a heading's start strips its `#`. The ordinary delete fused djot's
16301    /// `{.center}` line onto the text and took the blank line a Markdown div
16302    /// needs between its tag and its paragraph.
16303    #[test]
16304    fn backspace_at_the_start_of_a_centred_paragraph_strips_its_attributes() {
16305        let mut md = wysiwyg_doc(
16306            "wys_attr_bksp",
16307            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
16308        );
16309        md.caret = md.source.find("hello").unwrap();
16310        md.backspace();
16311        assert_eq!(
16312            md.source, "above\n\nhello\n\nbelow\n",
16313            "the div is unwrapped"
16314        );
16315        assert_eq!(md.caret, 7, "the caret stays at the start of its text");
16316        md.backspace();
16317        assert_eq!(
16318            md.source, "above\nhello\n\nbelow\n",
16319            "the next press joins the paragraphs, as it always did"
16320        );
16321
16322        let mut dj = wysiwyg_djot("above\n\n{.center}\nhello\n\nbelow\n");
16323        dj.caret = dj.source.find("hello").unwrap();
16324        dj.backspace();
16325        assert_eq!(
16326            dj.source, "above\n\nhello\n\nbelow\n",
16327            "the attribute line goes"
16328        );
16329        assert_eq!(dj.caret, 7);
16330
16331        // A heading's own marker is the nearer hidden markup, and goes first;
16332        // the attributes are the next press's.
16333        let mut dj = wysiwyg_djot("{.center}\n# Title\n");
16334        dj.caret = dj.source.find("Title").unwrap();
16335        dj.backspace();
16336        assert_eq!(dj.source, "{.center}\nTitle\n", "the `#` first");
16337        dj.build_visual(80);
16338        dj.backspace();
16339        assert_eq!(dj.source, "Title\n", "then the attributes");
16340        assert_eq!(dj.caret, 0);
16341    }
16342
16343    /// A div around several blocks has no sole child for twig to unwrap, so
16344    /// at its first block the caret steps back to the stop before rather than
16345    /// taking the div apart; a later block has an ordinary paragraph above it
16346    /// and joins as any paragraph does.
16347    #[test]
16348    fn backspace_at_the_first_of_a_div_s_blocks_steps_back_and_a_later_one_joins() {
16349        let src = "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n";
16350        let mut d = wysiwyg_doc("wys_div_first", src);
16351        d.caret = d.source.find("hello").unwrap();
16352        d.backspace();
16353        assert_eq!(d.source, src, "nothing is deleted");
16354        assert_eq!(d.caret, 5, "the caret steps back to the end of `above`");
16355
16356        let mut d = wysiwyg_doc("wys_div_later", src);
16357        d.caret = d.source.find("world").unwrap();
16358        d.backspace();
16359        assert_eq!(
16360            d.source, "above\n\n<div class=\"center\">\n\nhello\nworld\n\n</div>\n",
16361            "a later block joins the one above it"
16362        );
16363    }
16364
16365    /// Backspace at the start of the paragraph after a Markdown div joins it
16366    /// into the div's last paragraph — the join any two paragraphs make, with
16367    /// the hidden `</div>` carried past the joined text. The ordinary delete
16368    /// took the newline under the tag, which drew nothing different, and the
16369    /// next press took the `>` and left the div unclosed.
16370    #[test]
16371    fn backspace_after_a_div_joins_the_paragraph_into_it() {
16372        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
16373        let mut d = wysiwyg_doc("wys_div_join", src);
16374        d.caret = d.source.find("below").unwrap();
16375        d.backspace();
16376        assert_eq!(
16377            d.source,
16378            "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n"
16379        );
16380        assert_eq!(
16381            d.caret,
16382            d.source.find("below").unwrap(),
16383            "the caret stays at the start of the joined text"
16384        );
16385        d.build_visual(80);
16386        assert_eq!(
16387            d.alignment_at_caret(),
16388            Some(Align::Center),
16389            "and is centred now"
16390        );
16391        d.undo();
16392        assert_eq!(d.source, src, "one undo step");
16393
16394        // A list closes the div: the paragraph joins the last item's text,
16395        // under the item's continuation indent, inside the div.
16396        let src = "<div class=\"center\">\n\n- item\n\n</div>\n\nbelow\n";
16397        let mut d = wysiwyg_doc("wys_div_list", src);
16398        d.caret = d.source.find("below").unwrap();
16399        d.backspace();
16400        assert_eq!(
16401            d.source, "<div class=\"center\">\n\n- item\n  below\n\n</div>\n",
16402            "the paragraph joins the item"
16403        );
16404        assert_eq!(d.caret, d.source.find("below").unwrap());
16405
16406        // And where twig has nothing to join into — a code block above — the
16407        // caret steps back to the stop before, and nothing is deleted.
16408        let src = "```\ncode\n```\n\nbelow\n";
16409        let mut d = wysiwyg_doc("wys_code_then_para", src);
16410        d.caret = d.source.find("below").unwrap();
16411        d.backspace();
16412        assert_eq!(d.source, src, "nothing is deleted");
16413        assert!(
16414            d.caret < d.source.find("below").unwrap(),
16415            "the caret stepped back"
16416        );
16417    }
16418
16419    /// Backspace on a blank line collapses to the stop before it — but not
16420    /// across hidden markup, which that collapse deleted whole: a `</div>`,
16421    /// or a comment between two blocks. There the blank line goes alone, and
16422    /// the caret lands where the collapse would have put it.
16423    #[test]
16424    fn backspace_on_a_blank_line_after_hidden_markup_keeps_the_markup() {
16425        let mut d = wysiwyg_doc(
16426            "wys_div_blank",
16427            "<div class=\"center\">\n\nhello\n\n</div>\n\n\n\nbelow\n",
16428        );
16429        d.caret = d.source.find("below").unwrap() - 2; // the empty paragraph
16430        assert!(
16431            d.vmap.is_stop(d.caret),
16432            "the empty paragraph is a caret home"
16433        );
16434        d.backspace();
16435        assert_eq!(
16436            d.source, "<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
16437            "the blank line goes and the div stays closed"
16438        );
16439        assert_eq!(
16440            d.caret,
16441            d.source.find("hello").unwrap() + 5,
16442            "onto the end of `hello`"
16443        );
16444
16445        let mut d = wysiwyg_doc("wys_comment_blank", "above\n\n<!-- note -->\n\n\n\nbelow\n");
16446        d.caret = d.source.find("below").unwrap() - 2;
16447        assert!(d.vmap.is_stop(d.caret));
16448        d.backspace();
16449        assert_eq!(
16450            d.source, "above\n\n<!-- note -->\n\nbelow\n",
16451            "the comment stays"
16452        );
16453        assert_eq!(d.caret, 5);
16454    }
16455
16456    /// Backspace at the end of an attributed span steps inside its hidden
16457    /// closing tag the way it steps inside a `**`, and takes the span with
16458    /// its last letter. Before, the byte-step took the `>` of `</span>`,
16459    /// which left the paragraph unparseable: it vanished from the rich view,
16460    /// and the Backspace after that joined the next block into the wreck.
16461    #[test]
16462    fn backspace_walks_into_a_sized_span_and_takes_the_emptied_span_with_its_space() {
16463        let src = "above\n\nThis <span data-size=\"x-large\">is</span> a test\n\nTest 2\n";
16464        let mut d = wysiwyg_doc("wys_span_bs", src);
16465        d.caret = d.source.find("a test").unwrap() + 6;
16466        for _ in 0..7 {
16467            d.backspace();
16468        }
16469        assert_eq!(
16470            d.source,
16471            "above\n\nThis <span data-size=\"x-large\">is</span>\n\nTest 2\n"
16472        );
16473        d.backspace();
16474        assert_eq!(
16475            d.source, "above\n\nThis <span data-size=\"x-large\">i</span>\n\nTest 2\n",
16476            "the first Backspace after the tag takes the letter, not the `>`"
16477        );
16478        d.backspace();
16479        assert_eq!(
16480            d.source, "above\n\nThis \n\nTest 2\n",
16481            "the last letter takes the span with it"
16482        );
16483        assert_eq!(d.caret, 12, "the caret is where the letter was");
16484        d.backspace();
16485        assert_eq!(d.source, "above\n\nThis\n\nTest 2\n");
16486        assert_eq!(d.caret, 11);
16487        d.build_visual(80);
16488        assert!(
16489            d.vmap
16490                .rows
16491                .iter()
16492                .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "This"),
16493            "the paragraph is still drawn"
16494        );
16495    }
16496
16497    #[test]
16498    fn backspace_walks_into_a_djot_sized_span_too() {
16499        let mut d = wysiwyg_djot("This [is]{data-size=\"x-large\"}\n\nTest 2\n");
16500        d.caret = d.source.find("\n\nTest 2").unwrap();
16501        // The caret home at the paragraph's end is inside the span, before
16502        // its `]`: the map offers no stop after `]{…}`.
16503        d.build_visual(80);
16504        assert_eq!(d.vmap.stop_before(31), Some(8));
16505        d.caret = 8;
16506        d.backspace();
16507        assert_eq!(d.source, "This [i]{data-size=\"x-large\"}\n\nTest 2\n");
16508        d.backspace();
16509        assert_eq!(
16510            d.source, "This \n\nTest 2\n",
16511            "the attribute block outside the span goes with it"
16512        );
16513        d.backspace();
16514        assert_eq!(d.source, "This\n\nTest 2\n");
16515        assert_eq!(d.caret, 4);
16516    }
16517
16518    /// A span that is empty as the file was written has no stop of its own;
16519    /// Backspace reaching it from behind takes it with the character before
16520    /// it, the character the key looked aimed at.
16521    #[test]
16522    fn backspace_over_an_already_empty_span_takes_it_with_the_character_before() {
16523        let src = "This <span data-size=\"x-large\"></span> a test\n";
16524        let mut d = wysiwyg_doc("wys_span_empty", src);
16525        d.caret = d.source.find(" a test").unwrap();
16526        d.backspace();
16527        assert_eq!(d.source, "This a test\n");
16528        assert_eq!(d.caret, 4);
16529    }
16530
16531    /// The mirror: Delete in front of a span's opening tag takes its first
16532    /// letter, and the span with its last.
16533    #[test]
16534    fn delete_walks_into_a_sized_span_and_takes_the_span_with_its_last_letter() {
16535        let src = "This <span data-size=\"x-large\">is</span> a test\n";
16536        let mut d = wysiwyg_doc("wys_span_del", src);
16537        d.caret = 5;
16538        d.delete_forward();
16539        assert_eq!(
16540            d.source,
16541            "This <span data-size=\"x-large\">s</span> a test\n"
16542        );
16543        d.delete_forward();
16544        assert_eq!(d.source, "This  a test\n");
16545        assert_eq!(d.caret, 5);
16546        d.delete_forward();
16547        assert_eq!(d.source, "This a test\n");
16548        assert_eq!(d.caret, 5);
16549    }
16550
16551    /// Backspace at a block's start is twig's join, spelled per format — so
16552    /// the cases the one-newline delete got wrong come out right: a
16553    /// paragraph joins onto a heading's line, HTML's `</p><p>` goes as one,
16554    /// and a quote's prefix is written on the joined line.
16555    #[test]
16556    fn backspace_at_a_block_start_joins_it_the_format_s_way() {
16557        let mut d = wysiwyg_doc("wys_join_heading", "# Title\n\nbelow\n");
16558        d.caret = d.source.find("below").unwrap();
16559        d.backspace();
16560        assert_eq!(d.source, "# Title below\n", "onto the heading's line");
16561        assert_eq!(d.caret, d.source.find("below").unwrap());
16562        d.undo();
16563        assert_eq!(d.source, "# Title\n\nbelow\n", "one undo step");
16564
16565        let mut d = wysiwyg_doc("wys_join_quote", "> a\n\nb\n");
16566        d.caret = d.source.find('b').unwrap();
16567        d.backspace();
16568        assert_eq!(d.source, "> a\n> b\n", "into the quote, with its prefix");
16569        assert_eq!(d.caret, d.source.find('b').unwrap());
16570
16571        let mut h = fmt_doc("<p>above</p>\n<p class=\"x\">below</p>\n", Format::Html);
16572        h.view = View::Wysiwyg;
16573        h.build_visual(80);
16574        h.caret = h.source.find("below").unwrap();
16575        h.backspace();
16576        assert_eq!(
16577            h.source, "<p>above\nbelow</p>\n",
16578            "one paragraph, the tag gone whole"
16579        );
16580        assert_eq!(h.caret, h.source.find("below").unwrap());
16581    }
16582
16583    /// Delete at the end of a block's content is the same join aimed at the
16584    /// block after it, and the caret stays where the joined text now begins.
16585    #[test]
16586    fn delete_at_a_block_end_joins_the_next_block_into_it() {
16587        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
16588        let mut d = wysiwyg_doc("wys_del_join", src);
16589        d.caret = d.source.find("hello").unwrap() + 5;
16590        d.delete_forward();
16591        assert_eq!(
16592            d.source, "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n",
16593            "below joins hello inside the div"
16594        );
16595        assert_eq!(
16596            d.caret,
16597            d.source.find("hello").unwrap() + 5,
16598            "the caret stays"
16599        );
16600
16601        let mut d = wysiwyg_doc("wys_del_join_head", "above\n\n# Title\n");
16602        d.caret = 5;
16603        d.delete_forward();
16604        assert_eq!(
16605            d.source, "above\nTitle\n",
16606            "the heading's marker goes with the join"
16607        );
16608        assert_eq!(d.caret, 5);
16609
16610        // A code block after the paragraph: nothing to join, the caret steps
16611        // forward onto the next stop and nothing is deleted.
16612        let src = "above\n\n```\ncode\n```\n";
16613        let mut d = wysiwyg_doc("wys_del_code", src);
16614        d.caret = 5;
16615        d.delete_forward();
16616        assert_eq!(d.source, src);
16617        assert!(d.caret > 5, "the caret stepped forward");
16618    }
16619}