Skip to main content

leaf_core/
doc.rs

1//! The document model: a `twig::Editor` plus a byte-offset caret and selection.
2//!
3//! Where bough moves a selection through the *tree*, leaf moves a *caret*
4//! through the *characters* — a normal text editor's model — and expresses
5//! every mutation as one of twig's offset-addressed ops:
6//!
7//!   - typing / delete  → `edit_range(start, end, text)`   (P0)
8//!   - re-anchoring      → the returned `Change`            (P1)
9//!   - cursor context    → `node_at` / `ancestors_at`       (P3)
10//!   - the toolbar       → `wrap_range`/`toggle_inline`/`set_block`,
11//!                         `toggle_block_container`/`insert_link`   (P5)
12//!
13//! twig reparses after every edit and leaves everything outside the splice
14//! byte-for-byte untouched, so the document stays a live, navigable AST while
15//! you type into it.
16
17// `PathBuf` names the `path` field and the untitled marker on every build;
18// `Path` is only touched by the filesystem I/O gated behind the `fs` feature.
19// The docs in this file lay their `- key → meaning` lists out in aligned
20// columns, which puts a continuation line further right than clippy's
21// list-indent rule likes. A lazy continuation renders as the same paragraph
22// either way, and the alignment is what makes those tables readable, so the
23// layout wins over the lint.
24#![allow(clippy::doc_overindented_list_items)]
25
26use std::collections::HashMap;
27use std::ops::Range;
28#[cfg(feature = "fs")]
29use std::path::Path;
30use std::path::PathBuf;
31
32#[cfg(feature = "fs")]
33use anyhow::Context;
34use anyhow::{Result, anyhow};
35use twig::{
36    Alignment, BlockContainerKind, BlockKind, Change, Editor, FlatNode, Format, Gesture,
37    InlineKind, Kind, MarkdownExtensions, NodeId, QueryMatch,
38};
39use unicode_segmentation::GraphemeCursor;
40
41use crate::counts::{self, TextCounts};
42use crate::html;
43use crate::source::{self, SourceMap};
44use crate::style::{Align, FontFace, FontSize, LineHeight, MarkColor, TextColor};
45use crate::wysiwyg::{self, MediaKind, MediaStop, Reveal, VisualMap};
46
47/// Which view the body shows.
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
49pub enum View {
50    /// The raw document with a caret in source bytes.
51    Source,
52    /// Markup resolved to real styles, caret riding the rendered glyphs.
53    Wysiwyg,
54}
55
56/// How much of the source markup the WYSIWYG view exposes — a per-editor
57/// preference, orthogonal to [`View`]. Named for markup rather than for Markdown
58/// because leaf is grammar-agnostic: twig hands it Djot, HTML and XML on the same
59/// terms, and every rung below is about *delimiters*, whatever grammar spells
60/// them. The examples are Markdown only because that is what most documents are.
61///
62/// A single ladder over two underlying axes, because only three of their four
63/// combinations are coherent:
64///
65/// | | authoring off | authoring on |
66/// |---|---|---|
67/// | delimiters hidden | [`None`](Self::None) | [`Shortcuts`](Self::Shortcuts) |
68/// | caret line revealed | *incoherent* | [`Full`](Self::Full) |
69///
70/// The empty quadrant would show delimiters on the caret's line and then escape
71/// the ones you type — a surface that displays a syntax it refuses to accept.
72/// Someone who wants to read raw markup without authoring it has
73/// [`View::Source`], which is the better tool for it.
74///
75/// The two axes are read separately by the code that cares — see
76/// [`reveals_caret_line`](Self::reveals_caret_line) and
77/// [`authors`](Self::authors) — so neither behaviour has to know it's spelled
78/// as a ladder.
79#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
80pub enum MarkupMode {
81    /// Delimiters stay hidden even on the caret's line, and typed syntax stays
82    /// literal — twig escapes anything that would open markup, so formatting
83    /// comes from commands (⌘b, the toolbar) instead of from spelling. The clean
84    /// reading surface for people who don't write markup by hand; the default,
85    /// and what Diaryx ships.
86    #[default]
87    None,
88    /// Delimiters stay hidden, but typing them authors real markup: `*x*`
89    /// becomes italic and the asterisks disappear into the styling
90    /// (Typora/Bear-shaped). For someone who knows the syntax but wants the
91    /// clean surface back once it has been applied.
92    Shortcuts,
93    /// The caret's line shows its raw markup while every other line renders
94    /// resolved (Obsidian live-preview-shaped), and typed syntax authors markup
95    /// — for people fluent in the document's grammar who want to see and edit
96    /// the delimiters they type.
97    Full,
98}
99
100impl MarkupMode {
101    /// Whether the rich view shows raw delimiters on the line holding the caret.
102    /// The rendering axis — read by [`Doc::reveal_line`] and threaded into the
103    /// WYSIWYG builder.
104    pub fn reveals_caret_line(self) -> bool {
105        matches!(self, MarkupMode::Full)
106    }
107
108    /// Whether typed markup characters author real formatting. The editing axis
109    /// — read by [`Doc::insert`], which escapes typed syntax when this is false.
110    pub fn authors(self) -> bool {
111        !matches!(self, MarkupMode::None)
112    }
113}
114
115/// How the WYSIWYG view treats a *soft break* — a bare newline inside a
116/// paragraph. An axis of its own, orthogonal to [`MarkupMode`] (which governs
117/// inline-markup delimiters) and to [`View`]: any reveal preference pairs with
118/// either flow. The renderer consults it when it lays a block's inline content
119/// into visual rows.
120#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
121pub enum LineFlow {
122    /// A soft break folds into a space and the paragraph reflows to the
123    /// viewport width — flowing prose, where the source's line wrapping is
124    /// insignificant. The default, and what Diaryx ships.
125    #[default]
126    Fold,
127    /// A soft break renders as a line break exactly where it was written, so
128    /// the author's source line structure shows on screen unchanged — the mode
129    /// for people who lay out their prose deliberately (one sentence or clause
130    /// per line, semantic line breaks). The break is still a soft break in the
131    /// source; only its rendering changes.
132    Preserve,
133}
134
135/// What the file behind a document looks like right now, against the bytes leaf
136/// last read from it or wrote to it — the question a frontend asks before it
137/// saves (a `Changed` file plus a `dirty` document is an overwrite about to
138/// happen) or when its window regains focus. See [`Doc::disk_state`].
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum DiskState {
141    /// The file holds exactly the bytes leaf last read or wrote.
142    Unchanged,
143    /// Someone else wrote the file since. Saving overwrites their work; see
144    /// [`Doc::reload`] for the other direction.
145    Changed,
146    /// The file is gone — deleted or renamed away. A save recreates it.
147    Missing,
148    /// There is a path, but the file couldn't be read (permissions, a directory
149    /// in the way): leaf can't tell, and won't guess.
150    Unreadable,
151    /// No file behind this document yet — see [`Doc::blank`]. Nothing can have
152    /// changed under a document that was never on disk.
153    Untitled,
154}
155
156/// The inline marks in force at a point in the document — what a toolbar
157/// lights up. A `Copy` bitset rather than a `HashSet`, because
158/// [`Doc::active_inline_marks`] is called on every frame that draws a toolbar
159/// and a set that allocates to answer "is Bold on?" is a set that shouldn't.
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
161pub struct InlineMarks(u8);
162
163impl InlineMarks {
164    /// Every kind, in the order [`InlineMarks::iter`] yields them.
165    const ALL: [InlineKind; 8] = [
166        InlineKind::Strong,
167        InlineKind::Emph,
168        InlineKind::Verbatim,
169        InlineKind::Mark,
170        InlineKind::Superscript,
171        InlineKind::Subscript,
172        InlineKind::Insert,
173        InlineKind::Delete,
174    ];
175
176    pub const fn empty() -> Self {
177        InlineMarks(0)
178    }
179
180    /// Private: the set is an *answer*, and adding a mark to it doesn't mark
181    /// anything ([`Doc::toggle`] does that). `FromIterator` is the way in.
182    fn insert(&mut self, kind: InlineKind) {
183        self.0 |= Self::bit(kind);
184    }
185
186    /// Flip `kind` in the set — the sticky-marks toggle at a collapsed caret.
187    fn flip(&mut self, kind: InlineKind) {
188        self.0 ^= Self::bit(kind);
189    }
190
191    /// The symmetric difference: which marks differ between the two sets. Used
192    /// to resolve the marks already in force at the caret against the pending
193    /// delta — a bit set in the delta flips the base mark for the next keystroke.
194    fn xor(self, other: InlineMarks) -> InlineMarks {
195        InlineMarks(self.0 ^ other.0)
196    }
197
198    /// Whether `kind` is in force — the toolbar's "is Bold active?".
199    pub fn contains(self, kind: InlineKind) -> bool {
200        self.0 & Self::bit(kind) != 0
201    }
202
203    pub fn is_empty(self) -> bool {
204        self.0 == 0
205    }
206
207    /// The marks in force, for a frontend that renders whatever is on rather
208    /// than asking after a fixed list.
209    pub fn iter(self) -> impl Iterator<Item = InlineKind> {
210        Self::ALL.into_iter().filter(move |&k| self.contains(k))
211    }
212
213    fn bit(kind: InlineKind) -> u8 {
214        1 << match kind {
215            InlineKind::Strong => 0,
216            InlineKind::Emph => 1,
217            InlineKind::Verbatim => 2,
218            InlineKind::Mark => 3,
219            InlineKind::Superscript => 4,
220            InlineKind::Subscript => 5,
221            InlineKind::Insert => 6,
222            InlineKind::Delete => 7,
223        }
224    }
225}
226
227impl FromIterator<InlineKind> for InlineMarks {
228    fn from_iter<I: IntoIterator<Item = InlineKind>>(iter: I) -> Self {
229        let mut m = InlineMarks::empty();
230        for k in iter {
231            m.insert(k);
232        }
233        m
234    }
235}
236
237/// What kind of edit produced an undo group. Same-kind edits in a row coalesce
238/// into one undo step (a run of typed characters undoes together); `Other` never
239/// coalesces, so a paste, format toggle, or block change is always its own step.
240#[derive(Clone, Copy, PartialEq, Eq)]
241enum EditKind {
242    Insert,
243    Delete,
244    /// One step of an IME composition — see [`Doc::edit_composing`]. Its own kind
245    /// rather than `Insert`'s because a composition is not typing: each step
246    /// *replaces* the last (`か` → `かん` → `感`), so the run has to coalesce even
247    /// though no two steps insert the same bytes, and it must not fold into the
248    /// typed characters on either side of it.
249    Compose,
250    Other,
251}
252
253/// Which side of the caret a delete looks for an in-cell `<br>` break to swallow
254/// whole — see [`Doc::cell_break_at`]. `Backward` is Backspace (a break ending at
255/// the caret), `Forward` is Delete (one starting at it).
256#[derive(Clone, Copy)]
257enum BreakEdge {
258    Backward,
259    Forward,
260}
261
262/// A re-spelling of one inline mark run, held ready in case the edit about to
263/// happen breaks it — see [`Doc::mark_edge_fix`] and [`Doc::repair_mark_edges`].
264/// Every offset in it is in the coordinates the document will have *after* the
265/// plain edit, since that is when it may be applied.
266struct MarkEdgeFix {
267    /// The run's kind, and an offset inside what was its content: together they
268    /// answer "did the plain edit actually break this mark?" — the question that
269    /// decides whether any of this is applied at all.
270    kind: InlineKind,
271    probe: usize,
272    /// The byte range to re-spell (the run's delimiters included) and its new
273    /// spelling, with the edge whitespace moved outside the delimiters.
274    start: usize,
275    end: usize,
276    text: String,
277    /// Where the caret belongs afterwards — the same place on screen it would
278    /// have had, which is now on the other side of a delimiter.
279    caret: usize,
280    /// The marks in force for text typed at that caret. The caret can land
281    /// outside a run it was inside, and the marks have to survive the move or
282    /// the toolbar goes dark mid-word.
283    want: InlineMarks,
284}
285
286/// The caret and selection at one moment — the part of a history step twig's
287/// `Change` cannot carry, because the caret is leaf's state and twig only knows
288/// about bytes. leaf serializes it into the opaque per-state blob twig now
289/// stores in its own undo history (see `record_caret`), so undo and redo hand
290/// back the caret that matches the source they restore.
291#[derive(Clone, Copy)]
292struct CaretState {
293    caret: usize,
294    anchor: Option<usize>,
295}
296
297impl CaretState {
298    /// Pack into the fixed 17-byte blob leaf hands twig: the caret as a u64,
299    /// then an anchor-present flag and the anchor. twig copies these bytes and
300    /// never reads them.
301    fn to_blob(self) -> [u8; 17] {
302        let mut b = [0u8; 17];
303        b[..8].copy_from_slice(&(self.caret as u64).to_le_bytes());
304        if let Some(a) = self.anchor {
305            b[8] = 1;
306            b[9..].copy_from_slice(&(a as u64).to_le_bytes());
307        }
308        b
309    }
310
311    /// Recover a state from twig's blob, or `None` when it is empty or the wrong
312    /// length — a state twig restored that never had a caret set on it, which
313    /// leaves the caller to fall back to the edit site.
314    fn from_blob(b: &[u8]) -> Option<Self> {
315        let b: &[u8; 17] = b.try_into().ok()?;
316        let caret = u64::from_le_bytes(b[..8].try_into().unwrap()) as usize;
317        let anchor = (b[8] != 0).then(|| u64::from_le_bytes(b[9..].try_into().unwrap()) as usize);
318        Some(CaretState { caret, anchor })
319    }
320}
321
322/// A footnote reference and the note it names — the answer to
323/// [`Doc::footnote_at`].
324///
325/// The two `Option`s move together: a reference whose definition is missing has
326/// neither a body to show nor a place to jump to, and one that resolved has
327/// both.
328#[derive(Clone, PartialEq, Eq, Debug)]
329pub struct FootnoteRef {
330    /// The reference's label — the `1` of `[^1]`, with neither the `^` that
331    /// spells it a footnote nor the brackets around it.
332    pub label: String,
333    /// The note's body as source bytes (see
334    /// [`wysiwyg::footnote_body_span`](crate::wysiwyg)), or `None` when the
335    /// document defines no `[^label]:` to read one from.
336    pub text: Option<String>,
337    /// Where the note's *body* starts, for a "go to note" that moves the caret
338    /// there. `None` alongside a `None` `text`.
339    ///
340    /// The body rather than the definition, because this is an offset to put a
341    /// caret on and the `[^1]:` marker is decoration the caret can't occupy —
342    /// aiming at the definition's first byte snaps to the nearest real stop,
343    /// which is up in the paragraph above the note. It is also simply where a
344    /// reader following a reference wants to land: at the note's first word,
345    /// ready to read or amend it.
346    pub offset: Option<usize>,
347    /// Where the note's body ends, exclusive — so a frontend can ask which
348    /// *rendered rows* the note occupies and draw those instead of [`text`](Self::text).
349    ///
350    /// The rows are the note with its markup resolved: `see *later*` reaches a
351    /// frontend as an italic run, not as asterisks. `text` is the source bytes
352    /// and stays the honest answer for anything that wants the note as written
353    /// (a search index, a copy); this pair of offsets is for anything that wants
354    /// it as *read*. `None` alongside a `None` `offset`.
355    pub end: Option<usize>,
356}
357
358/// A footnote definition and the reference that sends a reader to it — the
359/// answer to [`Doc::footnote_definition_at`], and the other half of the round
360/// trip [`FootnoteRef`] starts.
361///
362/// A note is a place a reader *arrives*, so the useful thing to know while
363/// standing in one is the way back. Without this the jump to a note is a
364/// one-way door: the definitions sit at the foot of the document, so returning
365/// by hand means scrolling back up and finding the sentence again.
366#[derive(Clone, PartialEq, Eq, Debug)]
367pub struct FootnoteDef {
368    /// The definition's label — the `1` of `[^1]: …`, marker and colon stripped,
369    /// spelled exactly as [`FootnoteRef::label`] spells the same footnote's.
370    pub label: String,
371    /// Where the reference's *label* is, for a "back to reference" that moves
372    /// the caret there. `None` for a note nothing refers to — an orphan, which
373    /// is worth being able to say rather than silently doing nothing.
374    ///
375    /// The label rather than the reference's first byte, for
376    /// [`FootnoteRef::offset`]'s reason: a reference's brackets are decoration
377    /// and its label is the only part of it the caret can rest on.
378    ///
379    /// The *first* reference, when a label is cited more than once: a repeated
380    /// citation has no one true home, and the first is both the one a reader
381    /// most likely came from and the only choice that doesn't depend on how
382    /// they got here.
383    pub offset: Option<usize>,
384}
385
386/// twig's cap on retained undo steps (`MAX_UNDO` in its splicer), which
387/// [`Doc::can_undo`]'s count follows: past it twig drops the oldest step.
388const UNDO_CAP: usize = 200;
389
390/// An open [`Doc::begin_undo_group`]: how deeply it is nested, and whether an
391/// edit made inside it has put its one step on the history yet.
392#[derive(Clone, Copy, Debug)]
393struct UndoGroup {
394    depth: usize,
395    has_step: bool,
396}
397
398/// What [`Doc::set_unrevealed`] sets aside: the screen's map, what it was
399/// built from, and the caret state a paper build's clamp must not move.
400struct ScreenMap {
401    vmap: VisualMap,
402    key: Option<(u64, Option<usize>, Option<Reveal>)>,
403    caret: usize,
404    anchor: Option<usize>,
405    goal_col: Option<usize>,
406}
407
408/// Where a locator lands — the answer to [`Doc::locate`].
409///
410/// A locator (the `v2` of a `chapter.dj#v2`) names a *place* rather than a
411/// document, and a place is a span rather than a point: a reader following one
412/// wants the caret at its first byte, and a reader merely *peeking* at one wants
413/// the block it covers drawn. Both are served by carrying the whole span, and
414/// only one of the two can be recovered from an offset alone.
415#[derive(Clone, PartialEq, Eq, Debug)]
416pub struct Landing {
417    /// The first byte of the block the locator names — where a caret goes.
418    pub start: usize,
419    /// One past its last byte, so a frontend can map the pair through
420    /// [`VisualMap::row_range_for`](crate::wysiwyg::VisualMap::row_range_for) to the rendered rows the block occupies and draw
421    /// those, the way a footnote peek draws a note ([`FootnoteRef::end`]).
422    pub end: usize,
423}
424
425/// The heading a place in the document sits under — the answer to
426/// [`Doc::heading_at`].
427///
428/// What a host writing a link *to* a position needs: the `#its-slug` half of a
429/// reference is made from `text`, and a peek at the target draws `span`.
430#[derive(Clone, PartialEq, Eq, Debug)]
431pub struct Heading {
432    /// The heading's inline content with its markup stripped — `A *big* day`
433    /// is `A big day` — which is what a slug is made from.
434    pub text: String,
435    /// 1 for `#`, 2 for `##`, and so on.
436    pub level: u32,
437    /// The heading block's own source span, marker and all — the heading, not
438    /// the section it opens.
439    pub span: Range<usize>,
440}
441
442/// Where a dragged block would land — the answer to [`Doc::drop_target_at`].
443///
444/// A drop is aimed at a *row* (the one under the pointer) and lands at a
445/// *boundary* (between two blocks), and a frontend needs both halves: the
446/// offset to hand [`Doc::move_block`], and the row to draw the indicator
447/// above — which is not the row aimed at, since a drop on the lower half of a
448/// block lands below it.
449#[derive(Clone, Copy, PartialEq, Eq, Debug)]
450pub struct DropTarget {
451    /// The boundary offset — `move_block`'s `to`.
452    pub offset: usize,
453    /// The rendered row the indicator is drawn above; `rows.len()` for a drop
454    /// below everything.
455    pub row: usize,
456}
457
458/// A selection cited out of the source: the text itself, up to a requested
459/// number of characters either side, and the byte range it came from. See
460/// [`Doc::selection_quote`].
461///
462/// The prefix and suffix are what make the quote *re-findable*: the same text
463/// can occur twice, and a little of what surrounded it is how a later reader —
464/// or the same document after an edit — tells the occurrences apart. The Web
465/// Annotation model calls this a `TextQuoteSelector`; the shape is older than
466/// the name.
467#[derive(Debug, Clone, PartialEq, Eq)]
468pub struct Quote {
469    /// The selected source, verbatim.
470    pub exact: String,
471    /// What immediately preceded it — possibly empty, at the document's start.
472    pub prefix: String,
473    /// What immediately followed it — possibly empty, at the document's end.
474    pub suffix: String,
475    /// Byte offset in the source where the selection begins.
476    pub start: usize,
477    /// Byte offset where it ends (exclusive).
478    pub end: usize,
479}
480
481/// A host-painted range of the source — an annotation's footprint, a search
482/// hit, a reviewer's mark. Leaf renders it (a background wash behind the
483/// glyphs whose source falls inside it) and hands back the `id` when the
484/// reader activates it; what the range *means* is entirely the host's.
485///
486/// Ranges are source bytes, like the caret and the selection, so a host that
487/// anchors quotes against the source ([`Doc::selection_quote`] is the other
488/// half of that loop) can paint what it found without any coordinate
489/// conversion. A range that drifts off the text it meant is the host's to
490/// re-anchor; leaf draws what it is told.
491#[derive(Debug, Clone, PartialEq, Eq)]
492pub struct Highlight {
493    /// Byte offset in the source where the wash begins.
494    pub start: usize,
495    /// Byte offset where it ends (exclusive).
496    pub end: usize,
497    /// The host's name for it, handed back on activation. Opaque to leaf.
498    pub id: String,
499    /// A rendering hint the frontend maps — a `#RRGGBB` hex string, or
500    /// nothing for the theme's default wash.
501    pub color: Option<String>,
502    /// A margin glyph's name, or nothing for wash-only ink. A highlight with
503    /// a marker gets a small glyph in the margin beside its first line, and
504    /// the glyph — not the wash — is what activates it: the wash is ink, the
505    /// marker is the control, which is what lets a reader put a caret in (or
506    /// copy from) annotated text without a card leaping at them. The name is
507    /// opaque to leaf; an Apple frontend reads it as an SF Symbol, a web one
508    /// as a class.
509    pub marker: Option<String>,
510}
511
512impl Highlight {
513    /// The range covering source `offset` in a list [`Doc::set_highlights`]
514    /// sorted, first by start where several overlap — the one place that
515    /// question is answered, for the frontends that paint by asking it as well
516    /// as for [`Doc::highlight_at`].
517    ///
518    /// The list is sorted by `(start, end)`, so the scan can stop at the first
519    /// range starting past `offset` rather than running to the end. A painter
520    /// asking once per glyph wants [`HighlightCursor`] instead; this is the
521    /// one-shot form, for the host asking what the reader just activated.
522    pub fn covering(highlights: &[Highlight], offset: usize) -> Option<&Highlight> {
523        highlights
524            .iter()
525            .take_while(|h| h.start <= offset)
526            .find(|h| offset < h.end)
527    }
528}
529
530/// [`Highlight::covering`] for a caller walking the document in order — which
531/// is every painter, since a frontend draws rows top to bottom and glyphs left
532/// to right.
533///
534/// The one-shot form is a scan from the front of the list per glyph, and a
535/// document with two hundred search hits pays that two hundred times a row. A
536/// range that ends at or before an offset can never cover that offset *or any
537/// later one*, so the cursor retires those permanently and each glyph costs the
538/// ranges that actually reach it. The answer is identical to
539/// [`Highlight::covering`]'s, offset for offset — this is the same scan with
540/// the part that was being redone dropped, not a cheaper approximation.
541///
542/// Offsets are expected to arrive non-decreasing. One that goes backwards is
543/// still answered correctly: the cursor re-seats to the front, since a painter
544/// that revisits a row is asking a question the retired ranges may own again.
545pub struct HighlightCursor<'a> {
546    highlights: &'a [Highlight],
547    /// The first range not yet retired.
548    at: usize,
549    /// The last offset asked about, to notice a caller going backwards.
550    last: usize,
551}
552
553impl<'a> HighlightCursor<'a> {
554    pub fn new(highlights: &'a [Highlight]) -> Self {
555        HighlightCursor {
556            highlights,
557            at: 0,
558            last: 0,
559        }
560    }
561
562    /// The range covering `offset`, advancing the cursor past every range that
563    /// can no longer cover anything.
564    pub fn at(&mut self, offset: usize) -> Option<&'a Highlight> {
565        if offset < self.last {
566            self.at = 0;
567        }
568        self.last = offset;
569        while self
570            .highlights
571            .get(self.at)
572            .is_some_and(|h| h.end <= offset)
573        {
574            self.at += 1;
575        }
576        Highlight::covering(&self.highlights[self.at..], offset)
577    }
578}
579
580/// The identity of a built [`VisualMap`] — see [`Doc::visual_key`]. Opaque on
581/// purpose: the only useful question is whether two of them are the same map,
582/// and what is behind it — which `Doc` built it, and the (revision, wrap,
583/// reveal line) it was built from — is core's business.
584///
585/// The document is part of it because the rest is not unique to one: two
586/// documents opened at the same width are both at revision zero with no reveal
587/// line, and a frontend holding one copy of a map across the two would take
588/// the second's key for the first's and paint the wrong document.
589#[derive(Clone, PartialEq, Eq, Debug)]
590pub struct VisualKey(u64, Option<(u64, Option<usize>, Option<Reveal>)>);
591
592pub struct Doc {
593    editor: Editor,
594    pub format: Format,
595    pub path: PathBuf,
596    /// Current source, refreshed from the editor after every successful edit.
597    pub source: String,
598    /// The caret, as a byte offset into `source` (always on a char boundary).
599    pub caret: usize,
600    /// The selection's fixed end, if a selection is active; the moving end is
601    /// the caret. `None` means no selection.
602    pub anchor: Option<usize>,
603    pub dirty: bool,
604    pub status: Option<String>,
605    pub view: View,
606    /// Whether the document refuses to change — a *reading* surface over the
607    /// same rendering, selection, and navigation the editor has.
608    ///
609    /// Enforced here rather than by each frontend hiding its input paths,
610    /// because every mutation funnels through a few doors —
611    /// [`splice_exact`](Self::splice_exact), [`undo`](Self::undo),
612    /// [`redo`](Self::redo), and the handful of inserts that go to twig's own
613    /// verbs directly rather than through the splice (a typed literal, a link,
614    /// an image, a rule, a footnote, a cell's line break) — and guarded doors
615    /// are a guarantee where a frontend's suppressed keyboard is a hope. A
616    /// gated door reports exactly like a rolled-back splice, a path every
617    /// caller already handles. `a_read_only_document_refuses_every_door` is
618    /// the list; a new `self.editor.insert_*` call belongs on it.
619    read_only: bool,
620    /// The host-painted ranges, kept sorted by start — see [`Highlight`].
621    /// State like the selection rather than like the text: no edit history,
622    /// no dirty bit, redrawn from whatever the host last set.
623    highlights: Vec<Highlight>,
624    /// How much of the source markup the rich view exposes — a frontend preference (see
625    /// [`MarkupMode`]). Its two axes are read apart: the rendering one by
626    /// [`reveal_line`](Self::reveal_line), the editing one by
627    /// [`insert`](Self::insert).
628    markup_mode: MarkupMode,
629    /// Whether soft breaks fold into the reflowed paragraph or render where
630    /// they were written (see [`LineFlow`]) — an independent frontend
631    /// preference the WYSIWYG builder consults when it lays out a block.
632    line_flow: LineFlow,
633    /// The kind of the last edit, for coalescing: twig owns the undo *history*
634    /// (see `undo`/`redo`), but "what counts as one undo step" is a frontend-UX
635    /// call, so leaf decides when a run continues and tells twig to coalesce.
636    last_edit_kind: Option<EditKind>,
637    /// The inline marks the user has toggled *at a collapsed caret* with no
638    /// selection — "start typing bold here". Held as the XOR delta from the marks
639    /// already in force at [`pending_at`](Self::pending_at): a set bit means
640    /// "flip this kind for the next typed text", so it both turns a mark on where
641    /// none is (type into bold) and off where one already covers the caret (type
642    /// past the bold you're standing in). [`Doc::insert`] realises it onto the
643    /// freshly typed text and then clears it — a mark once realised is carried by
644    /// the caret sitting inside the run, not by this delta.
645    pending_marks: InlineMarks,
646    /// The caret offset [`pending_marks`](Self::pending_marks) applies to. The
647    /// delta is live only while the caret still stands here with no selection;
648    /// any motion or edit ([`move_to`](Self::move_to), a splice, a click) drops
649    /// it, so a toggled-but-never-typed format doesn't leak onto text elsewhere.
650    pending_at: Option<usize>,
651    /// The source as of the last open/save — `dirty` is `source != clean_source`,
652    /// so undoing back to the saved state correctly clears the modified flag.
653    clean_source: String,
654    /// A hash of the bytes leaf last read from `path` or wrote to it; `None`
655    /// while the document has no file behind it. [`Doc::disk_state`] compares
656    /// the file against this to catch an edit made *outside* leaf before a save
657    /// silently overwrites it — `clean_source` only knows what leaf itself did.
658    ///
659    /// A hash, not an mtime: mtime is the cheap answer and the wrong one — two
660    /// writes inside one filesystem timestamp tick are indistinguishable, a
661    /// clock that steps backwards (or a writer that restores an mtime) hides a
662    /// real change, and a `touch` invents one. The whole point of the watermark
663    /// is to not clobber someone's work, so it reads the bytes and compares what
664    /// is actually there. That costs a file read per question, which is why the
665    /// question is asked on a user event (focus, save) and not every frame.
666    disk_hash: Option<u64>,
667    /// The "sticky" display column vertical motion aims for, in the active
668    /// view's grid. Set on the first `move_up`/`move_down` of a run and
669    /// reused by every subsequent one in that run, so passing through a
670    /// shorter line doesn't permanently forget the original column. Any
671    /// horizontal motion or edit clears it.
672    ///
673    /// A column, not a character index: dropping down a line of `你好` onto one
674    /// of ASCII has to land under the glyph the caret was drawn beneath, which
675    /// is the only thing the user can see to aim by. Where the goal falls inside
676    /// a wide character on the target line, the mapping resolves it to that
677    /// character — the caret lands on it rather than between its cells.
678    goal_col: Option<usize>,
679    /// The rendered map for the WYSIWYG view; empty in the source view. Movement
680    /// and clicks read it to stay in visible space.
681    pub vmap: VisualMap,
682    /// The syntax map for the source view; empty in the WYSIWYG view, which
683    /// styles resolved glyphs instead. Built by [`Doc::build_source`] — a
684    /// frontend that never calls it paints raw source unstyled, which is what
685    /// every frontend did before this map existed.
686    pub smap: SourceMap,
687    /// The revision `smap` was built from, or `None` before the first build.
688    /// The map is a pure function of the text alone — no width, no caret, no
689    /// reveal line — so unlike [`vmap_key`](Self::vmap_key) the revision is the
690    /// whole key.
691    smap_key: Option<u64>,
692    /// Everything the map is built from, as one number: bumped whenever the
693    /// document's text changes, and never by a motion, a selection, or a save.
694    /// A frontend can hold work against it — see [`Doc::revision`].
695    revision: u64,
696    /// How many history steps stand behind the caret, and how many ahead of
697    /// it — the answer to a native Edit menu's "may Undo be enabled?", which
698    /// twig's history does not answer itself. A mirror of twig's two stacks,
699    /// kept exact by following every move twig makes to them: a step onto the
700    /// undo stack at [`refresh`](Self::refresh), the funnel every edit comes
701    /// through, capped where twig caps it ([`UNDO_CAP`]); one fewer at each
702    /// [`coalesce_last_undo`](Self::coalesce_last_undo), under twig's own
703    /// two-step rule; and moved back and forth by [`undo`](Self::undo) and
704    /// [`redo`](Self::redo). A counter that only ever went up — which this was
705    /// — answered `true` after a coalesced run had been undone whole. Should
706    /// it ever drift anyway, the first undo twig refuses sets it to zero.
707    undo_steps: usize,
708    redo_steps: usize,
709    /// The undo group a host has open, if any — see
710    /// [`begin_undo_group`](Self::begin_undo_group). `None` outside one.
711    undo_group: Option<UndoGroup>,
712    /// Make the next literal insert fail as twig would refuse one — a test's
713    /// way to reach the rollback no document provokes.
714    #[cfg(test)]
715    refuse_next_literal: bool,
716    /// What `vmap` was built from, or `None` before the first build. The map is
717    /// a pure function of `(revision, wrap, reveal line)`, so when those haven't
718    /// moved, rebuilding it produces the identical map — see
719    /// [`Doc::build_visual`].
720    ///
721    /// The reveal line ([`Doc::reveal_line`]) is the caret's, and is `None` in
722    /// every mode but [`MarkupMode::Full`] — so outside that mode the key is
723    /// text and width alone, and a caret motion still rebuilds nothing.
724    vmap_key: Option<(u64, Option<usize>, Option<Reveal>)>,
725    /// The screen's map, set aside while [`Doc::set_unrevealed`] lays the
726    /// document out as paper, and put back when it stops — `Some` exactly
727    /// while the map in `vmap` is the page's.
728    screen: Option<Box<ScreenMap>>,
729    /// Which `Doc` this is, distinct from every other one built in this
730    /// process. Folded into [`VisualKey`] so that a map stashed by a frontend
731    /// can never be mistaken for another document's — see
732    /// [`Doc::visual_key`]. Nothing else reads it.
733    identity: u64,
734    /// Per-block row cache backing the incremental rebuild: when the text
735    /// changes, only the top-level blocks whose bytes moved are re-rendered and
736    /// the rest are reused shifted (see [`wysiwyg::BlockCache`]). Persists across
737    /// builds; a pure accelerator, so it's never read for correctness.
738    block_cache: wysiwyg::BlockCache,
739    /// What the frontend has said about itself — how tall its pictures came
740    /// out, keyed by destination or by TeX, and whether it paints a picture in
741    /// a line — set through [`Doc::set_media_rows`], [`Doc::set_math_rows`] and
742    /// [`Doc::set_inline_pictures`]. Core does no I/O and lays out in glyphs,
743    /// so this is the only way it learns a height or a capability. Threaded
744    /// into every build; a change drops both caches, since none of it is in a
745    /// block's bytes.
746    surface: wysiwyg::Surface,
747
748    // View geometry the renderer stamps each frame, so mouse events can map a
749    // screen cell back to a byte offset.
750    pub scroll: usize,
751    pub body_origin: (u16, u16),
752    /// Width of the body rectangle last painted by the frontend. Zero means
753    /// unknown (used by tests or a frontend that has not drawn yet).
754    pub body_width: u16,
755    pub body_height: u16,
756    /// The caret as of the last frame drawn, or `None` before the first.
757    ///
758    /// Scrolling is the viewport's business, not the caret's: the view follows
759    /// the caret when the caret *moves*, but a wheel that doesn't touch the
760    /// caret has to be free to scroll away from it — otherwise the view is
761    /// pinned to the caret and stops dead at the edge of the document you can
762    /// see. Comparing against this is what tells the two apart, and it catches a
763    /// caret set by any route, including a frontend assigning the field itself.
764    pub drawn_caret: Option<usize>,
765}
766
767/// The Markdown extensions every leaf document is parsed with — five of them,
768/// each departing from twig's defaults for a reason leaf can state.
769///
770/// `html_elements` promotes embedded raw HTML (`<img>`, `<picture>`,
771/// `<source>`, …) into semantic AST nodes, so a picture becomes a real `image`
772/// node the frontends can frame and rasterize instead of opaque `raw_block`
773/// text. `directives` turns on generic `:::name{.class}` fenced-div containers
774/// (`directive` nodes), which a host app uses for its own semantics (diaryx's
775/// `:::vis{.audience}` visibility blocks) — core renders any directive as a
776/// plain tinted container, agnostic of `name`.
777///
778/// `highlight` and `highlight_colors` are the pair that makes Markdown read
779/// `==text==` as a `mark` node, and `==🔴 text==` as one carrying a
780/// `data-color`. leaf already had somewhere to put both: the
781/// [`Mark`](crate::Role::Mark) role and the ⌘⇧M highlight button predate them,
782/// and until twig 3.3 a Markdown document could only ever *receive* a highlight
783/// from a Djot one it was converted from — the button wrote `==…==` and the
784/// reparse read it straight back as text.
785/// They are on together because a colour is inert without the highlight itself,
786/// and a document that writes `==🔴 x==` means the colour by it.
787///
788/// `math` makes Markdown read `$…$` as an `inline_math` node and `$$…$$` as
789/// a `display_math` one — what djot reads natively and what leaf has
790/// somewhere to put: a formula typesets to a picture, or reveals to its TeX
791/// on the caret's line. Without it a `$$` block is a paragraph whose `\,`
792/// twig has already read as an escaped comma, and an author who types a
793/// backslash in it is authoring Markdown, not TeX. The flag is bounded by
794/// twig's own rule that a dollar followed by whitespace never opens math, so
795/// `$5 and $6` stays prose.
796///
797/// Every flag is inert for non-Markdown formats, so it's safe to pass them
798/// unconditionally. Threading this through every constructor (not just `open`)
799/// keeps `from_source`, `blank`, and `reload` parsing the same document the same
800/// way — twig reparses with these same flags after each edit.
801pub(crate) fn parse_extensions() -> MarkdownExtensions {
802    MarkdownExtensions {
803        html_elements: true,
804        directives: true,
805        highlight: true,
806        highlight_colors: true,
807        math: true,
808    }
809}
810
811/// Build an editor over `bytes` in `format` with leaf's [`parse_extensions`],
812/// mapping twig's error into the `anyhow` context every constructor shares.
813fn new_editor(bytes: &[u8], format: Format) -> Result<Editor> {
814    Editor::new_ext(bytes, format, parse_extensions()).map_err(|e| anyhow!("twig parse: {e}"))
815}
816
817/// Does `format` spell a table as a **pipe table** — the one grid twig's table
818/// editor knows how to emit?
819///
820/// This is the single capability leaf still has to answer for itself, and the
821/// only hand-maintained format list left in this file. Every other gesture is
822/// [`Format::supports`], which is twig's own answer read across the C ABI — but
823/// twig deliberately leaves the table ops out of that query, because they read
824/// no `Syntax` table at all. They rewrite a grid that is already in the source
825/// and refuse on *position*, never on format. Handed a caret inside an HTML
826/// `<table>`, `table_insert_row` therefore re-emits the whole element as
827/// `| a | b |` and reports success — a real splice, a clean reparse, an honest
828/// `dirty` flag, and nothing downstream able to tell it from a good edit.
829///
830/// So the list is narrow on purpose. `Format` is `#[non_exhaustive]`, and the
831/// wildcard answers "no" for a format leaf has never heard of: a new twig
832/// language that *does* spell pipe tables loses its grid controls until this
833/// line is updated, which shows up as a missing button. The other default hands
834/// it to [`Doc::table_op`], which rewrites documents it cannot spell.
835fn spells_pipe_tables(format: Format) -> bool {
836    matches!(format, Format::Markdown | Format::Djot)
837}
838
839/// Which of leaf's authoring controls this document's format can actually
840/// spell — one flag per toolbar button, resolved once so a frontend can build
841/// its chrome instead of discovering each refusal on a click.
842///
843/// Every field but [`table`](Self::table) is `Format::supports_with` on the
844/// gesture the matching [`Doc`] method calls, so this record cannot drift from
845/// what the ops do; `table` is [`spells_pipe_tables`], the one answer twig
846/// doesn't export.
847///
848/// `supports_with` rather than `supports` because two of these are facts about
849/// the *parse options* as much as about the format. `Format::supports` answers
850/// for twig's defaults, and leaf never parses with those — it parses with
851/// [`parse_extensions`], and a document's toolbar has to describe the document
852/// it is over. A Markdown editor holding `highlight` authors `==text==`; one
853/// without it would mint bytes its own reparse hands back as plain text, which
854/// is why twig asks before it writes.
855///
856/// **The formats are ragged, and that is the point.** A single per-document
857/// boolean was enough while the two authorable formats were Markdown and djot
858/// and everything else spelled nothing. HTML is neither: it writes seven of the
859/// eight inline marks as a tag pair, plus `<code>`, `<hr>`, an in-cell
860/// `<br>`, and — since twig 3.4 — a heading or paragraph rebuilt as its tag
861/// pair, and since 3.5 a quote, a list, a code block, a link and an image
862/// printed as fresh nodes; it spells no task box (a form control there) and
863/// no footnote, and its `<table>` is one twig reads but will not write. So
864/// ⌘B, ⌘1 and the quote button work in an HTML document and the task and
865/// table buttons do not, and no one flag can say that. Markdown and djot
866/// differ from each other too:
867/// `^superscript^` is djot-only, and an in-cell `<br>` is Markdown-only.
868#[derive(Clone, Copy, Debug, Eq, PartialEq)]
869pub struct Capabilities {
870    /// ⌘B — `InlineKind::Strong`.
871    pub bold: bool,
872    /// ⌘I — `InlineKind::Emph`.
873    pub italic: bool,
874    /// Inline code — `InlineKind::Verbatim`.
875    pub code: bool,
876    /// Highlight — `InlineKind::Mark`. Djot spells it, and so does Markdown
877    /// under the `highlight` extension [`parse_extensions`] turns on: the
878    /// button writes `==text==`, which is what the reparse reads back.
879    pub mark: bool,
880    /// ⌘U — `InlineKind::Insert`, which every format that marks at all spells.
881    pub underline: bool,
882    /// Strikethrough — `InlineKind::Delete`. Markdown spells GFM's `~~text~~`
883    /// out of the box, since twig parses it out of the box.
884    pub strike: bool,
885    /// The highlight *palette* — [`Doc::set_mark_color`]. Narrower than
886    /// [`mark`](Self::mark) and deliberately its own flag: Markdown spells a
887    /// colour on a highlight (`==🔴 text==`) and djot spells only the highlight,
888    /// so a toolbar offering the swatches wherever the button lights would offer
889    /// them in a document that cannot write one. Pair with
890    /// [`Doc::caret_in_mark`], which asks the other question — the palette needs
891    /// a highlight to colour as much as a format that spells one.
892    pub mark_color: bool,
893    pub superscript: bool,
894    pub subscript: bool,
895    /// Heading levels and "make this a paragraph" — [`Doc::set_block`].
896    pub heading: bool,
897    pub blockquote: bool,
898    pub bullet_list: bool,
899    pub ordered_list: bool,
900    /// The checkbox controls: giving an item a box, and ticking one.
901    pub task: bool,
902    pub link: bool,
903    /// Covers [`Doc::insert_media`] too — see the note there on why the three
904    /// media kinds stand or fall together.
905    pub image: bool,
906    /// The horizontal-rule button. HTML spells this one (`<hr>`).
907    pub thematic_break: bool,
908    /// The footnote button — [`Doc::insert_footnote`]. Markdown and djot spell
909    /// the pair; HTML has no footnote of its own, so the button goes away rather
910    /// than writing brackets that would render as brackets.
911    pub footnote: bool,
912    /// The code-block button — [`Doc::toggle_code_block`], twig's
913    /// `Gesture::ToggleCodeBlock`. Markdown and djot spell the fence; HTML
914    /// rebuilds the block as `<pre><code>`.
915    pub code_block: bool,
916    /// Setting a fenced block's language — a control only ever offered with the
917    /// caret already in a fence.
918    pub code_language: bool,
919    /// The grid controls: insert/delete/move a row or column, set a column's
920    /// alignment. Pair with [`Doc::caret_in_table`], which asks the other
921    /// question — an HTML `<table>` holds the caret and still can't be edited.
922    pub table: bool,
923    /// Shift+Return inside a cell. Markdown and HTML spell it; djot has no
924    /// idiomatic in-cell break.
925    pub cell_line_break: bool,
926    /// The alignment control — [`Doc::set_alignment`], twig's
927    /// `Gesture::SetBlockAttrs`. Every format leaf opens but XML spells a
928    /// block's attributes, Markdown under the `html_elements`
929    /// [`parse_extensions`] turns on (a `<div>` around the block) and AsciiDoc
930    /// through its `[…]` line.
931    pub alignment: bool,
932    /// The line-spacing menu — [`Doc::set_line_spacing`]. The same gesture as
933    /// [`alignment`](Self::alignment) and so the same answer, and its own flag
934    /// because a toolbar dims controls one at a time and the pair may yet
935    /// diverge.
936    pub line_spacing: bool,
937    /// The size menu — [`Doc::set_font_size`], twig's `Gesture::WrapRangeAttrs`
938    /// over a selection. **Narrower than the block pair**: AsciiDoc's
939    /// `[#id.role]#text#` keeps an id and a role and has no slot for a
940    /// `data-` key, so twig refuses the span there and this is `false` while
941    /// [`alignment`](Self::alignment) is `true`. The block-level form of the
942    /// same property — the caret in a paragraph, no selection — goes through
943    /// `SetBlockAttrs` and still works, which is why the flag describes the
944    /// control rather than the caret.
945    pub font_size: bool,
946    /// The face menu — [`Doc::set_font_family`]. `WrapRangeAttrs`, as
947    /// [`font_size`](Self::font_size) is.
948    pub font_family: bool,
949    /// The text-colour swatches — [`Doc::set_text_color`]. `WrapRangeAttrs`,
950    /// and not to be confused with [`mark_color`](Self::mark_color): that is a
951    /// highlight's background and rides the `mark` node twig already owns,
952    /// this is a run's foreground and rides an attributed span.
953    pub text_color: bool,
954    /// The page-break button — [`Doc::insert_page_break`], twig's
955    /// `Gesture::InsertDirective`. Markdown under the `directives` extension
956    /// [`parse_extensions`] turns on (`::page-break`), djot, which spells it
957    /// as an empty `::: page-break` fence, HTML (`<page-break></page-break>`)
958    /// and AsciiDoc (`<<<`) — each drawn as the same placeholder row.
959    pub page_break: bool,
960    /// Moving a block — [`Doc::move_block`] and the Alt+↑/↓ pair, twig's
961    /// `Gesture::MoveBlock`. Every format with blocks a caret can name; XML
962    /// has none.
963    pub move_block: bool,
964}
965
966impl Capabilities {
967    /// Resolve every flag for `format`, as leaf parses it. Pure and cheap —
968    /// twig computes each from a static table — but a frontend that wants to
969    /// hold them can.
970    ///
971    /// The extensions are not a parameter because they are not a choice a
972    /// caller makes: every leaf document is parsed with [`parse_extensions`],
973    /// so the format is the whole of what varies.
974    pub fn of(format: Format) -> Self {
975        let exts = parse_extensions();
976        let supports = |g| format.supports_with(exts, g);
977        let inline = |k| supports(Gesture::ToggleInline(k));
978        let container = |k| supports(Gesture::ToggleBlockContainer(k));
979        Self {
980            bold: inline(InlineKind::Strong),
981            italic: inline(InlineKind::Emph),
982            code: inline(InlineKind::Verbatim),
983            mark: inline(InlineKind::Mark),
984            underline: inline(InlineKind::Insert),
985            strike: inline(InlineKind::Delete),
986            mark_color: supports(Gesture::SetMarkColor),
987            superscript: inline(InlineKind::Superscript),
988            subscript: inline(InlineKind::Subscript),
989            heading: supports(Gesture::SetBlock),
990            blockquote: container(BlockContainerKind::BlockQuote),
991            bullet_list: container(BlockContainerKind::BulletList),
992            ordered_list: container(BlockContainerKind::OrderedList),
993            // Both halves of the checkbox story, and leaf offers no control that
994            // needs only one: the item gesture mints the box, the checked one
995            // ticks it, and a format spelling a `task_marker` spells both.
996            task: supports(Gesture::ToggleTaskItem) && supports(Gesture::ToggleTaskChecked),
997            link: supports(Gesture::InsertLink),
998            image: supports(Gesture::InsertImage),
999            thematic_break: supports(Gesture::InsertThematicBreak),
1000            footnote: supports(Gesture::InsertFootnote),
1001            code_block: supports(Gesture::ToggleCodeBlock),
1002            code_language: supports(Gesture::SetCodeLanguage),
1003            table: spells_pipe_tables(format),
1004            cell_line_break: supports(Gesture::InsertLineBreak),
1005            // The presentation vocabulary, one gesture per level: the two
1006            // line-level properties are a block's attributes and the three
1007            // run-level ones a span's. They are asked separately because the
1008            // formats answer differently — AsciiDoc spells the block and not
1009            // the span — and a toolbar that dimmed all five together would dim
1010            // three controls that work.
1011            alignment: supports(Gesture::SetBlockAttrs),
1012            line_spacing: supports(Gesture::SetBlockAttrs),
1013            font_size: supports(Gesture::WrapRangeAttrs),
1014            font_family: supports(Gesture::WrapRangeAttrs),
1015            text_color: supports(Gesture::WrapRangeAttrs),
1016            // Every format twig spells the directive in: the walker draws
1017            // HTML's `<page-break>` and AsciiDoc's `<<<` as the same
1018            // placeholder Markdown's `::page-break` and djot's fence get.
1019            page_break: supports(Gesture::InsertDirective),
1020            move_block: supports(Gesture::MoveBlock),
1021        }
1022    }
1023}
1024
1025/// The source of [`Doc::identity`], one per document ever built.
1026static NEXT_IDENTITY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1027
1028impl Doc {
1029    #[cfg(feature = "fs")]
1030    pub fn open(path: PathBuf) -> Result<Self> {
1031        let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
1032        Self::from_disk_bytes(path, bytes)
1033    }
1034
1035    /// An empty document *named* `path`, for a file that isn't there yet — what
1036    /// every other terminal editor gives you when you name a file that doesn't
1037    /// exist. It is a real named document, not a [`Doc::blank`]: `is_untitled`
1038    /// is false, so ⌘S writes straight to `path` with no Save As detour, and
1039    /// the header shows the name the user asked for.
1040    ///
1041    /// The format comes from the extension, exactly as [`Doc::open`] reads it —
1042    /// so `leaf notes.dj` starts a djot buffer rather than the Markdown
1043    /// [`Doc::blank`] has to assume for want of a name. An extension leaf can't
1044    /// parse is still an error: a mistyped flag or a stray argument should say
1045    /// so, not open a buffer promising to save somewhere.
1046    ///
1047    /// The watermark is the hash of *no bytes*, not `None`, and that is the
1048    /// whole trick: `None` means untitled, and would leave [`Doc::disk_state`]
1049    /// answering [`DiskState::Untitled`] for a document that has a path and
1050    /// intends to write to it. Hashing `""` instead makes the answers the true
1051    /// ones — [`DiskState::Missing`] while the file still isn't there (a save
1052    /// recreates it, which is exactly what this is for), and
1053    /// [`DiskState::Changed`] if somebody creates it underneath us between
1054    /// launch and save, so the frontend's overwrite prompt guards a new file as
1055    /// it guards an opened one.
1056    ///
1057    /// Nothing is written here. A buffer that is never typed into never touches
1058    /// the filesystem, and a `path` whose directory doesn't exist is allowed to
1059    /// open — the write is where that fails, and it says so then.
1060    #[cfg(feature = "fs")]
1061    pub fn create(path: PathBuf) -> Result<Self> {
1062        Self::from_disk_bytes(path, Vec::new())
1063    }
1064
1065    /// [`Doc::open`] when the file is there, [`Doc::create`] when it isn't —
1066    /// the call a CLI frontend wants for its path argument.
1067    ///
1068    /// The decision is made from the failed read itself rather than a `exists()`
1069    /// check first, so there is no window between the two for the file to appear
1070    /// or vanish in. Only `NotFound` opens a new buffer: a permissions error or
1071    /// a directory in the way is still an error, because pretending those are
1072    /// "no file yet" would offer to save over something leaf couldn't read.
1073    #[cfg(feature = "fs")]
1074    pub fn open_or_create(path: PathBuf) -> Result<Self> {
1075        match std::fs::read(&path) {
1076            Ok(bytes) => Self::from_disk_bytes(path, bytes),
1077            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::create(path),
1078            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
1079        }
1080    }
1081
1082    /// The shared body of [`Doc::open`] and [`Doc::create`]: bytes that are (or
1083    /// stand in for) the file at `path`, parsed as the format its extension
1084    /// names. Keeping the two on one path is what makes a new file's document
1085    /// identical in every respect to an opened one but its contents.
1086    #[cfg(feature = "fs")]
1087    fn from_disk_bytes(path: PathBuf, bytes: Vec<u8>) -> Result<Self> {
1088        let format = detect_format(&path)?;
1089        let editor = new_editor(&bytes, format)?;
1090        let source = String::from_utf8(bytes).map_err(|_| anyhow!("document is not UTF-8"))?;
1091        let disk_hash = Some(hash_bytes(source.as_bytes()));
1092        // Store the document's *absolute* path. A relative one (`leaf README.md`)
1093        // has an empty parent, so a frontend can't resolve a relative image
1094        // destination (`![](pic.png)`) against the document's directory and the
1095        // picture silently falls back to its text placeholder. `absolute` is
1096        // purely lexical — it prefixes the current directory and normalizes, but
1097        // reads nothing and resolves no symlinks — so `file_name` and save are
1098        // unchanged; it only gives `path.parent()` something to join against.
1099        let path = std::path::absolute(&path).unwrap_or(path);
1100        Ok(Doc::from_parts(editor, format, path, source, disk_hash))
1101    }
1102
1103    /// Build a document from an in-memory string, the format named explicitly —
1104    /// the portable, filesystem-free counterpart to [`Doc::open`] (which reads a
1105    /// path and sniffs the format from its extension). A wasm or FFI host, which
1106    /// has no path to read, uses this: it hands over bytes it fetched however it
1107    /// could, and later persists [`Doc::source`] however it can (a browser
1108    /// download, `localStorage`, a backend `PUT`) and calls [`Doc::mark_saved`].
1109    ///
1110    /// No file backs the result, so it starts untitled ([`Doc::is_untitled`] is
1111    /// true) exactly like a [`Doc::blank`] that has been given content.
1112    pub fn from_source(source: String, format: Format) -> Result<Self> {
1113        let editor = new_editor(source.as_bytes(), format)?;
1114        Ok(Doc::from_parts(
1115            editor,
1116            format,
1117            PathBuf::new(),
1118            source,
1119            None,
1120        ))
1121    }
1122
1123    /// An untitled, empty document — the `+` button and a `leaf` launched with
1124    /// no file argument. Nothing on disk backs it until a [`Doc::save_as`].
1125    ///
1126    /// It is Markdown, because a format has to be chosen before a name exists to
1127    /// read one from: `detect_format` reads the extension and an untitled
1128    /// document has neither. Markdown is what leaf's own files are, what its
1129    /// block markers are already written for (`insert_block_prefix`), and the
1130    /// extension a Save As will overwhelmingly pick — a wrong guess here would
1131    /// mean typing djot into a buffer parsing it as Markdown. Note that Save As
1132    /// *doesn't* revisit this: see [`Doc::save_as`].
1133    pub fn blank() -> Result<Self> {
1134        let format = Format::Markdown;
1135        let editor = new_editor(b"", format)?;
1136        // An empty `path` is the untitled marker (`path` is a public `PathBuf`
1137        // field two frontends already read; making it an `Option` to say this
1138        // would break both). `is_untitled` is the question to ask, not the
1139        // representation to copy.
1140        Ok(Doc::from_parts(
1141            editor,
1142            format,
1143            PathBuf::new(),
1144            String::new(),
1145            None,
1146        ))
1147    }
1148
1149    /// The fields every constructor agrees on, so `open` and `blank` can't drift
1150    /// apart in the ones neither of them has an opinion about.
1151    // `identity` is taken from a counter rather than from the `Doc`'s address,
1152    // which moves — a session that holds one is moved into and out of
1153    // containers freely, and an identity that changed with it would defeat the
1154    // one comparison it exists for.
1155    fn from_parts(
1156        editor: Editor,
1157        format: Format,
1158        path: PathBuf,
1159        source: String,
1160        disk_hash: Option<u64>,
1161    ) -> Self {
1162        Doc {
1163            editor,
1164            format,
1165            path,
1166            disk_hash,
1167            clean_source: source.clone(),
1168            source,
1169            caret: 0,
1170            anchor: None,
1171            dirty: false,
1172            status: None,
1173            read_only: false,
1174            highlights: Vec::new(),
1175            // leaf opens in the rich-text (WYSIWYG) view by default — the
1176            // markup-resolved surface is leaf's differentiator. Frontends can
1177            // still start in source view explicitly (e.g. a CLI flag), and ⌘e/⌥w
1178            // toggles at runtime.
1179            view: View::Wysiwyg,
1180            // `None` by default — the clean surface Diaryx ships, with typed
1181            // syntax kept literal; a markup-fluent frontend can climb the
1182            // ladder to `Shortcuts` or `Full`.
1183            markup_mode: MarkupMode::default(),
1184            // Fold by default — flowing prose that reflows to the viewport, the
1185            // behaviour every frontend had before this preference existed.
1186            line_flow: LineFlow::default(),
1187            last_edit_kind: None,
1188            pending_marks: InlineMarks::empty(),
1189            pending_at: None,
1190            goal_col: None,
1191            vmap: VisualMap::default(),
1192            smap: SourceMap::default(),
1193            // No map yet — the first `build_source` always builds.
1194            smap_key: None,
1195            revision: 0,
1196            undo_steps: 0,
1197            redo_steps: 0,
1198            undo_group: None,
1199            #[cfg(test)]
1200            refuse_next_literal: false,
1201            // No map yet — the first `build_visual` always builds.
1202            vmap_key: None,
1203            screen: None,
1204            identity: NEXT_IDENTITY.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
1205            block_cache: wysiwyg::BlockCache::default(),
1206            surface: wysiwyg::Surface::default(),
1207            scroll: 0,
1208            body_origin: (0, 0),
1209            body_width: 0,
1210            body_height: 0,
1211            drawn_caret: None,
1212        }
1213    }
1214
1215    /// Whether this document has no file behind it yet — a [`Doc::blank`] that
1216    /// has never been saved. The question a ⌘S handler asks to know it should
1217    /// open a Save As picker instead ([`Doc::save`] won't guess a name), and the
1218    /// header asks to know the name it shows is a placeholder.
1219    pub fn is_untitled(&self) -> bool {
1220        self.path.as_os_str().is_empty()
1221    }
1222
1223    pub fn toggle_view(&mut self) {
1224        self.view = match self.view {
1225            View::Source => View::Wysiwyg,
1226            View::Wysiwyg => View::Source,
1227        };
1228        self.scroll = 0;
1229        self.status = None;
1230        // Entering WYSIWYG, the caret may be sitting in now-hidden frontmatter;
1231        // lift it to the first rendered offset.
1232        self.clamp_caret();
1233    }
1234
1235    /// The current markup-exposure preference (see [`MarkupMode`]).
1236    pub fn markup_mode(&self) -> MarkupMode {
1237        self.markup_mode
1238    }
1239
1240    /// Set the markup-exposure preference. Both of its axes take effect at
1241    /// once: the editing one on the next [`insert`](Self::insert), and the
1242    /// rendering one on the next build — which is why this drops the cached
1243    /// visual map and the per-block render cache, exactly as
1244    /// [`set_line_flow`](Self::set_line_flow) does.
1245    pub fn set_markup_mode(&mut self, mode: MarkupMode) {
1246        if self.markup_mode == mode {
1247            return;
1248        }
1249        self.markup_mode = mode;
1250        // Neither cache is keyed on the mode, and moving between `Full` and the
1251        // hidden modes changes every row the caret's line renders to — so
1252        // invalidate both explicitly.
1253        self.vmap_key = None;
1254        self.block_cache = wysiwyg::BlockCache::default();
1255    }
1256
1257    /// The line the caret sits on, when that line should render something
1258    /// raw — `None` when nothing on it would, which is what the builder reads
1259    /// as "reveal nothing" and what keeps caret motion from costing a build.
1260    ///
1261    /// Two things ask for it. Under [`MarkupMode::Full`] every delimiter on
1262    /// the caret's line shows ([`Reveal::full`]). In the two hidden modes a
1263    /// *formula* on it still shows its TeX ([`Reveal::math`]), because a
1264    /// formula's content is not its picture and hiding the `$` alone would
1265    /// leave nothing to edit; there the line is threaded through only when it
1266    /// meets a block that holds one, which the last build's layout knows
1267    /// ([`wysiwyg::BlockCache::math_meets`]) — so a document with no math
1268    /// keeps the `None` it always had, and one with math pays a rebuild only
1269    /// while the caret is in the formula's block.
1270    ///
1271    /// A *source* line (newline to newline), not a visual row: a wrapped
1272    /// paragraph and a `LineFlow::Preserve` soft break both split one source
1273    /// line across several rows, and revealing half a delimiter pair because the
1274    /// other half wrapped would be worse than revealing neither. The range
1275    /// excludes the terminating newline and is empty-but-present on a blank
1276    /// line, which reveals nothing but still keys the caches correctly.
1277    ///
1278    /// Only in [`View::Wysiwyg`]: source view already shows every byte, so
1279    /// there is nothing there to reveal.
1280    pub(crate) fn reveal_line(&self) -> Option<Reveal> {
1281        // A page has no caret, so no line of it is the caret's.
1282        if self.view != View::Wysiwyg || self.screen.is_some() {
1283            return None;
1284        }
1285        let line = source_line_range(&self.source, self.caret);
1286        if self.markup_mode.reveals_caret_line() {
1287            return Some(Reveal::full(line));
1288        }
1289        self.block_cache
1290            .math_meets(&line)
1291            .then_some(Reveal::math(line))
1292    }
1293
1294    /// The current soft-break flow preference (see [`LineFlow`]).
1295    pub fn line_flow(&self) -> LineFlow {
1296        self.line_flow
1297    }
1298
1299    /// Set the soft-break flow preference. The mode changes how every block lays
1300    /// out, so a change drops the cached visual map and the per-block render
1301    /// cache, forcing the next [`build_visual`] to rebuild under the new flow.
1302    ///
1303    /// [`build_visual`]: Self::build_visual
1304    pub fn set_line_flow(&mut self, mode: LineFlow) {
1305        if self.line_flow == mode {
1306            return;
1307        }
1308        self.line_flow = mode;
1309        // Both caches are keyed on `(revision, wrap)`, neither of which moved —
1310        // so invalidate them explicitly, or the next build would reuse rows laid
1311        // out under the old flow.
1312        self.vmap_key = None;
1313        self.block_cache = wysiwyg::BlockCache::default();
1314    }
1315
1316    pub fn view_name(&self) -> &'static str {
1317        match self.view {
1318            View::Source => "source",
1319            View::Wysiwyg => "wysiwyg",
1320        }
1321    }
1322
1323    /// Rebuild the WYSIWYG visual map for the current tree at `width` columns
1324    /// (called by the renderer each frame it's in the WYSIWYG view).
1325    /// Build the WYSIWYG map, wrapped at `width` display columns.
1326    ///
1327    /// Cheap to call every frame, which is what both frontends do: the map is a
1328    /// pure function of the document and the wrap width, so a call that would
1329    /// rebuild the same map returns the one already built. Only an edit (or a
1330    /// resize) pays.
1331    ///
1332    /// That isn't a micro-optimisation. A frontend repaints for reasons that have
1333    /// nothing to do with the text — a blinking caret, a scroll, a focus change —
1334    /// and rebuilding here is O(document): 23 ms on a 1 MB file, of which 5 ms is
1335    /// marshalling twig's AST across the C ABI. Paid twice a second by the GUI's
1336    /// blink timer, that was 14% of a core spent redrawing an unchanged document.
1337    /// (`cargo run --release -p leaf-core --example bench` for the numbers.)
1338    pub fn build_visual(&mut self, width: usize) {
1339        self.build_map(Some(width));
1340    }
1341
1342    /// Build the WYSIWYG map with each block as a single unwrapped row — for a
1343    /// frontend (the GUI) that wraps at its own proportional pixel width rather
1344    /// than a fixed character column.
1345    pub fn build_visual_unwrapped(&mut self) {
1346        self.build_map(None);
1347    }
1348
1349    /// Lay the document out as paper shows it, with no line revealed — or,
1350    /// with `false`, go back to the screen's map.
1351    ///
1352    /// The reveal is core's, folded into the rows before a frontend sees them:
1353    /// under [`MarkupMode::Full`] the caret's line shows its delimiters, and in
1354    /// every mode a formula on it is its TeX rather than its picture. A page
1355    /// has no caret, so a PDF or a printout laid out from the screen's map
1356    /// printed the one line the reader happened to be standing on as source.
1357    /// While this is on, [`build_visual`](Self::build_visual) and its twin
1358    /// build as though nothing were revealed.
1359    ///
1360    /// Kept apart from the screen's build rather than replacing it: turning
1361    /// this on sets the screen's map aside — and the caret, which a build
1362    /// clamps against the map it builds — and turning it off puts both back
1363    /// as they were, so the screen's next build costs nothing it would not
1364    /// have cost anyway. Meant to bracket one read of the map, on and then
1365    /// off; an edit in between is not the paper's to make.
1366    pub fn set_unrevealed(&mut self, on: bool) {
1367        match (on, self.screen.take()) {
1368            (true, None) => {
1369                self.screen = Some(Box::new(ScreenMap {
1370                    vmap: std::mem::take(&mut self.vmap),
1371                    key: self.vmap_key.take(),
1372                    caret: self.caret,
1373                    anchor: self.anchor,
1374                    goal_col: self.goal_col,
1375                }));
1376            }
1377            (false, Some(screen)) => {
1378                let ScreenMap {
1379                    vmap,
1380                    key,
1381                    caret,
1382                    anchor,
1383                    goal_col,
1384                } = *screen;
1385                self.vmap = vmap;
1386                self.vmap_key = key;
1387                self.caret = caret;
1388                self.anchor = anchor;
1389                self.goal_col = goal_col;
1390            }
1391            // Already in the state asked for.
1392            (_, screen) => self.screen = screen,
1393        }
1394    }
1395
1396    /// Build the source view's syntax map ([`Doc::smap`]) — the styling for
1397    /// [`View::Source`], the way [`build_visual`](Self::build_visual) is the
1398    /// styling for [`View::Wysiwyg`].
1399    ///
1400    /// A frontend calls this before painting raw source. One that doesn't gets
1401    /// an empty map and paints unstyled text, so this is additive: nothing
1402    /// breaks by not calling it.
1403    ///
1404    /// Built at most once per revision, and the revision is the whole key — the
1405    /// map has no width and no caret in it, so it survives every resize, every
1406    /// motion, and every selection change.
1407    ///
1408    /// The builds it does do cost a whole-arena marshal, which is precisely what
1409    /// the WYSIWYG path works to avoid, so this has no incremental path where
1410    /// that one has two. From `cargo run --release -p leaf-core --example
1411    /// bench`, per keystroke, against the WYSIWYG build the source view is
1412    /// *not* doing:
1413    ///
1414    /// |  size |  nodes | marshal | `source::build` | (`wysiwyg::build`) |
1415    /// |------:|-------:|--------:|----------------:|-------------------:|
1416    /// |  10 KB|    613 |  0.16 ms|         0.07 ms |            0.28 ms |
1417    /// | 100 KB|  6 097 |  0.84 ms|         0.38 ms |            2.43 ms |
1418    /// |   1 MB| 60 601 |  5.67 ms|         3.12 ms |           23.39 ms |
1419    ///
1420    /// Linear, two thirds of it the marshal, and the build itself five to seven
1421    /// times cheaper than the one it stands in for at every size. Comfortable
1422    /// well past any document a person edits in a terminal — a megabyte is where
1423    /// it would want [`Editor::dirty_range`] and the same splice treatment
1424    /// `build_spliced` gives the other map. The door is open; nothing has needed
1425    /// it yet.
1426    pub fn build_source(&mut self) {
1427        if self.smap_key == Some(self.revision) {
1428            return;
1429        }
1430        let nodes = self.nodes();
1431        self.smap = source::build(&nodes, &self.source);
1432        self.smap_key = Some(self.revision);
1433    }
1434
1435    /// Tell the model how many visual rows each block image should reserve, keyed
1436    /// by the image's destination. A terminal frontend calls this once it has
1437    /// decoded and measured its pictures — core does no image I/O, so this is the
1438    /// only way it learns a height — and the next [`Doc::build_visual`] lays each
1439    /// placeholder out that tall (the label row plus blank filler rows the
1440    /// frontend paints the raster over). A destination left out of the map falls
1441    /// back to the bare one-row placeholder, which is also what a frontend that
1442    /// can't draw pictures (or lays them out in its own units, like the GUI) gets
1443    /// by never calling this.
1444    ///
1445    /// Cheap to call every frame with the same map: only a *change* invalidates
1446    /// the built map (and the block-row cache, since a height isn't part of a
1447    /// block's bytes and so wouldn't otherwise re-render it). Steady state is a
1448    /// no-op, so a frontend can just hand over its current measurements each frame.
1449    pub fn set_media_rows(&mut self, rows: HashMap<String, usize>) {
1450        if self.surface.media_rows == rows {
1451            return;
1452        }
1453        self.surface.media_rows = rows;
1454        self.surface_changed();
1455    }
1456
1457    /// Tell the model how many visual rows each display formula should
1458    /// reserve, keyed by the formula's TeX exactly as the map's
1459    /// [`MathInfo::tex`](wysiwyg::MathInfo::tex) handed it over. The peer of
1460    /// [`set_media_rows`](Self::set_media_rows) for the terminal, which
1461    /// typesets the picture, measures it in cells, and reports back; a
1462    /// frontend that lays formulas out in pixels never calls this and gets
1463    /// the one-row placeholder to paint over.
1464    pub fn set_math_rows(&mut self, rows: HashMap<String, usize>) {
1465        if self.surface.math_rows == rows {
1466            return;
1467        }
1468        self.surface.math_rows = rows;
1469        self.surface_changed();
1470    }
1471
1472    /// Tell the model whether the frontend can paint a picture *inside* a line
1473    /// of text. When it can, an inline formula renders to one atom glyph the
1474    /// frontend draws its typeset picture over — see
1475    /// [`MathInfo`](wysiwyg::MathInfo) — and when it cannot (a terminal), to
1476    /// the code-styled TeX it always showed. Off until a frontend says
1477    /// otherwise, so a host that has not caught up sees what it saw.
1478    pub fn set_inline_pictures(&mut self, on: bool) {
1479        if self.surface.inline_pictures == on {
1480            return;
1481        }
1482        self.surface.inline_pictures = on;
1483        self.surface_changed();
1484    }
1485
1486    /// A height or a capability lives outside a block's source bytes, so the
1487    /// content-keyed block cache would hand back the old rows on a hit. Drop
1488    /// it (and the splice layout it carries) so the next build re-renders
1489    /// every block against the new surface, and force that build by clearing
1490    /// the map key.
1491    fn surface_changed(&mut self) {
1492        self.block_cache = wysiwyg::BlockCache::default();
1493        self.vmap_key = None;
1494    }
1495
1496    /// The revision the document's text is at — bumped by every edit, undo,
1497    /// redo, and reload, and by nothing else. A frontend caches against this to
1498    /// tell a repaint that needs new work from one that doesn't.
1499    ///
1500    /// It counts *edits*, not distinct texts: typing `x` and deleting it again
1501    /// lands on the same text two revisions later. Work is only ever rebuilt
1502    /// needlessly, never wrongly reused.
1503    pub fn revision(&self) -> u64 {
1504        self.revision
1505    }
1506
1507    /// The identity of the map presently in [`vmap`](Self::vmap) — what the last
1508    /// [`build_visual`](Self::build_visual) built it from, or the identity of an
1509    /// unbuilt map before the first one.
1510    ///
1511    /// This is *not* [`revision`](Self::revision). The revision says where the
1512    /// text is; this says where the map is, and the two part company the moment
1513    /// an edit lands, until something rebuilds. A frontend that keeps its own
1514    /// copy of the map — leaf-ratatui stashes core's before splicing filler rows
1515    /// under an oversized heading — compares this against the value it held when
1516    /// it took the copy, and learns whether `vmap` is still the map it stashed
1517    /// or one somebody else has since rebuilt. Restoring a copy over a newer
1518    /// map would paint a stale document; restoring nothing hands core's
1519    /// incremental rebuild a map it never built.
1520    ///
1521    /// "Somebody else" includes another document. The key names the `Doc`
1522    /// as well as the build, so a frontend that draws two documents through
1523    /// one stash — a host with several buffers, or one that opens the next
1524    /// document where the last one stood — never has the copy it took of one
1525    /// accepted by the other, however alike their builds are.
1526    pub fn visual_key(&self) -> VisualKey {
1527        VisualKey(self.identity, self.vmap_key.clone())
1528    }
1529
1530    /// The map, built at most once per `(revision, wrap)`. `clamp_caret` still
1531    /// runs on every call: the caret moves without the document changing, and
1532    /// keeping it on a legal stop is this function's job either way.
1533    fn build_map(&mut self, wrap: Option<usize>) {
1534        // Under `MarkupMode::Full` the map is a function of the caret's *line*
1535        // as well as the text, so the line joins the key: moving within a line
1536        // still reuses the map, and crossing into another one rebuilds it. In
1537        // every other mode `reveal_line` is `None` and the key is what it was,
1538        // so caret motion goes on costing nothing.
1539        let reveal = self.reveal_line();
1540        let key = (self.revision, wrap, reveal.clone());
1541        if self.vmap_key.as_ref() != Some(&key) {
1542            self.build_map_with(wrap, reveal);
1543            self.vmap_key = Some(key);
1544            // In a hidden mode the reveal line was decided from the *previous*
1545            // build's layout, whose spans are stale across an edit: the
1546            // keystroke that closes a new `$…$` on the caret's line asked "is
1547            // there math here?" of a layout that had none, and the formula
1548            // would snap to its picture under the caret until the next
1549            // motion. Ask again of the layout just built, and go once more if
1550            // the answer moved. Between edits the first answer is exact and
1551            // this is one comparison.
1552            let again = self.reveal_line();
1553            if again != self.vmap_key.as_ref().and_then(|k| k.2.clone()) {
1554                self.build_map_with(wrap, again.clone());
1555                self.vmap_key = Some((self.revision, wrap, again));
1556            }
1557        }
1558        self.clamp_caret();
1559    }
1560
1561    /// One build of the map at `wrap` under `reveal`, incremental where it can
1562    /// be — the body of [`build_map`](Self::build_map), which decides whether
1563    /// to call it.
1564    fn build_map_with(&mut self, wrap: Option<usize>, reveal: Option<Reveal>) {
1565        {
1566            // Enumerate the top-level blocks cheaply — no whole-arena marshal.
1567            // A subtree is pulled only for the block(s) that actually changed, so
1568            // the FFI marshal shrinks from O(document) to O(edited block).
1569            let top = self.top_blocks();
1570
1571            // Fast path: when twig reports a dirty byte range, try to patch the
1572            // previous map in place — a single-block edit moves the prefix,
1573            // shifts the suffix, and re-renders only one block. `build_spliced`
1574            // returns `None` (and we fall back to the always-correct full rebuild)
1575            // whenever the edit reshaped the block structure, hit a table, or
1576            // there's no previous map to patch.
1577            // Preserve soft breaks as written when the flow preference asks for
1578            // it — the builder renders each as its own visual row instead of
1579            // folding it into the reflowed paragraph.
1580            let preserve_soft = self.line_flow == LineFlow::Preserve;
1581            let spliced = match self.editor.dirty_range() {
1582                Some(dirty) => {
1583                    let prev = std::mem::take(&mut self.vmap);
1584                    let source = &self.source;
1585                    let cache = &mut self.block_cache;
1586                    let surface = &self.surface;
1587                    let editor = &mut self.editor;
1588                    wysiwyg::build_spliced(
1589                        prev,
1590                        source,
1591                        wrap,
1592                        preserve_soft,
1593                        &top,
1594                        dirty,
1595                        surface,
1596                        reveal.clone(),
1597                        cache,
1598                        |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1599                    )
1600                }
1601                None => None,
1602            };
1603            self.vmap = spliced.unwrap_or_else(|| {
1604                let source = &self.source;
1605                let cache = &mut self.block_cache;
1606                let surface = &self.surface;
1607                let editor = &mut self.editor;
1608                wysiwyg::build_cached(
1609                    &top,
1610                    source,
1611                    wrap,
1612                    preserve_soft,
1613                    surface,
1614                    reveal,
1615                    cache,
1616                    |id| editor.subtree(NodeId(id)).unwrap_or_default(),
1617                )
1618            });
1619            // Acknowledge the dirty range so the next edit's range starts fresh.
1620            self.editor.clear_dirty();
1621        }
1622    }
1623
1624    fn nodes(&mut self) -> Vec<FlatNode> {
1625        self.editor.nodes().unwrap_or_default()
1626    }
1627
1628    /// The document's top-level blocks for the incremental render. See
1629    /// [`wysiwyg::top_blocks`] for why this isn't simply `child_spans(None)`.
1630    fn top_blocks(&mut self) -> Vec<QueryMatch> {
1631        wysiwyg::top_blocks(&mut self.editor)
1632    }
1633
1634    pub fn format_name(&self) -> &'static str {
1635        // `Format` is `#[non_exhaustive]` as of twig 3.0, so the wildcard is
1636        // required. It also covers `Asciidoc`, which twig parses but cannot
1637        // serialize — leaf never opens a document in it (see `Doc::open`).
1638        match self.format {
1639            Format::Djot => "djot",
1640            Format::Markdown => "markdown",
1641            Format::Xml => "xml",
1642            Format::Html => "html",
1643            _ => "unknown",
1644        }
1645    }
1646
1647    /// Whether this document's format offers *any* door in — `false` only for a
1648    /// wholly parse-only format (XML, AsciiDoc), where every gesture refuses and
1649    /// a frontend may as well open the file read-only.
1650    ///
1651    /// This is a much weaker claim than the name suggests, and driving per-button
1652    /// state from it is exactly the mistake to avoid: HTML answers `true` because
1653    /// it spells the inline marks with a tag pair (`<strong>`, `<em>`, `<code>`)
1654    /// while a heading, a quote, a list, a task box, a link and a code fence all
1655    /// remain unspellable there. Ask [`capabilities`](Self::capabilities) — or
1656    /// [`supports`](Self::supports) — per control.
1657    pub fn authorable(&self) -> bool {
1658        self.format.is_authorable()
1659    }
1660
1661    /// Whether this document can spell `gesture`, which is twig's own answer
1662    /// rather than a copy of it: `Format::supports_with` reads the same
1663    /// `Syntax` table the `Editor` method consults before refusing, chosen by
1664    /// the very [`parse_extensions`] this document's editor reparses with — so
1665    /// what the toolbar offers and what the splice will accept are one table.
1666    ///
1667    /// It is a fact about the *document*, not about the caret. `true` does not
1668    /// promise the gesture succeeds where it is standing — a link over a table
1669    /// border still fails — only that it will not fail with
1670    /// `UnsupportedFormat`. Gray out on `false`; don't read `true` as "this
1671    /// will work here".
1672    pub fn supports(&self, gesture: Gesture) -> bool {
1673        self.format.supports_with(parse_extensions(), gesture)
1674    }
1675
1676    /// Every control's enabled state in one read — what a toolbar builds itself
1677    /// from when a document opens or its format changes. See [`Capabilities`].
1678    pub fn capabilities(&self) -> Capabilities {
1679        Capabilities::of(self.format)
1680    }
1681
1682    /// Refuse a gesture this document's format cannot spell, saying so in the
1683    /// status line. `true` means the caller must return without calling twig.
1684    ///
1685    /// Most of these refusals duplicate one twig would make anyway, and they are
1686    /// made here regardless because a message naming the *document's* format
1687    /// reads better than one naming twig's internals. Two of them are not
1688    /// duplicates and are the reason this is a guard rather than an error
1689    /// translation:
1690    ///
1691    /// - The table family (see [`table_op`](Self::table_op)) consults no
1692    ///   `Syntax` table, so twig does not refuse it at all.
1693    /// - [`toggle`](Self::toggle) at a collapsed caret never reaches twig — it
1694    ///   arms a sticky mark for text not yet typed, which is a promise `insert`
1695    ///   could not keep.
1696    fn refuse_unsupported(&mut self, what: &str, gesture: Gesture) -> bool {
1697        self.refuse_unless(what, self.supports(gesture))
1698    }
1699
1700    /// [`refuse_unsupported`](Self::refuse_unsupported) against a capability leaf
1701    /// answers itself — today only [`spells_pipe_tables`].
1702    fn refuse_unless(&mut self, what: &str, supported: bool) -> bool {
1703        if supported {
1704            return false;
1705        }
1706        self.status = Some(format!("{what}: not supported in {}", self.format_name()));
1707        true
1708    }
1709
1710    /// The name to show for this document. An untitled one has no file to name
1711    /// it, and both frontends put this straight on screen — an empty path
1712    /// renders as an empty header, so it says so instead.
1713    pub fn file_name(&self) -> String {
1714        if self.is_untitled() {
1715            return "untitled".into();
1716        }
1717        self.path
1718            .file_name()
1719            .map(|s| s.to_string_lossy().into_owned())
1720            .unwrap_or_else(|| self.path.display().to_string())
1721    }
1722
1723    /// The selection as an ordered `[start, end)` byte range, or `None` when the
1724    /// caret and anchor coincide (an empty selection is no selection).
1725    pub fn selection(&self) -> Option<(usize, usize)> {
1726        self.anchor
1727            .map(|a| (a.min(self.caret), a.max(self.caret)))
1728            .filter(|(s, e)| s != e)
1729    }
1730
1731    /// The selected text, or `None` when there's no selection — the source
1732    /// slice a copy/cut hands to the system clipboard.
1733    pub fn selected_text(&self) -> Option<&str> {
1734        self.selection().map(|(s, e)| &self.source[s..e])
1735    }
1736
1737    /// The selection as a quote with a little of what surrounds it — the shape
1738    /// a host that cites, annotates, or searches for a passage wants, cut from
1739    /// the **source** rather than from anything rendered, so the quote is
1740    /// findable in the document again by plain string search.
1741    ///
1742    /// `context` is a count of characters (not bytes) on each side, clipped at
1743    /// the document's edges; the slices land on char boundaries by
1744    /// construction. `None` when nothing is selected.
1745    pub fn selection_quote(&self, context: usize) -> Option<Quote> {
1746        let (start, end) = self.selection()?;
1747        let mut before = start;
1748        for _ in 0..context {
1749            match self.source[..before].chars().next_back() {
1750                Some(c) => before -= c.len_utf8(),
1751                None => break,
1752            }
1753        }
1754        let mut after = end;
1755        for _ in 0..context {
1756            match self.source[after..].chars().next() {
1757                Some(c) => after += c.len_utf8(),
1758                None => break,
1759            }
1760        }
1761        Some(Quote {
1762            exact: self.source[start..end].to_string(),
1763            prefix: self.source[before..start].to_string(),
1764            suffix: self.source[end..after].to_string(),
1765            start,
1766            end,
1767        })
1768    }
1769
1770    /// Words, characters, and paragraphs over the whole document — the numbers
1771    /// a status bar or an inspector puts next to a piece of writing.
1772    ///
1773    /// Counted over the text a **reader** sees, not the markup that spells it:
1774    /// `**bold**` is one word and four characters, a link is its label and not
1775    /// its destination, a block picture's `🖼 alt` placeholder is a picture and
1776    /// counts nothing, and leading frontmatter — which the WYSIWYG view does
1777    /// not render at all — is not writing. [`crate::counts`] states the rules
1778    /// in full; [`TextCounts`] states them per field.
1779    ///
1780    /// The same numbers in both views. They have to be: a word count that fell
1781    /// when you pressed ⌘E would be telling you the view had changed, which
1782    /// you knew already. So this reads neither [`Doc::view`] nor the map the
1783    /// frontend last built — it renders the source afresh, unwrapped, with
1784    /// soft breaks folded and no line revealed, and counts that. A narrower
1785    /// window, a different [`MarkupMode`], a different [`LineFlow`], and the
1786    /// source view all give the identical answer, because none of them is an
1787    /// input.
1788    ///
1789    /// That costs a reparse and an unwrapped layout — O(document), about 4 ms
1790    /// on a 45 KB file in release and 36 ms on half a megabyte. Fine on a
1791    /// settle and wrong in a paint loop, so a frontend should ask when the
1792    /// typing stops rather than once a keystroke. Caching it against
1793    /// [`revision`](Self::revision) is the obvious next move if that is ever
1794    /// not enough; nothing has needed it yet.
1795    pub fn counts(&self) -> TextCounts {
1796        self.count_over(None)
1797    }
1798
1799    /// The same statistics over the selection alone — `None` when nothing is
1800    /// selected, since an empty selection is no selection.
1801    ///
1802    /// Same rules, over the same rendering, narrowed to the glyphs whose
1803    /// source byte falls inside [`selection`](Self::selection)'s range. A
1804    /// block the selection only clips still counts as one paragraph, and one
1805    /// it enters without catching a visible character counts as none — a
1806    /// selection that starts on a hidden `**` gains no paragraph from it.
1807    pub fn selection_counts(&self) -> Option<TextCounts> {
1808        let (start, end) = self.selection()?;
1809        Some(self.count_over(Some(start..end)))
1810    }
1811
1812    /// The rendering both counters tally, and the tally itself.
1813    ///
1814    /// A fresh parse rather than `self.editor`, because these take `&self` and
1815    /// twig's arena is reached through `&mut`. A document that will not
1816    /// reparse is a "cannot happen" — the source came out of an editor that
1817    /// had already accepted it — and answers zero rather than panicking in
1818    /// what is very likely a paint path.
1819    fn count_over(&self, range: Option<Range<usize>>) -> TextCounts {
1820        let Ok(mut editor) = new_editor(self.source.as_bytes(), self.format) else {
1821            return TextCounts::default();
1822        };
1823        let Ok(nodes) = editor.nodes() else {
1824            return TextCounts::default();
1825        };
1826        // A surface that paints pictures in a line, so an inline formula is
1827        // an atom here and never its TeX: a formula is a picture to a reader
1828        // whichever way it is written, and the count says so consistently.
1829        let surface = wysiwyg::Surface {
1830            inline_pictures: true,
1831            ..Default::default()
1832        };
1833        let map = wysiwyg::build(&nodes, &self.source, None, false, &surface, None);
1834        counts::tally(&map, range)
1835    }
1836
1837    /// Whether the document refuses to change — see the field.
1838    pub fn read_only(&self) -> bool {
1839        self.read_only
1840    }
1841
1842    /// Turn the read-only gate on or off. A frontend preference like
1843    /// [`set_markup_mode`](Self::set_markup_mode): nothing about the document
1844    /// itself changes, only what may be done to it from here on.
1845    pub fn set_read_only(&mut self, on: bool) {
1846        self.read_only = on;
1847    }
1848
1849    /// The host-painted ranges, sorted by start — see [`Highlight`].
1850    pub fn highlights(&self) -> &[Highlight] {
1851        &self.highlights
1852    }
1853
1854    /// Replace the host-painted ranges wholesale. The whole set each time,
1855    /// rather than add/remove verbs: the host owns the list (it derives it
1856    /// from its own state — annotations, search hits), and a replace can
1857    /// never leave the two disagreeing about what should be on screen.
1858    pub fn set_highlights(&mut self, mut highlights: Vec<Highlight>) {
1859        highlights.retain(|h| h.start < h.end);
1860        highlights.sort_by_key(|h| (h.start, h.end));
1861        self.highlights = highlights;
1862    }
1863
1864    /// The highlight covering source `offset`, if one does — first by start
1865    /// when several overlap, which makes overlapping washes resolvable rather
1866    /// than undefined. What a frontend asks when the reader activates a spot.
1867    ///
1868    /// [`Highlight::covering`] is the whole of it: the frontends paint by
1869    /// asking the same question per glyph, against a slice they were handed
1870    /// rather than against a `Doc`, and one answer for both is what keeps a
1871    /// wash and an activation agreeing about which range a spot is in.
1872    pub fn highlight_at(&self, offset: usize) -> Option<&Highlight> {
1873        Highlight::covering(&self.highlights, offset)
1874    }
1875
1876    /// The AST breadcrumb at the caret (root → deepest), e.g.
1877    /// `doc › para › strong`. Read live from twig via `ancestors_at`.
1878    pub fn breadcrumb(&mut self) -> String {
1879        match self.editor.ancestors_at(self.caret) {
1880            Ok(chain) => chain
1881                .iter()
1882                .map(|m| m.kind.as_str())
1883                .collect::<Vec<_>>()
1884                .join(" › "),
1885            Err(_) => String::new(),
1886        }
1887    }
1888
1889    // ── editing ──────────────────────────────────────────────────────────────
1890
1891    /// Replace the byte range `[start, end)` with `text`, re-anchoring the caret
1892    /// after it. The public form of the internal splice — a pixel frontend that
1893    /// hit-tests to a byte offset (or an IME that hands back an explicit range)
1894    /// edits through this, the same twig `edit_range` the caret ops use.
1895    pub fn edit(&mut self, start: usize, end: usize, text: &str) {
1896        self.splice(start, end, text, EditKind::Other);
1897    }
1898
1899    /// Replace `[start, end)` with `text` in place, behind the caret — an
1900    /// automatic substitution a host makes as the user types: a misspelling
1901    /// corrected, a text replacement expanded, a straight quote curled, a `--`
1902    /// made a dash. Whether it did: `false` for a read-only document, a range
1903    /// that is not one, or an edit twig refused.
1904    ///
1905    /// Unlike [`edit`](Self::edit), the caret and the selection stay where they
1906    /// were, moved along by the edit — a word corrected behind the caret does
1907    /// not pull the caret back to it — and so does a sticky mark armed at the
1908    /// caret. It is an undo step of its own, folded into neither the typing
1909    /// before it nor the typing after, so one undo puts back exactly what was
1910    /// typed, with the caret where it stood. The bytes are replaced exactly,
1911    /// snapping neither end, so a word at the edge of `**bold**` keeps its
1912    /// delimiters. `text` is written the way typing writes it: literally, with
1913    /// anything that would open markup escaped, where typing is literal
1914    /// ([`MarkupMode::None`] in the rendered view).
1915    pub fn substitute(&mut self, start: usize, end: usize, text: &str) -> bool {
1916        if self.read_only
1917            || start > end
1918            || end > self.source.len()
1919            || !self.source.is_char_boundary(start)
1920            || !self.source.is_char_boundary(end)
1921        {
1922            return false;
1923        }
1924        let before = self.source.len();
1925        let (caret, anchor) = (self.caret, self.anchor);
1926        let (pending_marks, pending_at) = (self.pending_marks, self.pending_at);
1927        let group_had_step = self.undo_group.map(|g| g.has_step);
1928        self.last_edit_kind = None;
1929        let literal = !self.markup_mode.authors()
1930            && self.view == View::Wysiwyg
1931            && !text.is_empty()
1932            && self.supports(Gesture::InsertLiteral);
1933        let landed = if literal {
1934            let deleted = self.source[start..end].to_owned();
1935            if start != end && !self.splice_exact(start, end, "", EditKind::Other) {
1936                false
1937            } else if self.insert_literal_at(start, text, EditKind::Other, start != end) {
1938                true
1939            } else {
1940                // The deletion landed and the text did not: take the deletion
1941                // back rather than leave half a substitution.
1942                if start != end {
1943                    self.restore_deleted(start, &deleted, group_had_step);
1944                }
1945                false
1946            }
1947        } else {
1948            self.splice_exact(start, end, text, EditKind::Other)
1949        };
1950        if !landed {
1951            self.caret = caret;
1952            self.anchor = anchor;
1953            self.record_caret();
1954            return false;
1955        }
1956        self.carry_selection(
1957            caret,
1958            anchor,
1959            (pending_marks, pending_at),
1960            start,
1961            end,
1962            before,
1963        );
1964        true
1965    }
1966
1967    /// Bring the source to `text` in one step that leaves the caret where it
1968    /// was — what a host does when the file changed under an open editor, as
1969    /// another device's edit arriving does.
1970    ///
1971    /// Only the span that differs is replaced: the longest prefix and suffix
1972    /// the two share are kept, so a caret or selection outside the change
1973    /// stays on the characters it was on, and one inside it goes to the end
1974    /// of what replaced it, as [`substitute`](Self::substitute) moves them.
1975    /// Unlike a substitution, `text` is source and written exactly — nothing
1976    /// in it is escaped — since it is the document as it now stands, not
1977    /// something typed. An undo step of its own. `true` with nothing done
1978    /// when the source is already `text`; `false` when the document is
1979    /// read-only or the edit was refused.
1980    pub fn replace_source(&mut self, text: &str) -> bool {
1981        if self.source == text {
1982            return true;
1983        }
1984        if self.read_only {
1985            return false;
1986        }
1987        let (start, end, with) = differing_span(&self.source, text);
1988        let with = with.to_owned();
1989        let before = self.source.len();
1990        let (caret, anchor) = (self.caret, self.anchor);
1991        let pending = (self.pending_marks, self.pending_at);
1992        self.last_edit_kind = None;
1993        if !self.splice_exact(start, end, &with, EditKind::Other) {
1994            self.caret = caret;
1995            self.anchor = anchor;
1996            self.record_caret();
1997            return false;
1998        }
1999        self.carry_selection(caret, anchor, pending, start, end, before);
2000        true
2001    }
2002
2003    /// Put the caret and selection back after an edit of `[start, end)` that
2004    /// left them wherever the edit did, moved along by it — see
2005    /// [`substitute`](Self::substitute). `before` is the source's length
2006    /// before the edit; `pending` the sticky marks armed at the old caret.
2007    fn carry_selection(
2008        &mut self,
2009        caret: usize,
2010        anchor: Option<usize>,
2011        pending: (InlineMarks, Option<usize>),
2012        start: usize,
2013        end: usize,
2014        before: usize,
2015    ) {
2016        let (pending_marks, pending_at) = pending;
2017        let delta = self.source.len() as isize - before as isize;
2018        let new_end = (end as isize + delta).max(start as isize) as usize;
2019        // A place after the range moves with it, one inside it goes to the end
2020        // of what replaced it, and one before it stays.
2021        fn shift(p: usize, start: usize, end: usize, new_end: usize, delta: isize) -> usize {
2022            if p >= end {
2023                (p as isize + delta).max(0) as usize
2024            } else if p > start {
2025                new_end
2026            } else {
2027                p
2028            }
2029        }
2030        self.caret = shift(caret, start, end, new_end, delta);
2031        self.anchor = anchor
2032            .map(|a| shift(a, start, end, new_end, delta))
2033            .filter(|&a| a != self.caret);
2034        if pending_at == Some(caret) {
2035            self.pending_marks = pending_marks;
2036            self.pending_at = Some(self.caret);
2037        }
2038        self.goal_col = None;
2039        self.last_edit_kind = None;
2040        self.clamp_caret();
2041        // The caret the step leaves, so a redo puts it back here too.
2042        self.record_caret();
2043    }
2044
2045    /// Put back `deleted`, the bytes a half-made [`substitute`](Self::substitute)
2046    /// took out at `at`, and leave nothing of the pair on the history.
2047    ///
2048    /// Not [`undo`](Self::undo): that closes an open group and takes the whole
2049    /// of it back — every substitution of the keystroke made before this one
2050    /// — and leaves a redo step that would delete the bytes again. Instead the
2051    /// bytes go back as an edit of their own, and the two edits, which change
2052    /// nothing together, are folded away: inside a group that already had a
2053    /// step they fold into it as they land; as a group's first step, or
2054    /// outside a group, into the step before. With no step before it there is
2055    /// nothing to fold into, and one step that changes nothing is left.
2056    /// `group_had_step` is what the group said before the deletion — `None`
2057    /// outside one.
2058    fn restore_deleted(&mut self, at: usize, deleted: &str, group_had_step: Option<bool>) {
2059        if !self.splice_exact(at, at, deleted, EditKind::Other) {
2060            // twig will not take its own bytes back: the history's way, which
2061            // at least leaves the document as it was.
2062            self.undo();
2063            return;
2064        }
2065        match group_had_step {
2066            Some(true) => {}
2067            Some(false) => {
2068                let steps = self.undo_steps;
2069                self.fold_last_undo();
2070                if self.undo_steps < steps
2071                    && let Some(g) = &mut self.undo_group
2072                {
2073                    g.has_step = false;
2074                }
2075            }
2076            None => {
2077                self.fold_last_undo();
2078                self.fold_last_undo();
2079            }
2080        }
2081        self.last_edit_kind = None;
2082    }
2083
2084    /// Insert typed `text` at the caret, replacing the selection if there is one.
2085    /// A single typed character coalesces with the run of typing before it; a
2086    /// newline or a multi-character insert is its own undo step.
2087    ///
2088    /// Typed input only — clipboard text goes through [`paste`](Self::paste).
2089    pub fn insert(&mut self, text: &str) {
2090        // The read-only gate, up front: the paths below reach twig by several
2091        // verbs, not all of them through the splice — see the field.
2092        if self.read_only {
2093            return;
2094        }
2095        // Typing against a block picture would dissolve it, and typing past a
2096        // table would grow it a row — see `open_paragraph_at_block_edge`. Give
2097        // the text a paragraph first, so what the caret was standing beside
2098        // stays what it was.
2099        self.open_paragraph_at_block_edge(text);
2100        // Armed sticky marks (⌘b with no selection) turn the next typed text
2101        // bold/italic/… and then retire — see `insert_with_marks`. Whitespace is
2102        // the exception: it takes no mark of its own and keeps the delta armed
2103        // for the character behind it — see `insert_space_with_marks`.
2104        let pending = self.pending_here();
2105        if !pending.is_empty() && self.selection().is_none() && !text.is_empty() {
2106            if text.trim().is_empty() {
2107                self.insert_space_with_marks(self.caret, text, pending);
2108            } else {
2109                self.insert_with_marks(self.caret, text, pending);
2110            }
2111            return;
2112        }
2113        // `MarkupMode::None`: typed syntax stays literal — twig escapes
2114        // anything that would open markup, so a Diaryx user never mints
2115        // formatting by keyboard (it comes from commands instead). The other two
2116        // rungs of the ladder author markup from what you type, which is the
2117        // whole difference between them and this one. Only in the rendered view
2118        // (source view is for typing raw markup) and only where the format has a
2119        // literal spelling at all: escaping is a backslash before a byte from the
2120        // format's own alphabet, and a format with no such alphabet (HTML escapes
2121        // with entities, XML spells nothing) would have `\&` written into it,
2122        // which is two literal characters and not an escape. Marks (⌘b) still
2123        // format — that path returned above; and leaf's own structural inserts go
2124        // through `insert_raw`, never here, so a list marker or quote gutter is
2125        // written as the markup it is.
2126        if !self.markup_mode.authors()
2127            && self.view == View::Wysiwyg
2128            && !text.is_empty()
2129            && self.supports(Gesture::InsertLiteral)
2130        {
2131            self.insert_literal_typed(text);
2132            return;
2133        }
2134        self.insert_raw(text);
2135    }
2136
2137    /// Insert `text` verbatim at the caret (replacing any selection) — the plain
2138    /// path with no Hidden-mode literal escaping. leaf's own structural inserts
2139    /// (a list marker, a quote gutter, an in-cell `<br>`) call this: they ARE
2140    /// markup by design and must not be escaped.
2141    fn insert_raw(&mut self, text: &str) {
2142        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2143        self.splice(s, e, text, typed_edit_kind(text));
2144    }
2145
2146    /// Open a paragraph for text about to be inserted at one of a block media's
2147    /// two caret stops, or at a table's trailing stop, and leave the caret
2148    /// standing in it.
2149    ///
2150    /// A block image is a paragraph whose entire content is the picture, and the
2151    /// caret's only homes on it are in front of it and just past it (see
2152    /// [`VisualMap::block_media_stop`]). Text inserted at either offset joins
2153    /// *that* paragraph — and a paragraph holding anything besides the image is
2154    /// no longer a block image but a line of text with an inline one in it. The
2155    /// frontend that was painting a photo there paints a text run instead; the
2156    /// picture is still in the file, and nothing said a word. Those two offsets
2157    /// are also exactly where a click on the picture lands, so the whole accident
2158    /// is one tap and one keystroke.
2159    ///
2160    /// So the break goes in first and the text lands in the new empty paragraph —
2161    /// what pressing Return before typing would have done, which is a habit no
2162    /// one should have to learn from losing a photo. A no-op everywhere else, and
2163    /// over a selection (which is replaced, not joined into).
2164    ///
2165    /// A picture inside a quote or a list leaves its container, because `\n\n`
2166    /// ends the block. The alternative is worse: the `\n> ` / next-item
2167    /// continuation [`newline`](Self::newline) writes stays in the same
2168    /// *paragraph*, which is the thing being prevented.
2169    ///
2170    /// A table's trailing stop ([`VisualMap::table_end_stop`]) is the same
2171    /// accident from the other side of a different block: the stop sits at the
2172    /// end of the table's last source line, and a line glued under a table is
2173    /// a row of it — `| 1 | 2 |x` is a three-cell row, not a paragraph. So the
2174    /// break goes in there too, and the text lands under the table.
2175    ///
2176    /// Only in the rendered view. Source view is for typing raw markup, where
2177    /// putting a character against an image is exactly what it looks like.
2178    fn open_paragraph_at_block_edge(&mut self, text: &str) {
2179        if self.view != View::Wysiwyg || text.is_empty() || text == "\n" {
2180            return;
2181        }
2182        if self.selection().is_some() {
2183            return;
2184        }
2185        // The map may be a revision behind (nothing has drawn since the last
2186        // edit), and this asks it about offsets — a stale answer would splice a
2187        // break into the wrong place. Free when it is already current, which it
2188        // is whenever a frontend drew a frame between keystrokes.
2189        self.rebuild_map();
2190        let at = self.caret;
2191        let side = match self.vmap.block_media_stop(at) {
2192            Some((side, _)) => side,
2193            None if self.vmap.table_end_stop(at) => MediaStop::After,
2194            None => return,
2195        };
2196        if !self.splice(at, at, "\n\n", EditKind::Other) {
2197            return;
2198        }
2199        // The break is part of the keystroke, not an edit of its own: leave the
2200        // run marked as typing so the character about to arrive folds into it and
2201        // one undo puts the document back the way it was found. (A paste, or a
2202        // multi-character insert, is `EditKind::Other` and stays its own step —
2203        // as it would have been anywhere else in the document.)
2204        self.last_edit_kind = Some(EditKind::Insert);
2205        if side == MediaStop::Before {
2206            // The break went in above the picture and the caret rode to the end
2207            // of it — which is still hard against the picture. Step back onto the
2208            // blank line it opened, so the text lands above rather than in front.
2209            self.caret = at;
2210        }
2211    }
2212
2213    /// A delete key pressed at one of a block picture's two caret stops, handled
2214    /// as the picture being an *atom* rather than a run of bytes. Returns whether
2215    /// the key was consumed.
2216    ///
2217    /// The caret rests in front of a block image and just past it, never inside
2218    /// its markup — which the rendered view doesn't show. So the byte a delete
2219    /// key nominally takes there is one the writer cannot see, and taking it
2220    /// leaves the picture as broken markup rather than as anything anyone asked
2221    /// for: Backspace at the stop past `![](p.png)` removes the closing paren, and
2222    /// a photo becomes the literal text `![](p.png`. That is how a picture goes
2223    /// missing from a document with nobody having touched it — the same
2224    /// dissolution [`open_paragraph_at_block_edge`](Self::open_paragraph_at_block_edge)
2225    /// prevents from the typing side, and it cost this repository's own test vault
2226    /// a photo before it was found.
2227    ///
2228    /// So the key aimed *at* the picture deletes the picture, whole — Backspace
2229    /// when it is behind the caret, Delete when it is in front — which is what
2230    /// every editor does with an embed, and one undo away. The key aimed *away*
2231    /// from it would otherwise delete the paragraph break and merge a neighbour
2232    /// into the picture's own paragraph, which dissolves it just as surely; it
2233    /// steps the caret over the boundary instead and leaves the
2234    /// next press to delete in the block it has reached — the same "first press
2235    /// steps out of the atom, second press deletes" every delete key here gets,
2236    /// word-deletes included (⌥⌫ in front of a picture is aimed at the prose
2237    /// above, and reaches it on the second press rather than taking the break and
2238    /// the picture with it on the first).
2239    fn delete_around_block_media(&mut self, forward: bool) -> bool {
2240        // The map answers about offsets, so it has to be this revision's — see
2241        // the same call in `open_paragraph_at_block_edge`.
2242        self.rebuild_map();
2243        let Some((side, span)) = self.vmap.block_media_stop(self.caret) else {
2244            return false;
2245        };
2246        let aimed_at_it = side
2247            == if forward {
2248                MediaStop::Before
2249            } else {
2250                MediaStop::After
2251            };
2252        if !aimed_at_it {
2253            let over = if forward {
2254                self.vmap.stop_after(self.caret)
2255            } else {
2256                self.vmap.stop_before(self.caret)
2257            };
2258            if let Some(off) = over.filter(|&o| o >= self.caret_floor()) {
2259                self.caret = off;
2260                self.anchor = None;
2261                self.goal_col = None;
2262            }
2263            return true;
2264        }
2265        // Take the break that held the picture apart from its neighbour with it,
2266        // so the delete doesn't leave a blank paragraph standing where the
2267        // picture was. The last arm is a picture that is the whole document.
2268        let (from, to) = if self.source[..span.start].ends_with("\n\n") {
2269            (span.start - 2, span.end)
2270        } else if self.source[span.end..].starts_with("\n\n") {
2271            (span.start, span.end + 2)
2272        } else {
2273            (span.start, span.end)
2274        };
2275        self.splice(from.max(self.caret_floor()), to, "", EditKind::Other);
2276        true
2277    }
2278
2279    /// The Hidden-mode typing path: replace any selection, then insert `text`
2280    /// escaped so it stays literal. When it replaces a selection the two edits
2281    /// fold into one undo step, so an overwrite undoes atomically (and restores
2282    /// the selection) exactly as a plain one does.
2283    fn insert_literal_typed(&mut self, text: &str) {
2284        let kind = typed_edit_kind(text);
2285        match self.selection() {
2286            Some((s, e)) => {
2287                if !self.splice(s, e, "", EditKind::Other) {
2288                    return;
2289                }
2290                // Typing over a whole marked run takes its delimiters with it
2291                // (the empty content couldn't hold them — see
2292                // `repair_mark_edges`) and leaves its marks armed at the caret.
2293                // The text taking the run's place inherits them, exactly as it
2294                // would have by landing inside a run that survived.
2295                let pending = self.pending_here();
2296                if !pending.is_empty() && !text.trim().is_empty() {
2297                    self.insert_with_marks(self.caret, text, pending);
2298                    return;
2299                }
2300                self.insert_literal_at(self.caret, text, kind, true);
2301            }
2302            None => {
2303                self.insert_literal_at(self.caret, text, kind, false);
2304            }
2305        }
2306    }
2307
2308    /// The sticky-mark delta that is live right now: the marks armed by [`toggle`]
2309    /// at a collapsed caret, but only while the caret still stands where they
2310    /// were armed and nothing is selected. Empty otherwise, so a stale delta
2311    /// never styles text it wasn't meant for.
2312    fn pending_here(&self) -> InlineMarks {
2313        if self.anchor.is_none() && self.pending_at == Some(self.caret) {
2314            self.pending_marks
2315        } else {
2316            InlineMarks::empty()
2317        }
2318    }
2319
2320    /// Drop the armed sticky marks — any caret motion, selection, or edit does
2321    /// this, so "start bold here" only ever applies at the exact spot it was
2322    /// asked for.
2323    fn clear_pending(&mut self) {
2324        self.pending_marks = InlineMarks::empty();
2325        self.pending_at = None;
2326    }
2327
2328    /// Insert `text` at `at` carrying the armed sticky `marks`: a mark not yet in
2329    /// force is wrapped around the freshly typed text; a mark the caret already
2330    /// stands inside is *shed* — the text is inserted past the run's end so it
2331    /// lands unmarked ("type normally again"). The caret comes to rest inside any
2332    /// added runs, so continued typing inherits the marks with no re-wrapping,
2333    /// and the delta is cleared: the marks now live in the document, not here.
2334    fn insert_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
2335        let base = self.mark_spans_at(at);
2336        let base_set: InlineMarks = base.iter().map(|(k, _)| *k).collect();
2337        // Nothing to shed, and a run of exactly these marks standing just behind
2338        // the caret: carry on writing *that* run rather than opening a second
2339        // one beside it.
2340        if base_set.is_empty() && self.rejoin_run(at, text, marks) {
2341            return;
2342        }
2343        // Shed the marks we're turning off: step the insertion point past the
2344        // end of each run the caret sits in, so the new text falls outside it.
2345        let mut ins_at = at;
2346        for (kind, span) in &base {
2347            if marks.contains(*kind) {
2348                ins_at = ins_at.max(span.end);
2349            }
2350        }
2351        if !self.splice_exact(ins_at, ins_at, text, EditKind::Other) {
2352            return;
2353        }
2354        // The plain splice inserted exactly `text` at `ins_at`; that byte range
2355        // is the content every added mark wraps.
2356        let (mut cs, mut ce) = (ins_at, ins_at + text.len());
2357        for kind in marks.iter() {
2358            if !base_set.contains(kind) {
2359                let (ncs, nce) = self.wrap_span(cs, ce, kind);
2360                cs = ncs;
2361                ce = nce;
2362            }
2363        }
2364        self.caret = ce.min(self.source.len());
2365        self.anchor = None;
2366        self.last_edit_kind = None;
2367        // Realised: the marks are in the document now, and the caret sits inside
2368        // them, so there is no delta left to carry. Arm nothing, but remember the
2369        // spot so a *further* toggle before typing starts a clean delta here.
2370        self.pending_marks = InlineMarks::empty();
2371        self.pending_at = Some(self.caret);
2372        self.clamp_caret();
2373        self.record_caret();
2374    }
2375
2376    /// Carry on the marked run just behind `at` — moving its closing delimiters
2377    /// out past the new text — instead of opening a second run of the same marks
2378    /// beside it. Returns whether it did.
2379    ///
2380    /// This is the far half of the mark-edge rule (see [`splice`](Self::splice)).
2381    /// A space typed after a bold word steps the caret out of the run, because
2382    /// `**bold **` is not bold; the next character has to step back *in*, or the
2383    /// writer who typed one bold phrase is left with `**bold** **and**` — two
2384    /// runs that read the same to a reader but spell the file in a way nobody
2385    /// wrote. Only whitespace may stand in the gap (a run doesn't reach across
2386    /// words it isn't marking), and the marks behind it must be exactly the ones
2387    /// armed — a run of *some* other kind is a neighbour, not this phrase.
2388    fn rejoin_run(&mut self, at: usize, text: &str, marks: InlineMarks) -> bool {
2389        if text.is_empty() || text.trim() != text {
2390            return false;
2391        }
2392        let gap_at = self.source[..at].trim_end_matches([' ', '\t']).len();
2393        // Walk in through the delimiters stacked at that point, innermost last:
2394        // `***both*** ` closes two runs with one `***`, and rejoining means
2395        // getting behind all of them.
2396        let (mut cut, mut kinds) = (gap_at, InlineMarks::empty());
2397        while let Some((kind, content_end)) = self
2398            .editor
2399            .ancestors_at(prev_boundary(&self.source, cut))
2400            .unwrap_or_default()
2401            .into_iter()
2402            .filter(|m| m.span.end == cut)
2403            .find_map(|m| Some((inline_kind(&m.kind)?, m.content_span.clone()?.end)))
2404        {
2405            if content_end >= cut {
2406                break; // a mark with no closing delimiter to step behind
2407            }
2408            kinds.insert(kind);
2409            cut = content_end;
2410        }
2411        if cut == gap_at || kinds != marks {
2412            return false;
2413        }
2414        // Re-spell the tail: the gap, then the new text, then the delimiters that
2415        // used to close in front of them — read out of the document rather than
2416        // written from a table, so whatever twig spells them with is what moves.
2417        let tail = format!(
2418            "{}{text}{}",
2419            &self.source[gap_at..at],
2420            &self.source[cut..gap_at]
2421        );
2422        if !self.splice_exact(cut, at, &tail, EditKind::Other) {
2423            return false;
2424        }
2425        self.caret = (cut + (at - gap_at) + text.len()).min(self.source.len());
2426        self.anchor = None;
2427        self.last_edit_kind = None;
2428        self.pending_marks = InlineMarks::empty();
2429        self.pending_at = Some(self.caret);
2430        self.clamp_caret();
2431        self.record_caret();
2432        true
2433    }
2434
2435    /// Insert typed whitespace at a caret with sticky marks armed. Whitespace is
2436    /// never itself wrapped: a mark around a space draws nothing a reader can
2437    /// see, and in Markdown and Djot it draws its own delimiters instead
2438    /// (`** **`). So the space goes in unmarked — outside any run the armed
2439    /// marks are shedding — and the marks stay armed for the character after it,
2440    /// which rejoins the run (see [`rejoin_run`](Self::rejoin_run)).
2441    fn insert_space_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
2442        let base = self.mark_spans_at(at);
2443        // What the *next* character carries: the armed delta resolved against the
2444        // marks in force here, which the space must not quietly drop.
2445        let want = base
2446            .iter()
2447            .map(|(k, _)| *k)
2448            .collect::<InlineMarks>()
2449            .xor(marks);
2450        let mut ins_at = at;
2451        for (kind, span) in &base {
2452            if marks.contains(*kind) {
2453                ins_at = ins_at.max(span.end);
2454            }
2455        }
2456        if !self.splice(ins_at, ins_at, text, typed_edit_kind(text)) {
2457            return;
2458        }
2459        self.rearm(want);
2460        self.record_caret();
2461    }
2462
2463    /// Wrap `[s, e)` in `kind` via twig and return the byte span the *content*
2464    /// (not the delimiters) occupies afterwards. Markdown/Djot inline delimiters
2465    /// are symmetric (`**`…`**`, `_`…`_`, `` ` ``…`` ` ``), so the bytes twig
2466    /// added split evenly around the content — half the growth on each side.
2467    fn wrap_span(&mut self, s: usize, e: usize, kind: InlineKind) -> (usize, usize) {
2468        // The read-only gate — this door reaches twig without the splice.
2469        if self.read_only {
2470            return (s, e);
2471        }
2472        match self.editor.toggle_inline(s, e, kind) {
2473            Ok(change) => {
2474                self.last_edit_kind = None;
2475                self.refresh();
2476                self.dirty = self.source != self.clean_source;
2477                let added = (change.new.end - change.new.start).saturating_sub(e - s);
2478                let half = added / 2;
2479                (change.new.start + half, change.new.end - half)
2480            }
2481            // Unsupported here (e.g. mark on Markdown): leave the text unwrapped
2482            // rather than lose the keystroke.
2483            Err(e2) => {
2484                self.status = Some(format!("{kind:?}: {e2}"));
2485                (s, e)
2486            }
2487        }
2488    }
2489
2490    /// The safe offset to splice a block-level break at, given a caret that may
2491    /// sit exactly between an inline mark's content and its own closing
2492    /// delimiter (`content_span.end == off < span.end` for some enclosing mark
2493    /// — the WYSIWYG caret's natural resting place at the end of `**bold**`
2494    /// with nothing following it on the line: the closing `**` renders no
2495    /// glyph of its own, so the caret's "end of line" offset lands right
2496    /// before it). Splicing a paragraph/list/quote break at `off` itself would
2497    /// sever the delimiter from its content, stranding it alone on the new
2498    /// line. Walks out to the *outermost* such mark's `span.end` instead, so
2499    /// nested marks closing at the same point (`**_x_**`) all clear together.
2500    /// A no-op everywhere else — mid-run, or past real trailing content, no
2501    /// mark's `content_span` ends exactly at `off`.
2502    fn skip_trailing_close_delims(&mut self, off: usize) -> usize {
2503        let off = off.min(self.source.len());
2504        let runs = self.run_span_ids();
2505        self.editor
2506            .ancestors_at(off)
2507            .unwrap_or_default()
2508            .into_iter()
2509            .filter(|m| hides_delims(m, &runs))
2510            .filter(|m| off < m.span.end && m.content_span.as_ref().is_some_and(|c| c.end == off))
2511            .map(|m| m.span.end)
2512            .max()
2513            .unwrap_or(off)
2514    }
2515
2516    /// The offset a *delete* aimed at the character before `off` should stop at,
2517    /// when `off` is the start of a run's text and the bytes behind it are that
2518    /// run's opening delimiter. The rich view draws no glyph for a `**`, so the
2519    /// byte behind the caret at the start of a bold word is not a character the
2520    /// writer can see, let alone one they aimed Backspace at: taking it leaves
2521    /// `a *bold** c` — the styling gone and a literal asterisk in its place. The
2522    /// delete steps over the whole delimiter to the visible character in front of
2523    /// it instead. Walks out to the *outermost* mark opening there, so
2524    /// `**_x_**` clears every delimiter at once, and is a no-op anywhere else.
2525    fn skip_leading_open_delims(&mut self, off: usize) -> usize {
2526        let off = off.min(self.source.len());
2527        let runs = self.run_span_ids();
2528        self.editor
2529            .ancestors_at(off)
2530            .unwrap_or_default()
2531            .into_iter()
2532            .filter(|m| hides_delims(m, &runs))
2533            .filter(|m| {
2534                m.span.start < off && m.content_span.as_ref().is_some_and(|c| c.start == off)
2535            })
2536            .map(|m| m.span.start)
2537            .min()
2538            .unwrap_or(off)
2539    }
2540
2541    /// `off` moved *inside* the run whose closing delimiters end there — the
2542    /// other offset the rich view draws in the same place, since a `**` renders
2543    /// no glyph of its own. `**bold**` has a caret home on each side of its
2544    /// closing delimiter, one column apart on screen and eight bytes and a whole
2545    /// run apart in the file, and a plain ← lands on the outer one whenever a
2546    /// space follows the phrase. The inner one is what the writer is pointing at
2547    /// there: the end of their bold word. Walks in through every mark closing at
2548    /// that point, innermost last, so `***both***` lands inside both. A no-op
2549    /// anywhere else — mid-run, or in prose, no mark's span ends at `off`.
2550    fn step_inside_close_delims(&mut self, off: usize) -> usize {
2551        let mut off = off.min(self.source.len());
2552        let runs = self.run_span_ids();
2553        loop {
2554            let inner = self
2555                .editor
2556                .ancestors_at(prev_boundary(&self.source, off))
2557                .unwrap_or_default()
2558                .into_iter()
2559                .filter(|m| hides_delims(m, &runs) && m.span.end == off)
2560                .filter_map(|m| m.content_span.clone().map(|c| c.end))
2561                .filter(|&end| end < off)
2562                .max();
2563            match inner {
2564                Some(end) => off = end,
2565                None => return off,
2566            }
2567        }
2568    }
2569
2570    /// The mirror at the opening edge: `off` moved inside the run whose
2571    /// delimiters *start* there, onto the first character of its text. See
2572    /// [`step_inside_close_delims`](Self::step_inside_close_delims).
2573    fn step_inside_open_delims(&mut self, off: usize) -> usize {
2574        let mut off = off.min(self.source.len());
2575        let runs = self.run_span_ids();
2576        loop {
2577            let inner = self
2578                .editor
2579                .ancestors_at(off)
2580                .unwrap_or_default()
2581                .into_iter()
2582                .filter(|m| hides_delims(m, &runs) && m.span.start == off)
2583                .filter_map(|m| m.content_span.clone().map(|c| c.start))
2584                .filter(|&start| start > off)
2585                .min();
2586            match inner {
2587                Some(start) => off = start,
2588                None => return off,
2589            }
2590        }
2591    }
2592
2593    /// The ids of the document's attributed run spans — the inline
2594    /// `Container`s [`wysiwyg::is_run_span`] picks out — for [`hides_delims`],
2595    /// which sees an ancestor chain and so only a kind. Read once per gesture,
2596    /// not once per step of a walk.
2597    fn run_span_ids(&mut self) -> Vec<NodeId> {
2598        self.nodes()
2599            .iter()
2600            .filter(|n| wysiwyg::is_run_span(n))
2601            .map(|n| n.id)
2602            .collect()
2603    }
2604
2605    /// The attributed span whose text is exactly `content` — the whole of
2606    /// `<span …>i</span>`'s `i`, or nothing at all when `content` is empty
2607    /// and sits between the tags of `<span …></span>` — as the whole range
2608    /// spelling the span: the node's span, widened to its attribute block
2609    /// where the format writes that outside the node, as djot's
2610    /// `[i]{data-size="large"}` does. `None` for any other range, including
2611    /// part of a span's text.
2612    ///
2613    /// An empty span has an interior of no bytes, or no known interior at
2614    /// all: twig gives Markdown's `<span …></span>` the first and djot's
2615    /// `[]{…}` the second, and the chain already says the offset is inside.
2616    fn run_span_of_content(&mut self, content: Range<usize>) -> Option<Range<usize>> {
2617        let runs = self.run_span_ids();
2618        let m = self
2619            .editor
2620            .ancestors_at(content.start)
2621            .unwrap_or_default()
2622            .into_iter()
2623            .filter(|m| runs.contains(&NodeId(m.node_id)))
2624            .find(|m| match &m.content_span {
2625                Some(c) => *c == content,
2626                None => content.is_empty(),
2627            })?;
2628        let mut range = m.span;
2629        if let Some(attrs) = self
2630            .editor
2631            .document()
2632            .ok()
2633            .and_then(|mut d| d.attrs_span(NodeId(m.node_id)).ok().flatten())
2634        {
2635            range.start = range.start.min(attrs.start);
2636            range.end = range.end.max(attrs.end);
2637        }
2638        Some(range)
2639    }
2640
2641    /// The attributed block whose whole text is exactly `content` — the `T`
2642    /// of Markdown's `<div class="center">\n\nT\n\n</div>` or djot's
2643    /// `{.center}\nT` — as the range a delete that takes that text takes with
2644    /// it: the whole `<div>` when the block is all the div holds, or the
2645    /// `{…}` line down to the end of the text. The block version of
2646    /// [`run_span_of_content`](Self::run_span_of_content), for the same
2647    /// reason: a paragraph with no text is no block, so the div would stand
2648    /// around nothing and the `{…}` line above nothing, and a from-scratch
2649    /// map gives neither a caret home — the `T`'s row is gone with the `T`.
2650    /// `None` for a block with more text, a div holding more, a heading (an
2651    /// empty `# ` is still a heading), and a format whose attributes are the
2652    /// block's own tag (HTML's `<p class="center"></p>` is still a
2653    /// paragraph).
2654    fn attributed_block_of_content(&mut self, content: Range<usize>) -> Option<Range<usize>> {
2655        if content.is_empty() || !matches!(self.format, Format::Markdown | Format::Djot) {
2656            return None;
2657        }
2658        let nodes = self.nodes();
2659        let block = nodes
2660            .iter()
2661            .filter(|n| n.kind == Kind::Para)
2662            .find(|n| n.content_span.as_ref() == Some(&content))?;
2663        match self.format {
2664            Format::Djot => {
2665                let attrs = self
2666                    .editor
2667                    .document()
2668                    .ok()
2669                    .and_then(|mut d| d.attrs_span(block.id).ok().flatten())?;
2670                (attrs.end <= block.span.start).then_some(attrs.start..content.end)
2671            }
2672            _ => {
2673                let div = block
2674                    .parent
2675                    .and_then(|p| nodes.iter().find(|n| n.id == p))
2676                    .filter(|p| wysiwyg::element_tag(p) == Some("div"))?;
2677                let alone = nodes.iter().filter(|n| n.parent == Some(div.id)).count() == 1;
2678                alone.then(|| div.span.clone())
2679            }
2680        }
2681    }
2682
2683    /// The inline mark kinds whose span covers `off`, each with that span — the
2684    /// span-carrying sibling of [`marks_at`](Self::marks_at), which reports node
2685    /// ids instead. Used to shed a mark by stepping past the end of its run.
2686    fn mark_spans_at(&mut self, off: usize) -> Vec<(InlineKind, std::ops::Range<usize>)> {
2687        let off = off.min(self.source.len());
2688        self.editor
2689            .ancestors_at(off)
2690            .unwrap_or_default()
2691            .into_iter()
2692            .filter(|m| off < m.span.end)
2693            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.span.clone())))
2694            .collect()
2695    }
2696
2697    /// Insert clipboard `text` at the caret, replacing the selection if there is
2698    /// one — always its own undo step, whatever its length.
2699    ///
2700    /// Provenance is the whole point, and only the caller has it. `insert` reads
2701    /// a lone character as a keystroke and folds it into the run around it,
2702    /// which is right for typing and wrong for a one-character paste: that paste
2703    /// would vanish mid-run on an undo it was never part of, and the characters
2704    /// the user actually typed would go with it. Length can't tell the two
2705    /// apart — `⌘V` of `x` and typing `x` are the same string — so the door the
2706    /// caller comes through is what says which happened.
2707    pub fn paste(&mut self, text: &str) {
2708        // Pasting against a block picture or a table's end joins the block
2709        // exactly as typing does, and for the same reason — see
2710        // `open_paragraph_at_block_edge`.
2711        self.open_paragraph_at_block_edge(text);
2712        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2713        self.splice(s, e, text, EditKind::Other);
2714    }
2715
2716    /// Replace `[start, end)` with `text` as one step of an IME composition —
2717    /// the same splice as [`edit`](Self::edit), but marked so the run of steps
2718    /// folds into a single undo.
2719    ///
2720    /// A composition is *one* act of writing. Typing `かんじ` and picking 感じ is a
2721    /// dozen calls here, each replacing the last one's provisional bytes, and an
2722    /// undo step per call means undoing a word means pressing ⌘Z until the reading
2723    /// unspools backwards through kana — the intermediate states were never text
2724    /// the user wrote. Only the frontend knows a call is provisional (the bytes
2725    /// look like any other edit), so the door the caller comes through is what
2726    /// says so, exactly as it is for [`paste`](Self::paste) versus
2727    /// [`insert`](Self::insert).
2728    ///
2729    /// Pair with [`end_composition`](Self::end_composition), or the *next*
2730    /// composition folds into this one.
2731    pub fn edit_composing(&mut self, start: usize, end: usize, text: &str) {
2732        self.splice(start, end, text, EditKind::Compose);
2733    }
2734
2735    /// Close the open composition run, so the next one is its own undo step.
2736    /// Call when the IME commits or withdraws a composition.
2737    ///
2738    /// Only clears a *composition* run: a frontend that reports an end it never
2739    /// began (some IMEs unmark unprompted) would otherwise split the run of
2740    /// typing around it into two undo steps for no reason the user can see.
2741    pub fn end_composition(&mut self) {
2742        if self.last_edit_kind == Some(EditKind::Compose) {
2743            self.last_edit_kind = None;
2744        }
2745    }
2746
2747    // ── the clipboard's rich flavor ──────────────────────────────────────────
2748
2749    /// The selection rendered as HTML, for the clipboard's `text/html` flavor —
2750    /// what lets a paste into Docs/Mail/Slack keep its formatting. `None` when
2751    /// nothing is selected, or when the selection doesn't render (the caller
2752    /// still has [`selected_text`](Self::selected_text), which is what to publish
2753    /// as `text/plain` either way).
2754    ///
2755    /// **The fragment is a source substring, and that is the honest limit here.**
2756    /// It's parsed standalone, so a selection whose meaning depends on its
2757    /// surroundings converts as what it literally says rather than what it looks
2758    /// like on screen: half a list item is a paragraph, a row torn out of a table
2759    /// is the text of a row, the `**` of a bold run selected without its closing
2760    /// `**` is two asterisks. Every one of those still *renders* — there's no
2761    /// error to report — it just renders as the fragment and not as the document.
2762    /// Widening the range to whole blocks would publish text the user didn't
2763    /// select, which is a worse lie than a fragment being a fragment; the plain
2764    /// flavor has the same substring, so the two flavors at least agree.
2765    pub fn selection_html(&mut self) -> Option<String> {
2766        let (start, end) = self.selection()?;
2767        let inline = self.selection_is_inline(start, end);
2768        let html = html::render_fragment(&self.source[start..end], self.format)?;
2769        Some(match inline {
2770            true => html::strip_sole_paragraph(html),
2771            false => html,
2772        })
2773    }
2774
2775    /// Paste the clipboard's `text/html` flavor, converting it to this document's
2776    /// format first. Its own undo step, like any [`paste`](Self::paste).
2777    ///
2778    /// Returns whether it landed. `false` means the HTML didn't convert to
2779    /// anything worth pasting — the caller should fall back to the plain flavor
2780    /// rather than treat it as an error. The `html` module has the full list of
2781    /// what that covers: a table twig won't build, markup it doesn't recognise,
2782    /// an empty result.
2783    pub fn paste_html(&mut self, html: &str) -> bool {
2784        match html::parse_fragment(html, self.format) {
2785            Some(source) => {
2786                self.paste(&source);
2787                true
2788            }
2789            None => false,
2790        }
2791    }
2792
2793    /// Does the selection live *inside* a single top-level block?
2794    ///
2795    /// The question [`selection_html`](Self::selection_html) needs and the
2796    /// fragment can't answer: `**bold**` renders as `<p><strong>bold</strong></p>`
2797    /// whether the user selected one word of a sentence or a whole paragraph, and
2798    /// only the document knows which. Selecting a word and pasting into Docs
2799    /// should extend the line you paste into; selecting the paragraph should make
2800    /// a paragraph. So a selection strictly within one block is inline (its `<p>`
2801    /// is an artifact of standalone parsing), and one that covers a whole block —
2802    /// or spans two — keeps its structure.
2803    ///
2804    /// Reads the block from twig rather than guessing from the bytes:
2805    /// `ancestors_at` is `[doc, block, …inline]`, so index 1 is the top-level
2806    /// block containing an offset, and two ends inside the same one cannot have
2807    /// crossed a block boundary.
2808    fn selection_is_inline(&mut self, start: usize, end: usize) -> bool {
2809        // The last *character*, not `end - 1`: the selection's end is exclusive
2810        // and may sit mid-codepoint's-worth of bytes past the last char.
2811        let Some((off, _)) = self.source[start..end].char_indices().next_back() else {
2812            return false;
2813        };
2814        let (Some(head), Some(tail)) =
2815            (self.top_block_span(start), self.top_block_span(start + off))
2816        else {
2817            return false;
2818        };
2819        head == tail && !(start <= head.start && end >= head.end)
2820    }
2821
2822    /// The byte span of the top-level block containing `offset`, or `None` at an
2823    /// offset that belongs to no block (the blank line between two of them).
2824    fn top_block_span(&mut self, offset: usize) -> Option<std::ops::Range<usize>> {
2825        self.editor
2826            .ancestors_at(offset)
2827            .ok()?
2828            .get(1)
2829            .map(|m| m.span.clone())
2830    }
2831
2832    // ── indentation ──────────────────────────────────────────────────────────
2833
2834    /// One indent level.
2835    ///
2836    /// Two spaces, not the four both frontends type for Tab today, because in a
2837    /// markdown document four columns isn't a width — it's a *meaning*. Four
2838    /// spaces at the head of a line is markdown's indented-code-block marker, so
2839    /// one Tab on a paragraph would reparse it into code and style it as such;
2840    /// two cannot, and the line stays the prose it was. Two is also exactly
2841    /// where a `- ` bullet's content starts, so an indented line lands under its
2842    /// parent item's text instead of beside it — the column a list-aware indent
2843    /// has to hit anyway, which keeps this width from being relitigated later.
2844    const INDENT: &'static str = "  ";
2845
2846    /// Indent the selected lines — or the caret's line, with no selection — by
2847    /// one level (Tab).
2848    pub fn indent(&mut self) {
2849        self.reindent(true);
2850        // Nesting changes an ordered list's numbering (the nested item restarts,
2851        // its old siblings resume) — keep the source markers in step.
2852        self.renumber_here();
2853        // Nesting an empty `-` item under a text line reparses that text as a
2854        // setext heading; swap the dash for a `*` before it can (a no-op unless
2855        // the collapse actually happened).
2856        self.avoid_setext_collapse();
2857    }
2858
2859    /// Take one indent level back off the selected lines, or the caret's line
2860    /// (Shift+Tab). A line with no indentation is left exactly as it is.
2861    ///
2862    /// A line with *less* than a full level gives back what it has rather than
2863    /// refusing: outdent's job is to walk a line left, and real documents — hand
2864    /// written, or reflowed by some other editor — are full of indentation that
2865    /// was never a clean multiple of anything. Refusing there would strand the
2866    /// line at a depth Shift+Tab couldn't undo.
2867    pub fn outdent(&mut self) {
2868        self.reindent(false);
2869        self.renumber_here();
2870    }
2871
2872    /// The body of [`indent`](Self::indent) / [`outdent`](Self::outdent).
2873    ///
2874    /// One splice across the whole line range, never one per line: a Tab is one
2875    /// thing the user did, so it has to be one undo step and one reparse. Per
2876    /// line, twig would reparse the document once per line and leave a stack of
2877    /// steps that Shift+⌘Z walks back one line at a time.
2878    fn reindent(&mut self, add: bool) {
2879        let (sel_start, sel_end) = self.selection().unwrap_or((self.caret, self.caret));
2880        let start = source_line_range(&self.source, sel_start).start;
2881        let end = source_line_range(&self.source, sel_end).end;
2882        let region = self.source[start..end].to_string();
2883        let lines: Vec<&str> = region.split('\n').collect();
2884        // A blank line has no text to move, and padding it would leave nothing
2885        // but trailing whitespace — but Tab on a blank line *is* a request for
2886        // indentation to type into, so the skip only applies where the op has
2887        // other lines to do real work on.
2888        let skip_blank = add && lines.len() > 1;
2889
2890        let mut out = String::with_capacity(region.len() + lines.len() * Self::INDENT.len());
2891        let mut deltas: Vec<isize> = Vec::with_capacity(lines.len());
2892        let mut line_off = start;
2893        for (i, full) in lines.iter().enumerate() {
2894            if i > 0 {
2895                out.push('\n');
2896            }
2897            // A list item moves by having its whole leading prefix *replaced*,
2898            // never by having spaces pushed in front of the line. twig spells
2899            // both prefixes, so the quote markers, the parent's indent and an
2900            // ordered marker's extra column all come out right without leaf
2901            // measuring any of them — and a line that only looks like an item
2902            // (a Djot continuation) reports no marker and is left to the plain
2903            // path, where a Tab is just a Tab.
2904            let marker = self.list_marker_on_line(line_off);
2905            let own = marker
2906                .as_ref()
2907                .map(|m| m.marker_start - m.line_start)
2908                .unwrap_or(0);
2909            let delta = if add {
2910                if skip_blank && full.trim().is_empty() {
2911                    out.push_str(full);
2912                    0
2913                } else if marker.is_some() && self.first_item_of_list(line_off) {
2914                    // The first item of a list has no preceding sibling to nest
2915                    // under, so a Tab here can't spell a sub-list — twig would
2916                    // reparse the shoved-over marker as the same list, only
2917                    // indented, which Shift+Tab then can't cleanly undo. Leave the
2918                    // item where it is, the way every list editor refuses to
2919                    // over-indent a list's first line.
2920                    out.push_str(full);
2921                    0
2922                } else if marker.is_some() {
2923                    // Nesting means standing where a *continuation* of this line
2924                    // would stand: past the parent's marker, inside its content
2925                    // column. That is `continuation_prefix`, less a checkbox.
2926                    let new = self.nesting_prefix_at(line_off);
2927                    let delta = new.len() as isize - own as isize;
2928                    out.push_str(&new);
2929                    out.push_str(&full[own..]);
2930                    delta
2931                } else {
2932                    out.push_str(Self::INDENT);
2933                    out.push_str(full);
2934                    Self::INDENT.len() as isize
2935                }
2936            } else if marker.is_some() {
2937                // Unnesting is the mirror: stand where the parent item's own
2938                // line starts, which drops exactly the level it contributed.
2939                let new = self.outdent_prefix_at(line_off);
2940                let delta = new.len() as isize - own as isize;
2941                out.push_str(&new);
2942                out.push_str(&full[own..]);
2943                delta
2944            } else {
2945                // A plain line gives back the ordinary step.
2946                let strip = outdent_width(full, Self::INDENT.len());
2947                out.push_str(&full[strip..]);
2948                -(strip as isize)
2949            };
2950            deltas.push(delta);
2951            line_off += full.len() + 1;
2952        }
2953        // Nothing to give back. Returning before the splice keeps an outdent at
2954        // column zero from spending an undo step on a document it never changed.
2955        if deltas.iter().all(|d| *d == 0) {
2956            return;
2957        }
2958
2959        // Every line's text keeps its offset *within the line*, so the caret is
2960        // remapped by its column, not by its byte offset — which the prefixes on
2961        // the lines above it have already invalidated.
2962        let remap = |off: usize| -> usize {
2963            let (mut old_ls, mut new_ls) = (start, start);
2964            for (line, delta) in lines.iter().zip(&deltas) {
2965                let old_le = old_ls + line.len();
2966                let new_len = (line.len() as isize + delta) as usize;
2967                if off <= old_le {
2968                    let col = (off - old_ls) as isize;
2969                    return new_ls + ((col + delta).max(0) as usize).min(new_len);
2970                }
2971                old_ls = old_le + 1;
2972                new_ls += new_len + 1;
2973            }
2974            start + out.len()
2975        };
2976        let placed = match self.selection() {
2977            // Keep the rewritten region selected, the way a container toggle
2978            // keeps its own: it leaves a second Tab aimed at the same lines
2979            // rather than at whatever the shifted offsets now happen to cover.
2980            Some(_) => (start + out.len(), Some(start)),
2981            None => (remap(self.caret), None),
2982        };
2983
2984        // A rolled-back splice leaves the old source in place, where every offset
2985        // computed above addresses text that was never written.
2986        if !self.splice(start, end, &out, EditKind::Other) {
2987            return;
2988        }
2989        // `splice` re-anchors to the end of the `Change`, which for a whole-region
2990        // rewrite is the last line's end — nowhere the caret was. Place it, then
2991        // re-record the caret so this is the state redo restores, not the one
2992        // `splice` left behind from the `Change`.
2993        self.caret = placed.0.min(self.source.len());
2994        self.anchor = placed.1;
2995        self.clamp_caret();
2996        self.record_caret();
2997    }
2998
2999    /// The Enter key.
3000    ///
3001    /// In source view it's a literal newline. In WYSIWYG it's **AST-aware**: a
3002    /// bare `\n` is only a markdown soft break (same paragraph), so the block the
3003    /// caret is in decides what actually gets written.
3004    ///
3005    ///   - paragraph            → twig's [`Editor::split_block`], which parts the
3006    ///                            block at the caret and reopens its container
3007    ///   - list item            → likewise: the next item, its indent, quote
3008    ///                            prefix and `[ ]` box all reproduced by twig —
3009    ///                            except an *empty* item, which exits the list
3010    ///   - block quote          → likewise: a new paragraph inside the quote
3011    ///   - heading              → a new *paragraph*, not another heading
3012    ///   - code block           → a literal newline (stay in the block)
3013    ///   - thematic break       → the line under the rule, opened if it has
3014    ///                            none ([`stand_under_block`](Self::stand_under_block))
3015    ///   - blank line           → a literal newline (one Backspace undoes it)
3016    ///   - [`LineFlow::Preserve`] → a single soft break, which renders as a
3017    ///                            visible line
3018    ///
3019    /// Where `split_block` is used it replaces markup leaf used to spell by hand,
3020    /// and it is better at it: it drops the whitespace the caret was sitting in
3021    /// front of instead of stranding it at the head of the second half, and it
3022    /// knows continuations leaf's marker scan never covered — a checklist item
3023    /// continues as an *unchecked* checklist item rather than a plain bullet.
3024    ///
3025    /// The exceptions above are exceptions because `split_block` is either wrong
3026    /// there or refuses: parting a fence yields two fences with the code split
3027    /// between them, parting a heading yields a second heading where every editor
3028    /// gives a paragraph, and a blank line, an empty item, a setext heading and a
3029    /// table all report an error rather than a split.
3030    pub fn newline(&mut self) {
3031        if self.view == View::Source {
3032            self.insert_raw("\n");
3033            return;
3034        }
3035        // Enter over a selection replaces it with a paragraph break.
3036        if let Some((s, e)) = self.selection() {
3037            self.splice(s, e, "\n\n", EditKind::Other);
3038            return;
3039        }
3040        // On a blank page there is no block to push down, and a blank line
3041        // with nothing under it is not something Fold flow draws. Enter wrote
3042        // one anyway: an edit, and an undo step, that showed nothing.
3043        if self.line_flow == LineFlow::Fold && self.source[self.caret_floor()..].trim().is_empty() {
3044            return;
3045        }
3046        // A caret resting exactly between an inline mark's content and its own
3047        // closing delimiter (`**bold**` with nothing after it on the line —
3048        // the WYSIWYG caret's natural end-of-line position) must not splice a
3049        // block break there: every path below eventually does via
3050        // `insert_raw`/`self.caret`, and splicing before the hidden closing
3051        // delimiter would strand it alone on the new line.
3052        self.caret = self.skip_trailing_close_delims(self.caret);
3053        // The block the caret is in. `block_offset_for_caret` nudges off a line
3054        // end (where the caret sits at the doc level); on a bare line (e.g. an
3055        // empty list item) fall back to the caret so the enclosing list/quote is
3056        // still visible in the ancestors.
3057        let off = self.block_offset_for_caret().unwrap_or(self.caret);
3058        let kinds: Vec<Kind> = self
3059            .editor
3060            .ancestors_at(off)
3061            .map(|c| c.into_iter().map(|m| m.kind).collect())
3062            .unwrap_or_default();
3063        let has = |k: Kind| kinds.contains(&k);
3064
3065        if has(Kind::CodeBlock) {
3066            self.insert_raw("\n");
3067            return;
3068        }
3069        // An *empty* list item exits the list — the standard double-Enter — which
3070        // `split_block` reports as an error rather than a split (there is no
3071        // content to part), so it stays leaf's. `list_marker_on_line` is itself
3072        // the AST gate — it answers from the tree, so a `- ` that reads as a
3073        // marker byte-for-byte but opens no item (a setext underline, a Djot
3074        // continuation line) never reaches here.
3075        if let Some(marker) = self.list_marker_on_line(self.caret)
3076            && self.item_is_empty(&marker)
3077        {
3078            self.exit_list(&marker);
3079            return;
3080        }
3081        // Beside a rule, at the home past it, the caret's source line is the
3082        // blank one under the rule, which the branch below would take for an
3083        // empty paragraph. Mid-document its lone newline left the caret on the
3084        // next block's first line, and what was typed there joined that block.
3085        if let Some(end) = self.rule_above_caret() {
3086            self.stand_under_block(end);
3087            return;
3088        }
3089        // On an *empty* paragraph line, a lone Enter should add a single blank line,
3090        // not another full paragraph break — so it moves down one line and one
3091        // Backspace undoes it, not two. (`split_block` errors here too.)
3092        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
3093        let line_end = self.source[self.caret..]
3094            .find('\n')
3095            .map_or(self.source.len(), |i| self.caret + i);
3096        if self.source[line_start..line_end].trim().is_empty() {
3097            self.insert_raw("\n");
3098            return;
3099        }
3100        // At the start of a paragraph with a block above it, twig's split
3101        // writes a lone newline ahead of the paragraph, which Fold draws as one
3102        // more gap: the first Enter showed nothing. A heading's branch below
3103        // parted it after its `#`, leaving an empty heading over a paragraph
3104        // that had been the heading's text. Both open an empty paragraph above
3105        // instead, the caret staying with the text. In Preserve flow too: its
3106        // lone newline went inside a div, where nothing drew it, and between
3107        // a mark's delimiters, where it cut the mark.
3108        if let Some((at, text)) = self.paragraph_opening_at_caret() {
3109            let caret = self.caret;
3110            if self.splice(at, at, text, EditKind::Other) {
3111                self.caret = caret + text.len();
3112                self.record_caret();
3113            }
3114            return;
3115        }
3116        // In `Preserve` flow a soft break is a *visible* line the author means to
3117        // make, so Enter writes a single `\n` and typing continues the same
3118        // paragraph on the next line — the behaviour of an ordinary text editor.
3119        // A second Enter then lands on the blank line above and takes the
3120        // empty-line branch, so double-Enter still promotes to a full paragraph
3121        // break; and Backspace, which deletes a lone `\n` over a soft break,
3122        // undoes a single Enter symmetrically. In `Fold` flow a lone `\n` would
3123        // render as an invisible space, so Enter keeps making the paragraph break
3124        // that actually shows.
3125        //
3126        // Only in running prose. A list or a quote has a continuation of its own
3127        // to write, and a `\n` there is not a soft line but a lost container.
3128        // Nor in a heading, which a newline ends in Markdown and runs on
3129        // unseen in djot: it takes the heading's own branch below.
3130        let in_container = has(Kind::ListItem) || has(Kind::TaskListItem) || has(Kind::BlockQuote);
3131        if self.line_flow == LineFlow::Preserve && !in_container && !has(Kind::Heading) {
3132            self.insert_raw("\n");
3133            return;
3134        }
3135        // A heading gets a *paragraph*, never a second heading: Enter at the end
3136        // of a title is how every editor is asked for the body under it, and
3137        // `split_block` would repeat the `#` instead. Whitespace at the split
3138        // point goes with the break rather than opening the new paragraph, which
3139        // is what `split_block` does everywhere else.
3140        if has(Kind::Heading) {
3141            let mut end = self.caret;
3142            while self.source.as_bytes().get(end) == Some(&b' ') {
3143                end += 1;
3144            }
3145            self.splice(self.caret, end, "\n\n", EditKind::Other);
3146            return;
3147        }
3148        self.split_block_here();
3149    }
3150
3151    /// Where Enter writes to open an empty paragraph above the paragraph or
3152    /// heading the caret starts, and what — `None` when the caret does not
3153    /// start one.
3154    ///
3155    /// The caret starts a paragraph that is in no list item, quote, fence or
3156    /// table when no text of the paragraph stands before it: at its first
3157    /// byte, or past only the opening delimiters of marks that begin with it
3158    /// (`**`, a colour's `<span …>`), which is where a tap before the first
3159    /// letter lands. A heading's `#` marker is such a delimiter. Parted there, twig's split cut the mark in two. The break
3160    /// goes in front of those delimiters, and in front of any `<div>` or
3161    /// fenced div the paragraph opens — the view draws no row for a blank line
3162    /// above a container's first block, so a centred paragraph's empty line
3163    /// has to open outside its div.
3164    ///
3165    /// Inside a list twig's split already writes a marked line, which draws,
3166    /// and so it does in a quote, except above the quote's first line.
3167    ///
3168    /// What is written is what it takes to draw one more empty row. Between
3169    /// two blocks the first and last blank lines are the gap, so a paragraph
3170    /// break goes where there are fewer than two and a newline where the gap
3171    /// is already there. Above the first block only the last blank line is
3172    /// the gap, so a newline goes where there is one already. Preserve flow
3173    /// draws every blank line, so a newline is always enough there, but under
3174    /// frontmatter, whose own blank line draws nothing.
3175    fn paragraph_opening_at_caret(&mut self) -> Option<(usize, &'static str)> {
3176        let caret = self.caret.min(self.source.len());
3177        let chain = self.editor.ancestors_at(caret).ok()?;
3178        if chain.iter().any(|m| {
3179            matches!(
3180                m.kind,
3181                Kind::ListItem | Kind::TaskListItem | Kind::CodeBlock | Kind::Table
3182            )
3183        }) {
3184            return None;
3185        }
3186        let para = chain
3187            .iter()
3188            .find(|m| matches!(m.kind, Kind::Para | Kind::Heading))?;
3189        // An empty heading has nothing to push down: Enter there is still
3190        // the body under it.
3191        let end = para.span.end.min(self.source.len());
3192        if self.source[caret.min(end)..end].trim().is_empty() {
3193            return None;
3194        }
3195        let mut at = para.span.start;
3196        if at != caret {
3197            let text_before = self
3198                .editor
3199                .subtree(twig::NodeId(para.node_id))
3200                .ok()?
3201                .iter()
3202                .any(|n| {
3203                    n.span.start < caret
3204                        && (n.kind == Kind::Image
3205                            || n.text.as_deref().is_some_and(|t| !t.trim().is_empty()))
3206                });
3207            if text_before {
3208                return None;
3209            }
3210        }
3211        // Out past each container this paragraph opens, innermost first: one
3212        // whose source before it is its opening line and blank lines. A quote
3213        // opens on its first paragraph's own line, and draws no line above
3214        // that paragraph: the break goes above the quote. Further down a
3215        // quote twig's split writes a quoted line, which draws.
3216        let mut outer: Vec<_> = chain
3217            .iter()
3218            .filter(|m| matches!(m.kind, Kind::Container | Kind::BlockQuote) && m.span.start < at)
3219            .collect();
3220        outer.sort_by_key(|m| std::cmp::Reverse(m.span.start));
3221        for c in outer {
3222            let before = &self.source[c.span.start..at];
3223            let opens = match c.kind {
3224                Kind::BlockQuote => !before.contains('\n'),
3225                _ => before.lines().skip(1).all(|l| l.trim().is_empty()),
3226            };
3227            if !opens {
3228                break;
3229            }
3230            at = c.span.start;
3231        }
3232        if chain
3233            .iter()
3234            .any(|m| m.kind == Kind::BlockQuote && m.span.start < at)
3235        {
3236            return None;
3237        }
3238        let content = self.source[..at].trim_end().len();
3239        let newlines = self.source[content..at].matches('\n').count();
3240        // Every newline starts a blank line but one that ends the line of
3241        // what stands above, a block or hidden frontmatter.
3242        let blank = if content == 0 {
3243            newlines
3244        } else {
3245            newlines.saturating_sub(1)
3246        };
3247        let first = self
3248            .top_blocks()
3249            .iter()
3250            .all(|m| m.kind == Kind::Metadata || m.span.start >= at);
3251        // Preserve flow draws every blank line, but the one under frontmatter.
3252        let gap = match (self.line_flow, first) {
3253            (LineFlow::Preserve, true) => usize::from(content > 0),
3254            (LineFlow::Preserve, false) => 0,
3255            (LineFlow::Fold, true) => 1,
3256            (LineFlow::Fold, false) => 2,
3257        };
3258        Some((at, if blank >= gap { "\n" } else { "\n\n" }))
3259    }
3260
3261    /// Part the block at the caret with twig's [`Editor::split_block`], leaving
3262    /// the caret in the second half.
3263    ///
3264    /// twig reopens whatever the first half was inside of — the bullet with its
3265    /// indent, the quote's `>`, a checklist item's `[ ]` — which is the whole
3266    /// reason this replaced the markup leaf used to spell from the line's bytes.
3267    /// It renumbers nothing, though: a new item mid-list is written with its
3268    /// neighbour's number, so [`renumber_here`](Self::renumber_here) still runs
3269    /// behind it, folded into the same undo step.
3270    ///
3271    /// Falls back to a plain paragraph break if twig declines, so an unhandled
3272    /// shape still moves the caret down rather than swallowing the keystroke.
3273    fn split_block_here(&mut self) {
3274        // The read-only gate — this door reaches twig without the splice.
3275        if self.read_only {
3276            return;
3277        }
3278        match self.editor.split_block(self.caret) {
3279            Ok(change) => {
3280                self.last_edit_kind = None;
3281                self.refresh();
3282                self.anchor = None;
3283                self.caret = change.new.end;
3284                self.dirty = self.source != self.clean_source;
3285                self.status = None;
3286                self.clamp_caret();
3287                self.record_caret();
3288                // Aimed at the new block's *start*: the caret twig leaves is one
3289                // past the marker it wrote, where there is no list in reach.
3290                self.renumber_at(change.new.start);
3291            }
3292            Err(_) => self.insert_raw("\n\n"),
3293        }
3294    }
3295
3296    /// Whether the item on the marker's line carries no content — the shape
3297    /// double-Enter reads as "I'm done with this list."
3298    fn item_is_empty(&self, line: &ListMarker) -> bool {
3299        let content_start = line.content_start().min(self.source.len());
3300        let line_end = self.source[self.caret..]
3301            .find('\n')
3302            .map(|i| self.caret + i)
3303            .unwrap_or(self.source.len());
3304        self.source[content_start..line_end.max(content_start)]
3305            .trim()
3306            .is_empty()
3307    }
3308
3309    /// Leave the list: replace the empty item's marker with a blank line, so the
3310    /// caret lands in a fresh paragraph below it.
3311    ///
3312    /// Inside a quote the blank line has to stay quoted (a bare one would end the
3313    /// quote), and the caret's new line keeps the `> ` it was already behind —
3314    /// leaving the list without also leaving the quote.
3315    fn exit_list(&mut self, line: &ListMarker) {
3316        let prefix = self.quote_prefix_at(line.marker_start);
3317        let blank = prefix.trim_end();
3318        self.splice(
3319            line.line_start,
3320            self.caret,
3321            &format!("{blank}\n{prefix}"),
3322            EditKind::Other,
3323        );
3324    }
3325
3326    /// What a line continuing the containers at `off` has to open with — the
3327    /// quote markers reproduced, each enclosing item's marker as its width in
3328    /// spaces. Also the column a nested item's marker stands in, which is what
3329    /// makes it Tab's answer.
3330    fn continuation_prefix_at(&mut self, off: usize) -> String {
3331        self.editor
3332            .document()
3333            .and_then(|mut d| d.continuation_prefix(off))
3334            .map(|p| p.text)
3335            .unwrap_or_default()
3336    }
3337
3338    /// The column a *nested list* may open at inside the item at `off` — which
3339    /// is not always where the item's own text continues.
3340    ///
3341    /// twig counts a task item's `[ ] ` box as part of its marker, correctly:
3342    /// it is markup a rich view hides, and the item's own wrapped text does
3343    /// stand past it. But a nested list may only open at the *list* marker's
3344    /// column, and four columns further in is an indented continuation of the
3345    /// paragraph instead — `- [ ] a` + `      - [ ] b` is one item, not two.
3346    /// So the box's own width goes back.
3347    ///
3348    /// The one place leaf still reads a checkbox's spelling. It goes when twig
3349    /// reports the list marker's column apart from the box; `checked` is what
3350    /// says a box is there at all, so only its width is being measured here.
3351    fn nesting_prefix_at(&mut self, off: usize) -> String {
3352        let cont = self.continuation_prefix_at(off);
3353        let Some(item) = self.innermost_list_item(off) else {
3354            return cont;
3355        };
3356        if item.checked.is_none() {
3357            return cont;
3358        }
3359        let box_width = item
3360            .marker_span
3361            .and_then(|m| self.source.get(m))
3362            .and_then(|marker| marker.rfind('[').map(|i| marker.len() - i))
3363            .unwrap_or(0);
3364        // The trailing columns are the ones the item's own marker contributed,
3365        // so trimming from the end leaves any quote prefix standing.
3366        cont[..cont.len().saturating_sub(box_width)].to_string()
3367    }
3368
3369    /// Where the line of the item *containing* the item at `off` begins — the
3370    /// prefix Shift+Tab moves back to, which gives up exactly the level the
3371    /// parent contributed. The quote prefix alone for a top-level item, which
3372    /// has no level left to give.
3373    fn outdent_prefix_at(&mut self, off: usize) -> String {
3374        let items: Vec<usize> = self
3375            .editor
3376            .document()
3377            .and_then(|mut d| d.ancestors_at_caret(off))
3378            .map(|c| {
3379                c.into_iter()
3380                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
3381                    .map(|m| m.span.start)
3382                    .collect()
3383            })
3384            .unwrap_or_default();
3385        // The second-innermost item is the parent; its own line's indent is the
3386        // target. `list_marker_on_line` gives that line's prefix directly.
3387        let parent = items.len().checked_sub(2).map(|i| items[i]);
3388        match parent.and_then(|p| self.list_marker_on_line(p)) {
3389            Some(m) => self.source[m.line_start..m.marker_start].to_string(),
3390            None => self.quote_prefix_at(off),
3391        }
3392    }
3393
3394    /// The block-quote prefix in force at `off` — `""` outside a quote, `"> "`
3395    /// inside one, `"> > "` inside two.
3396    ///
3397    /// Assembled from each enclosing quote's own [`FlatNode::marker_span`], so
3398    /// the `>` and the space after it are twig's spelling rather than leaf's.
3399    /// The whole line prefix can't answer this: it also carries the indent of
3400    /// whatever the quote holds, which a blank separator line must *not* repeat.
3401    fn quote_prefix_at(&mut self, off: usize) -> String {
3402        let Ok(chain) = self
3403            .editor
3404            .document()
3405            .and_then(|mut d| d.ancestors_at_caret(off))
3406        else {
3407            return String::new();
3408        };
3409        let quotes: Vec<usize> = chain
3410            .iter()
3411            .filter(|m| m.kind == Kind::BlockQuote)
3412            .map(|m| m.node_id as usize)
3413            .collect();
3414        let Ok(nodes) = self.editor.nodes() else {
3415            return String::new();
3416        };
3417        quotes
3418            .iter()
3419            .filter_map(|id| nodes.get(*id)?.marker_span.clone())
3420            .filter_map(|s| self.source.get(s))
3421            .collect()
3422    }
3423
3424    /// Whether the item at `off` sits inside another one — the test Backspace
3425    /// uses to choose between outdenting and dropping the marker.
3426    ///
3427    /// Counted from the AST rather than from the line's leading whitespace,
3428    /// which is indentation in Markdown and, in Djot, may be nothing at all.
3429    fn item_is_nested(&mut self, off: usize) -> bool {
3430        self.editor
3431            .document()
3432            .and_then(|mut d| d.ancestors_at_caret(off))
3433            .map(|c| {
3434                c.into_iter()
3435                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
3436                    .count()
3437                    > 1
3438            })
3439            .unwrap_or(false)
3440    }
3441
3442    /// The innermost list item containing `probe`, under twig's **caret**
3443    /// containment rule — a block's end is inside it.
3444    ///
3445    /// Half-open containment can't answer this. An empty item's span is exactly
3446    /// its marker, so the caret sitting after `- ` is one past the end and the
3447    /// item it is plainly in tests as out of reach; that is the shape
3448    /// double-Enter has to recognise to leave the list.
3449    fn innermost_list_item(&mut self, probe: usize) -> Option<FlatNode> {
3450        let chain = self
3451            .editor
3452            .document()
3453            .and_then(|mut d| d.ancestors_at_caret(probe))
3454            .ok()?;
3455        let id = chain
3456            .iter()
3457            .rev()
3458            .find(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)?
3459            .node_id as usize;
3460        self.editor.nodes().ok()?.get(id).cloned()
3461    }
3462
3463    /// The list marker opening `off`'s line, per twig — `None` when that line
3464    /// opens no list item.
3465    ///
3466    /// [`Document::line_prefix`] is the whole hidden run from the line start:
3467    /// `>   1. ` is a quote's marker, an indent, and an item's marker together,
3468    /// and it is `None` on a *continuation* line, which opens nothing. That last
3469    /// case is the one leaf could never get right by reading bytes. `- a\n  - b`
3470    /// is two items in Markdown and one in Djot, where a marker cannot interrupt
3471    /// a paragraph and `  - b` is literal text — identical bytes, and only the
3472    /// parser knows which document it is looking at.
3473    ///
3474    /// The item's own marker is separated out via its
3475    /// [`FlatNode::marker_span`], so `marker_start` splits the prefix into what
3476    /// the containers around it contribute and what the item does.
3477    fn list_marker_on_line(&mut self, off: usize) -> Option<ListMarker> {
3478        let off = off.min(self.source.len());
3479        let prefix = self.editor.document().ok()?.line_prefix(off).ok()??;
3480        // The prefix belongs to a list only when an item's marker closes it —
3481        // a heading's `# ` or a bare quote's `> ` is a prefix too.
3482        let item = self.innermost_list_item(prefix.end.min(self.source.len()))?;
3483        let marker = item.marker_span.clone()?;
3484        if marker.end != prefix.end {
3485            return None;
3486        }
3487        Some(ListMarker {
3488            line_start: prefix.start,
3489            marker_start: marker.start,
3490            text: self.source.get(prefix)?.to_string(),
3491        })
3492    }
3493
3494    /// Whether the list item on `line_start`'s line is the **first item** of its
3495    /// list — the one Tab must not nest, because nesting needs a preceding
3496    /// sibling to become the new parent and a first item has none. `false` for a
3497    /// line that isn't a list item, and for an item with a sibling above it (the
3498    /// one Tab *can* nest). Gated on the AST, not the marker bytes: `- ` reads
3499    /// the same in a setext underline that opens no list at all.
3500    fn first_item_of_list(&mut self, line_start: usize) -> bool {
3501        let Some(marker) = self.list_marker_on_line(line_start) else {
3502            return false;
3503        };
3504        // Probe just inside the marker, where the item's own node is in reach —
3505        // the marker offset itself can resolve to the enclosing list, not the
3506        // `list_item`, whose span starts at the marker.
3507        let probe = marker.content_start().min(self.source.len());
3508        let Some(item) = self.innermost_list_item(probe) else {
3509            return false;
3510        };
3511        let Ok(nodes) = self.editor.nodes() else {
3512            return false;
3513        };
3514        match item.parent {
3515            // First when the parent list opens with this very item.
3516            Some(pid) => nodes
3517                .get(pid.0 as usize)
3518                .is_some_and(|p| p.first_child == Some(item.id)),
3519            // A parentless item is trivially the first (and only) one.
3520            None => true,
3521        }
3522    }
3523
3524    pub fn backspace(&mut self) {
3525        if let Some((s, e)) = self.selection() {
3526            self.splice(s, e, "", EditKind::Other);
3527            return;
3528        }
3529        // WYSIWYG: Backspace at the very start of a list item's content is a
3530        // structural key, not a character delete — it walks the "un-indent, then
3531        // un-list" ladder every list editor gives that keystroke (outdent a
3532        // nested item, strip a top-level one's marker to a paragraph). In source
3533        // view the `- ` is visible text the user is deleting a byte of, so it
3534        // keeps its literal meaning there, like Enter does.
3535        if self.view != View::Source && self.backspace_list_start() {
3536            return;
3537        }
3538        // WYSIWYG: and the same at the start of a heading's content — the `# `
3539        // there is markup the rich view hides, not text the user typed.
3540        if self.view != View::Source && self.backspace_heading_start() {
3541            return;
3542        }
3543        // WYSIWYG: and at the start of a block whose presentation is spelled
3544        // as hidden markup before it — djot's `{.center}` line, Markdown's
3545        // `<div class="center">` — Backspace takes that markup, the way it
3546        // takes a heading's `#`, rather than a byte out of it.
3547        if self.view != View::Source && self.backspace_attributed_block_start() {
3548            return;
3549        }
3550        // WYSIWYG: at a block picture's stops, a byte-at-a-time delete would take
3551        // the markup apart under a caret that cannot see it — see
3552        // `delete_around_block_media`.
3553        if self.view != View::Source && self.delete_around_block_media(false) {
3554            return;
3555        }
3556        // WYSIWYG: Backspace at a table's trailing stop steps back into its last
3557        // cell rather than taking the byte behind the caret — the row's closing
3558        // `|`, which the rich view never drew, so the key would have looked like
3559        // it did nothing. The stop before is the last cell's end.
3560        if self.view != View::Source && self.backspace_at_table_end() {
3561            return;
3562        }
3563        // WYSIWYG: a table cell's start is a wall. The bytes behind it are the
3564        // padding and the `|` that make the grid, and taking them merges two
3565        // cells — a structural edit nobody asked for, and one no table editor
3566        // gives the key. Tab and Shift+Tab are how the caret leaves a cell.
3567        if self.view != View::Source && self.at_cell_wall(BreakEdge::Backward) {
3568            return;
3569        }
3570        // WYSIWYG: at the start of a block's content, the byte behind the caret
3571        // is a block boundary, and Backspace over one is a join — twig's, so
3572        // that what a join is in each format is not this file's to know. After
3573        // the picture and table cases, which are block starts with their own
3574        // answers.
3575        if self.view != View::Source && self.backspace_joins_block() {
3576            return;
3577        }
3578        // WYSIWYG: Backspace on a *blank line* deletes back to the previous caret
3579        // stop, not a single newline. On a line with no text of its own, the byte
3580        // before the caret is a `\n` that spells part of a block boundary — the gap
3581        // between two blocks, drawn but never a caret home. Removing just it strands
3582        // the caret in that gap and leaves an odd blank line the eye reads as one
3583        // separator but the caret can't land on: the "extra newline" left behind
3584        // after leaving a list (Enter, Enter) or a paragraph and pressing Backspace.
3585        // Deleting to the previous stop instead collapses the whole break at once,
3586        // landing the caret at the end of the block above. Two blank lines in a row
3587        // are one stop apart, so this still removes exactly one — the lone-Enter /
3588        // lone-Backspace symmetry the empty-line case is built on is untouched.
3589        if self.view != View::Source
3590            && self.caret > self.caret_floor()
3591            && self.caret_on_blank_line()
3592            && let Some(stop) = self.vmap.stop_before(self.caret)
3593        {
3594            let stop = stop.max(self.caret_floor());
3595            if stop < self.caret {
3596                if self.source[stop..self.caret].trim().is_empty() {
3597                    self.splice(stop, self.caret, "", EditKind::Delete);
3598                } else {
3599                    // Hidden markup stands between the stop and the caret — a
3600                    // `</div>`, a comment, a link reference definition — and
3601                    // collapsing to the stop would delete it. Take the blank
3602                    // line alone, with the newline that opened it, and land
3603                    // the caret where the collapse would have.
3604                    self.delete_blank_line_to(stop);
3605                }
3606                return;
3607            }
3608        }
3609        if self.caret > self.caret_floor() {
3610            // An in-cell `<br>` draws as one newline glyph, so Backspace over it
3611            // takes the whole tag — a single-byte step would leave a broken `<br`
3612            // showing in the cell. Rich view only (source view edits the literal).
3613            if self.view != View::Source
3614                && let Some((start, end)) = self.cell_break_at(BreakEdge::Backward)
3615            {
3616                let start = start.max(self.caret_floor());
3617                if start < end {
3618                    self.splice(start, end, "", EditKind::Delete);
3619                    return;
3620                }
3621            }
3622            // Aim the delete at the character the writer can *see* behind the
3623            // caret, never at a delimiter the rich view drew nothing for. Two
3624            // steps, and either can apply: from the far side of a run's closing
3625            // `**` step back into the run (the caret is drawn at the end of its
3626            // word), and at the start of a run's text step out past its opening
3627            // `**` to the character in front of it, leaving the run standing.
3628            // Without them a plain Backspace unspells the phrase it is editing
3629            // and leaves a literal asterisk on screen.
3630            let end = if self.view == View::Source {
3631                self.caret
3632            } else {
3633                let inside = self.step_inside_close_delims(self.caret);
3634                // An attributed span with no text — `<span …></span>` as the
3635                // file was written — is hidden markup around nothing, and a
3636                // byte-step here would take its `>`. Backspace takes the span
3637                // whole, with the character before it: the character the key
3638                // looks aimed at, since the span draws nothing.
3639                if let Some(span) = self.run_span_of_content(inside..inside) {
3640                    let from = if self.source[..span.start].ends_with('\n') {
3641                        span.start
3642                    } else {
3643                        prev_boundary(&self.source, span.start)
3644                    };
3645                    let from = from.max(self.caret_floor());
3646                    self.splice(from, span.end, "", EditKind::Delete);
3647                    return;
3648                }
3649                self.skip_leading_open_delims(inside)
3650                    .max(self.caret_floor())
3651            };
3652            // Never delete back across the floor — that would eat hidden
3653            // frontmatter the WYSIWYG caret can't even see.
3654            let mut prev = prev_boundary(&self.source, end).max(self.caret_floor());
3655            // Take a hidden escape backslash with the char it escapes: the rich
3656            // view draws `\*` as a single `*`, so Backspace over it must delete
3657            // both bytes, never strand the `\` as a lone visible backslash (the
3658            // mirror of the Hidden-mode typing that wrote the escape). Source view
3659            // shows the `\`, so there it is an ordinary character.
3660            if self.view != View::Source
3661                && prev > self.caret_floor()
3662                && self.is_hidden_escape(prev - 1)
3663            {
3664                prev -= 1;
3665            }
3666            // The delete that takes the last of a span's text takes the span
3667            // with it, in the same edit: `<span …>i</span>` losing its `i`
3668            // would leave an empty span the map has no stop inside, so the
3669            // caret would draw at the next stop — a line away — until a
3670            // further key removed the span. Landing on the span's start is
3671            // where the letter was.
3672            if self.view != View::Source
3673                && let Some(span) = self.run_span_of_content(prev..end)
3674            {
3675                self.splice(span.start, span.end, "", EditKind::Delete);
3676                return;
3677            }
3678            // And the same for a block: the letter that was all of a centred
3679            // paragraph's text goes with the `<div>` around it, or the `{…}`
3680            // line above it, leaving a plain blank line where the letter was.
3681            // A paragraph with no text is no block, so the markup would stand
3682            // around nothing, the map would give it no caret home, and the
3683            // next key would take the tag apart.
3684            if self.view != View::Source
3685                && let Some(block) = self.attributed_block_of_content(prev..end)
3686            {
3687                self.splice(block.start, block.end, "", EditKind::Delete);
3688                return;
3689            }
3690            if prev < end {
3691                self.splice(prev, end, "", EditKind::Delete);
3692            }
3693        }
3694    }
3695
3696    /// Remove the blank line the caret is on — its own newline and the one
3697    /// that ended the line before it — and put the caret on `stop`, the caret
3698    /// stop before it. The [`backspace`](Self::backspace) blank-line rule for a
3699    /// blank line that hidden markup separates from the block above: the
3700    /// navigable blank row after a `</div>` is always one of at least three
3701    /// newlines under the tag (the drawn separators either side of it), so
3702    /// taking two leaves the blank line the tag needs under it.
3703    fn delete_blank_line_to(&mut self, stop: usize) {
3704        let caret = self.caret;
3705        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
3706        let line_end = self.source[caret..]
3707            .find('\n')
3708            .map_or(self.source.len(), |i| caret + i);
3709        let from = line_start.saturating_sub(1).max(stop);
3710        let to = (line_end + 1).min(self.source.len());
3711        self.splice(from, to, "", EditKind::Delete);
3712        self.caret = stop;
3713        self.anchor = None;
3714        self.goal_col = None;
3715        self.record_caret();
3716    }
3717
3718    /// Move the caret to the stop before it and consume the key — what
3719    /// Backspace does where the byte behind the caret is hidden markup it
3720    /// has no structural answer for, rather than take that markup apart.
3721    fn step_back_to_stop(&mut self) {
3722        // The map answers about offsets, so it has to be this revision's — see
3723        // `open_paragraph_at_block_edge`.
3724        self.rebuild_map();
3725        if let Some(off) = self
3726            .vmap
3727            .stop_before(self.caret)
3728            .filter(|&o| o >= self.caret_floor())
3729        {
3730            self.caret = off;
3731            self.anchor = None;
3732            self.goal_col = None;
3733        }
3734    }
3735
3736    /// Backspace's presentation behaviour: with the caret exactly at the start
3737    /// of a block's content, and that block's attributes spelled as hidden
3738    /// markup before it, strip the attributes. The peer of
3739    /// [`backspace_heading_start`](Self::backspace_heading_start), and the same
3740    /// reasoning: the `{.center}` line above a djot block and the
3741    /// `<div class="center">` around a Markdown one are what the byte behind
3742    /// the caret belongs to, and the rich view draws neither. The ordinary
3743    /// delete took the newline out of `{.center}\nhello` and left
3744    /// `{.center}hello` — the attribute line fused onto the text as prose —
3745    /// and out of `<div …>\n\nhello` it took the blank line the div needs.
3746    ///
3747    /// The whole attribute set goes, the way the whole `#` marker does — the
3748    /// press is over the line that spells it, not over one key of it — and
3749    /// twig's `set_block_attrs` with an empty list is the edit: it removes the
3750    /// djot line and unwraps the Markdown div. Where the block is the first of
3751    /// several in a div, twig has no sole child to unwrap and answers with a
3752    /// no-op, so the caret steps back to the stop before instead, as it does
3753    /// at a table's end. A later child of the div has an ordinary paragraph
3754    /// above it and is not this rule's.
3755    ///
3756    /// Returns whether it acted; `false` leaves Backspace its character delete.
3757    fn backspace_attributed_block_start(&mut self) -> bool {
3758        if !matches!(self.format, Format::Markdown | Format::Djot) {
3759            return false;
3760        }
3761        let caret = self.caret;
3762        let nodes = self.nodes();
3763        let Some(block) = nodes
3764            .iter()
3765            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3766            .find(|n| n.content_span.as_ref().map_or(n.span.start, |c| c.start) == caret)
3767        else {
3768            return false;
3769        };
3770        match self.format {
3771            Format::Djot => {
3772                // twig records where the `{…}` block was written, so this is
3773                // the parser's own answer and not a scan for a `{` above the
3774                // block; `None` (a synthesized or merged set) is not a line
3775                // the caret is standing after.
3776                let spelled = self
3777                    .editor
3778                    .document()
3779                    .ok()
3780                    .and_then(|mut d| d.attrs_span(block.id).ok().flatten())
3781                    .is_some_and(|s| s.end <= caret);
3782                if !spelled {
3783                    return false;
3784                }
3785            }
3786            _ => {
3787                let Some(div) = block
3788                    .parent
3789                    .and_then(|p| nodes.iter().find(|n| n.id == p))
3790                    .filter(|p| wysiwyg::element_tag(p) == Some("div"))
3791                else {
3792                    return false;
3793                };
3794                let mut kids = nodes.iter().filter(|n| n.parent == Some(div.id));
3795                if kids.clone().any(|k| k.span.start < block.span.start) {
3796                    return false;
3797                }
3798                if kids.nth(1).is_some() {
3799                    self.step_back_to_stop();
3800                    return true;
3801                }
3802            }
3803        }
3804        self.write_block_attrs("block attributes", Vec::new());
3805        true
3806    }
3807
3808    /// Backspace at the start of a block's content: join the block into the
3809    /// block before it, as one gesture — twig's `join_blocks`, the inverse of
3810    /// the split Enter makes, spelled the format's way. Two paragraphs join
3811    /// on a soft break; a paragraph under a marker heading joins onto the
3812    /// heading's line; a paragraph after a Markdown `<div>` moves inside it,
3813    /// the hidden `</div>` carried past the joined text; HTML's `</p><p>` is
3814    /// taken as one; a quote's or an item's continuation prefix is written.
3815    /// The joined text takes the block above's presentation and containers,
3816    /// which is the rule every editor with a centred paragraph follows.
3817    ///
3818    /// Leaf used to join by deleting the one newline behind the caret, which
3819    /// is the right bytes for two Markdown paragraphs and nothing else: under
3820    /// a heading it left two blocks, in HTML it took the `>` off a tag, and
3821    /// after a div it took the newline under the hidden `</div>`, which drew
3822    /// nothing different and took the tag apart on the next press. What a
3823    /// join is in each format is twig's to know, and now it does.
3824    ///
3825    /// Where twig refuses — the block above is a code block, a table or a
3826    /// rule with no text to join into, or the caret's block would have to
3827    /// leave a div that holds more after it — the caret steps back to the
3828    /// stop before instead, as it does at a table's end: the key moves the
3829    /// caret and takes no markup apart. Where nothing precedes the block, or
3830    /// the format cannot join at all, Backspace keeps its character delete.
3831    ///
3832    /// Returns whether it acted.
3833    fn backspace_joins_block(&mut self) -> bool {
3834        let caret = self.caret;
3835        if caret <= self.caret_floor() {
3836            return false;
3837        }
3838        let Some(text) = self.text_block_opening_at(caret) else {
3839            return false;
3840        };
3841        match self.join_blocks(caret) {
3842            Ok(change) => {
3843                // The caret keeps its place at the start of the text it stood
3844                // on, wherever the join put that text — after a soft break,
3845                // a space, or a quote's prefix. Found by the bytes, as
3846                // `block_content_in` finds a re-spelled block.
3847                let region = &self.source[change.new.clone()];
3848                let at = region
3849                    .find(&text)
3850                    .map_or(change.new.start, |i| change.new.start + i);
3851                self.land_after_join(at);
3852                true
3853            }
3854            Err(twig::Error::NotEditable) => {
3855                self.step_back_to_stop();
3856                true
3857            }
3858            Err(twig::Error::NotFound | twig::Error::UnsupportedFormat) => false,
3859            Err(e) => {
3860                self.status = Some(format!("join: {e}"));
3861                true
3862            }
3863        }
3864    }
3865
3866    /// Delete at the end of a block's content: join the block after it into
3867    /// this one — [`backspace_joins_block`](Self::backspace_joins_block)'s
3868    /// mirror, and the same twig gesture aimed at the next block. The caret
3869    /// stays where it was, which is where the joined text now begins after
3870    /// the separator. Where twig refuses, the caret steps forward to the next
3871    /// stop instead; where no block follows, Delete keeps its character
3872    /// delete.
3873    fn delete_forward_joins_block(&mut self) -> bool {
3874        let caret = self.caret;
3875        let at_end = self
3876            .nodes()
3877            .iter()
3878            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3879            .any(|n| n.content_span.as_ref().is_some_and(|c| c.end == caret));
3880        if !at_end {
3881            return false;
3882        }
3883        // The next stop, across a line end, in a block: what Delete at a
3884        // block's end points at. On the same line it is a hidden delimiter's
3885        // far side, which the ordinary delete handles; on a blank line it is
3886        // the empty paragraph the byte delete has always closed.
3887        self.rebuild_map();
3888        let Some(stop) = self.vmap.stop_after(caret) else {
3889            return false;
3890        };
3891        if !self.source[caret..stop].contains('\n') || !self.has_block_at(stop) {
3892            return false;
3893        }
3894        match self.join_blocks(stop) {
3895            Ok(change) => {
3896                self.land_after_join(change.old.start);
3897                true
3898            }
3899            Err(twig::Error::NotEditable | twig::Error::NotFound) => {
3900                self.caret = stop;
3901                self.anchor = None;
3902                self.goal_col = None;
3903                true
3904            }
3905            Err(twig::Error::UnsupportedFormat) => false,
3906            Err(e) => {
3907                self.status = Some(format!("join: {e}"));
3908                true
3909            }
3910        }
3911    }
3912
3913    /// The content bytes of the paragraph or heading whose content opens
3914    /// exactly at `off` — the block a Backspace there is at the start of.
3915    fn text_block_opening_at(&mut self, off: usize) -> Option<String> {
3916        self.nodes()
3917            .into_iter()
3918            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3919            .find_map(|n| {
3920                let c = n.content_span?;
3921                (c.start == off).then(|| self.source[c].to_string())
3922            })
3923    }
3924
3925    /// Hand the block at `offset` to twig's `join_blocks`, with the undo
3926    /// plumbing every structural gesture has; the caret is the caller's to
3927    /// place from the change, via [`land_after_join`](Self::land_after_join).
3928    fn join_blocks(&mut self, offset: usize) -> Result<Change, twig::Error> {
3929        if self.read_only {
3930            return Err(twig::Error::NotEditable);
3931        }
3932        self.record_caret();
3933        let change = self.editor.join_blocks(offset)?;
3934        self.last_edit_kind = None; // structural edit is its own undo step
3935        self.refresh();
3936        Ok(change)
3937    }
3938
3939    /// Finish a join: the caret at `at`, no selection, the map this
3940    /// revision's before the clamp — see `write_block_attrs` for why.
3941    fn land_after_join(&mut self, at: usize) {
3942        self.caret = at;
3943        self.anchor = None;
3944        self.goal_col = None;
3945        self.dirty = self.source != self.clean_source;
3946        self.status = None;
3947        self.rebuild_map();
3948        self.clamp_caret();
3949        self.record_caret();
3950    }
3951
3952    // ── moving a block ─────────────────────────────────────────────────────────
3953
3954    /// The block a move picks up at `offset` — the same one
3955    /// [`select_block_at`](Self::select_block_at) selects (the deepest node
3956    /// that is neither inline nor a multi-block container), widened to the
3957    /// list item when it is the item's first block, because that is what
3958    /// twig's `move_block` moves: a bullet's text is the bullet, and dragging
3959    /// it takes the item and everything under it. A block later in an item's
3960    /// tail moves alone. `None` on a blank line, and past the source.
3961    fn movable_block_at(&mut self, offset: usize) -> Option<FlatNode> {
3962        let off = offset.min(self.source.len());
3963        let chain = self.editor.ancestors_at(off).ok()?;
3964        let block = chain
3965            .iter()
3966            .rev()
3967            .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))?;
3968        let nodes = self.nodes();
3969        let block = nodes.get(block.node_id as usize)?.clone();
3970        let item = block
3971            .parent
3972            .and_then(|p| nodes.get(p.0 as usize))
3973            .filter(|p| matches!(p.kind, Kind::ListItem | Kind::TaskListItem))
3974            .filter(|p| p.first_child == Some(block.id));
3975        Some(item.cloned().unwrap_or(block))
3976    }
3977
3978    /// The source range of the block a move would pick up at `offset` — for
3979    /// the outline of the block being carried, without moving the caret. The
3980    /// range [`select_block_at`](Self::select_block_at) would select, except
3981    /// that it is the whole item for a bullet's text, as
3982    /// [`move_block`](Self::move_block) is.
3983    pub fn block_range_at(&mut self, offset: usize) -> Option<Range<usize>> {
3984        self.movable_block_at(offset).map(|b| b.span)
3985    }
3986
3987    /// Move the block at `from` to the boundary `to` — twig's `move_block`,
3988    /// with the undo plumbing every structural gesture has and the caret
3989    /// riding the block to its new place. `from` is any offset inside the
3990    /// block (the one [`block_range_at`](Self::block_range_at) finds); `to`
3991    /// is a position *between* blocks — a block's first byte lands before it,
3992    /// its last after it, a blank line is itself a boundary, and the source's
3993    /// length is the document's end. The block takes the line prefixes of
3994    /// the container the boundary is inside — a `> ` on the way into a quote,
3995    /// none on the way out — and the blank lines a person would have typed
3996    /// are written and removed; twig spells all of that.
3997    ///
3998    /// A move that would move nothing — `to` inside the block, or on the
3999    /// boundary it already sits on — is a quiet no-op rather than an error,
4000    /// since it is what a block dropped back where it was asks for. Any other
4001    /// refusal reaches the status line: a `to` interior to a fence or a table,
4002    /// or a format with no blocks a caret could name.
4003    ///
4004    /// In WYSIWYG the frontmatter is hidden, and a boundary above it is not
4005    /// one a person can see: `to` is raised to the first rendered offset.
4006    ///
4007    /// `true` when the document changed. A move twig accepts that rewrites
4008    /// nothing — a one-item list sent past a paragraph is still a one-item
4009    /// list past that paragraph — is taken back rather than left as an undo
4010    /// step with no difference in it, and is `false` too.
4011    pub fn move_block(&mut self, from: usize, to: usize) -> bool {
4012        if self.read_only || self.refuse_unsupported("move block", Gesture::MoveBlock) {
4013            return false;
4014        }
4015        let len = self.source.len();
4016        let from = from.min(len);
4017        let to = to.clamp(self.caret_floor().min(len), len);
4018        let Some(block) = self.movable_block_at(from) else {
4019            self.status = Some("move block: no block here".into());
4020            return false;
4021        };
4022        // Where the caret stands in the block, as (line within the block,
4023        // bytes back from that line's end) — the shape that survives a
4024        // prefix being added or stripped on the way through a container.
4025        let caret = self.caret.clamp(block.span.start, block.span.end);
4026        let block_line = self.source[block.span.start..caret].matches('\n').count();
4027        let line_end = self.source[caret..block.span.end]
4028            .find('\n')
4029            .map_or(block.span.end, |i| caret + i);
4030        let tail = line_end - caret;
4031        let block_lines = self.source[block.span.start..block.span.end]
4032            .matches('\n')
4033            .count()
4034            + 1;
4035        let upward = to <= block.span.start;
4036        self.record_caret();
4037        match self.editor.move_block(from, to) {
4038            Ok(_) if self.editor.source_str().ok().as_deref() == Some(self.source.as_str()) => {
4039                let _ = self.editor.undo();
4040                self.status = None;
4041                false
4042            }
4043            Ok(change) => {
4044                self.last_edit_kind = None; // structural edit is its own undo step
4045                self.refresh();
4046                let at = self.moved_block_caret(&change.new, upward, block_lines, block_line, tail);
4047                self.caret = at;
4048                self.anchor = None;
4049                self.goal_col = None;
4050                self.dirty = self.source != self.clean_source;
4051                self.status = None;
4052                self.rebuild_map();
4053                self.clamp_caret();
4054                self.record_caret();
4055                true
4056            }
4057            // Nothing to move: the block dropped back onto its own boundary.
4058            Err(twig::Error::InvalidArgument) => {
4059                self.status = None;
4060                false
4061            }
4062            Err(e) => {
4063                self.status = Some(format!("move block: {e}"));
4064                false
4065            }
4066        }
4067    }
4068
4069    /// The caret's place in the rewritten region after a move: the moved
4070    /// block's lines open the region when it went up (below the blank line it
4071    /// was dropped on, when it was) and close it (above the separator twig
4072    /// wrote after it) when it went down, and within them the
4073    /// caret keeps its line and its distance from that line's end. Clamped
4074    /// into the region rather than trusted, since a block can lose a line on
4075    /// the way — a quote it was the only content of goes with it.
4076    fn moved_block_caret(
4077        &self,
4078        new: &Range<usize>,
4079        upward: bool,
4080        block_lines: usize,
4081        block_line: usize,
4082        tail: usize,
4083    ) -> usize {
4084        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
4085        let mut lines: Vec<(usize, usize)> = Vec::new();
4086        let mut start = 0;
4087        loop {
4088            match region[start..].find('\n') {
4089                Some(i) => {
4090                    lines.push((start, start + i));
4091                    start += i + 1;
4092                }
4093                None => {
4094                    lines.push((start, region.len()));
4095                    break;
4096                }
4097            }
4098        }
4099        // A separator line is blank, or a quote's bare `>`; the region can
4100        // open with one (the blank line the block was dropped on) or close
4101        // with one (the one twig wrote after it).
4102        let separator = |&(s, e): &(usize, usize)| {
4103            region[s..e]
4104                .trim()
4105                .trim_start_matches('>')
4106                .trim()
4107                .is_empty()
4108        };
4109        let first = if upward {
4110            lines.iter().position(|l| !separator(l)).unwrap_or(0)
4111        } else {
4112            let filled = lines
4113                .iter()
4114                .rposition(|l| !separator(l))
4115                .map_or(0, |i| i + 1);
4116            filled.saturating_sub(block_lines)
4117        };
4118        let (s, e) = lines[(first + block_line).min(lines.len() - 1)];
4119        new.start + e.saturating_sub(tail).max(s)
4120    }
4121
4122    /// Move the caret's block one place up — Alt+↑: above the block before it,
4123    /// and out of its container, to just above it, when it is the first block
4124    /// there. Nothing above the document's first block, and nothing to do for
4125    /// a caret on a blank line; both say so in the status line.
4126    pub fn move_block_up(&mut self) {
4127        self.move_block_by(true);
4128    }
4129
4130    /// Move the caret's block one place down — Alt+↓, the mirror of
4131    /// [`move_block_up`](Self::move_block_up): below the block after it, and
4132    /// out of its container when it is the last block there.
4133    pub fn move_block_down(&mut self) {
4134        self.move_block_by(false);
4135    }
4136
4137    fn move_block_by(&mut self, up: bool) {
4138        if self.read_only || self.refuse_unsupported("move block", Gesture::MoveBlock) {
4139            return;
4140        }
4141        let Some(from) = self.block_offset_for_caret() else {
4142            self.status = Some("move block: no block here".into());
4143            return;
4144        };
4145        let Some(block) = self.movable_block_at(from) else {
4146            self.status = Some("move block: no block here".into());
4147            return;
4148        };
4149        let nodes = self.nodes();
4150        let to = if up {
4151            self.boundary_above(&nodes, &block)
4152        } else {
4153            self.boundary_below(&nodes, &block)
4154        };
4155        if to.is_none_or(|to| !self.move_block(from, to)) && self.status.is_none() {
4156            self.status = Some(if up {
4157                "move block: nothing above".into()
4158            } else {
4159                "move block: nothing below".into()
4160            });
4161        }
4162    }
4163
4164    /// The boundary one step above `block`: before its previous sibling, or
4165    /// — for the first block in a container — before the container itself.
4166    /// `None` for the document's first block.
4167    fn boundary_above(&self, nodes: &[FlatNode], block: &FlatNode) -> Option<usize> {
4168        let parent = block.parent.and_then(|p| nodes.get(p.0 as usize))?;
4169        let previous = nodes
4170            .iter()
4171            .filter(|n| n.parent == Some(parent.id))
4172            .take_while(|n| n.id != block.id)
4173            .last();
4174        match previous {
4175            Some(p) => self.before(p),
4176            None if parent.kind == Kind::Doc => None,
4177            // An item leaving a nested list upward goes before the item
4178            // holding that list, as an item of the outer one; the list's own
4179            // first byte is inside the holding item's tail.
4180            None if matches!(
4181                parent.kind,
4182                Kind::BulletList | Kind::OrderedList | Kind::TaskList
4183            ) =>
4184            {
4185                match parent.parent.and_then(|p| nodes.get(p.0 as usize)) {
4186                    Some(item) if matches!(item.kind, Kind::ListItem | Kind::TaskListItem) => {
4187                        self.before(item)
4188                    }
4189                    _ => self.before(parent),
4190                }
4191            }
4192            None => self.before(parent),
4193        }
4194    }
4195
4196    /// The boundary one step below `block`: after its next sibling, or — for
4197    /// the last block in a container — just past the container, at its
4198    /// parent's level ([`exit_below`](Self::exit_below)). `None` for the
4199    /// document's last block.
4200    fn boundary_below(&self, nodes: &[FlatNode], block: &FlatNode) -> Option<usize> {
4201        let parent = block.parent.and_then(|p| nodes.get(p.0 as usize))?;
4202        if let Some(n) = block.next_sibling.and_then(|n| nodes.get(n.0 as usize)) {
4203            return Some(self.after(n));
4204        }
4205        match parent.kind {
4206            Kind::Doc => None,
4207            _ => self.exit_below(nodes, parent),
4208        }
4209    }
4210
4211    /// The boundary just past `container` at its parent's level: before its
4212    /// next sibling, or past its parent when it is the last thing there —
4213    /// the document's end at the top. Leaving a list item is the exception
4214    /// that keeps a block in the list: the next item's tail, which is what
4215    /// [`after`](Self::after) an item names.
4216    fn exit_below(&self, nodes: &[FlatNode], container: &FlatNode) -> Option<usize> {
4217        let item = matches!(container.kind, Kind::ListItem | Kind::TaskListItem);
4218        match container.next_sibling.and_then(|n| nodes.get(n.0 as usize)) {
4219            Some(n) if item => Some(self.after(n)),
4220            Some(n) => self.before(n),
4221            None => {
4222                let parent = container.parent.and_then(|p| nodes.get(p.0 as usize))?;
4223                match parent.kind {
4224                    Kind::Doc => Some(self.source.len()),
4225                    _ => self.exit_below(nodes, parent),
4226                }
4227            }
4228        }
4229    }
4230
4231    /// The boundary before `node`: its first byte. twig reads a container's
4232    /// opening as before it — a quote's marker, a fence's first byte — so the
4233    /// span's start is the boundary at the parent's level for every kind.
4234    fn before(&self, node: &FlatNode) -> Option<usize> {
4235        Some(node.span.start)
4236    }
4237
4238    /// The boundary after `node`: its own end, which for a container proper
4239    /// (a quote, a list, a fenced or tagged container) is the end of its last
4240    /// line — after its last block, still inside it, where a block arriving
4241    /// from outside joins it. Past the container is the next line's start: a
4242    /// blank line, the next block, or the document's end.
4243    fn after(&self, node: &FlatNode) -> usize {
4244        let container = is_block_container(&node.kind)
4245            && !matches!(node.kind, Kind::ListItem | Kind::TaskListItem);
4246        let end = node.span.end.min(self.source.len());
4247        if container && self.source.as_bytes().get(end) == Some(&b'\n') {
4248            end + 1
4249        } else {
4250            end
4251        }
4252    }
4253
4254    /// Where a block dragged over rendered row `row` would land — the
4255    /// boundary before the row's block when the row is in its upper half, the
4256    /// boundary after it otherwise, and the document's end for a row below
4257    /// everything. `None` for a row that holds no block (a decoration row is
4258    /// resolved to the block under it, so this is a table's bottom rule with
4259    /// nothing after it, or a map with no rows). The frontend draws its
4260    /// indicator above [`DropTarget::row`] and hands
4261    /// [`DropTarget::offset`] to [`move_block`](Self::move_block).
4262    ///
4263    /// The block is the deepest one, not the widened item: a drop on a
4264    /// bullet's text lands before or after that bullet, and its nested
4265    /// children — rows of their own — answer for themselves.
4266    pub fn drop_target_at(&mut self, row: usize) -> Option<DropTarget> {
4267        let rows = self.vmap.rows.len();
4268        if row >= rows {
4269            return Some(DropTarget {
4270                offset: self.source.len(),
4271                row: rows,
4272            });
4273        }
4274        // A gap or a rule is not a block; the block under it is the one meant.
4275        let row = (row..rows).find(|&r| self.vmap.row_is_navigable(r))?;
4276        let start = self.vmap.row_start(row)?;
4277        let chain = self.editor.ancestors_at(start).ok()?;
4278        let block = chain
4279            .iter()
4280            .rev()
4281            .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))?;
4282        let span = block.span.clone();
4283        let (first, last) = self.vmap.row_range_for(span.clone());
4284        if row <= usize::midpoint(first, last) {
4285            Some(DropTarget {
4286                offset: span.start,
4287                row: first,
4288            })
4289        } else {
4290            Some(DropTarget {
4291                offset: span.end.min(self.source.len()),
4292                row: last + 1,
4293            })
4294        }
4295    }
4296
4297    /// Backspace at a table's trailing stop: move onto the stop before it (the
4298    /// last cell's end) and consume the key. `false` anywhere else. See
4299    /// [`VisualMap::table_end_stop`] for why the byte behind the caret there is
4300    /// not one to delete.
4301    fn backspace_at_table_end(&mut self) -> bool {
4302        // The map answers about offsets, so it has to be this revision's — see
4303        // `open_paragraph_at_block_edge`.
4304        self.rebuild_map();
4305        if !self.vmap.table_end_stop(self.caret) {
4306            return false;
4307        }
4308        if let Some(off) = self
4309            .vmap
4310            .stop_before(self.caret)
4311            .filter(|&o| o >= self.caret_floor())
4312        {
4313            self.caret = off;
4314            self.anchor = None;
4315            self.goal_col = None;
4316        }
4317        true
4318    }
4319
4320    /// Whether the caret stands at a table cell's wall on the `edge` side — at
4321    /// or before its first caret stop for Backspace, at or past its last for
4322    /// Delete — where the only bytes between it and the neighbouring cell are
4323    /// the padding and the `|` the rich view draws as the grid. The padding
4324    /// counts as the cell's: a caret placed between `| ` and the text is at the
4325    /// same wall, so the first press cannot eat the space either. An in-cell
4326    /// `<br>` at the edge is not a wall; the delete takes it whole, as ever.
4327    fn at_cell_wall(&mut self, edge: BreakEdge) -> bool {
4328        // The map answers about offsets, so it has to be this revision's.
4329        self.rebuild_map();
4330        if self.cell_break_at(edge).is_some() {
4331            return false;
4332        }
4333        let caret = self.caret;
4334        let src = self.source.as_bytes();
4335        let pad = |b: &u8| *b == b' ' || *b == b'\t';
4336        self.vmap
4337            .tables
4338            .iter()
4339            .flat_map(|t| &t.grid)
4340            .flat_map(|row| &row.cells)
4341            .any(|cell| {
4342                let lo = cell.start
4343                    - src[..cell.start]
4344                        .iter()
4345                        .rev()
4346                        .take_while(|b| pad(b))
4347                        .count();
4348                let hi = cell.end + src[cell.end..].iter().take_while(|b| pad(b)).count();
4349                (lo..=hi).contains(&caret)
4350                    && match edge {
4351                        BreakEdge::Backward => {
4352                            self.vmap.stop_before(caret).is_none_or(|s| s < cell.start)
4353                        }
4354                        BreakEdge::Forward => {
4355                            self.vmap.stop_after(caret).is_none_or(|s| s > cell.end)
4356                        }
4357                    }
4358            })
4359    }
4360
4361    /// Whether the caret's own source line holds nothing but whitespace — an
4362    /// empty paragraph, or the blank line a block boundary is spelled with. The
4363    /// test for [`backspace`](Self::backspace)'s stop-wise delete: such a line has
4364    /// no text of its own, so the newline before the caret belongs to the gap
4365    /// between blocks rather than to any word the caret is editing.
4366    fn caret_on_blank_line(&self) -> bool {
4367        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
4368        let line_end = self.source[self.caret..]
4369            .find('\n')
4370            .map_or(self.source.len(), |i| self.caret + i);
4371        self.source[line_start..line_end].trim().is_empty()
4372    }
4373
4374    /// The source span of an in-cell hard break (`<br>`) touching the caret on the
4375    /// `edge` side — the byte range to delete whole. A table row is one source
4376    /// line, so its break is spelled `<br>` yet drawn as a single newline glyph
4377    /// (see `wysiwyg.rs`); a delete over it must take every byte, or a one-byte
4378    /// step strands a broken `<br` in the cell. `Backward` matches a break ending
4379    /// at the caret (Backspace), `Forward` one starting at it (Delete). `None`
4380    /// when no such break is adjacent. Only the in-cell break is spelled `<br>`
4381    /// (an ordinary hard break is `  \n`), so the leading `<` alone tells them
4382    /// apart — no ancestor walk needed. Rich view only; source view shows the
4383    /// literal tag and deletes it a byte at a time.
4384    fn cell_break_at(&mut self, edge: BreakEdge) -> Option<(usize, usize)> {
4385        let caret = self.caret;
4386        let nodes = self.nodes();
4387        let src = self.source.as_bytes();
4388        nodes
4389            .iter()
4390            .find(|n| {
4391                n.kind == Kind::HardBreak
4392                    && n.span.start < n.span.end
4393                    && src.get(n.span.start) == Some(&b'<')
4394                    && match edge {
4395                        BreakEdge::Backward => n.span.end == caret,
4396                        BreakEdge::Forward => n.span.start == caret,
4397                    }
4398            })
4399            .map(|n| (n.span.start, n.span.end))
4400    }
4401
4402    /// Whether the source byte at `off` is a backslash twig consumed as an escape
4403    /// (hidden in the rich view), as against a literal backslash (drawn). A
4404    /// backslash escapes exactly an ASCII-punctuation character (the CommonMark /
4405    /// Djot rule twig follows), so `\` + punctuation is the whole test — no AST
4406    /// round-trip needed.
4407    fn is_hidden_escape(&self, off: usize) -> bool {
4408        let b = self.source.as_bytes();
4409        b.get(off) == Some(&b'\\') && b.get(off + 1).is_some_and(u8::is_ascii_punctuation)
4410    }
4411
4412    /// Backspace's list behaviour: when the caret sits exactly at the start of a
4413    /// list item's content (right after its marker), outdent the item if it's
4414    /// nested, else strip the marker so it becomes a paragraph. Returns whether
4415    /// it acted — `false` leaves Backspace its ordinary character delete.
4416    fn backspace_list_start(&mut self) -> bool {
4417        let Some(marker) = self.list_marker_on_line(self.caret) else {
4418            return false;
4419        };
4420        // Only right after the marker. That the line opens a real item is
4421        // already settled: `list_marker_on_line` answers from the tree.
4422        if self.caret != marker.content_start() {
4423            return false;
4424        }
4425        if self.item_is_nested(marker.marker_start) {
4426            // Nested: give back one level, keeping the marker and carrying the
4427            // caret with it.
4428            self.outdent();
4429        } else {
4430            // Top level: drop the marker, leaving a paragraph, then renumber the
4431            // siblings the removed item was counted among. Only the marker goes —
4432            // a quote prefix in front of it still has a quote to hold up.
4433            self.splice(marker.marker_start, self.caret, "", EditKind::Other);
4434            self.renumber_here();
4435        }
4436        true
4437    }
4438
4439    /// Backspace's heading behaviour: with the caret exactly at the start of an
4440    /// ATX heading's content — right after the `#` marker the rich view hides —
4441    /// strip the marker so the line becomes a paragraph. The peer of
4442    /// [`backspace_list_start`](Self::backspace_list_start)'s ladder, and the same
4443    /// reasoning: hidden block markup is structure, so the keystroke over it is
4444    /// structural.
4445    ///
4446    /// Without this the ordinary delete takes the space out of `# Title` and
4447    /// leaves `#Title`, which is no longer a heading at all — the hash the view
4448    /// had been hiding surfaces as literal text the user has to delete a second
4449    /// time, having never typed it. A closing sequence (`# Title #`, hidden at the
4450    /// other end) goes with the marker for the same reason.
4451    ///
4452    /// Returns whether it acted; `false` leaves Backspace its character delete.
4453    fn backspace_heading_start(&mut self) -> bool {
4454        let caret = self.caret;
4455        // The heading whose content opens exactly at the caret. A bare `#` has no
4456        // content span at all — its content starts (and ends) where the line does.
4457        let Some((span, content_end, marker)) = self.nodes().iter().find_map(|n| {
4458            let (start, end) = match &n.content_span {
4459                Some(c) => (c.start, c.end),
4460                None => (n.span.end, n.span.end),
4461            };
4462            (n.kind == Kind::Heading && start == caret)
4463                .then(|| (n.span.clone(), end, n.marker_span.clone()))
4464        }) else {
4465            return false;
4466        };
4467        // twig reports the marker's own extent, so there is nothing to walk back
4468        // over and no `#` in this file. A setext heading has no marker — its
4469        // content opens the line — so it falls through to the ordinary delete,
4470        // as does anything else sitting at a content start.
4471        // `m.end == caret` is what excludes a setext heading, whose marker is the
4472        // underline *after* the content rather than a prefix before it.
4473        let Some(marker) = marker.filter(|m| m.end == caret) else {
4474            return false;
4475        };
4476        let start = marker.start;
4477        // A closing `#` sequence is hidden too, so it can't be left behind. Only
4478        // when the tail really is one: trailing spaces alone are nothing to strip.
4479        let tail = &self.source[content_end..span.end];
4480        if tail.contains('#') && tail.chars().all(|c| c == '#' || c.is_whitespace()) {
4481            let kept = self.source[caret..content_end].to_string();
4482            self.splice(start, span.end, &kept, EditKind::Other);
4483            // The splice leaves the caret past the text it re-wrote; the caret
4484            // belongs where the content now starts, which is where it already was.
4485            self.caret = start;
4486            self.record_caret();
4487        } else {
4488            self.splice(start, caret, "", EditKind::Other);
4489        }
4490        true
4491    }
4492
4493    pub fn delete_forward(&mut self) {
4494        if let Some((s, e)) = self.selection() {
4495            self.splice(s, e, "", EditKind::Other);
4496        } else if self.caret < self.source.len() {
4497            // The mirror of Backspace's: forward-delete in front of a picture
4498            // would eat the `!` off its markup and leave a link where a photo was.
4499            if self.view != View::Source && self.delete_around_block_media(true) {
4500                return;
4501            }
4502            // And of Backspace's cell wall: Delete at a cell's end would take
4503            // the padding and the `|` after it.
4504            if self.view != View::Source && self.at_cell_wall(BreakEdge::Forward) {
4505                return;
4506            }
4507            // And of Backspace's join: at the end of a block's content, Delete
4508            // joins the next block into this one.
4509            if self.view != View::Source && self.delete_forward_joins_block() {
4510                return;
4511            }
4512            // Delete forward over an in-cell `<br>` takes the whole tag, the mirror
4513            // of Backspace's swallow (see `cell_break_at`) — else a byte-step
4514            // strands a broken `<br` in the cell.
4515            if self.view != View::Source
4516                && let Some((start, end)) = self.cell_break_at(BreakEdge::Forward)
4517            {
4518                self.splice(start, end, "", EditKind::Delete);
4519                return;
4520            }
4521            // The mirror of Backspace's two steps: from in front of a run's
4522            // opening `**` step into it, onto the first letter of its text, and
4523            // at the end of a run's text step out past its closing `**` to the
4524            // character beyond. Either way Delete takes the character it looks
4525            // like it is pointing at, and never a delimiter drawn as nothing.
4526            // The caret then settles back inside the run it was standing in —
4527            // see `settle_inside_close_delims`.
4528            let from = if self.view == View::Source {
4529                self.caret
4530            } else {
4531                let inside = self.step_inside_open_delims(self.caret);
4532                // The mirror of Backspace's empty-span rule: an attributed
4533                // span with no text goes whole, with the character after it.
4534                if let Some(span) = self.run_span_of_content(inside..inside) {
4535                    let to = if self.source[span.end..].starts_with('\n') {
4536                        span.end
4537                    } else {
4538                        next_boundary(&self.source, span.end)
4539                    };
4540                    self.splice(span.start, to, "", EditKind::Delete);
4541                    return;
4542                }
4543                self.skip_trailing_close_delims(inside)
4544            };
4545            let next = next_boundary(&self.source, from);
4546            // And of its emptying rules: the span goes with its last letter,
4547            // and so does the block's div or `{…}` line.
4548            if self.view != View::Source
4549                && let Some(span) = self.run_span_of_content(from..next)
4550            {
4551                self.splice(span.start, span.end, "", EditKind::Delete);
4552                return;
4553            }
4554            if self.view != View::Source
4555                && let Some(block) = self.attributed_block_of_content(from..next)
4556            {
4557                self.splice(block.start, block.end, "", EditKind::Delete);
4558                return;
4559            }
4560            if from < next {
4561                self.splice(from, next, "", EditKind::Delete);
4562            }
4563        }
4564    }
4565
4566    /// Delete from the caret back to the start of the previous word (⌥⌫ /
4567    /// Ctrl+⌫). Deletes the selection instead when one is active.
4568    pub fn delete_word_back(&mut self) {
4569        if let Some((s, e)) = self.selection() {
4570            self.splice(s, e, "", EditKind::Other);
4571        } else {
4572            // A word back from just past a picture is a word *of its markup*, and
4573            // a word back from in front of one runs through the paragraph break
4574            // into the prose above — dissolving the picture either way. See
4575            // `delete_around_block_media`.
4576            if self.view != View::Source && self.delete_around_block_media(false) {
4577                return;
4578            }
4579            let start = self.word_left_from(self.caret).max(self.caret_floor());
4580            if start < self.caret {
4581                let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
4582                self.splice(s, e, "", EditKind::Delete);
4583            }
4584        }
4585    }
4586
4587    /// Delete from the caret forward to the end of the next word (⌥⌦ /
4588    /// Ctrl+Del). Deletes the selection instead when one is active.
4589    pub fn delete_word_forward(&mut self) {
4590        if let Some((s, e)) = self.selection() {
4591            self.splice(s, e, "", EditKind::Other);
4592        } else {
4593            // The mirror: a word forward from in front of a picture is its markup.
4594            if self.view != View::Source && self.delete_around_block_media(true) {
4595                return;
4596            }
4597            let end = self.word_right_from(self.caret);
4598            if end > self.caret {
4599                let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
4600                self.splice(s, e, "", EditKind::Delete);
4601            }
4602        }
4603    }
4604
4605    /// Delete from the caret back to the start of its line (⌘⌫). Deletes the
4606    /// selection instead when one is active, as every other delete here does.
4607    ///
4608    /// The line is the view's own — the one Home and End work on, so in WYSIWYG
4609    /// a soft-wrapped row is a line. It is not Home's *target*, though: Home
4610    /// stops at the first character and this takes the indentation with it, the
4611    /// way Cocoa's `deleteToBeginningOfLine:` does. Stopping at the text would
4612    /// leave an indent behind that nothing can then ask to delete, where a caret
4613    /// left at column 0 is one press of Home away from either.
4614    pub fn delete_to_line_start(&mut self) {
4615        if let Some((s, e)) = self.selection() {
4616            self.splice(s, e, "", EditKind::Other);
4617            return;
4618        }
4619        // Never back across the floor: hidden frontmatter isn't on this line, or
4620        // on any line the WYSIWYG caret can see.
4621        let (start, _) = self.line_span();
4622        let start = start.max(self.caret_floor());
4623        if start < self.caret {
4624            let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
4625            self.splice(s, e, "", EditKind::Delete);
4626        }
4627    }
4628
4629    /// Kill from the caret to the end of its line (^K). Deletes the selection
4630    /// instead when one is active.
4631    ///
4632    /// At the end of the line it does nothing, rather than pulling the line
4633    /// below up into this one. Joining has no meaning to give it in both views
4634    /// at once: a WYSIWYG line ends at a soft wrap as often as at a newline, and
4635    /// there is nothing there to delete, while the newline a *source* line ends
4636    /// with is only half of the blank line that separates two paragraphs —
4637    /// deleting one leaves a soft break, which is not the join it looks like.
4638    /// The views agreeing is worth more than emacs' second press, and Delete is
4639    /// already the key that joins.
4640    pub fn delete_to_line_end(&mut self) {
4641        if let Some((s, e)) = self.selection() {
4642            self.splice(s, e, "", EditKind::Other);
4643            return;
4644        }
4645        let (_, end) = self.line_span();
4646        if end > self.caret {
4647            let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
4648            self.splice(s, e, "", EditKind::Delete);
4649        }
4650    }
4651
4652    /// Grow a WYSIWYG word-delete to swallow any inline node it empties.
4653    ///
4654    /// A glyph-space range covers what the user can see, which for `**bold**` is
4655    /// the word and never the delimiters around it — so deleting the word on its
4656    /// own leaves `a **** c`, markup wrapped around nothing. They asked for the
4657    /// word, and the styling was the word's; the two go together. Only the
4658    /// node's delimiters are taken, and those are hidden here anyway, so nothing
4659    /// visible outside the range is lost.
4660    ///
4661    /// Repeated to a fixed point: emptying `***bold***` empties the emph inside
4662    /// the strong, and only then is the strong empty too.
4663    fn widen_over_emptied_inlines(&mut self, start: usize, end: usize) -> (usize, usize) {
4664        if self.view == View::Source {
4665            return (start, end);
4666        }
4667        let nodes = self.nodes();
4668        let (mut s, mut e) = (start, end);
4669        loop {
4670            let mut grew = false;
4671            for n in nodes.iter().filter(|n| wysiwyg::is_inline(n)) {
4672                let Some(text) = inline_content_span(n, &self.source) else {
4673                    continue;
4674                };
4675                // Some of its text survives, so the node still has a job.
4676                if text.start < s || text.end > e {
4677                    continue;
4678                }
4679                if n.span.start < s || n.span.end > e {
4680                    s = s.min(n.span.start);
4681                    e = e.max(n.span.end);
4682                    grew = true;
4683                }
4684            }
4685            if !grew {
4686                return (s, e);
4687            }
4688        }
4689    }
4690
4691    /// One splice of document text, keeping the **mark-edge rule**: an inline
4692    /// mark's content never begins or ends with whitespace. In Markdown and Djot
4693    /// a delimiter standing against a space is not a delimiter at all — `**bold **`
4694    /// is four literal asterisks around a word, and a rich view drawing the
4695    /// document faithfully has no choice but to show them. That is correct
4696    /// rendering of what the file says, and nobody typing a space after a bold
4697    /// word meant to say it.
4698    ///
4699    /// So the space goes *outside* the run instead — `**bold** ` — which is the
4700    /// same document to a reader and a live one to a parser. The caret follows it
4701    /// out and keeps the marks armed (see [`rearm`](Self::rearm)), so the next
4702    /// character rejoins the run (see [`rejoin_run`](Self::rejoin_run)) and the
4703    /// writer sees one unbroken bold phrase, never a flash of raw syntax.
4704    ///
4705    /// Every ordinary edit — typing, deleting, pasting, an IME step — comes
4706    /// through here, so the rule holds however the whitespace arrives at the
4707    /// edge. The repair is decided *after* the plain edit, by asking whether the
4708    /// mark actually died: a code span's backticks aren't whitespace-sensitive
4709    /// (`` `code ` `` is still code), and nothing is re-spelled when nothing broke.
4710    fn splice(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
4711        let fix = self.mark_edge_fix(start, end, text);
4712        if !self.splice_exact(start, end, text, kind) {
4713            return false;
4714        }
4715        if let Some(fix) = fix {
4716            self.repair_mark_edges(fix);
4717        }
4718        if text.is_empty() && end > start {
4719            self.settle_inside_close_delims();
4720        }
4721        true
4722    }
4723
4724    /// After a delete, take a caret left standing past a run's closing delimiters
4725    /// back inside the run.
4726    ///
4727    /// A delete leaves the caret where the deleted bytes began, and when those
4728    /// bytes were the last thing after a marked phrase — the space the mark-edge
4729    /// rule pushed out of `**bold** `, say — that spot is the far side of the
4730    /// closing `**`. The rich view has nothing to draw there: the delimiters are
4731    /// hidden, so the caret shows at the end of the word either way, and the two
4732    /// offsets are one place on screen with two different meanings. Typing at the
4733    /// outer one lands past the run, so the writer who backspaced a space out of
4734    /// their bold phrase watches the next character come out plain, and the
4735    /// toolbar button go dark, with the caret never appearing to move.
4736    ///
4737    /// The end of the run's text is the caret's home there — a delete that took
4738    /// away everything after a phrase leaves the caret at the end of that phrase,
4739    /// which is inside it — so it settles onto that
4740    /// ([`step_inside_close_delims`](Self::step_inside_close_delims) does the
4741    /// walk, through every mark closing at the point): the word stays bold, the
4742    /// button stays lit, and the next character carries on the phrase.
4743    ///
4744    /// Rich view only, and only where a mark really closes at the caret — mid-run
4745    /// or in plain prose no span ends there and the caret stays put. The opening
4746    /// edge is left alone on purpose: a caret in front of a run inherits from the
4747    /// text on its left, which is the plain text outside.
4748    fn settle_inside_close_delims(&mut self) {
4749        if self.view != View::Wysiwyg {
4750            return;
4751        }
4752        let at = self.step_inside_close_delims(self.caret);
4753        if at != self.caret {
4754            self.caret = at;
4755            self.clear_pending();
4756            self.record_caret();
4757        }
4758    }
4759
4760    /// The splice exactly as asked, with no mark-edge repair — for the callers
4761    /// that are *writing* the delimiters themselves ([`insert_with_marks`](Self::insert_with_marks)
4762    /// and [`rejoin_run`](Self::rejoin_run)) and place their own offsets around
4763    /// the bytes they inserted.
4764    ///
4765    /// One `edit_range` through twig, then re-anchor the caret from the returned
4766    /// `Change` and refresh the cached source. A reparse-breaking edit (rare for
4767    /// Markdown/Djot) leaves the document untouched and reports.
4768    ///
4769    /// Returns whether the edit landed — for a caller that has offsets of its
4770    /// own to place afterwards, which a rolled-back splice would leave pointing
4771    /// into text that never came to exist.
4772    fn splice_exact(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
4773        // The read-only gate, for every edit at once — see the field.
4774        if self.read_only {
4775            return false;
4776        }
4777        // twig records an undo step for every edit; when this one continues a
4778        // run of the same kind (typing, deleting), tell twig to fold it into the
4779        // step before it so the whole run undoes at once.
4780        let coalesce = kind != EditKind::Other && self.last_edit_kind == Some(kind);
4781        // Hand twig the pre-edit caret before the splice, so the undo step it
4782        // retires carries where the caret was standing.
4783        self.record_caret();
4784        match self.editor.edit_range(start, end, text) {
4785            Ok(change) => {
4786                self.last_edit_kind = Some(kind);
4787                // Counted first, so the fold has the step it folds.
4788                self.refresh();
4789                if coalesce {
4790                    self.coalesce_last_undo();
4791                }
4792                self.caret = change.new.end;
4793                self.anchor = None;
4794                self.goal_col = None;
4795                self.clear_pending();
4796                self.dirty = self.source != self.clean_source;
4797                self.status = None;
4798                // And the post-edit caret, so a later redo restores it.
4799                self.record_caret();
4800                true
4801            }
4802            // The edit was rolled back, so twig's history did not move and
4803            // neither may ours: pushing here would leave a step with no edit
4804            // under it and shift every later undo onto the wrong caret.
4805            Err(e) => {
4806                self.status = Some(format!("edit: {e}"));
4807                false
4808            }
4809        }
4810    }
4811
4812    /// The re-spelling that would keep the mark-edge rule for the edit
4813    /// `[start, end)` → `text`, or `None` when the edit leaves no whitespace
4814    /// against a delimiter and the plain splice is already right. Computed
4815    /// *before* the edit, while the run's spans and delimiters can still be read
4816    /// off the document; applied afterwards, and only if the mark really died —
4817    /// see [`repair_mark_edges`](Self::repair_mark_edges).
4818    ///
4819    /// Rich view only. Source view is for typing raw markup, where a space put
4820    /// against a `**` is exactly the character it looks like.
4821    fn mark_edge_fix(&mut self, start: usize, end: usize, text: &str) -> Option<MarkEdgeFix> {
4822        if self.view != View::Wysiwyg || start > end || end > self.source.len() {
4823            return None;
4824        }
4825        // Every inline mark standing over the edit, outermost first, with the
4826        // content span that says where its delimiters are.
4827        let chain: Vec<(InlineKind, std::ops::Range<usize>, std::ops::Range<usize>)> = self
4828            .editor
4829            .ancestors_at(start)
4830            .unwrap_or_default()
4831            .into_iter()
4832            .filter_map(|m| {
4833                let kind = inline_kind(&m.kind)?;
4834                let content = m.content_span.clone()?;
4835                Some((kind, m.span.clone(), content))
4836            })
4837            .collect();
4838        // The innermost run whose *content* holds the whole edit: the one whose
4839        // text is being changed, rather than one the edit merely sits under.
4840        let (kind, span, content) = chain
4841            .iter()
4842            .rev()
4843            .find(|(_, _, c)| c.start <= start && end <= c.end)?
4844            .clone();
4845        // What that content becomes. Whitespace at either end of it is what
4846        // would put out the mark.
4847        let body = format!(
4848            "{}{text}{}",
4849            &self.source[content.start..start],
4850            &self.source[end..content.end]
4851        );
4852        let (lead, trail) = if body.trim().is_empty() {
4853            // Nothing but whitespace left: there is no content to mark at all,
4854            // and the delimiters go with it rather than closing on a space.
4855            (body.len(), 0)
4856        } else {
4857            (
4858                body.len() - body.trim_start().len(),
4859                body.len() - body.trim_end().len(),
4860            )
4861        };
4862        // Nothing against a delimiter, and something still between them: the
4863        // plain edit stands. An emptied run is broken just as surely (`**b**`
4864        // with the `b` deleted is the literal `****`) and is re-spelt as the
4865        // nothing it now says.
4866        if lead == 0 && trail == 0 && !body.is_empty() {
4867            return None;
4868        }
4869        // Marks that open or close exactly where this one does — `***both***` is
4870        // two runs sharing an edge — spell their delimiters as one run of bytes,
4871        // so the whitespace has to clear all of them together.
4872        let (mut open_at, mut close_at) = (span.start, span.end);
4873        for _ in 0..chain.len() {
4874            match chain.iter().find(|(_, _, c)| c.start == open_at) {
4875                Some((_, s, _)) => open_at = s.start,
4876                None => break,
4877            }
4878        }
4879        for _ in 0..chain.len() {
4880            match chain.iter().find(|(_, _, c)| c.end == close_at) {
4881                Some((_, s, _)) => close_at = s.end,
4882                None => break,
4883            }
4884        }
4885        let open = &self.source[open_at..content.start];
4886        let close = &self.source[content.end..close_at];
4887        let core = &body[lead..body.len() - trail];
4888        let respelt = if core.is_empty() {
4889            body.clone()
4890        } else {
4891            format!(
4892                "{}{open}{core}{close}{}",
4893                &body[..lead],
4894                &body[body.len() - trail..]
4895            )
4896        };
4897        // The caret sits just past the inserted text within the new content —
4898        // which, when that lands in the whitespace, is now outside the delimiters.
4899        let pos = (start - content.start) + text.len();
4900        let caret = if core.is_empty() || pos <= lead {
4901            open_at + pos
4902        } else if pos >= lead + core.len() {
4903            open_at + lead + open.len() + core.len() + close.len() + (pos - lead - core.len())
4904        } else {
4905            open_at + lead + open.len() + (pos - lead)
4906        };
4907        Some(MarkEdgeFix {
4908            kind,
4909            probe: content.start,
4910            start: open_at,
4911            end: close_at + text.len() - (end - start),
4912            text: respelt,
4913            caret,
4914            // The marks in force here, resolved against any armed sticky delta —
4915            // what the writer is typing in, and so what has to still be true on
4916            // the far side of the delimiter the caret just stepped over.
4917            want: chain
4918                .iter()
4919                .filter(|(_, s, _)| start < s.end)
4920                .map(|(k, _, _)| *k)
4921                .collect::<InlineMarks>()
4922                .xor(self.pending_here()),
4923        })
4924    }
4925
4926    /// Apply a [`MarkEdgeFix`] — but only if the edit it was computed for really
4927    /// did break the mark. Whether whitespace at a delimiter is fatal is the
4928    /// format's business, not leaf's: `**bold **` is no longer strong, while
4929    /// `` `code ` `` is still perfectly good verbatim, and Djot's braced spellings
4930    /// don't care either. Asking the parser afterwards settles it for every kind
4931    /// and format at once, and costs a re-spelling only where one is due.
4932    ///
4933    /// The repair rides along with the edit that caused it — one undo step puts
4934    /// back what the writer typed, not a delimiter shuffle they never saw.
4935    fn repair_mark_edges(&mut self, fix: MarkEdgeFix) {
4936        if fix.end > self.source.len() {
4937            return;
4938        }
4939        if self.marks_at(fix.probe).iter().any(|(k, _)| *k == fix.kind) {
4940            return; // still a mark: these delimiters don't mind the whitespace
4941        }
4942        let resumed = self.last_edit_kind;
4943        if !self.splice_exact(fix.start, fix.end, &fix.text, EditKind::Other) {
4944            return;
4945        }
4946        self.coalesce_last_undo();
4947        // The keystroke owns the undo step, so the run of typing it belongs to
4948        // keeps coalescing over the repair rather than breaking in two here.
4949        self.last_edit_kind = resumed;
4950        self.caret = fix.caret.min(self.source.len());
4951        self.anchor = None;
4952        self.goal_col = None;
4953        self.rearm(fix.want);
4954        self.clamp_caret();
4955        self.record_caret();
4956    }
4957
4958    /// Arm whatever sticky delta reproduces `want` at the caret — the marks the
4959    /// writer is typing in, carried across an edit that moved the caret out of
4960    /// the run holding them. Arms nothing when the caret already stands in
4961    /// exactly those marks, but still remembers the spot, so a further ⌘b starts
4962    /// a clean delta here (see [`toggle`](Self::toggle)).
4963    fn rearm(&mut self, want: InlineMarks) {
4964        let here: InlineMarks = self
4965            .marks_at(self.caret)
4966            .into_iter()
4967            .map(|(k, _)| k)
4968            .collect();
4969        self.pending_marks = want.xor(here);
4970        self.pending_at = Some(self.caret);
4971    }
4972
4973    /// Insert `text` at `at` as a *literal* run via twig's `insert_literal`,
4974    /// which backslash-escapes any character that would otherwise open markup in
4975    /// this format and position (`*` → `\*`, a line-start `#` → `\#`). The mirror
4976    /// of [`splice`](Self::splice) for the Hidden reveal mode's typing path, with
4977    /// the same caret re-anchor, coalescing, and rollback contract. `at` must be
4978    /// a collapsed point — a selection is deleted by the caller first, since
4979    /// `insert_literal` inserts rather than replaces.
4980    fn insert_literal_at(
4981        &mut self,
4982        at: usize,
4983        text: &str,
4984        kind: EditKind,
4985        force_coalesce: bool,
4986    ) -> bool {
4987        // The read-only gate: this door goes to twig directly, not through
4988        // `splice_exact`, so it guards itself — see the field.
4989        if self.read_only {
4990            return false;
4991        }
4992        // `force_coalesce` folds this into the immediately preceding edit (the
4993        // selection-delete of an overwrite) so the pair is one undo step; else it
4994        // coalesces only when it continues a run of the same-kind typing.
4995        let coalesce =
4996            force_coalesce || (kind != EditKind::Other && self.last_edit_kind == Some(kind));
4997        // The mark-edge rule holds for typed text however it is spelled — see
4998        // `splice`. Only an insert twig passed through unchanged can use it,
4999        // since a fix is measured in the bytes that actually land, and an escape
5000        // adds bytes this couldn't have counted.
5001        let fix = self.mark_edge_fix(at, at, text);
5002        #[cfg(test)]
5003        if std::mem::take(&mut self.refuse_next_literal) {
5004            self.status = Some("edit: refused".into());
5005            return false;
5006        }
5007        self.record_caret();
5008        match self.editor.insert_literal(at, text) {
5009            Ok(change) => {
5010                self.last_edit_kind = Some(kind);
5011                // Counted first, so the fold has the step it folds.
5012                self.refresh();
5013                if coalesce {
5014                    self.coalesce_last_undo();
5015                }
5016                self.caret = change.new.end;
5017                self.anchor = None;
5018                self.goal_col = None;
5019                self.clear_pending();
5020                self.dirty = self.source != self.clean_source;
5021                self.status = None;
5022                self.record_caret();
5023                if let Some(fix) = fix.filter(|_| change.new.end - change.new.start == text.len()) {
5024                    self.repair_mark_edges(fix);
5025                }
5026                true
5027            }
5028            Err(e) => {
5029                self.status = Some(format!("edit: {e}"));
5030                false
5031            }
5032        }
5033    }
5034
5035    /// After a structural list edit (a new item, a nest/unnest), renumber the
5036    /// ordered list the caret sits in so its source markers run `1, 2, 3, …`
5037    /// again — a raw splice leaves them stale (`1. 2. 2. 3.`). twig does the
5038    /// renumber as its own edit; fold it into the edit that triggered it so the
5039    /// two undo as one, and only when it actually changed the source (a no-op or
5040    /// a caret outside any ordered list must not coalesce the real edit into the
5041    /// step before it).
5042    fn renumber_here(&mut self) {
5043        self.renumber_at(self.caret);
5044    }
5045
5046    /// [`renumber_here`](Self::renumber_here) aimed somewhere other than the
5047    /// caret — for an edit that leaves the caret one past the item it just wrote,
5048    /// where twig resolves no list to renumber.
5049    fn renumber_at(&mut self, off: usize) {
5050        // The read-only gate — this door reaches twig without the splice.
5051        if self.read_only {
5052            return;
5053        }
5054        let before = self.source.clone();
5055        if self.editor.renumber_ordered_lists(off).is_err() {
5056            return; // not inside an ordered list — nothing to renumber
5057        }
5058        self.refresh();
5059        if self.source != before {
5060            self.coalesce_last_undo();
5061            self.dirty = self.source != self.clean_source;
5062            self.clamp_caret();
5063            self.record_caret();
5064        }
5065    }
5066
5067    /// Repair the one trap a list edit can spring on itself. An *empty* `-`
5068    /// sub-item written directly beneath a text line reparses that text as a
5069    /// setext heading — `- hello\n  - ` is `<h2>hello</h2>`, because a lone `-`
5070    /// is also a setext-H2 underline (twig is right; pandoc agrees). `*` and `+`
5071    /// bullets can't underline anything, so swap the dash for a `*`: the item
5072    /// stays an empty nested bullet, the parent stays prose, and the source
5073    /// round-trips instead of hiding a heading the user never asked for. Folded
5074    /// into the triggering edit's undo step, the way renumbering is.
5075    ///
5076    /// Gated on the collapse having actually happened (the swapped dash was
5077    /// swallowed into a `heading`), so a real setext heading the author wrote —
5078    /// or a `- x` with content, which can't underline anything — is never
5079    /// touched. This has to live in the *edit*, not the renderer: leaving the
5080    /// hazardous bytes on disk and only painting over them would ship a file
5081    /// every other CommonMark tool reads as a heading.
5082    ///
5083    /// This one keeps its own byte scan, and has to: the hazard is precisely
5084    /// that the dash stopped being a list marker, so [`list_marker_on_line`] —
5085    /// which asks twig which lines open an item — reports nothing here. There is
5086    /// no node to ask about. It is also the last Markdown spelling leaf writes on
5087    /// purpose rather than for want of an answer; once twig spells continuations
5088    /// itself, avoiding the trap becomes twig's, and this goes.
5089    ///
5090    /// [`list_marker_on_line`]: Self::list_marker_on_line
5091    fn avoid_setext_collapse(&mut self) {
5092        let caret = self.caret.min(self.source.len());
5093        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
5094        let bytes = self.source.as_bytes();
5095        let mut dash = line_start;
5096        while matches!(bytes.get(dash), Some(b' ' | b'\t')) {
5097            dash += 1;
5098        }
5099        // A dash bullet is the only marker that doubles as a setext underline.
5100        if bytes.get(dash) != Some(&b'-') {
5101            return;
5102        }
5103        // Only an *empty* item is a bare underline; `- x` carries content and
5104        // can't fold the line above into a heading.
5105        let line_end = self.source[dash..]
5106            .find('\n')
5107            .map_or(self.source.len(), |i| dash + i);
5108        if !self.source[dash + 1..line_end].trim().is_empty() {
5109            return;
5110        }
5111        // The tell: that dash was swallowed into a `heading`. A properly nested
5112        // empty item sits under a `list_item`, with no heading in reach. Probe
5113        // the dash byte itself (well inside the heading), not the caret, whose
5114        // end-of-line offset can fall on the half-open span boundary.
5115        let collapsed = self
5116            .editor
5117            .ancestors_at(dash)
5118            .map(|c| c.into_iter().any(|m| m.kind == Kind::Heading))
5119            .unwrap_or(false);
5120        if !collapsed {
5121            return;
5122        }
5123        let caret = self.caret;
5124        if self.splice(dash, dash + 1, "*", EditKind::Other) {
5125            // Same width, so the caret keeps its column; fold into the edit that
5126            // triggered this so Tab stays one undo step.
5127            self.coalesce_last_undo();
5128            self.caret = caret.min(self.source.len());
5129            self.clamp_caret();
5130            self.record_caret();
5131        }
5132    }
5133
5134    fn snapshot(&self) -> CaretState {
5135        CaretState {
5136            caret: self.caret,
5137            anchor: self.anchor,
5138        }
5139    }
5140
5141    /// Hand twig the current caret and selection as the blob for the live
5142    /// document state. Called before an edit — so the step twig retires records
5143    /// where the caret was, and undo can restore it — and again once the op has
5144    /// placed the caret, so redo restores where the edit left it.
5145    ///
5146    /// This is the whole of leaf's undo-caret bookkeeping now. twig carries the
5147    /// caret through its own history, so coalescing falls out for free (folding
5148    /// two twig steps into one drops the intermediate blob, keeping the run's
5149    /// first) and the parallel stacks that had to march in lockstep — and could
5150    /// silently drift out of it — are gone.
5151    fn record_caret(&mut self) {
5152        let _ = self.editor.set_caret_blob(&self.snapshot().to_blob());
5153    }
5154
5155    /// Toggle an inline mark over the selection (Bold / Italic / Code / …). Keeps
5156    /// the toggled region selected so a second press cleanly reverses it.
5157    pub fn toggle(&mut self, kind: InlineKind) {
5158        // The read-only gate — this door reaches twig without the splice.
5159        if self.read_only {
5160            return;
5161        }
5162        // Ahead of the no-selection branch below: arming a mark for text not yet
5163        // typed is a promise `insert` cannot keep in a format with no delimiters
5164        // to spell it with. Per *kind*, not per format — Markdown spells five
5165        // of the eight marks (highlight among them, under the `highlight`
5166        // extension leaf parses with), djot all eight, HTML seven.
5167        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleInline(kind)) {
5168            return;
5169        }
5170        let Some((s, e)) = self.selection() else {
5171            // No selection: arm the mark for the next text typed here, the way a
5172            // word processor does. `⌘b`, type, `⌘b` again toggles bold on and off
5173            // in the flow of typing without ever selecting anything — the delta
5174            // is realised onto the freshly typed text by `insert`. A fresh caret
5175            // position starts the delta over from the marks actually in force.
5176            if self.pending_at != Some(self.caret) {
5177                self.pending_marks = InlineMarks::empty();
5178                self.pending_at = Some(self.caret);
5179            }
5180            self.pending_marks.flip(kind);
5181            self.status = None;
5182            return;
5183        };
5184        // Whitespace at the edge of a selection is not part of what was chosen —
5185        // a double-click takes the space after the word with it — and a mark
5186        // cannot close against one anyway: `**word **` is four literal asterisks
5187        // (the mark-edge rule, see `splice`). Mark the words, leave the spaces.
5188        let picked = &self.source[s..e];
5189        let (s, e) = (
5190            s + (picked.len() - picked.trim_start().len()),
5191            e - (picked.len() - picked.trim_end().len()),
5192        );
5193        if s >= e {
5194            self.status = Some(format!("{kind:?}: nothing selected to mark"));
5195            return;
5196        }
5197        // Styling a selection is a one-shot act, not a sticky mode.
5198        self.clear_pending();
5199        self.record_caret();
5200        match self.editor.toggle_inline(s, e, kind) {
5201            Ok(change) => {
5202                self.last_edit_kind = None; // structural edit is its own undo step
5203                self.refresh();
5204                self.anchor = Some(change.new.start);
5205                self.caret = change.new.end;
5206                self.dirty = self.source != self.clean_source;
5207                self.status = None;
5208                self.record_caret();
5209            }
5210            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
5211        }
5212    }
5213
5214    /// Whether the caret stands in a highlight — what a frontend asks to enable
5215    /// or disable its highlight-colour controls, the way
5216    /// [`caret_in_table`](Self::caret_in_table) gates the grid ones.
5217    ///
5218    /// A fact about the *caret*, and the other half of
5219    /// [`Capabilities::mark_color`], which is the fact about the format. A
5220    /// frontend needs both: djot spells a highlight and no colour for it, so a
5221    /// caret standing in `{=word=}` answers `true` here and still has no palette
5222    /// to offer.
5223    ///
5224    /// The rule is [`active_inline_marks`](Self::active_inline_marks)' rule, so
5225    /// the palette appears exactly where the Highlight button is lit — with one
5226    /// deliberate exception: a mark *armed* at a bare caret and not yet typed
5227    /// into lights the button and answers `false` here, because there is no node
5228    /// to colour until the text exists.
5229    pub fn caret_in_mark(&mut self) -> bool {
5230        self.mark_offset().is_some()
5231    }
5232
5233    /// The offset [`set_mark_color`](Self::set_mark_color) speaks for — the one
5234    /// standing in the highlight the gesture means — or `None` when neither end
5235    /// of what is selected is in one.
5236    ///
5237    /// The caret first, and the selection's *start* after it, because of what
5238    /// [`toggle`](Self::toggle) leaves behind: a fresh `==word==` is selected
5239    /// whole, with the caret at its far edge, one past the closing `==` and so
5240    /// (by `marks_at`' half-open rule) not in the mark at all. Highlight a word
5241    /// and colour it — the two presses a coloured highlight is made of — would
5242    /// otherwise refuse on the second, having just written the highlight the
5243    /// author is pointing at.
5244    fn mark_offset(&mut self) -> Option<usize> {
5245        let in_mark = |d: &mut Self, off: usize| {
5246            d.marks_at(off)
5247                .into_iter()
5248                .any(|(k, _)| k == InlineKind::Mark)
5249                .then_some(off)
5250        };
5251        let caret = self.caret.min(self.source.len());
5252        in_mark(self, caret).or_else(|| {
5253            let start = self.selection()?.0;
5254            in_mark(self, start)
5255        })
5256    }
5257
5258    /// The colour of the highlight at the caret — `None` both when the caret is
5259    /// in no highlight and when the highlight it is in names no colour, which
5260    /// are the same answer to "which swatch is lit".
5261    ///
5262    /// The innermost mark, by span, for the same reason
5263    /// [`current_heading_level`](Self::current_heading_level) walks the tree:
5264    /// what the caret is *in* is the deepest node containing it. A `data-color`
5265    /// naming a colour this build has no variant for reads as `None` — the
5266    /// renderer already draws that as a plain highlight rather than guessing,
5267    /// and the toolbar agrees with the renderer.
5268    pub fn mark_color_at_caret(&mut self) -> Option<MarkColor> {
5269        let at = self.mark_offset()?;
5270        self.mark_color_at(at)
5271    }
5272
5273    /// [`mark_color_at_caret`](Self::mark_color_at_caret) at a given offset —
5274    /// the innermost `mark` covering it, and the colour it names.
5275    fn mark_color_at(&mut self, off: usize) -> Option<MarkColor> {
5276        self.nodes()
5277            .into_iter()
5278            .filter(|n| n.kind == Kind::Mark)
5279            .filter(|n| n.span.start <= off && off < n.span.end)
5280            .min_by_key(|n| n.span.end - n.span.start)
5281            .and_then(|n| MarkColor::from_attrs(&n.attrs))
5282    }
5283
5284    /// Colour the highlight at the caret, or clear its colour with `None` — the
5285    /// palette behind a toolbar's Highlight button.
5286    ///
5287    /// Markdown only, and the one gesture whose availability is a fact about the
5288    /// *parse extensions* rather than about the format alone: the colour is
5289    /// spelled `==🔴 text==`, an emoji twig reads back out of the content and
5290    /// records as the mark's `data-color`, and only an editor parsing with
5291    /// `highlight_colors` (which [`parse_extensions`] turns on for every leaf
5292    /// document) reads it back that way. Djot spells the highlight and no colour
5293    /// for it, so this refuses there — see [`Capabilities::mark_color`].
5294    ///
5295    /// **A colour is a property of a highlight that already exists.** There is
5296    /// no "highlight this in red" here, because that is two splices and would be
5297    /// two undo steps under one press; a frontend that wants it calls
5298    /// [`toggle`](Self::toggle) with [`InlineKind::Mark`] first, which is the
5299    /// order the two buttons already sit in. With no highlight at the caret this
5300    /// says so in the status line and writes nothing.
5301    ///
5302    /// The caret keeps its place in the *text*: the splice is entirely in the
5303    /// prefix between the opening `==` and the first word, so an offset past it
5304    /// rides the emoji's width, and one standing on the prefix itself lands
5305    /// where the prefix now ends.
5306    pub fn set_mark_color(&mut self, color: Option<MarkColor>) {
5307        // The read-only gate — this door reaches twig without the splice.
5308        if self.read_only {
5309            return;
5310        }
5311        if self.refuse_unsupported("highlight colour", Gesture::SetMarkColor) {
5312            return;
5313        }
5314        let Some(at) = self.mark_offset() else {
5315            self.status = Some("highlight colour: no highlight at the caret".into());
5316            return;
5317        };
5318        // Clearing a colour a highlight hasn't got is twig's one *successful*
5319        // no-op, and the `Change` it hands back then describes whatever edit came
5320        // before it — a stale span that would drag the caret somewhere it never
5321        // was. Answer it here, where the question is cheap, rather than trusting
5322        // a change that isn't one.
5323        if color.is_none() && self.mark_color_at(at).is_none() {
5324            self.status = None;
5325            return;
5326        }
5327        self.record_caret();
5328        match self.editor.set_mark_color(at, color.map(twig_mark_color)) {
5329            Ok(change) => {
5330                // Re-anchored from the offsets as they were, *before* `refresh`
5331                // sees the new bytes: the caret it clamps is one standing inside
5332                // a prefix that didn't exist a moment ago, and walking it back to
5333                // a char boundary of the emoji loses the place this is restoring.
5334                let caret = reanchor(self.caret, &change);
5335                let anchor = self.anchor.map(|a| reanchor(a, &change));
5336                self.last_edit_kind = None; // structural edit is its own undo step
5337                self.refresh();
5338                self.caret = caret;
5339                self.anchor = anchor;
5340                self.dirty = self.source != self.clean_source;
5341                self.status = None;
5342                self.clamp_caret();
5343                self.record_caret();
5344            }
5345            Err(e) => self.status = Some(format!("highlight colour: {e}")),
5346        }
5347    }
5348
5349    /// One press of a colour swatch: colour the highlight at the caret, or —
5350    /// over a selection that isn't highlighted yet — highlight it and colour it,
5351    /// as **one** undo step.
5352    ///
5353    /// [`set_mark_color`](Self::set_mark_color) is the exact gesture and stays
5354    /// one splice; this is the compound every toolbar actually presses, and it
5355    /// lives here rather than in each frontend because the rule it encodes —
5356    /// what a swatch means when there is no highlight under it yet — is one
5357    /// answer, not one per frontend. The two splices are folded into a single
5358    /// history step, so the press that made a red highlight is taken back by a
5359    /// single undo rather than leaving an uncoloured one behind.
5360    ///
5361    /// `None` clears the colour, and over an unhighlighted selection means
5362    /// simply "highlight this" — the same thing the Highlight button does.
5363    /// A bare caret in no highlight is left alone with a status line, because
5364    /// [`toggle`](Self::toggle) there arms a mark for text not yet typed and a
5365    /// colour cannot be armed with it.
5366    pub fn highlight(&mut self, color: Option<MarkColor>) {
5367        if self.caret_in_mark() || self.selection().is_none() {
5368            self.set_mark_color(color);
5369            return;
5370        }
5371        self.toggle(InlineKind::Mark);
5372        // The format may not spell a highlight at all (`toggle` said so), and
5373        // there is nothing to colour if it doesn't.
5374        if self.status.is_some() {
5375            return;
5376        }
5377        let before = self.revision;
5378        self.set_mark_color(color);
5379        // Only fold when the colour really spliced. `highlight(None)` over a
5380        // fresh highlight is a no-op by design, and coalescing there would eat
5381        // the *previous* edit into the toggle instead.
5382        if self.revision != before {
5383            self.coalesce_last_undo();
5384        }
5385    }
5386
5387    // ── the presentation vocabulary ─────────────────────────────────────────
5388    //
5389    // Six gestures and five queries over twig's two attribute ops. Each gesture
5390    // edits **one key and keeps the rest**: it reads the node's attributes,
5391    // removes its own key (and, for alignment, its own tokens out of `class`),
5392    // adds the new value or nothing, and passes the list back whole — twig's
5393    // contract is replace-not-merge, so the read is the caller's job. A
5394    // paragraph that came in as `class="lead center" id="intro"
5395    // data-line-height="1.5"` and is right-aligned goes out as `class="lead
5396    // right" id="intro" data-line-height="1.5"`. Nothing leaf did not write is
5397    // touched, which is what lets a document from elsewhere pass through the
5398    // editor unharmed.
5399    //
5400    // Clearing is the same gesture with `None`: the key goes, and an empty list
5401    // at the end unwraps the span or the Markdown div, which twig does.
5402
5403    /// Set — or with `None` clear — the alignment of the block the caret is in.
5404    ///
5405    /// A block property, so the gesture is `set_block_attrs` on the caret's
5406    /// block **whatever is selected**: a line is a block's, and "centre this"
5407    /// with three words selected means the paragraph, not the words. The
5408    /// vocabulary is [`Align`], written as `class` tokens; other tokens on the
5409    /// same `class` are kept.
5410    ///
5411    /// In Markdown the attributes live on a `<div>` around the block — twig has
5412    /// no paragraph attribute syntax to write — and this reads them back off
5413    /// that div when the block is its sole child, so a second press rewrites
5414    /// the div rather than nesting a second one.
5415    pub fn set_alignment(&mut self, align: Option<Align>) {
5416        let attrs = self.block_attrs_at_caret();
5417        if align.is_none()
5418            && self.refuse_clear_from_div("alignment", &attrs, |a| Align::from_attrs(a).is_some())
5419        {
5420            return;
5421        }
5422        let attrs = with_class_token(
5423            &attrs,
5424            |t| Align::from_token(t).is_some(),
5425            align.map(Align::name),
5426        );
5427        self.write_block_attrs("alignment", attrs);
5428    }
5429
5430    /// Set — or with `None` clear — the line spacing of the block the caret is
5431    /// in. [`set_alignment`](Self::set_alignment)'s peer in every respect but
5432    /// the key: [`LineHeight`] under `data-line-height`, one of the menu's
5433    /// three names or an exact ratio, written in its canonical spelling.
5434    pub fn set_line_spacing(&mut self, spacing: Option<LineHeight>) {
5435        let attrs = self.block_attrs_at_caret();
5436        if spacing.is_none()
5437            && self.refuse_clear_from_div("line spacing", &attrs, |a| {
5438                LineHeight::from_attrs(a).is_some()
5439            })
5440        {
5441            return;
5442        }
5443        let spelling = spacing.map(LineHeight::name);
5444        let attrs = with_attr(&attrs, "data-line-height", spelling.as_deref());
5445        self.write_block_attrs("line spacing", attrs);
5446    }
5447
5448    /// Set — or with `None` clear — the size of the selected run, or of the
5449    /// caret's whole block when nothing is selected.
5450    ///
5451    /// Size, face and colour are the *run's*, and the block's when no run is
5452    /// chosen. With a selection the gesture is `wrap_range_attrs`, which wraps
5453    /// the range in an attributed span or re-styles the span it already lies in
5454    /// (never nesting a second, and unwrapping it when the last key goes). With
5455    /// no selection it is `set_block_attrs` on the caret's block, so that "make
5456    /// this paragraph larger" is a click with the caret in it rather than a
5457    /// select-all first.
5458    ///
5459    /// The walker reads the key at both levels with the nearer winning, so a
5460    /// span's `data-size` inside a block carrying its own applies to the span.
5461    ///
5462    /// The vocabulary is [`FontSize`]: one of CSS's seven keywords, which is
5463    /// what a menu offers first because a step reads as a step up under every
5464    /// theme, or the point size an author asked for, which is exact and is all
5465    /// it is. Either is written in its canonical spelling, so a size set twice
5466    /// from the same field writes the same bytes both times.
5467    pub fn set_font_size(&mut self, size: Option<FontSize>) {
5468        let spelling = size.map(FontSize::name);
5469        self.set_run_attr("size", "data-size", spelling.as_deref());
5470    }
5471
5472    /// Set — or with `None` clear — the face of the selected run, or of the
5473    /// caret's whole block. [`set_font_size`](Self::set_font_size)'s peer, with
5474    /// [`FontFace`] under `data-font` — one of the four generics, or the family
5475    /// the author named, which the frontends resolve through the platform's
5476    /// font registry and fall back to the body face without.
5477    pub fn set_font_family(&mut self, font: Option<FontFace>) {
5478        let spelling = font.as_ref().map(FontFace::name);
5479        self.set_run_attr("font", "data-font", spelling.as_deref());
5480    }
5481
5482    /// Set — or with `None` clear — the *text* colour of the selected run, or of
5483    /// the caret's whole block. [`set_font_size`](Self::set_font_size)'s peer,
5484    /// with [`TextColor`] under `data-color` — one of the seven names, whose
5485    /// two inks the theme owns, or the triple the author picked, which is
5486    /// painted as written in both appearances.
5487    ///
5488    /// The same key and the same seven names [`set_mark_color`](Self::set_mark_color)
5489    /// writes, and a different thing: that one colours a highlight's
5490    /// *background* and rides the `mark` node twig owns the spelling of, this
5491    /// one colours the letters and rides an attributed span. The two never
5492    /// collide, because a `mark` is a `mark` and a span is a span — and they
5493    /// share a vocabulary on purpose, so that a frontend with a red for a
5494    /// highlight has a red for text and both are *that* red.
5495    pub fn set_text_color(&mut self, color: Option<TextColor>) {
5496        let spelling = color.map(TextColor::name);
5497        self.set_run_attr("text colour", "data-color", spelling.as_deref());
5498    }
5499
5500    /// Insert a page break at the caret — `::page-break`, a leaf directive with
5501    /// no label and no attributes, which twig spells in every format that names
5502    /// a leaf container (Markdown under the `directives` extension
5503    /// [`parse_extensions`] turns on, and djot, where it is an empty `:::
5504    /// page-break` fence).
5505    ///
5506    /// Placed exactly as [`insert_thematic_break`](Self::insert_thematic_break)
5507    /// places a rule, and for the same reason: a directive is a block, so twig
5508    /// alone has nowhere to put one mid-paragraph and lands it after the
5509    /// caret's whole block. A bare paragraph is therefore parted at the caret
5510    /// first and the break aimed at the *first* half. See that method for the
5511    /// whole of the rule, including why a code block, a list item, a table and
5512    /// a setext heading are left unsplit.
5513    ///
5514    /// The frontends that paginate read the row's
5515    /// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) and open a page there;
5516    /// the ones that do not draw the `⧉ page-break` placeholder every leaf
5517    /// directive gets.
5518    pub fn insert_page_break(&mut self) {
5519        if self.read_only || self.refuse_unsupported("page break", Gesture::InsertDirective) {
5520            return;
5521        }
5522        self.caret = self.skip_trailing_close_delims(self.caret);
5523        // A selection is replaced by the break, as a rule replaces one.
5524        if let Some((s, e)) = self.selection() {
5525            self.splice(s, e, "", EditKind::Other);
5526        }
5527        self.anchor = None;
5528        self.record_caret();
5529        let at = self.caret;
5530        // A failure here is not fatal: the break still lands after the
5531        // block, which is what this call was trying to improve on.
5532        let parted = self.part_for_block(at);
5533        match self.editor.insert_directive(at, PAGE_BREAK, None, &[]) {
5534            Ok(change) => {
5535                self.last_edit_kind = None;
5536                self.refresh();
5537                if parted {
5538                    self.coalesce_last_undo();
5539                }
5540                self.anchor = None;
5541                self.caret = change.new.end;
5542                self.dirty = self.source != self.clean_source;
5543                self.status = None;
5544                self.clamp_caret();
5545                self.record_caret();
5546                self.caret_under_written_block(change.new, parted);
5547            }
5548            Err(e) => self.status = Some(format!("page break: {e}")),
5549        }
5550    }
5551
5552    /// The alignment in force at the caret, or `None` for the theme's default —
5553    /// which swatch of an alignment control is lit.
5554    ///
5555    /// Read off the nearest node that names one: the block the caret is in, and
5556    /// the `div`s around it after that. [`mark_color_at_caret`](Self::mark_color_at_caret)'s
5557    /// shape, one property along.
5558    pub fn alignment_at_caret(&mut self) -> Option<Align> {
5559        self.presentation_chain()
5560            .iter()
5561            .find_map(|attrs| Align::from_attrs(attrs))
5562    }
5563
5564    /// The line spacing in force at the caret, or `None` for the theme's own.
5565    /// [`alignment_at_caret`](Self::alignment_at_caret)'s peer.
5566    pub fn line_spacing_at_caret(&mut self) -> Option<LineHeight> {
5567        self.presentation_chain()
5568            .iter()
5569            .find_map(|attrs| LineHeight::from_attrs(attrs))
5570    }
5571
5572    /// The size in force at the caret, or `None` for the theme's own — the
5573    /// entry a size menu shows ticked.
5574    ///
5575    /// Run-level, so the chain starts one node deeper: the attributed span the
5576    /// caret stands in, then its block, then the `div`s around it. The nearest
5577    /// wins, which is the rule the walker draws by.
5578    ///
5579    /// A name or a value, whichever the nearest node wrote. A `data-size` the
5580    /// grammar does not cover — a `huge` from elsewhere — is not a size this
5581    /// can answer, so the answer is `None` and the menu ticks *Default*, the
5582    /// same thing it did before the vocabulary opened.
5583    pub fn font_size_at_caret(&mut self) -> Option<FontSize> {
5584        self.presentation_chain()
5585            .iter()
5586            .find_map(|attrs| FontSize::from_attrs(attrs))
5587    }
5588
5589    /// The face in force at the caret, or `None` for the theme's body face.
5590    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer.
5591    pub fn font_family_at_caret(&mut self) -> Option<FontFace> {
5592        self.presentation_chain()
5593            .iter()
5594            .find_map(|attrs| FontFace::from_attrs(attrs))
5595    }
5596
5597    /// The *text* colour in force at the caret, or `None` for the theme's.
5598    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer, and not
5599    /// [`mark_color_at_caret`](Self::mark_color_at_caret) — that one reads a
5600    /// highlight's background off a `mark`, and a `mark` is never in this chain.
5601    pub fn text_color_at_caret(&mut self) -> Option<TextColor> {
5602        self.presentation_chain()
5603            .iter()
5604            .find_map(|attrs| TextColor::from_attrs(attrs))
5605    }
5606
5607    /// The selection-or-caret half of the three run-level gestures: a span over
5608    /// a real selection, the caret's block over none.
5609    fn set_run_attr(&mut self, what: &str, key: &str, value: Option<&str>) {
5610        match self.selection() {
5611            Some((start, end)) => {
5612                let attrs = with_attr(&self.run_attrs_over(start, end), key, value);
5613                self.write_run_attrs(what, start, end, attrs);
5614            }
5615            None => {
5616                let own = self.block_attrs_at_caret();
5617                if value.is_none()
5618                    && self.refuse_clear_from_div(what, &own, |a| a.iter().any(|(k, _)| k == key))
5619                {
5620                    return;
5621                }
5622                let attrs = with_attr(&own, key, value);
5623                self.write_block_attrs(what, attrs);
5624            }
5625        }
5626    }
5627
5628    /// A clear this gesture cannot carry out, said out loud instead of written:
5629    /// the node it rewrites — the caret's block, or the `<div>` around it that
5630    /// [`block_attrs_at_caret`](Self::block_attrs_at_caret) folds to in Markdown
5631    /// — does not name the property at all, and a `div` further out does.
5632    ///
5633    /// Handing twig the block's attributes with the key already absent changes
5634    /// no byte, and the query goes on answering `Some` off the div: the menu
5635    /// entry the author pressed stays unticked, and nothing says why. Twig's
5636    /// `set_block_attrs` reaches one node, so leaf cannot clear a key it did not
5637    /// write on a node it is not rewriting — the honest answer is the status
5638    /// line, in the voice the other refusals use.
5639    ///
5640    /// `names` is the property's own reading of an attribute list, because
5641    /// alignment lives in a `class` token rather than a key of its own. Spans
5642    /// are skipped: one inside the block is not what a *block* gesture writes
5643    /// either, but neither is it "the div around the block", and the run-level
5644    /// gestures reach it through a selection.
5645    fn refuse_clear_from_div(
5646        &mut self,
5647        what: &str,
5648        own: &Attrs,
5649        names: impl Fn(&Attrs) -> bool,
5650    ) -> bool {
5651        if names(own) {
5652            return false;
5653        }
5654        let caret = self.caret.min(self.source.len());
5655        if !self
5656            .attr_chain_at(caret)
5657            .iter()
5658            .any(|(span, attrs)| !span && names(attrs))
5659        {
5660            return false;
5661        }
5662        self.status = Some(format!("{what}: set on the div around the block"));
5663        true
5664    }
5665
5666    /// Hand `attrs` to twig as the caret's block's whole attribute set, with the
5667    /// status, undo and caret plumbing [`set_mark_color`](Self::set_mark_color)
5668    /// has.
5669    ///
5670    /// **The caret keeps its place in the text, not its byte offset.** How a
5671    /// format spells a block's attributes is markup written *around* the block
5672    /// — djot's `{…}` line above it, a `<div …>` and two blank lines in front of
5673    /// it in Markdown, a longer opening tag in HTML — and every one of those
5674    /// grows or shrinks above the author's own bytes. Where twig's change
5675    /// rewrites the block whole (Markdown's div is spliced as one region, block
5676    /// included) the plain arithmetic of [`reanchor`] has nothing to shift by
5677    /// and parks the caret at the end of the splice, past the closing `</div>`:
5678    /// the caret is then in no block at all, so a second press of the same menu
5679    /// answers "no block at the caret" and the toolbar's queries read nothing.
5680    /// [`reanchor_in_block`] is what carries it across instead — the block's
5681    /// content span before and after, which is the one thing the respelling
5682    /// leaves alone.
5683    ///
5684    /// Read *before* the splice and applied *after* `refresh`, because both
5685    /// halves of that mapping are facts about a tree twig is between: the
5686    /// block's old bytes are gone once the edit lands, and its new ones are not
5687    /// in `self.source` until the refresh puts them there.
5688    fn write_block_attrs(&mut self, what: &str, attrs: Attrs) {
5689        if self.read_only || self.refuse_unsupported(what, Gesture::SetBlockAttrs) {
5690            return;
5691        }
5692        // A blank line has no block to carry an attribute, and twig answers
5693        // `NotFound` there — say so in leaf's own words instead.
5694        let Some(at) = self.block_offset_for_caret() else {
5695            self.status = Some(format!("{what}: no block at the caret"));
5696            return;
5697        };
5698        self.record_caret();
5699        let pairs = attr_pairs(&attrs);
5700        let was = self.block_content_at(at);
5701        let text = was.clone().map(|s| self.source[s].to_string());
5702        match self.editor.set_block_attrs(at, &pairs) {
5703            Ok(change) => {
5704                let (caret, anchor) = (self.caret, self.anchor);
5705                self.last_edit_kind = None; // structural edit is its own undo step
5706                self.refresh();
5707                let now = self.block_content_in(&change.new, text.as_deref());
5708                // A block the two halves cannot both name — a code block, a
5709                // caret in a list's marker — takes the plain arithmetic, which
5710                // is what it had before.
5711                let block = was.as_ref().zip(now.as_ref());
5712                self.caret = reanchor_in_block(caret, &change, block);
5713                self.anchor = anchor.map(|a| reanchor_in_block(a, &change, block));
5714                self.dirty = self.source != self.clean_source;
5715                self.status = None;
5716                // The clamp reads the caret floor off the map, and this edit
5717                // can move the floor: taking the `{…}` line off a djot
5718                // document's first block moves the first rendered offset to 0,
5719                // and a floor read from the old map stood the caret past the
5720                // block's text. So the map is this revision's before the clamp
5721                // — see `open_paragraph_at_block_edge`.
5722                self.rebuild_map();
5723                self.clamp_caret();
5724                self.record_caret();
5725            }
5726            Err(e) => self.status = Some(format!("{what}: {e}")),
5727        }
5728    }
5729
5730    /// The content span of the innermost paragraph or heading covering `off` —
5731    /// the author's own bytes, without the `# ` or the `<p>` that spells the
5732    /// block around them.
5733    ///
5734    /// The same two kinds [`block_attrs_at_caret`](Self::block_attrs_at_caret)
5735    /// reads, so that what a gesture re-anchors by is the block it wrote to.
5736    fn block_content_at(&mut self, off: usize) -> Option<Range<usize>> {
5737        self.nodes()
5738            .into_iter()
5739            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
5740            .filter(|n| n.span.start <= off && off <= n.span.end)
5741            .min_by_key(|n| n.span.end - n.span.start)
5742            .map(|n| n.content_span.unwrap_or(n.span))
5743    }
5744
5745    /// [`block_content_at`](Self::block_content_at)'s other half: the content
5746    /// span of the block `region` holds now, found by the bytes it held before.
5747    ///
5748    /// Matched on the text rather than taken as the first block in the region,
5749    /// because a rewritten region is markup and all — `<div class="center">`
5750    /// carries words of its own — and because the block this gesture moved is
5751    /// the one whose content the respelling did not touch. `None` where the
5752    /// region holds no block at all, which is djot's every case: the `{…}` line
5753    /// is spliced above the block and the block itself never moves through the
5754    /// change at all, only past it.
5755    fn block_content_in(
5756        &mut self,
5757        region: &Range<usize>,
5758        text: Option<&str>,
5759    ) -> Option<Range<usize>> {
5760        let text = text?;
5761        let spans: Vec<Range<usize>> = self
5762            .nodes()
5763            .into_iter()
5764            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
5765            .filter(|n| region.start <= n.span.start && n.span.end <= region.end)
5766            .map(|n| n.content_span.unwrap_or(n.span))
5767            .collect();
5768        spans
5769            .into_iter()
5770            .find(|s| self.source.get(s.clone()) == Some(text))
5771    }
5772
5773    /// Hand `attrs` to twig as the attribute set of the span over `[start,
5774    /// end)` — wrapping one, or re-styling the one the range already lies in,
5775    /// or unwrapping it when `attrs` is empty.
5776    ///
5777    /// What the splice leaves selected is the span's **content** — the author's
5778    /// words — and not the whole of `change.new`, which is markup and all:
5779    /// `[big]{data-size="large"}` in djot, `<span …>big</span>` in Markdown. A
5780    /// selection reaching past the node's own span lies in no span at all, so a
5781    /// second press of the menu would nest a fresh one instead of re-styling
5782    /// the one just written.
5783    fn write_run_attrs(&mut self, what: &str, start: usize, end: usize, attrs: Attrs) {
5784        if self.read_only || self.refuse_unsupported(what, Gesture::WrapRangeAttrs) {
5785            return;
5786        }
5787        self.record_caret();
5788        let pairs = attr_pairs(&attrs);
5789        match self.editor.wrap_range_attrs(start, end, &pairs) {
5790            Ok(change) => {
5791                self.last_edit_kind = None;
5792                self.refresh();
5793                let content = self.span_content_in(&change.new);
5794                self.anchor = Some(content.start);
5795                self.caret = content.end;
5796                self.dirty = self.source != self.clean_source;
5797                self.status = None;
5798                self.clamp_caret();
5799                self.record_caret();
5800            }
5801            Err(e) => self.status = Some(format!("{what}: {e}")),
5802        }
5803    }
5804
5805    /// The content range of the attributed span `spliced` now holds — the
5806    /// outermost one inside it, since that is the one just written — or
5807    /// `spliced` itself where the splice left no span, which is what an unwrap
5808    /// leaves behind.
5809    fn span_content_in(&mut self, spliced: &Range<usize>) -> Range<usize> {
5810        self.nodes()
5811            .into_iter()
5812            .filter(wysiwyg::is_run_span)
5813            .filter(|n| spliced.start <= n.span.start && n.span.end <= spliced.end)
5814            .max_by_key(|n| n.span.end - n.span.start)
5815            .and_then(|n| n.content_span)
5816            .unwrap_or_else(|| spliced.clone())
5817    }
5818
5819    /// The attribute set `set_block_attrs` is about to **replace** at the caret
5820    /// — which is the block's own, except in Markdown, where twig writes a
5821    /// block's attributes onto a `<div>` around it and rewrites that div when
5822    /// the block is its sole child. Reading the paragraph there would hand back
5823    /// an empty list and quietly drop everything the div said.
5824    ///
5825    /// Empty when the caret is in no block at all, which is the same list a
5826    /// block carrying no attributes gives — and the right one either way, since
5827    /// the gesture then refuses on its own.
5828    fn block_attrs_at_caret(&mut self) -> Attrs {
5829        let Some(off) = self.block_offset_for_caret() else {
5830            return Vec::new();
5831        };
5832        let nodes = self.nodes();
5833        let Some(block) = nodes
5834            .iter()
5835            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
5836            .filter(|n| n.span.start <= off && off <= n.span.end)
5837            .min_by_key(|n| n.span.end - n.span.start)
5838        else {
5839            return Vec::new();
5840        };
5841        if self.format == Format::Markdown
5842            && let Some(parent) = block.parent.and_then(|p| nodes.iter().find(|n| n.id == p))
5843            && wysiwyg::element_tag(parent) == Some("div")
5844            && nodes.iter().filter(|n| n.parent == Some(parent.id)).count() == 1
5845        {
5846            return parent.attrs.clone();
5847        }
5848        block.attrs.clone()
5849    }
5850
5851    /// The attribute set `wrap_range_attrs` is about to **replace** over
5852    /// `[start, end)` — the innermost attributed span the range lies inside,
5853    /// which twig re-styles rather than nesting a second one in. Empty when the
5854    /// range lies in no span, where the gesture mints a fresh one.
5855    fn run_attrs_over(&mut self, start: usize, end: usize) -> Attrs {
5856        self.nodes()
5857            .into_iter()
5858            .filter(wysiwyg::is_run_span)
5859            .filter(|n| n.span.start <= start && end <= n.span.end)
5860            .min_by_key(|n| n.span.end - n.span.start)
5861            .map(|n| n.attrs)
5862            .unwrap_or_default()
5863    }
5864
5865    /// The attribute lists that bear on a presentation query, **nearest first**:
5866    /// the attributed spans the caret stands in (innermost first), then its
5867    /// block, then the `div`s around it. A `find_map` down this is the whole of
5868    /// each query, and the order is the rule the walker draws by.
5869    ///
5870    /// Read at the caret, and at the selection's *start* when the caret stands
5871    /// in no span there. [`write_run_attrs`](Self::write_run_attrs) leaves the
5872    /// caret one past the span it just wrote — `toggle`'s convention — so
5873    /// asking the menu which entry that press just ticked must not answer
5874    /// `None`. Exactly the reason [`mark_offset`](Self::mark_offset) tries both.
5875    fn presentation_chain(&mut self) -> Vec<Attrs> {
5876        let caret = self.caret.min(self.source.len());
5877        let mut chain = self.attr_chain_at(caret);
5878        if !chain.iter().any(|(span, _)| *span)
5879            && let Some((start, _)) = self.selection()
5880        {
5881            let alt = self.attr_chain_at(start);
5882            if alt.iter().any(|(span, _)| *span) {
5883                chain = alt;
5884            }
5885        }
5886        chain.into_iter().map(|(_, attrs)| attrs).collect()
5887    }
5888
5889    /// [`presentation_chain`](Self::presentation_chain) at one offset — every
5890    /// node bearing the vocabulary that covers it, innermost first, each paired
5891    /// with whether it is an attributed span (which is what tells the caller
5892    /// its run-level answer came from a run).
5893    ///
5894    /// Sorted by span length, which *is* the nesting order: a span lies inside
5895    /// its block and a block inside its div, so shortest-first is
5896    /// nearest-first without a second tree walk.
5897    fn attr_chain_at(&mut self, off: usize) -> Vec<(bool, Attrs)> {
5898        let off = off.min(self.source.len());
5899        let mut hits: Vec<(usize, bool, Attrs)> = Vec::new();
5900        for n in self.nodes() {
5901            let span = wysiwyg::is_run_span(&n);
5902            let block = matches!(n.kind, Kind::Para | Kind::Heading);
5903            let div = wysiwyg::element_tag(&n) == Some("div");
5904            if !(span || block || div) {
5905                continue;
5906            }
5907            // A span is half-open, the way a mark is: the offset one past it is
5908            // the text after it. A block and a div claim their end too, so a
5909            // caret resting at the end of a line still reads its paragraph.
5910            let inside = if span {
5911                n.span.start <= off && off < n.span.end
5912            } else {
5913                n.span.start <= off && off <= n.span.end
5914            };
5915            if !inside {
5916                continue;
5917            }
5918            hits.push((n.span.end - n.span.start, span, n.attrs));
5919        }
5920        hits.sort_by_key(|(len, _, _)| *len);
5921        hits.into_iter()
5922            .map(|(_, span, attrs)| (span, attrs))
5923            .collect()
5924    }
5925
5926    /// Convert the block at the caret to a heading level or paragraph.
5927    pub fn set_block(&mut self, kind: BlockKind) {
5928        // The read-only gate — this door reaches twig without the splice.
5929        if self.read_only {
5930            return;
5931        }
5932        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::SetBlock) {
5933            return;
5934        }
5935        self.record_caret();
5936        // A blank line has no node to convert, and twig opens a block there
5937        // rather than declining — so the caret's own offset is the right thing
5938        // to hand it when `block_offset_for_caret` finds nothing.
5939        let offset = self.block_offset_for_caret().unwrap_or(self.caret);
5940        match self.editor.set_block(offset, kind) {
5941            Ok(change) => {
5942                self.last_edit_kind = None;
5943                self.refresh();
5944                // Opening a block on a blank line writes a marker the caret
5945                // belongs *after*; converting an existing one moves nothing.
5946                self.caret = self.caret.max(change.new.end);
5947                self.clamp_caret();
5948                self.anchor = None;
5949                self.dirty = self.source != self.clean_source;
5950                self.status = None;
5951                self.record_caret();
5952            }
5953            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
5954        }
5955    }
5956
5957    /// Whether `off` is inside a text block (paragraph, heading, code block…).
5958    fn has_block_at(&mut self, off: usize) -> bool {
5959        self.editor.ancestors_at(off).ok().is_some_and(|chain| {
5960            chain
5961                .iter()
5962                .any(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
5963        })
5964    }
5965
5966    /// The offset to hand twig's `set_block`: the caret when it is already inside
5967    /// a block, otherwise nudged onto the previous character (a caret at a line
5968    /// end sits at the doc level, outside the block). `None` when the caret is on
5969    /// a blank line — a new paragraph with no block node to convert.
5970    fn block_offset_for_caret(&mut self) -> Option<usize> {
5971        let caret = self.caret.min(self.source.len());
5972        if self.has_block_at(caret) {
5973            return Some(caret);
5974        }
5975        // Nudge to the previous character — but never across a newline: that would
5976        // target the previous block, and a blank line genuinely has no block.
5977        if let Some((i, ch)) = self.source[..caret].char_indices().next_back()
5978            && ch != '\n'
5979            && self.has_block_at(i)
5980        {
5981            return Some(i);
5982        }
5983        None
5984    }
5985
5986    /// The heading level of the text block at the caret, or `None` when that
5987    /// block is not a heading.
5988    pub fn current_heading_level(&mut self) -> Option<u32> {
5989        let caret = self.caret;
5990        self.nodes()
5991            .into_iter()
5992            .filter(|n| n.kind == Kind::Heading)
5993            .find(|n| n.span.start <= caret && caret <= n.span.end)
5994            .and_then(|n| n.level)
5995    }
5996
5997    /// The inline marks in force at the caret (or over the selection) — what a
5998    /// toolbar draws lit, and the block-level [`Doc::current_heading_level`]'s
5999    /// inline counterpart. Cheap enough to call every frame: one twig
6000    /// `ancestors_at` query per caret (two with a selection), each walking root
6001    /// → deepest node at one offset. It never snapshots the tree the way
6002    /// `current_heading_level` does, and the returned set is a `Copy` bitset, so
6003    /// the only allocation is twig's own small ancestor `Vec`.
6004    ///
6005    /// **A selection reports a mark only when the mark covers *all* of it.**
6006    /// That's what every real toolbar means by an active button — Bold lit over
6007    /// a half-bold selection would claim a press turns bold *off*, when
6008    /// [`Doc::toggle`] hands the range to twig and gets the whole thing bolded.
6009    /// Whole-coverage is asked as "is the same mark node standing over both the
6010    /// first and the last character?": inline nodes are contiguous, so one node
6011    /// covering both ends covers every byte between them. Two touching runs
6012    /// (`**a****b**`) are two nodes, and correctly light nothing.
6013    ///
6014    /// At a bare caret a mark is active when the caret stands inside the mark's
6015    /// span — `span.start <= caret < span.end`, delimiters included, which is
6016    /// what makes the boundaries behave. In `a **bold** b` the offsets from the
6017    /// opening `*` (2) through the last byte of the closing `**` (9) are all
6018    /// bold, so the WYSIWYG caret both before `b` and after `d` (the delimiters
6019    /// are hidden, and those offsets are 4 and 8) reports bold — matching where
6020    /// typing would actually land inside the marked run. The offset one past the
6021    /// mark (10) is the text after it and reports nothing, at the end of the
6022    /// buffer exactly as in the middle.
6023    pub fn active_inline_marks(&mut self) -> InlineMarks {
6024        let Some((start, end)) = self.selection() else {
6025            // The marks actually in force at the caret, flipped by any armed
6026            // sticky delta — so `⌘b` at a bare caret lights the Bold button
6027            // immediately, before a single character is typed.
6028            let base: InlineMarks = self
6029                .marks_at(self.caret)
6030                .into_iter()
6031                .map(|(k, _)| k)
6032                .collect();
6033            return base.xor(self.pending_here());
6034        };
6035        // The selection's *last character*, not its exclusive end: `end` is the
6036        // offset one past the selection, which for a selection ending exactly at
6037        // a mark's close is already outside it (`[4,10)` of `a **bold** b` is
6038        // entirely bold, but offset 10 is the space after).
6039        let last = prev_boundary(&self.source, end);
6040        let head = self.marks_at(start);
6041        let tail = self.marks_at(last);
6042        head.into_iter()
6043            .filter(|m| tail.contains(m))
6044            .map(|(k, _)| k)
6045            .collect()
6046    }
6047
6048    /// The inline marks whose span covers `off`, each with the id of the node
6049    /// carrying it — the id is what lets a selection tell one mark node from
6050    /// another of the same kind.
6051    fn marks_at(&mut self, off: usize) -> Vec<(InlineKind, u32)> {
6052        let off = off.min(self.source.len());
6053        self.editor
6054            .ancestors_at(off)
6055            .unwrap_or_default()
6056            .into_iter()
6057            // `span.end` is the offset one *past* the mark, so it isn't in it.
6058            // twig already resolves a boundary to whatever starts there — in
6059            // `**bold** x` offset 8 is the following text, not the strong — but
6060            // when nothing follows, the tie has nobody to break for and the
6061            // chain still ends at the mark. That would make the answer at the
6062            // last offset of the document depend on whether the file happens to
6063            // end in a newline; the rule is `span.start <= off < span.end`, and
6064            // it's the same rule at the end of a buffer as in the middle.
6065            .filter(|m| off < m.span.end)
6066            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.node_id)))
6067            .collect()
6068    }
6069
6070    /// Toggle a heading at the caret: if the block is already this heading level,
6071    /// revert it to a paragraph; otherwise convert it to this heading level.
6072    /// This gives the heading commands the same toggle feel as bold/italic/code —
6073    /// re-applying a heading a line already has turns it back into body text.
6074    pub fn toggle_heading(&mut self, level: u32) {
6075        if self.current_heading_level() == Some(level) {
6076            self.set_block(BlockKind::Paragraph);
6077        } else {
6078            self.set_block(BlockKind::Heading(level));
6079        }
6080    }
6081
6082    /// Toggle a block quote around the selection, or around the block at the
6083    /// caret — the toolbar's Quote button.
6084    pub fn toggle_blockquote(&mut self) {
6085        self.toggle_container(BlockContainerKind::BlockQuote);
6086    }
6087
6088    /// Toggle a numbered (`ordered`) or bulleted list over the selection, or
6089    /// over the block at the caret — one op with the kind as a flag, the way
6090    /// `toggle_heading` takes its level, so a frontend needs no twig type to
6091    /// name the two buttons.
6092    ///
6093    /// Pressing the *other* list's button while in a list converts in place
6094    /// rather than nesting, so the pair reads as one three-state control
6095    /// (bulleted / numbered / neither) rather than two independent wrappers.
6096    pub fn toggle_list(&mut self, ordered: bool) {
6097        self.toggle_container(if ordered {
6098            BlockContainerKind::OrderedList
6099        } else {
6100            BlockContainerKind::BulletList
6101        });
6102    }
6103
6104    /// Toggle a fenced code block over the selection, or over the block at the
6105    /// caret — the toolbar's Code Block button, and the only way the rich view
6106    /// offers to open one: a typed backtick is escaped there, since it is a
6107    /// character the author wrote and not markup they meant.
6108    ///
6109    /// Fencing is twig's ([`Editor::toggle_code_block`]): it measures the fence
6110    /// against the body, keeps a quote's `> ` on every line, and peels a fence
6111    /// (or dedents an indented block) on the way back. What is leaf's is the
6112    /// shape twig declines: a blank line holds no block to fence, and the
6113    /// gesture nobody should have to learn is "type something first" — so leaf
6114    /// spells the empty fence itself, with the caret on the empty line inside it
6115    /// and a blank line either side, which is what typing into a new block and
6116    /// then Backspacing out of it would have left.
6117    ///
6118    /// Inside a list item twig fences at the item's content column and keeps
6119    /// the marker (a task item's box too) on the opening fence's line, so the
6120    /// block stays the item's; unfencing puts the marker back on the text.
6121    /// What twig still refuses — an AsciiDoc item's own first line — is
6122    /// reported rather than worked around.
6123    pub fn toggle_code_block(&mut self) {
6124        // The read-only gate — this door reaches twig without the splice.
6125        if self.read_only {
6126            return;
6127        }
6128        if self.refuse_unsupported("code block", Gesture::ToggleCodeBlock) {
6129            return;
6130        }
6131        let selected = self.selection();
6132        // The caret at a code block's rows resolves to its *content*, and twig
6133        // finds the block from any offset inside its span — but a caret parked
6134        // on the closing fence's own line end is past it, so the block's start
6135        // is handed over whenever the caret is in one at all.
6136        let (start, end) = match selected {
6137            Some(range) => range,
6138            None => match self.code_block_start_at_caret() {
6139                Some(start) => (start, start),
6140                None => match self.block_offset_for_caret() {
6141                    Some(off) => (off, off),
6142                    None => return self.open_empty_code_block(),
6143                },
6144            },
6145        };
6146        self.record_caret();
6147        match self.editor.toggle_code_block(start, end, None) {
6148            Ok(change) => {
6149                // Read the caret's place out of the *pre-edit* source, before
6150                // `refresh` swaps it out — and how many lines the region held,
6151                // which is what says whether a fence line went in above the
6152                // caret's line or came off it.
6153                let place = selected
6154                    .is_none()
6155                    .then(|| self.caret_line_tail(&change.old));
6156                let old_lines = self.source[change.old.clone()].matches('\n').count();
6157                self.last_edit_kind = None; // structural edit is its own undo step
6158                self.refresh();
6159                match place {
6160                    // From a selection: keep the block selected, so a second
6161                    // press reverses the first (twig unfences from any offset in
6162                    // the fence's span, the region's start included).
6163                    None => {
6164                        self.anchor = Some(change.new.start);
6165                        self.caret = change.new.end;
6166                    }
6167                    // From a caret: the same line, the same distance from its
6168                    // end, shifted by the opening fence that was written above
6169                    // it (or peeled off). Dedenting an indented block keeps the
6170                    // lines one-to-one, and shifts nothing.
6171                    Some((line, tail)) => {
6172                        let new_lines = self.source[change.new.start.min(self.source.len())
6173                            ..change.new.end.min(self.source.len())]
6174                            .matches('\n')
6175                            .count();
6176                        let line = match new_lines.cmp(&old_lines) {
6177                            std::cmp::Ordering::Greater => line + 1,
6178                            std::cmp::Ordering::Less => line.saturating_sub(1),
6179                            std::cmp::Ordering::Equal => line,
6180                        };
6181                        self.anchor = None;
6182                        self.caret = self.line_tail_offset(&change.new, (line, tail));
6183                    }
6184                }
6185                self.dirty = self.source != self.clean_source;
6186                self.status = None;
6187                self.clamp_caret();
6188                self.record_caret();
6189            }
6190            Err(e) => self.status = Some(format!("code block: {e}")),
6191        }
6192    }
6193
6194    /// Write an empty fenced block on the blank line the caret stands on, and
6195    /// put the caret on the empty line inside it — the half of
6196    /// [`toggle_code_block`](Self::toggle_code_block) that is leaf's, because
6197    /// twig reports `NotFound` for a range no block covers.
6198    ///
6199    /// Inside a quote the fence lines and the empty line keep the quote's
6200    /// prefix, as twig's own fencing does. A blank line goes in on whichever
6201    /// side has text against it, since a fence may interrupt a paragraph in
6202    /// Markdown but a block standing tight against its neighbours is not the
6203    /// document any editor writes.
6204    fn open_empty_code_block(&mut self) {
6205        let caret = self.caret.min(self.source.len());
6206        let prefix = self.quote_prefix_at(caret);
6207        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
6208        let line_end = self.source[caret..]
6209            .find('\n')
6210            .map_or(self.source.len(), |i| caret + i);
6211        let prev_blank = line_start == 0
6212            || self.source[..line_start - 1]
6213                .rsplit('\n')
6214                .next()
6215                .is_some_and(|l| l.trim_start_matches(['>', ' ']).is_empty());
6216        let next_blank = line_end >= self.source.len()
6217            || self.source[line_end + 1..]
6218                .split('\n')
6219                .next()
6220                .is_some_and(|l| l.trim_start_matches(['>', ' ']).is_empty());
6221        // A blank line inside a quote is a bare `>`: the space after it is
6222        // the content's, and there is none.
6223        let blank = prefix.trim_end();
6224        let mut text = String::new();
6225        if !prev_blank {
6226            text.push_str(blank);
6227            text.push('\n');
6228        }
6229        text.push_str(&prefix);
6230        text.push_str("```\n");
6231        text.push_str(&prefix);
6232        let inside = text.len();
6233        text.push('\n');
6234        text.push_str(&prefix);
6235        text.push_str("```");
6236        if !next_blank {
6237            text.push('\n');
6238            text.push_str(blank);
6239        }
6240        // Over whatever the blank line held (its quote prefix, trailing
6241        // spaces), so the block's own prefix is the one twig will read back.
6242        let at = line_start;
6243        if !self.splice(at, line_end, &text, EditKind::Other) {
6244            return;
6245        }
6246        self.caret = at + inside;
6247        self.anchor = None;
6248        self.clamp_caret();
6249        self.record_caret();
6250    }
6251
6252    /// Whether the caret stands in a code block, fenced or indented — what
6253    /// lights the Code Block button. Wider than
6254    /// [`caret_in_fenced_code`](Self::caret_in_fenced_code), which asks the
6255    /// narrower question a language prompt needs.
6256    pub fn caret_in_code_block(&mut self) -> bool {
6257        self.code_block_start_at_caret().is_some()
6258    }
6259
6260    /// Whether the caret stands anywhere inside a block quote, however deep —
6261    /// what lights the Block Quote button. A quote is a container rather than
6262    /// a block kind, so this is true alongside a heading or a code block, not
6263    /// instead of one.
6264    pub fn caret_in_blockquote(&mut self) -> bool {
6265        let off = self.caret.min(self.source.len());
6266        // A quote's span stops short of its closing newline, so the end of its
6267        // last line is `span.end` itself, and has to count.
6268        self.nodes()
6269            .into_iter()
6270            .any(|n| n.kind == Kind::BlockQuote && n.span.start <= off && off <= n.span.end)
6271    }
6272
6273    // ── Task list items ──────────────────────────────────────────────────────
6274    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
6275    // inline content of the item's first paragraph rather than part of its
6276    // marker, so adding or removing one must leave the item's continuation
6277    // indentation alone, and an item inside a quote is found past the quote
6278    // markers. leaf names the gesture and the offset; the spelling is twig's.
6279
6280    /// Whether the list item at the caret carries a checkbox, and which way it
6281    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
6282    /// item or no item at all. What a toolbar reads to light its checkbox button.
6283    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
6284        self.task_checked_at(self.caret)
6285    }
6286
6287    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
6288    /// offset — what a frontend asks before deciding a click landed on a box.
6289    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
6290        self.innermost_list_item(offset.min(self.source.len()))?
6291            .checked
6292    }
6293
6294    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
6295    /// A no-op with a reported reason when the caret is in no task item — minting
6296    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
6297    pub fn toggle_task_checked(&mut self) {
6298        self.toggle_task_at(self.caret);
6299    }
6300
6301    /// Tick or untick the task item covering `offset` — what a *click* on a
6302    /// rendered checkbox is. Separate from the caret form because a click carries
6303    /// its own offset and must not first move the caret there: ticking a box
6304    /// three paragraphs away should not take the cursor with it.
6305    pub fn toggle_task_at(&mut self, offset: usize) {
6306        // The read-only gate — this door reaches twig without the splice.
6307        if self.read_only {
6308            return;
6309        }
6310        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
6311            return;
6312        }
6313        let offset = offset.min(self.source.len());
6314        self.record_caret();
6315        match self.editor.toggle_task_checked(offset) {
6316            Ok(_) => self.after_task_edit(),
6317            Err(e) => self.status = Some(format!("task: {e}")),
6318        }
6319    }
6320
6321    /// Give the list item at the caret a checkbox, or take its checkbox away —
6322    /// the gesture that converts between a plain bullet and a task. A new box
6323    /// arrives unticked.
6324    ///
6325    /// Outside a list the caret's block becomes a bullet first, and the box
6326    /// goes on the new item — one undo step. twig's gesture only converts an
6327    /// item that is already there, and a Checklist button that did nothing on
6328    /// a paragraph read as broken.
6329    pub fn toggle_task_item(&mut self) {
6330        // The read-only gate — this door reaches twig without the splice.
6331        if self.read_only {
6332            return;
6333        }
6334        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
6335            return;
6336        }
6337        if self
6338            .innermost_list_item(self.caret.min(self.source.len()))
6339            .is_none()
6340        {
6341            if self.refuse_unsupported(
6342                "task",
6343                Gesture::ToggleBlockContainer(BlockContainerKind::BulletList),
6344            ) {
6345                return;
6346            }
6347            self.begin_undo_group();
6348            self.toggle_list(false);
6349            if self
6350                .innermost_list_item(self.caret.min(self.source.len()))
6351                .is_some()
6352            {
6353                self.box_item_at_caret();
6354            }
6355            self.end_undo_group();
6356            return;
6357        }
6358        self.box_item_at_caret();
6359    }
6360
6361    /// twig's half of [`toggle_task_item`](Self::toggle_task_item): the box on
6362    /// the item the caret is already in.
6363    fn box_item_at_caret(&mut self) {
6364        let caret = self.caret.min(self.source.len());
6365        self.record_caret();
6366        match self.editor.toggle_task_item(caret) {
6367            Ok(_) => self.after_task_edit(),
6368            Err(e) => self.status = Some(format!("task: {e}")),
6369        }
6370    }
6371
6372    /// Settle after a task gesture. The caret rides its old byte offset and is
6373    /// clamped back in: a box is three or four bytes on the item's first line, so
6374    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
6375    /// real stop either way.
6376    fn after_task_edit(&mut self) {
6377        self.last_edit_kind = None;
6378        self.refresh();
6379        self.anchor = None;
6380        self.dirty = self.source != self.clean_source;
6381        self.status = None;
6382        self.clamp_caret();
6383        self.record_caret();
6384    }
6385
6386    // ── Tables ───────────────────────────────────────────────────────────────
6387    // A table is a grid, and twig edits it as one — add/remove/move a row or
6388    // column, set a column's alignment — re-spelling the whole table in a single
6389    // splice. Every gesture is anchored at the caret's cell. leaf just names the
6390    // gesture and re-reads the result; the whole table's numbering, borders, and
6391    // delimiter are twig's to keep straight.
6392
6393    /// Whether the caret is inside a table — what a frontend asks to enable or
6394    /// disable its table controls.
6395    ///
6396    /// An HTML `<table>` still answers `true`: the caret really is in a table,
6397    /// and the reason the grid controls stay dark there is
6398    /// [`Capabilities::table`], which is a fact about the document's format
6399    /// rather than about the caret. A frontend needs both.
6400    pub fn caret_in_table(&mut self) -> bool {
6401        let caret = self.caret.min(self.source.len());
6402        self.editor
6403            .ancestors_at(caret)
6404            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
6405            .unwrap_or(false)
6406    }
6407
6408    /// One grid op, guarded and settled — the shared body of the seven below.
6409    ///
6410    /// The guard is why this exists rather than seven copies of the same three
6411    /// lines, and it is the one guard leaf cannot delegate to twig. The table
6412    /// editor is the gesture family that consults no `Syntax` table (it spells a
6413    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
6414    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
6415    /// grid as a *pipe table* and reports success, swapping the element out for
6416    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
6417    /// downstream could tell that from a successful edit — the splice is real,
6418    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
6419    /// stopping at the door rather than detecting after the fact. See
6420    /// [`spells_pipe_tables`].
6421    fn table_op(
6422        &mut self,
6423        what: &str,
6424        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
6425    ) {
6426        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
6427            return;
6428        }
6429        self.record_caret();
6430        let at = self.caret;
6431        let r = op(&mut self.editor, at);
6432        self.apply_table(r, what);
6433    }
6434
6435    /// Insert an empty row below (`below`) or above the caret's row.
6436    pub fn table_insert_row(&mut self, below: bool) {
6437        self.table_op("table row", |e, at| e.table_insert_row(at, below));
6438    }
6439
6440    /// Delete the caret's row (not the header, not the last body row).
6441    pub fn table_delete_row(&mut self) {
6442        self.table_op("table row", |e, at| e.table_delete_row(at));
6443    }
6444
6445    /// Insert an empty column right (`right`) or left of the caret's column.
6446    pub fn table_insert_column(&mut self, right: bool) {
6447        self.table_op("table column", |e, at| e.table_insert_column(at, right));
6448    }
6449
6450    /// Delete the caret's column (unless it is the only one).
6451    pub fn table_delete_column(&mut self) {
6452        self.table_op("table column", |e, at| e.table_delete_column(at));
6453    }
6454
6455    /// Set the caret's column to `alignment`.
6456    pub fn table_set_alignment(&mut self, alignment: Alignment) {
6457        self.table_op("table alignment", |e, at| {
6458            e.table_set_alignment(at, alignment)
6459        });
6460    }
6461
6462    /// Move the caret's row one place down (`down`) or up, within the body rows.
6463    pub fn table_move_row(&mut self, down: bool) {
6464        self.table_op("table row", |e, at| e.table_move_row(at, down));
6465    }
6466
6467    /// Move the caret's column one place right (`right`) or left.
6468    pub fn table_move_column(&mut self, right: bool) {
6469        self.table_op("table column", |e, at| e.table_move_column(at, right));
6470    }
6471
6472    /// Settle the caret and document flags after a table op (or report its
6473    /// error). twig re-spells the whole table, so the caret rides its old byte
6474    /// offset and is clamped back into the rebuilt bytes — near enough to where
6475    /// it was, since the op preserves the cells' content and order around it.
6476    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
6477        match result {
6478            Ok(()) => {
6479                self.last_edit_kind = None;
6480                self.refresh();
6481                self.anchor = None;
6482                self.clamp_caret();
6483                self.dirty = self.source != self.clean_source;
6484                self.status = None;
6485                self.record_caret();
6486            }
6487            Err(e) => self.status = Some(format!("{what}: {e}")),
6488        }
6489    }
6490
6491    /// One `toggle_block_container` over the block-level target.
6492    ///
6493    /// leaf says *where*; twig decides everything else — which blocks the range
6494    /// covers, whether that means wrapping, unwrapping, nesting or converting,
6495    /// and how this document's format spells the prefix. The rule that a
6496    /// container only comes off when the range covers every block it holds is
6497    /// what the re-anchoring below is built around.
6498    fn toggle_container(&mut self, kind: BlockContainerKind) {
6499        // The read-only gate — this door reaches twig without the splice.
6500        if self.read_only {
6501            return;
6502        }
6503        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
6504            return;
6505        }
6506        let selected = self.selection();
6507        // A blank line holds no block, and twig opens an *empty* container on one
6508        // — since 3.2.0; it used to decline the range with `NotFound`, which is
6509        // why this used to lend it a scratch paragraph to wrap. Worth knowing
6510        // here because the line-for-line caret mapping below cannot describe it:
6511        // opening one under a paragraph writes the blank line the format needs
6512        // above the marker too, so the rewritten region has a line the old one
6513        // didn't, and "the same line, the same distance from its end" lands on
6514        // that new blank instead of in the container.
6515        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
6516        // Without a selection the target is the caret's own block, resolved the
6517        // way `set_block` resolves it — a caret at a line end sits at the doc
6518        // level and has to be nudged back onto the block it looks like it's in.
6519        // An empty range is enough: twig widens to the whole lines it touches.
6520        let (start, end) = match selected {
6521            Some(range) => range,
6522            None => {
6523                let off = self.block_offset_for_caret().unwrap_or(self.caret);
6524                (off, off)
6525            }
6526        };
6527        self.record_caret();
6528        match self.editor.toggle_block_container(start, end, kind) {
6529            Ok(change) => {
6530                // Read the caret's place out of the *pre-edit* source, before
6531                // `refresh` swaps that source out from under it.
6532                let place = (selected.is_none() && !opened_empty)
6533                    .then(|| self.caret_line_tail(&change.old));
6534                self.last_edit_kind = None; // structural edit is its own undo step
6535                self.refresh();
6536                match place {
6537                    // Both land the caret at the far end of what twig wrote, and
6538                    // differ only in what they leave selected.
6539                    //
6540                    // From a selection: select what the container now holds, the
6541                    // way `toggle` keeps its marked region selected — and for a
6542                    // stronger reason than symmetry: a container comes *off* only
6543                    // a range covering every block it holds, so a selection left
6544                    // on its old bytes (now short by a prefix per line) would nest
6545                    // on the second press instead of reversing the first.
6546                    //
6547                    // From a blank line: nothing to select, and the end of the
6548                    // region is exactly past the bare `> ` / `- ` twig wrote —
6549                    // the caret standing inside the container that was asked for.
6550                    None => {
6551                        self.anchor = (!opened_empty).then_some(change.new.start);
6552                        self.caret = change.new.end;
6553                    }
6554                    Some(place) => {
6555                        self.anchor = None;
6556                        self.caret = self.line_tail_offset(&change.new, place);
6557                    }
6558                }
6559                self.dirty = self.source != self.clean_source;
6560                self.status = None;
6561                self.clamp_caret();
6562                self.record_caret();
6563            }
6564            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
6565        }
6566    }
6567
6568    /// The caret's place inside the region a container toggle is rewriting, in
6569    /// the only terms the rewrite preserves: which of the region's lines it sits
6570    /// on, and how many bytes of that line lie ahead of it.
6571    ///
6572    /// A container's markup goes in at column 0 and never touches what follows
6573    /// on the line, so that pair survives the edit exactly where a byte offset
6574    /// does not — a caret left on its old offset slides back by one prefix per
6575    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
6576    /// `> ` it just asked for.
6577    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
6578        let caret = self.caret.clamp(old.start, old.end);
6579        let line = self.source[old.start..caret].matches('\n').count();
6580        let end = self.source[caret..old.end]
6581            .find('\n')
6582            .map_or(old.end, |i| caret + i);
6583        (line, end - caret)
6584    }
6585
6586    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
6587    /// region: the offset `tail` bytes back from the end of the region's `line`.
6588    ///
6589    /// Both walks are clamped rather than trusted, because the one op that does
6590    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
6591    /// the items back apart with blank lines between them — and a caret landing
6592    /// on the nearest line of the right item beats one landing out of the region
6593    /// entirely.
6594    fn line_tail_offset(
6595        &self,
6596        new: &std::ops::Range<usize>,
6597        (line, tail): (usize, usize),
6598    ) -> usize {
6599        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
6600        let mut start = 0;
6601        for _ in 0..line {
6602            match region[start..].find('\n') {
6603                Some(i) => start += i + 1,
6604                None => break,
6605            }
6606        }
6607        let end = region[start..]
6608            .find('\n')
6609            .map_or(region.len(), |i| start + i);
6610        new.start + end.saturating_sub(tail).max(start)
6611    }
6612
6613    /// Link the selection to `destination` — the toolbar's Link button. With no
6614    /// selection it acts at the caret, which re-points a link the caret is
6615    /// already standing in (twig replaces an existing link's destination and
6616    /// keeps its text) and otherwise spells a link that has no text of its own:
6617    /// an autolink (`<https://x.dev>`) where the destination is one, and
6618    /// `[destination](destination)` where it isn't.
6619    ///
6620    /// `destination` reaches twig raw. Escaping it is format knowledge and the
6621    /// two formats genuinely disagree — Markdown ends a destination at the first
6622    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
6623    /// itself — so the side holding the document is the side that gets to spell
6624    /// it. A destination twig can't carry at all (one with a newline) comes back
6625    /// as an error rather than a quietly rewritten URL.
6626    pub fn insert_link(&mut self, destination: &str) {
6627        if self.read_only || self.refuse_unsupported("link", Gesture::InsertLink) {
6628            return;
6629        }
6630        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6631        self.record_caret();
6632        match self.editor.insert_link(start, end, destination) {
6633            Ok(change) => {
6634                self.last_edit_kind = None;
6635                self.refresh();
6636                match self.link_text_span(change.new.start) {
6637                    // A link with text of its own: select it, so typing replaces
6638                    // a `[dest](dest)`'s stand-in label and a second press
6639                    // re-points what the first one linked.
6640                    Some(text) => {
6641                        self.anchor = (text.start != text.end).then_some(text.start);
6642                        self.caret = text.end;
6643                    }
6644                    // An autolink is finished the moment it's written — its text
6645                    // *is* the URL. Leaving it selected would aim the next press
6646                    // at the one shape twig still wraps instead of re-points.
6647                    None => {
6648                        self.anchor = None;
6649                        self.caret = change.new.end;
6650                    }
6651                }
6652                self.dirty = self.source != self.clean_source;
6653                self.status = None;
6654                self.clamp_caret();
6655                self.record_caret();
6656            }
6657            Err(e) => self.status = Some(format!("link: {e}")),
6658        }
6659    }
6660
6661    /// Insert a block-level image at the caret: `![alt](destination)`. Any
6662    /// selection becomes the alt text (so "select a caption, insert image" labels
6663    /// it); with no selection, `alt` is used — empty for none. The caret lands
6664    /// just past the inserted image.
6665    ///
6666    /// Both halves go through twig (`insert_literal` for the alt text,
6667    /// `insert_image` for the image), so neither is spelled here. That used to be a
6668    /// `format!`, and it was wrong the first time an app inserted a real filename:
6669    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
6670    /// not an image at all — and the fix is per-format, since moving into the
6671    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
6672    pub fn insert_image(&mut self, destination: &str, alt: &str) {
6673        if self.read_only || self.refuse_unsupported("image", Gesture::InsertImage) {
6674            return;
6675        }
6676        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6677        self.record_caret();
6678        // With no selection and an explicit `alt`, the alt text has to exist in the
6679        // document before it can be the image's — and it is raw caller input, so
6680        // it goes in through `insert_literal`, which escapes it for the format
6681        // rather than letting a `]` in someone's caption close the image early.
6682        let (start, end) = if start == end && !alt.is_empty() {
6683            match self.editor.insert_literal(start, alt) {
6684                Ok(change) => (change.new.start, change.new.end),
6685                Err(e) => {
6686                    self.status = Some(format!("image: {e}"));
6687                    return;
6688                }
6689            }
6690        } else {
6691            (start, end)
6692        };
6693        match self.editor.insert_image(start, end, destination) {
6694            Ok(change) => {
6695                self.last_edit_kind = None;
6696                self.refresh();
6697                // Just past the image, nothing selected — where a caret belongs
6698                // after inserting one.
6699                self.anchor = None;
6700                self.caret = change.new.end;
6701                self.dirty = self.source != self.clean_source;
6702                self.status = None;
6703                self.clamp_caret();
6704                self.record_caret();
6705            }
6706            Err(e) => self.status = Some(format!("image: {e}")),
6707        }
6708    }
6709
6710    /// Insert a block-level image, video, or audio at the caret. The image case
6711    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
6712    /// HTML elements, which is the only spelling Markdown and Djot have for them:
6713    ///
6714    /// ```text
6715    /// <video src="clip.mp4" controls>alt</video>
6716    /// <audio src="take.mp3" controls>alt</audio>
6717    /// ```
6718    ///
6719    /// HTML rather than a `::video{…}` directive deliberately. A directive means
6720    /// something only to an app that knows the vocabulary, so the document would
6721    /// read as literal punctuation everywhere else; `<video>` is what every other
6722    /// renderer already understands, and what leaf's own reader picks back up
6723    /// through `html_elements` promotion (see [`parse_extensions`]).
6724    ///
6725    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
6726    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
6727    /// `html_elements`. Before that only the multi-line form parsed as a block at
6728    /// all, and this wrote three lines to work around it.
6729    ///
6730    /// `controls` is always written: a player with no transport is a still frame
6731    /// the reader can't do anything with. Any selection becomes the element's
6732    /// fallback text, exactly as it becomes an image's alt.
6733    ///
6734    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
6735    /// applies, and bites harder here: a `"` in `destination` closes the
6736    /// attribute. A frontend taking these from a file picker is fine; one taking
6737    /// them from free text should keep them tame.
6738    ///
6739    /// [`MediaInfo`]: crate::MediaInfo
6740    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
6741        if kind == MediaKind::Image {
6742            return self.insert_image(destination, alt);
6743        }
6744        // Gated on the *image* gesture, not on one of its own — there isn't one,
6745        // since the bytes below are spelled here rather than by twig, and an HTML
6746        // document would in fact parse them. The button is one control with three
6747        // kinds behind it, and two of them working in a format where the third
6748        // cannot is a worse surface than three that agree — especially as
6749        // `insert_image` is the kind anyone reaches for first.
6750        if self.refuse_unsupported("media", Gesture::InsertImage) {
6751            return;
6752        }
6753        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6754        let alt_text = self
6755            .selected_text()
6756            .map(str::to_string)
6757            .unwrap_or_else(|| alt.to_string());
6758        let tag = match kind {
6759            MediaKind::Audio => "audio",
6760            _ => "video",
6761        };
6762        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
6763        self.edit(start, end, &markup);
6764    }
6765
6766    /// Append media at the **end** of the document, as a block of its own —
6767    /// the verb for a picture that *arrives* rather than one the writer
6768    /// places: an attachment imported while the caret was wherever it last
6769    /// was, a drawing placed from a tray under the body. At the caret it
6770    /// would land inline in front of whatever word the caret happened to be
6771    /// beside, which for an editor nobody has tapped yet is the first word
6772    /// of the document.
6773    ///
6774    /// The document is ended with a blank line first, where it does not
6775    /// already end with one, so the media is a paragraph of its own rather
6776    /// than a lazy continuation of the last one; an empty document needs no
6777    /// separator. Then [`insert_media`](Self::insert_media) at the new end,
6778    /// with everything that means: the same markup per kind, the same
6779    /// refusal on a format without images. The selection is dropped — the
6780    /// verb is about the end of the document, not about what was selected —
6781    /// and the caret is left past the media, as `insert_media` leaves it.
6782    pub fn append_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
6783        if self.read_only || self.refuse_unsupported("media", Gesture::InsertImage) {
6784            return;
6785        }
6786        let separator = if self.source.is_empty() || self.source.ends_with("\n\n") {
6787            ""
6788        } else if self.source.ends_with('\n') {
6789            "\n"
6790        } else {
6791            "\n\n"
6792        };
6793        let end = self.source.len();
6794        self.anchor = None;
6795        self.caret = end;
6796        if !separator.is_empty() {
6797            self.edit(end, end, separator);
6798        }
6799        self.anchor = None;
6800        self.caret = self.source.len();
6801        self.insert_media(kind, destination, alt);
6802    }
6803
6804    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
6805    /// button. Spelling and placement are both twig's; leaf used to write `---`
6806    /// itself, which was the Markdown spelling in a djot document too.
6807    ///
6808    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
6809    /// mid-paragraph and lands it after the caret's whole block. To get a rule
6810    /// *at* the caret — the paragraph parted in two around it, which is what a
6811    /// rule button is understood to do — the paragraph is first divided with
6812    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
6813    /// the offset `split_block` returns puts the rule after the *second* half
6814    /// instead, which is a rule in the right document and the wrong place.
6815    ///
6816    /// Only a plain paragraph is split, and only where there is something to
6817    /// part: at the paragraph's end the split has no second half to mint and
6818    /// would write the separator anyway — a blank line and the empty slot Enter
6819    /// leaves for the next paragraph, which the rule then lands above and
6820    /// nothing fills — so there the rule goes straight after the paragraph,
6821    /// which is where the split-and-aim was sending it regardless. At the
6822    /// paragraph's *start* the split is kept, though it parts nothing either:
6823    /// `|para` becomes `\npara` with the caret on the new blank line, and a
6824    /// rule aimed at a blank line is written on it (twig ≥ 3.5.2), which is how
6825    /// "before the paragraph" is said through a gesture that only knows
6826    /// "after" — `---\n\npara`, and `prev\n\n---\n\npara` mid-document. Everywhere
6827    /// else the rule simply lands after the block, which is both twig's own
6828    /// answer and the better one: splitting a fenced code block would leave two
6829    /// fences with a rule between them, and splitting a list item would mint an
6830    /// item nobody asked for on the way to a rule that lands after the list
6831    /// regardless. A table and a setext heading refuse the split outright, so
6832    /// they take the same path by themselves.
6833    ///
6834    /// The caret ends on the line under the rule, which is where the writer
6835    /// goes on: at the start of the paragraph's second half when the rule
6836    /// parted one, and otherwise on an empty line opened under the rule — see
6837    /// [`stand_under_block`](Self::stand_under_block). It used to be left at
6838    /// the end of what twig wrote, which is the rule's own row: the caret was
6839    /// drawn beside the rule, and mid-document the next keystroke joined the
6840    /// block below.
6841    pub fn insert_thematic_break(&mut self) {
6842        if self.read_only || self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak)
6843        {
6844            return;
6845        }
6846        self.caret = self.skip_trailing_close_delims(self.caret);
6847        // A selection is replaced by the rule, so collapse it first and let the
6848        // split-and-rule below run from the caret it leaves behind.
6849        if let Some((s, e)) = self.selection() {
6850            self.splice(s, e, "", EditKind::Other);
6851        }
6852        self.anchor = None;
6853        self.record_caret();
6854        let at = self.caret;
6855        // A failure here is not fatal: the rule still lands after the block,
6856        // which is exactly what this call was trying to improve on.
6857        let parted = self.part_for_block(at);
6858        match self.editor.insert_thematic_break(at) {
6859            Ok(change) => {
6860                self.last_edit_kind = None;
6861                self.refresh();
6862                if parted {
6863                    self.coalesce_last_undo();
6864                }
6865                self.anchor = None;
6866                self.caret = change.new.end;
6867                self.dirty = self.source != self.clean_source;
6868                self.status = None;
6869                self.clamp_caret();
6870                self.record_caret();
6871                self.caret_under_written_block(change.new, parted);
6872            }
6873            Err(e) => self.status = Some(format!("thematic break: {e}")),
6874        }
6875    }
6876
6877    /// Part the bare paragraph at `at` for a block gesture, where
6878    /// [`caret_parts_bare_paragraph`](Self::caret_parts_bare_paragraph) says
6879    /// to, and say whether it was parted.
6880    ///
6881    /// The split is counted as a step of its own, so the gesture can fold the
6882    /// block it writes next into it. It used to go to twig uncounted: twig
6883    /// kept it as a step and leaf's count did not, so one Undo took back the
6884    /// block and left the paragraph parted, with Undo then reporting nothing
6885    /// left to undo.
6886    fn part_for_block(&mut self, at: usize) -> bool {
6887        if !self.caret_parts_bare_paragraph() || self.editor.split_block(at).is_err() {
6888            return false;
6889        }
6890        self.refresh();
6891        true
6892    }
6893
6894    /// Where a block gesture leaves the caret once twig has written the block
6895    /// `new` spans — a rule, a page break: on the line under it. That is the
6896    /// start of the paragraph's second half when the gesture `parted` one,
6897    /// and otherwise the line [`stand_under_block`](Self::stand_under_block)
6898    /// finds or writes, folded into the gesture's step.
6899    ///
6900    /// The block is the outermost node twig's change opens, whatever its
6901    /// kind, since the kind a leaf directive comes back as is the format's.
6902    fn caret_under_written_block(&mut self, new: Range<usize>, parted: bool) {
6903        let block = self
6904            .nodes()
6905            .into_iter()
6906            .filter(|n| n.kind != Kind::Doc && new.contains(&n.span.start))
6907            .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)));
6908        let Some(block) = block else {
6909            return;
6910        };
6911        let (end, _) = wysiwyg::block_line(&self.source, block.span.end);
6912        if parted {
6913            // The second half starts at the first text under the block; the
6914            // split left it no leading whitespace.
6915            let rest = &self.source[end..];
6916            self.caret = end + (rest.len() - rest.trim_start().len());
6917            self.record_caret();
6918        } else if self.stand_under_block(end) {
6919            self.coalesce_last_undo();
6920        }
6921    }
6922
6923    /// Stand the caret on the line under the block whose last line's text ends
6924    /// at `end` — a thematic break, a page break — first writing that line if
6925    /// the block has none: where the rule and page-break buttons leave the
6926    /// caret, and where Enter on a rule takes it. Whether anything was
6927    /// written, so a caller can fold it into its own step.
6928    ///
6929    /// The caret's line is the first under the block that the view gives a
6930    /// home: the second blank line in [`LineFlow::Fold`], which draws the
6931    /// first as the gap closing the block, and the first in
6932    /// [`LineFlow::Preserve`], where every blank line is somewhere to type.
6933    /// When anything follows, one more blank line has to stand between the
6934    /// caret's line and it, or what is typed there runs on into the next
6935    /// block. Only what that shape is missing is written. A block twig wrote on
6936    /// a blank line still has the blank lines that were under the caret and
6937    /// needs one line more, or none, where a rule written under a paragraph
6938    /// needs two.
6939    ///
6940    /// Blank means blank inside the block's container: a quote's blank lines
6941    /// keep their `>`, and the caret's line wears the quote's whole prefix, as
6942    /// the line Enter opens in a quote does. The document's last line, when no
6943    /// newline ends it, counts only once a blank line stands above it, since
6944    /// only then does the view draw it as a row. Fold always writes the gap
6945    /// above it if it isn't there, so there a block ending the document takes
6946    /// one newline more and the caret its end.
6947    fn stand_under_block(&mut self, end: usize) -> bool {
6948        let prefix = self.continuation_prefix_at(end);
6949        let blank = prefix.trim_end();
6950        let gap = usize::from(self.line_flow == LineFlow::Fold);
6951        // The blank lines directly under the block's own, by where each starts,
6952        // and whether the line that ends the run has anything on it.
6953        let mut blanks = Vec::new();
6954        let mut follows = false;
6955        let mut at = end;
6956        while let Some(nl) = self.source[at..].find('\n') {
6957            let start = at + nl + 1;
6958            let len = self.source[start..].find('\n');
6959            let line = &self.source[start..len.map_or(self.source.len(), |len| start + len)];
6960            let line = line.trim_end();
6961            if line != blank {
6962                follows = !line.trim().is_empty();
6963                break;
6964            }
6965            let Some(len) = len else {
6966                if gap > 0 || !blanks.is_empty() {
6967                    blanks.push(start);
6968                }
6969                break;
6970            };
6971            blanks.push(start);
6972            at = start + len;
6973        }
6974        let missing = (gap + 1 + usize::from(follows)).saturating_sub(blanks.len());
6975        // What is missing goes in at the rule's end, above the blank lines
6976        // already there, so the caret's line is the same one counted from
6977        // the rule either way: written here, or one of those, moved down.
6978        let mut text = String::new();
6979        let mut caret = None;
6980        for line in 1..=missing {
6981            text.push('\n');
6982            if line == gap + 1 {
6983                text.push_str(&prefix);
6984                caret = Some(end + text.len());
6985            } else {
6986                text.push_str(blank);
6987            }
6988        }
6989        let caret = caret.unwrap_or_else(|| {
6990            let start = blanks[gap - missing];
6991            let line = self.source[start..].split('\n').next().unwrap_or("");
6992            start + text.len() + line.trim_end_matches('\r').len().min(prefix.len())
6993        });
6994        if !text.is_empty() && !self.splice(end, end, &text, EditKind::Other) {
6995            return false;
6996        }
6997        self.caret = caret.min(self.source.len());
6998        self.anchor = None;
6999        self.goal_col = None;
7000        self.record_caret();
7001        !text.is_empty()
7002    }
7003
7004    /// The thematic break the caret stands under, as its text's end, when
7005    /// Enter there belongs to the rule: the caret at the rule's home past it
7006    /// (the start of the line under it), that line blank, and the caret drawn
7007    /// on the rule's own row.
7008    ///
7009    /// Drawn on the rule's row, because the home past a rule is also the start
7010    /// of the line under it, and which of the two the view draws it on is the
7011    /// flow's. [`LineFlow::Fold`] draws that line as the gap under the rule,
7012    /// no caret's home, so the caret is beside the rule. [`LineFlow::Preserve`]
7013    /// makes every blank line a home, so it draws the caret there and Enter is
7014    /// an ordinary blank line's — unless it is the document's unterminated
7015    /// last line, which is no row in either flow.
7016    fn rule_above_caret(&mut self) -> Option<usize> {
7017        let caret = self.caret.min(self.source.len());
7018        let above = self.source[..caret].strip_suffix('\n')?;
7019        let above_start = above.rfind('\n').map_or(0, |i| i + 1);
7020        let text = above[above_start..].trim_end();
7021        let (last, _) = text.char_indices().next_back()?;
7022        let rule = self
7023            .editor
7024            .ancestors_at(above_start + last)
7025            .ok()?
7026            .into_iter()
7027            .find(|m| m.kind == Kind::ThematicBreak)?;
7028        let (end, home) = wysiwyg::block_line(&self.source, rule.span.end);
7029        if home != caret {
7030            return None;
7031        }
7032        let blank = self.continuation_prefix_at(end);
7033        let line_end = self.source[caret..].find('\n').map(|i| caret + i);
7034        let line = &self.source[caret..line_end.unwrap_or(self.source.len())];
7035        if line.trim_end() != blank.trim_end() && !line.trim().is_empty() {
7036            return None;
7037        }
7038        (self.line_flow == LineFlow::Fold || line_end.is_none()).then_some(end)
7039    }
7040
7041    /// Insert a fresh table at the caret — the toolbar's Table button. One
7042    /// header row, `rows` empty body rows, `cols` columns, spelled by twig in
7043    /// the document's own dialect and placed the way its thematic break is:
7044    /// after the caret's block, blank-separated. A bare paragraph is parted
7045    /// around the caret first, exactly as
7046    /// [`insert_thematic_break`](Self::insert_thematic_break) parts it, so the
7047    /// table lands *at* the caret rather than after everything the caret's
7048    /// paragraph says.
7049    ///
7050    /// The caret ends in the first header cell, selected the way Tab selects
7051    /// a cell — the natural next act is to type the heading, and Tab then
7052    /// walks the grid. That cell is read back from the rebuilt table map
7053    /// rather than computed from the splice, because twig's blank line and
7054    /// quote prefix put the first bar at an offset only the reparse knows.
7055    ///
7056    /// The shape is the caller's: a menu offers a few, a dialog asks. Zero
7057    /// rows or columns is twig's refusal (a header with nothing under it is
7058    /// what its row delete refuses to leave), reported through `status` —
7059    /// and refused here before the paragraph is parted, which would otherwise
7060    /// be left parted around a table never written.
7061    pub fn insert_table(&mut self, rows: usize, cols: usize) {
7062        if self.read_only || self.refuse_unsupported("table", Gesture::InsertTable) {
7063            return;
7064        }
7065        // twig's one refusal of a shape, asked before the paragraph is parted
7066        // for a table that would never be written into it.
7067        if rows == 0 || cols == 0 {
7068            self.status = Some("table: needs at least one row and one column".into());
7069            return;
7070        }
7071        self.caret = self.skip_trailing_close_delims(self.caret);
7072        if let Some((s, e)) = self.selection() {
7073            self.splice(s, e, "", EditKind::Other);
7074        }
7075        self.anchor = None;
7076        self.record_caret();
7077        let at = self.caret;
7078        let parted = self.part_for_block(at);
7079        match self.editor.insert_table(at, rows, cols) {
7080            Ok(change) => {
7081                self.last_edit_kind = None;
7082                self.refresh();
7083                if parted {
7084                    self.coalesce_last_undo();
7085                }
7086                self.anchor = None;
7087                self.caret = change.new.end;
7088                self.dirty = self.source != self.clean_source;
7089                self.status = None;
7090                self.clamp_caret();
7091                // Into the first header cell of the table just written: the
7092                // first table whose grid begins inside the splice.
7093                self.rebuild_map();
7094                let first_cell = self
7095                    .vmap
7096                    .tables
7097                    .iter()
7098                    .filter_map(|t| t.grid.first().and_then(|row| row.cells.first()))
7099                    .find(|cell| cell.start >= change.new.start && cell.start < change.new.end)
7100                    .map(|cell| (cell.start, cell.end));
7101                if let Some((start, end)) = first_cell {
7102                    self.select_cell(start, end);
7103                }
7104                self.record_caret();
7105            }
7106            Err(e) => self.status = Some(format!("table: {e}")),
7107        }
7108    }
7109
7110    /// Whether the caret sits in a paragraph and nothing else — no list item, no
7111    /// quote, no fence, no table — with paragraph text still ahead of it. The
7112    /// one shape where parting the block around the caret is unambiguously what
7113    /// a rule button means; see
7114    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
7115    /// container is left to take the rule after itself.
7116    ///
7117    /// The "text ahead" half is what keeps `split_block` from running at the
7118    /// one edge where its output composes badly. At a paragraph's end twig
7119    /// cannot mint the empty second half (no format spells an empty
7120    /// paragraph), so it writes only the separator — a blank line and the
7121    /// slot Enter leaves for the paragraph to come — and a block then aimed at
7122    /// the first half lands above a slot that nothing fills: `para\n` with the
7123    /// caret at 4 came out as `para\n\n* * *\n\n\n`. Trailing whitespace counts
7124    /// as nothing ahead, since the split would shed it as the second half's
7125    /// leading indent and leave the same slot. Which end of the newline a
7126    /// paragraph's span stops at differs between the formats (Markdown before
7127    /// it, djot after), which is why this reads the remaining bytes rather
7128    /// than comparing offsets. The paragraph's
7129    /// start is deliberately not the same case — see
7130    /// [`insert_thematic_break`](Self::insert_thematic_break) for why that
7131    /// split is kept.
7132    fn caret_parts_bare_paragraph(&mut self) -> bool {
7133        let caret = self.caret.min(self.source.len());
7134        let Ok(chain) = self.editor.ancestors_at(caret) else {
7135            return false;
7136        };
7137        let mut para_end = None;
7138        for m in chain {
7139            match m.kind {
7140                Kind::Para => para_end = Some(m.span.end.min(self.source.len())),
7141                Kind::ListItem
7142                | Kind::TaskListItem
7143                | Kind::BlockQuote
7144                | Kind::CodeBlock
7145                | Kind::Table => return false,
7146                _ => {}
7147            }
7148        }
7149        match para_end {
7150            Some(end) if end > caret => !self.source[caret..end].trim().is_empty(),
7151            _ => false,
7152        }
7153    }
7154
7155    /// The destination of the link under the caret — what a Link prompt shows so
7156    /// ⌘K on an existing link edits its URL instead of asking for it again.
7157    /// `None` when the caret stands in no link.
7158    ///
7159    /// An autolink carries no separate destination: its text *is* the URL, so
7160    /// that's what comes back for one.
7161    pub fn link_destination_at_caret(&mut self) -> Option<String> {
7162        self.link_destination_at(self.caret)
7163    }
7164
7165    /// The destination of the link at `off`.
7166    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
7167    /// the caret isn't.
7168    ///
7169    /// The offset form exists for the same reason
7170    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
7171    /// the document somewhere else — a footnote's text in a popover, say — has
7172    /// rows and runs but no caret in them, and still needs to know which of those
7173    /// runs a reader can follow.
7174    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
7175        self.nodes()
7176            .into_iter()
7177            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
7178            .filter(|n| n.span.start <= off && off < n.span.end)
7179            .max_by_key(|n| n.span.start)
7180            .and_then(|n| n.destination.or(n.text))
7181    }
7182
7183    /// The heading the caret is under — the nearest heading at or above it,
7184    /// whatever its level. See [`heading_at`](Self::heading_at).
7185    pub fn heading_at_caret(&mut self) -> Option<Heading> {
7186        self.heading_at(self.caret)
7187    }
7188
7189    /// The heading `off` is under: the last heading that starts at or before
7190    /// it, or the one `off` stands in. `None` above the first heading.
7191    ///
7192    /// The question between [`link_destination_at`](Self::link_destination_at)
7193    /// ("which link is this") and [`locate`](Self::locate) ("where does this
7194    /// fragment land"): a host writing a link *to* a place needs the heading
7195    /// that place is under, to name it by `#slug`. Nearest, not enclosing —
7196    /// a level-3 heading under a level-2 is the answer for the text below the
7197    /// level-3, because it is the finer place to land.
7198    pub fn heading_at(&mut self, off: usize) -> Option<Heading> {
7199        let nodes = self.nodes();
7200        let h = nodes
7201            .iter()
7202            .filter(|n| n.kind == Kind::Heading && n.span.start <= off)
7203            .max_by_key(|n| n.span.start)?;
7204        let mut text = String::new();
7205        inline_text(&nodes, h.first_child, &mut text);
7206        Some(Heading {
7207            text: text.trim().to_string(),
7208            level: h.level.unwrap_or(1),
7209            span: h.span.clone(),
7210        })
7211    }
7212
7213    /// Where the locator `id` lands in this document — the `#v2` half of a
7214    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
7215    /// answers to it.
7216    ///
7217    /// The other end of a link, and the reason this exists: without it a
7218    /// destination has only file granularity, so following a citation into a
7219    /// chapter drops the reader at the top of it to hunt for the verse. Which is
7220    /// also why it is a *document* query rather than a caret one — the document
7221    /// being asked is usually not the one the reader is in.
7222    ///
7223    /// Three readings, tried in order, because the same `#some-heading` is
7224    /// written three ways across the formats leaf opens:
7225    ///
7226    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
7227    ///    the auto-ids djot mints for its headings. The only exact answer, so it
7228    ///    goes first — a document that says `{#v1}` has settled the question.
7229    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
7230    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
7231    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
7232    ///    authored anywhere land on a djot heading.
7233    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
7234    ///    none and `{#custom}` is literal text in a Markdown heading — so for
7235    ///    the format most vaults are written in, the heading's own words are the
7236    ///    only thing a fragment can name. This is the rule every Markdown
7237    ///    renderer already follows, which is what makes `#a-heading` mean in
7238    ///    diaryx what it means on the web.
7239    ///
7240    /// Ties go to the earliest match, then to the widest: a duplicated id is the
7241    /// document's mistake and the first one is the answer every anchor
7242    /// implementation gives, while preferring the wider span picks the section
7243    /// over the heading that opens it — more for a peek to show, same place to
7244    /// land.
7245    pub fn locate(&mut self, id: &str) -> Option<Landing> {
7246        let id = id.trim();
7247        if id.is_empty() {
7248            return None;
7249        }
7250        let nodes = self.nodes();
7251
7252        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
7253        // is picking, among nodes that start together, the one that ends last.
7254        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
7255            matches
7256                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
7257                .map(|n| Landing {
7258                    start: n.span.start,
7259                    end: n.span.end,
7260                })
7261        };
7262
7263        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
7264            return Some(landing);
7265        }
7266        let want = slug(id);
7267        if want.is_empty() {
7268            return None;
7269        }
7270        if let Some(landing) = pick(
7271            &mut nodes
7272                .iter()
7273                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
7274        ) {
7275            return Some(landing);
7276        }
7277
7278        // A heading by its words. Its span is one line, so the end comes from
7279        // where the *section* it opens gives out — the next heading that is not
7280        // under it, or the end of the document. A Markdown heading has no
7281        // section node to ask (twig only builds those for djot), and a peek that
7282        // showed the heading alone would answer "what does that say" with the
7283        // title of the thing it says.
7284        let heading = nodes
7285            .iter()
7286            .filter(|n| n.kind == Kind::Heading)
7287            .filter(|n| {
7288                n.content_span
7289                    .clone()
7290                    .and_then(|s| self.source.get(s))
7291                    .is_some_and(|text| slug(text) == want)
7292            })
7293            .min_by_key(|n| n.span.start)?;
7294        let level = heading.level.unwrap_or(u32::MAX);
7295        let end = nodes
7296            .iter()
7297            .filter(|n| n.kind == Kind::Heading)
7298            .filter(|n| n.span.start > heading.span.start)
7299            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
7300            .map(|n| n.span.start)
7301            .min()
7302            .unwrap_or(self.source.len());
7303        Some(Landing {
7304            start: heading.span.start,
7305            end,
7306        })
7307    }
7308
7309    /// Write a footnote at the caret — the toolbar's Footnote button, and the
7310    /// one gesture in the footnote story that *authors* rather than follows.
7311    ///
7312    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
7313    /// the `[^1]:` definition at the end of the document. Half a footnote is not
7314    /// a footnote — a bare reference with nothing defining it renders as literal
7315    /// brackets — so a single button that wrote only the reference would leave
7316    /// the author to hand-spell the other half in a document that had just
7317    /// stopped showing them what the first half meant. One edit also means one
7318    /// undo takes both back.
7319    ///
7320    /// The definition's body is left empty and **the caret lands in it**, which
7321    /// is the whole point of pressing the button: nobody wants a reference to a
7322    /// note they have not written yet. Getting back to where they were writing
7323    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
7324    /// the same return leg a reader following a reference already uses, so the
7325    /// author is left standing on the near end of a round trip that works.
7326    ///
7327    /// A selection collapses to its *end* rather than being replaced: a
7328    /// reference annotates the words before it, so "select the claim, add a
7329    /// footnote" should mark that claim, not consume it.
7330    pub fn insert_footnote(&mut self) {
7331        if self.read_only || self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
7332            return;
7333        }
7334        let at = self.selection().map_or(self.caret, |(_, end)| end);
7335        self.anchor = None;
7336        self.caret = at;
7337        self.record_caret();
7338        let label = self.next_footnote_label();
7339        match self.editor.insert_footnote(at, &label) {
7340            Ok(change) => {
7341                self.last_edit_kind = None;
7342                self.refresh();
7343                self.anchor = None;
7344                // `change.new` runs from the reference to the end of the
7345                // document, so its start is the `[^1]` just written and
7346                // `footnote_at` resolves it to the note the same way a reader's
7347                // tap does — and to the note's *body*, which is already a caret
7348                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
7349                // and has none), so this needs no snap on top. The fallback is
7350                // the reference's own offset: a format that spelled the pair some
7351                // way leaf can't read back should still leave the caret on the
7352                // edit rather than at the far end of a document it just grew.
7353                self.caret = self
7354                    .footnote_at(change.new.start)
7355                    .and_then(|note| note.offset)
7356                    .unwrap_or(change.new.start);
7357                self.dirty = self.source != self.clean_source;
7358                self.status = None;
7359                self.clamp_caret();
7360                self.record_caret();
7361            }
7362            Err(e) => self.status = Some(format!("footnote: {e}")),
7363        }
7364    }
7365
7366    /// The label to give a footnote the author has not named: the lowest counting
7367    /// number no footnote in the document is already wearing.
7368    ///
7369    /// twig takes the label rather than minting one, because it holds no opinion
7370    /// about what a document's footnotes should be called — and it is right not
7371    /// to. Numbering them is what every author of a numbered note expects, and
7372    /// re-using a taken number would silently point the new reference at somebody
7373    /// else's note (twig reuses an existing definition rather than appending a
7374    /// second one, which is the right rule for citing a note twice on purpose and
7375    /// exactly the wrong accident to have by default).
7376    ///
7377    /// *References* are counted alongside definitions, not just definitions: a
7378    /// document carrying a dangling `[^2]` has a 2 that means something to
7379    /// whoever wrote it, and minting a definition for it here would answer a
7380    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
7381    /// count entirely — they take no number, so they block none.
7382    fn next_footnote_label(&mut self) -> String {
7383        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
7384            .into_iter()
7385            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
7386            .filter_map(|label| label.parse().ok())
7387            .collect();
7388        taken.extend(
7389            self.nodes()
7390                .into_iter()
7391                .filter(|n| n.kind == Kind::FootnoteReference)
7392                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
7393                .filter_map(|label| label.parse::<u32>().ok()),
7394        );
7395        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
7396    }
7397
7398    /// The footnote reference under the caret, resolved to the note it names.
7399    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
7400    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
7401        self.footnote_at(self.caret)
7402    }
7403
7404    /// The footnote reference at `off`, resolved to the note it names — what a
7405    /// frontend shows when a reader activates a `[^1]`.
7406    ///
7407    /// A reference is not a link node, so
7408    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
7409    /// (and should not) answer for one: a link names a destination to leave for,
7410    /// a reference names a note that is already in this document. Following one
7411    /// is a move within the page, which is why this hands back an `offset`
7412    /// rather than something to open.
7413    ///
7414    /// Offset-based rather than caret-only because the gesture that wants this
7415    /// most is the one that must not move the caret: a pointer hovering a `[1]`
7416    /// asks what note it names without disturbing where the reader was typing.
7417    /// The caret is just the offset a click already placed —
7418    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
7419    ///
7420    /// `None` when `off` stands in no reference. A reference whose note the
7421    /// document never defines is *not* `None` — it answers with the label it
7422    /// looked for and no text, which is what lets a frontend say so instead of
7423    /// silently doing nothing.
7424    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
7425        // Innermost-wins by latest start, the rule its link sibling uses.
7426        let span = self
7427            .nodes()
7428            .into_iter()
7429            .filter(|n| n.kind == Kind::FootnoteReference)
7430            .filter(|n| n.span.start <= off && off < n.span.end)
7431            .max_by_key(|n| n.span.start)?
7432            .span;
7433        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();
7434
7435        // The note itself. Definitions are roots beside `doc` rather than
7436        // children of it, so they're asked for directly — see
7437        // `wysiwyg::footnote_definitions`.
7438        let note = wysiwyg::footnote_definitions(&mut self.editor)
7439            .into_iter()
7440            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
7441        let Some(note) = note else {
7442            return Some(FootnoteRef {
7443                label,
7444                text: None,
7445                offset: None,
7446                end: None,
7447            });
7448        };
7449        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
7450        Some(FootnoteRef {
7451            label,
7452            text: body
7453                .clone()
7454                .and_then(|b| self.source.get(b))
7455                .map(str::to_string),
7456            // The body's start, not the definition's — see `FootnoteRef::offset`.
7457            offset: body.clone().map(|b| b.start),
7458            end: body.map(|b| b.end),
7459        })
7460    }
7461
7462    /// The footnote *definition* the caret stands in, and where the reference
7463    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
7464    /// at the caret's offset.
7465    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
7466        self.footnote_definition_at(self.caret)
7467    }
7468
7469    /// The footnote definition spanning `off`, and where the reference that
7470    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
7471    ///
7472    /// The mirror image, deliberately: the same gesture that takes a reader from
7473    /// `[1]` down to the note takes them from the note back up to `[1]`, so
7474    /// following a footnote is a round trip rather than a fall. It needs no
7475    /// memory of how the reader arrived — the document says where the reference
7476    /// is — which is what makes it work for a reader who scrolled to the notes
7477    /// themselves, and what keeps it right after an edit moves either end.
7478    ///
7479    /// `None` when `off` stands in no definition. A definition nothing cites is
7480    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
7481    /// its label and no offset, so a frontend can say "nothing refers to this"
7482    /// rather than offer a jump that goes nowhere.
7483    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
7484        // Definitions are roots beside `doc`, so `nodes()` — which walks the
7485        // document body — never reports one. They're asked for directly, the way
7486        // `footnote_at` asks for the note it resolves to.
7487        //
7488        // Closed at the end, unlike the half-open test its neighbours use. A
7489        // definition's span stops at its last content byte — the newline ending
7490        // the line is outside it — so `span.end` is the caret stop at the end of
7491        // the note's own row, not the first byte of anything after. Excluding it
7492        // meant the one caret an author is guaranteed to have, the one left
7493        // sitting at the end of the note they just typed, was in no definition at
7494        // all: writing a note and then asking to go back to its reference
7495        // answered nothing. Two definitions in a row still can't both match —
7496        // there is a blank line between them — and `max_by_key` decides anyway.
7497        let note = wysiwyg::footnote_definitions(&mut self.editor)
7498            .into_iter()
7499            .filter(|m| m.span.start <= off && off <= m.span.end)
7500            .max_by_key(|m| m.span.start)?;
7501        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();
7502
7503        // The earliest reference carrying this label. `min` rather than a `find`,
7504        // because `nodes()` reports a flattened walk whose order is twig's
7505        // business, not document order. Bound first: the walk needs `&mut self`
7506        // and reading the labels back out needs `&self.source`.
7507        let nodes = self.nodes();
7508        let offset = nodes
7509            .into_iter()
7510            .filter(|n| n.kind == Kind::FootnoteReference)
7511            .filter(|n| {
7512                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
7513            })
7514            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
7515            .map(|n| n.span.start + 2)
7516            .min();
7517        Some(FootnoteDef { label, offset })
7518    }
7519
7520    /// The destination of the image under the caret — what an image prompt shows
7521    /// so editing an existing image starts from its current URL instead of blank,
7522    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
7523    /// `None` when the caret stands in no image. A caret resting just after a
7524    /// block image (its trailing stop) is still "in" it — the half-open span test
7525    /// excludes that offset, which is the intended precision: past the image is
7526    /// past it.
7527    pub fn image_destination_at_caret(&mut self) -> Option<String> {
7528        let off = self.caret;
7529        self.nodes()
7530            .into_iter()
7531            .filter(|n| n.kind == Kind::Image)
7532            .filter(|n| n.span.start <= off && off < n.span.end)
7533            .max_by_key(|n| n.span.start)
7534            .and_then(|n| n.destination)
7535    }
7536
7537    /// The language of the fenced code block the caret stands in — what a
7538    /// language prompt shows so editing it starts from the current value rather
7539    /// than blank. `None` when the caret is in no code block, or in one whose
7540    /// fence carries no language (or an indented block, which has no fence).
7541    pub fn code_language_at_caret(&mut self) -> Option<String> {
7542        let start = self.code_block_start_at_caret()?;
7543        wysiwyg::code_language(&self.source, start)
7544    }
7545
7546    /// Whether the caret stands in a fenced code block — the one a language
7547    /// prompt could edit. A frontend gates its "set language" affordance on this
7548    /// (an indented block, which can't carry a language, reports `false`).
7549    pub fn caret_in_fenced_code(&mut self) -> bool {
7550        self.code_block_start_at_caret()
7551            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
7552    }
7553
7554    /// Set (or clear, with `""`) the language of the fenced code block the caret
7555    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
7556    /// block, and a reported error for a language the format's fence cannot
7557    /// carry.
7558    ///
7559    /// twig rewrites the info string, so the fence's own width — measured
7560    /// against a body neither side touches — is kept, and a language holding a
7561    /// space, a line end or the fence character is refused rather than written
7562    /// out to reparse as something else. Leaf used to splice over the info span
7563    /// itself and `trim()` the input, which handled the one bad case it had
7564    /// thought of.
7565    pub fn set_code_language(&mut self, lang: &str) {
7566        // The read-only gate — this door reaches twig without the splice.
7567        if self.read_only {
7568            return;
7569        }
7570        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
7571            return;
7572        }
7573        if self.code_block_start_at_caret().is_none() {
7574            return;
7575        }
7576        let lang = lang.trim();
7577        // `None` clears the info string; `Some("")` asks for an empty one. Both
7578        // write a bare fence, and the prompt's empty value means "clear".
7579        let want = (!lang.is_empty()).then_some(lang);
7580        self.record_caret();
7581        match self.editor.set_code_language(self.caret, want) {
7582            Ok(_) => {
7583                self.last_edit_kind = None;
7584                self.refresh();
7585                self.anchor = None;
7586                self.dirty = self.source != self.clean_source;
7587                self.status = None;
7588                self.clamp_caret();
7589                self.record_caret();
7590            }
7591            Err(e) => self.status = Some(format!("code language: {e}")),
7592        }
7593    }
7594
7595    /// The `span.start` of the code block covering the caret — the anchor
7596    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
7597    /// in none.
7598    fn code_block_start_at_caret(&mut self) -> Option<usize> {
7599        let off = self.caret;
7600        self.nodes()
7601            .into_iter()
7602            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
7603            .max_by_key(|n| n.span.start)
7604            .map(|n| n.span.start)
7605    }
7606
7607    /// The source range of the text inside the link covering `off` — what sits
7608    /// between its `[` and `]`. `None` when twig reports no link there.
7609    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
7610        self.nodes()
7611            .into_iter()
7612            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
7613            // the other's `span.start`; the link that starts latest at or before
7614            // `off` is the one `off` is actually in.
7615            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
7616            .max_by_key(|n| n.span.start)
7617            .and_then(|n| n.content_span)
7618    }
7619
7620    // ── undo / redo ───────────────────────────────────────────────────────────
7621    // twig owns the history of *bytes* (it owns the buffer) and now carries the
7622    // caret through it too: `record_caret` stashes each state's caret in twig's
7623    // opaque per-step blob, and undo/redo hand it back with the source they
7624    // restore. So leaf keeps no history of its own — no parallel stacks to march
7625    // in lockstep and silently drift out of it.
7626
7627    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
7628    /// where they were when that step began. Whether it did: `false` when
7629    /// there was nothing to undo, the document is read-only, or twig refused —
7630    /// the answer a host composing several histories into one walks on by.
7631    pub fn undo(&mut self) -> bool {
7632        if self.read_only {
7633            return false;
7634        }
7635        // Stepping through the history ends a group: what comes after is not
7636        // part of the step just taken back.
7637        self.close_undo_group();
7638        let (undone, redoable) = (self.undo_steps, self.redo_steps);
7639        match self.editor.undo() {
7640            Ok(Some(change)) => {
7641                self.after_history(change);
7642                // `refresh` counted the restore as an edit; it was a step back.
7643                self.undo_steps = undone.saturating_sub(1);
7644                self.redo_steps = redoable + 1;
7645                true
7646            }
7647            Ok(None) => {
7648                self.undo_steps = 0;
7649                self.status = Some("nothing to undo".into());
7650                false
7651            }
7652            Err(e) => {
7653                self.status = Some(format!("undo: {e}"));
7654                false
7655            }
7656        }
7657    }
7658
7659    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
7660    /// selection back where that step originally left them. Whether it did,
7661    /// as [`undo`](Self::undo) reports.
7662    pub fn redo(&mut self) -> bool {
7663        if self.read_only {
7664            return false;
7665        }
7666        self.close_undo_group();
7667        let (undone, redoable) = (self.undo_steps, self.redo_steps);
7668        match self.editor.redo() {
7669            Ok(Some(change)) => {
7670                self.after_history(change);
7671                // `refresh` counted the restore as an edit; it was a step forward.
7672                self.undo_steps = (undone + 1).min(UNDO_CAP);
7673                self.redo_steps = redoable.saturating_sub(1);
7674                true
7675            }
7676            Ok(None) => {
7677                self.redo_steps = 0;
7678                self.status = Some("nothing to redo".into());
7679                false
7680            }
7681            Err(e) => {
7682                self.status = Some(format!("redo: {e}"));
7683                false
7684            }
7685        }
7686    }
7687
7688    /// Fold the edit just made into the undo step before it — twig's
7689    /// `coalesce_last_undo`, with the `undo_steps` mirror following
7690    /// it. twig merges only when there are two steps to merge. Call it after
7691    /// [`refresh`](Self::refresh) has counted the edit being folded.
7692    ///
7693    /// Inside an [undo group](Self::begin_undo_group) it does nothing: the
7694    /// group's edits are already one step, which [`refresh`](Self::refresh)
7695    /// folds as they come, so a fold here could only reach across the group's
7696    /// start into the step before it.
7697    fn coalesce_last_undo(&mut self) {
7698        if self.undo_group.is_some() {
7699            return;
7700        }
7701        self.fold_last_undo();
7702    }
7703
7704    /// twig's `coalesce_last_undo`, unconditionally, with the mirror following.
7705    fn fold_last_undo(&mut self) {
7706        if self.editor.coalesce_last_undo().is_ok() && self.undo_steps >= 2 {
7707            self.undo_steps -= 1;
7708        }
7709    }
7710
7711    /// Open an undo group: every edit from here to the matching
7712    /// [`end_undo_group`](Self::end_undo_group) is one step, which a single
7713    /// [`undo`](Self::undo) takes back whole and a single [`redo`](Self::redo)
7714    /// puts back — a Replace All over twelve matches, or a Writing Tools
7715    /// session, rather than twelve presses of ⌘Z.
7716    ///
7717    /// Groups nest, and only the outermost end closes one. The step is folded
7718    /// as each edit lands (twig's `coalesce_last_undo`, one edit at a time),
7719    /// so a group of a thousand edits holds one step on the history and never
7720    /// meets twig's cap. Nothing typed before the group folds into it, and
7721    /// nothing typed after: it is a step of its own, even when it is a single
7722    /// edit. A group no edit landed in leaves no step at all.
7723    ///
7724    /// An [`undo`](Self::undo) or [`redo`](Self::redo) closes any open group,
7725    /// whatever its depth — the history has moved, and an edit made after it
7726    /// is not part of the step it moved past. A later `end_undo_group` is
7727    /// then a no-op.
7728    pub fn begin_undo_group(&mut self) {
7729        match &mut self.undo_group {
7730            Some(g) => g.depth += 1,
7731            None => {
7732                self.undo_group = Some(UndoGroup {
7733                    depth: 1,
7734                    has_step: false,
7735                });
7736                // The first edit inside is not a continuation of the typing
7737                // before it.
7738                self.last_edit_kind = None;
7739            }
7740        }
7741    }
7742
7743    /// Close the undo group [`begin_undo_group`](Self::begin_undo_group)
7744    /// opened. A no-op when none is open.
7745    pub fn end_undo_group(&mut self) {
7746        let Some(g) = &mut self.undo_group else {
7747            return;
7748        };
7749        if g.depth > 1 {
7750            g.depth -= 1;
7751        } else {
7752            self.close_undo_group();
7753        }
7754    }
7755
7756    /// Whether an undo group is open.
7757    pub fn in_undo_group(&self) -> bool {
7758        self.undo_group.is_some()
7759    }
7760
7761    /// Close any open group, however deeply nested.
7762    fn close_undo_group(&mut self) {
7763        if self.undo_group.take().is_some() {
7764            // Typing after the group is not a continuation of the last edit
7765            // in it.
7766            self.last_edit_kind = None;
7767        }
7768    }
7769
7770    /// Refresh the cached source and put the caret back where the step being
7771    /// undone/redone had it, clearing any active run.
7772    ///
7773    /// The caret comes from twig's blob for the restored state (what
7774    /// `record_caret` stored). `change` is only the fallback for a state with no
7775    /// blob — a caret at the end of the restored text, which is where this always
7776    /// landed before the blobs were kept. It is the edit site, not where the user
7777    /// was standing, so it's a floor and not the behaviour: undoing should hand
7778    /// back the document *and* the place you were working, which for an edit made
7779    /// anywhere but under the caret are two different places.
7780    fn after_history(&mut self, change: Change) {
7781        self.refresh();
7782        match self
7783            .editor
7784            .caret_blob()
7785            .ok()
7786            .and_then(|b| CaretState::from_blob(&b))
7787        {
7788            Some(state) => {
7789                self.caret = state.caret.min(self.source.len());
7790                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
7791            }
7792            None => {
7793                self.caret = change.new.end.min(self.source.len());
7794                self.anchor = None;
7795            }
7796        }
7797        self.goal_col = None;
7798        self.last_edit_kind = None;
7799        self.dirty = self.source != self.clean_source;
7800        self.status = None;
7801        self.clamp_caret();
7802    }
7803
7804    // ── the file ──────────────────────────────────────────────────────────────
7805
7806    #[cfg(feature = "fs")]
7807    pub fn save(&mut self) {
7808        if self.is_untitled() {
7809            // No path to write and no name to invent: ⌘S on an untitled document
7810            // is a Save As, and only a frontend has a picker to ask with. Say so
7811            // rather than failing at the filesystem with an empty path.
7812            self.status = Some("untitled — save as…".into());
7813            return;
7814        }
7815        let path = self.path.clone();
7816        if self.write(&path) {
7817            self.mark_saved();
7818        }
7819    }
7820
7821    /// Save As: write the document to `path` and *move* it there — `self.path`
7822    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
7823    /// what Save As means; a copy would leave the user editing a document whose
7824    /// name is no longer where their keystrokes go.
7825    ///
7826    /// The move only happens if the bytes actually landed. A failed write leaves
7827    /// the path, `dirty`, and the disk watermark exactly as they were, with the
7828    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
7829    /// must never come away believing it was saved.
7830    ///
7831    /// An existing `path` is overwritten, and the caller is the one that knows
7832    /// whether to ask first: a Save As picker has already run that prompt, and a
7833    /// second confirmation from down here would be the same question twice.
7834    ///
7835    /// `format` does **not** follow the new extension. The buffer is parsed as
7836    /// the format it was opened with, and re-reading it as another one is a
7837    /// conversion — a different, lossy operation that would throw away the undo
7838    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
7839    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
7840    /// until it's reopened.
7841    #[cfg(feature = "fs")]
7842    pub fn save_as(&mut self, path: PathBuf) {
7843        if !self.write(&path) {
7844            return;
7845        }
7846        self.path = path;
7847        self.mark_saved();
7848    }
7849
7850    /// Put `source` on disk at `path`, reporting whether it got there. The one
7851    /// place leaf writes a document, so a save and a Save As can't disagree
7852    /// about what a failure looks like.
7853    #[cfg(feature = "fs")]
7854    fn write(&mut self, path: &Path) -> bool {
7855        match std::fs::write(path, self.source.as_bytes()) {
7856            Ok(()) => true,
7857            Err(e) => {
7858                self.status = Some(format!("save failed: {e}"));
7859                false
7860            }
7861        }
7862    }
7863
7864    /// Re-base the document's saved watermark to the current bytes: clears
7865    /// `dirty`, records `source` as the new clean state (so undoing back to here
7866    /// clears the flag again), and re-stamps the on-disk hash.
7867    ///
7868    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
7869    /// the hook a **filesystem-free host** calls itself once it has persisted
7870    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
7871    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
7872    /// are already where that host wants them, and this just tells the model they
7873    /// are safe.
7874    pub fn mark_saved(&mut self) {
7875        self.clean_source = self.source.clone();
7876        self.dirty = false;
7877        // The bytes on disk are now ours, so this is the new watermark: without
7878        // re-stamping it, every save would report its own work as an external
7879        // change forever after.
7880        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
7881        self.status = Some(format!("saved {}", self.file_name()));
7882    }
7883
7884    /// [`Doc::mark_saved`] for a host whose write is not instantaneous: `saved`
7885    /// is the source it read before writing, and the edits made since are
7886    /// still unsaved.
7887    ///
7888    /// A host that reads [`Doc::source`], hands it to a write that takes a
7889    /// while, and then calls `mark_saved` loses whatever was typed meanwhile:
7890    /// the flag is cleared over text that never reached the disk, so nothing
7891    /// saves it again. Here `saved` becomes the clean state and the disk
7892    /// watermark, and `dirty` is whether the buffer has moved on from it.
7893    pub fn mark_saved_as(&mut self, saved: &str) {
7894        self.clean_source = saved.to_string();
7895        self.dirty = self.source != self.clean_source;
7896        self.disk_hash = Some(hash_bytes(saved.as_bytes()));
7897        if !self.dirty {
7898            self.status = Some(format!("saved {}", self.file_name()));
7899        }
7900    }
7901
7902    /// What the file looks like now against the bytes leaf last read or wrote.
7903    ///
7904    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
7905    /// so this is a filesystem round-trip, not a per-frame question — ask it
7906    /// when a window regains focus, on a timer, or before a save.
7907    ///
7908    /// This *only* reports the file. Whether the document also has unsaved edits
7909    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
7910    /// [`DiskState::Changed`] means a save overwrites someone's work and a
7911    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
7912    /// it has no way to ask — so it hands a frontend both halves and lets it put
7913    /// the question to the person who can answer it.
7914    #[cfg(feature = "fs")]
7915    pub fn disk_state(&self) -> DiskState {
7916        let Some(want) = self.disk_hash else {
7917            return DiskState::Untitled;
7918        };
7919        match std::fs::read(&self.path) {
7920            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
7921            Ok(_) => DiskState::Changed,
7922            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
7923            Err(_) => DiskState::Unreadable,
7924        }
7925    }
7926
7927    /// Re-read the file and replace the document with what's there — the other
7928    /// answer to a [`DiskState::Changed`].
7929    ///
7930    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
7931    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
7932    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
7933    /// document shouldn't have to argue with a guard.
7934    ///
7935    /// **The undo history survives, and the reload is one step in it.** The
7936    /// whole buffer is spliced with the file's bytes through the same door every
7937    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
7938    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
7939    /// swapped the document out from under a reader gives them back what they
7940    /// were looking at, marked dirty, and ^Z again carries on into whatever they
7941    /// had done before it. This used to build a fresh parse and drop the stack,
7942    /// on the reasoning that twig's history belongs to the buffer and these are
7943    /// different bytes; that is true of *rebasing* a step onto them and not of
7944    /// recording the swap itself as one, which is all this is. A splice twig
7945    /// won't take falls back to the fresh parse, and only that path still costs
7946    /// the history.
7947    ///
7948    /// The caret keeps its byte offset, clamped to the new length; the selection
7949    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
7950    /// file changed, so it can't know where the caret "still" is. Clamping keeps
7951    /// it where the user left it in the common case (a change further down the
7952    /// file, or none in the text they're sitting in), and never puts it
7953    /// somewhere invalid. A selection has two such offsets and no such excuse —
7954    /// silently reinterpreting one over changed bytes would arm the *next*
7955    /// keystroke to delete something the user never selected.
7956    ///
7957    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
7958    /// document alone with a status.
7959    #[cfg(feature = "fs")]
7960    pub fn reload(&mut self) {
7961        if self.is_untitled() {
7962            self.status = Some("no file to reload".into());
7963            return;
7964        }
7965        let bytes = match std::fs::read(&self.path) {
7966            Ok(b) => b,
7967            Err(e) => {
7968                self.status = Some(format!("reload failed: {e}"));
7969                return;
7970            }
7971        };
7972        let Ok(source) = String::from_utf8(bytes) else {
7973            self.status = Some("reload failed: file is not UTF-8".into());
7974            return;
7975        };
7976        // Already these bytes — someone saved a file back unchanged, or leaf's
7977        // own write is being read back. Re-baseline against it and stop: a
7978        // splice of the text onto itself would put an undo step on the stack for
7979        // something nobody did.
7980        if source == self.source {
7981            self.disk_hash = Some(hash_bytes(source.as_bytes()));
7982            self.clean_source = source;
7983            self.dirty = false;
7984            self.status = Some(format!("reloaded {}", self.file_name()));
7985            return;
7986        }
7987        let caret = self.caret;
7988        // The pre-reload caret, so undoing the swap puts it back where the
7989        // reader was standing — the same bracketing `splice_exact` does.
7990        self.record_caret();
7991        if self
7992            .editor
7993            .edit_range(0, self.source.len(), &source)
7994            .is_ok()
7995        {
7996            self.refresh();
7997        } else {
7998            // twig wouldn't take the splice. Start over from the bytes, which is
7999            // what this always did, and is the one path that still costs the
8000            // history — `format` is the format this document *is*, not what the
8001            // (unchanged) name now says, see `save_as`.
8002            match new_editor(source.as_bytes(), self.format) {
8003                Ok(editor) => {
8004                    self.editor = editor;
8005                    // A fresh editor, and so a fresh history — with no
8006                    // step in it for an open group to fold into.
8007                    self.undo_steps = 0;
8008                    self.redo_steps = 0;
8009                    if let Some(g) = &mut self.undo_group {
8010                        g.has_step = false;
8011                    }
8012                    self.source = source.clone();
8013                    // Not going through `refresh`, so the revision has to move
8014                    // here or every frontend keeps painting the old file from
8015                    // cache.
8016                    self.revision += 1;
8017                }
8018                Err(e) => {
8019                    self.status = Some(format!("reload failed: {e}"));
8020                    return;
8021                }
8022            }
8023        }
8024        self.disk_hash = Some(hash_bytes(source.as_bytes()));
8025        self.clean_source = self.source.clone();
8026        self.caret = caret.min(self.source.len());
8027        self.anchor = None;
8028        self.goal_col = None;
8029        self.last_edit_kind = None;
8030        self.dirty = false;
8031        self.status = Some(format!("reloaded {}", self.file_name()));
8032        self.clamp_caret();
8033        // And the post-reload caret, so a redo restores it.
8034        self.record_caret();
8035    }
8036
8037    /// Re-read the source from twig after it has changed the document. The one
8038    /// funnel every edit, undo, and redo comes through — so it's where the
8039    /// revision moves, and anything cached against the text dies here.
8040    fn refresh(&mut self) {
8041        if let Ok(s) = self.editor.source_str() {
8042            self.source = s;
8043        }
8044        self.revision += 1;
8045        // An edit is a step onto the history and the end of anything undone;
8046        // `undo`/`redo` come through here too and correct this after.
8047        self.undo_steps = (self.undo_steps + 1).min(UNDO_CAP);
8048        self.redo_steps = 0;
8049        // Inside a group, fold each step into the group's first as it lands.
8050        // Not for `undo`/`redo`, which close the group before they get here.
8051        if let Some(g) = &mut self.undo_group {
8052            if g.has_step {
8053                self.fold_last_undo();
8054            } else {
8055                g.has_step = true;
8056            }
8057        }
8058        self.clamp_caret();
8059    }
8060
8061    /// Whether [`undo`](Self::undo) has a step to take back — for a native
8062    /// Edit menu to enable its item by, and exactly when `undo` would move.
8063    pub fn can_undo(&self) -> bool {
8064        !self.read_only && self.undo_steps > 0
8065    }
8066
8067    /// Whether [`redo`](Self::redo) has an undone step to restore.
8068    pub fn can_redo(&self) -> bool {
8069        !self.read_only && self.redo_steps > 0
8070    }
8071
8072    // ── caret movement ─────────────────────────────────────────────────────────
8073    // `extend` grows the selection (Shift+motion): it pins the anchor on the
8074    // first extended step and moves only the caret; an un-extended motion drops
8075    // the selection.
8076
8077    /// Place the caret at byte `offset` (clamped to a char boundary), extending
8078    /// the selection when `extend` is set. The public form of `move_to`, for a
8079    /// frontend that hit-tests pixels straight to a source offset.
8080    pub fn place_caret(&mut self, offset: usize, extend: bool) {
8081        self.goal_col = None;
8082        let before = self.caret;
8083        // A pixel hit-test can land between the visible caret stops — in the
8084        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
8085        // Snap to the nearest real stop so the caret can't come to rest where it
8086        // would draw in one place and type in another. The `(row, col)` click
8087        // path (`click`) already snaps this way through `offset_of_pos`; the
8088        // source view reaches every byte, so it snaps to nothing.
8089        let target = match self.view {
8090            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
8091            // The source view reaches every byte, so there is no stop to snap
8092            // to — but "every byte" still means every *character* boundary. A
8093            // caret resting inside a multi-byte character draws nowhere real
8094            // and panics the next time anything slices there.
8095            View::Source => self.char_boundary_at_or_before(offset),
8096        };
8097        self.move_to(target, extend);
8098        self.clamp_caret();
8099        self.debug_assert_on_a_stop(before);
8100    }
8101
8102    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
8103    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
8104    /// grab the metadata) while the source view still selects the literal whole.
8105    pub fn select_all(&mut self) {
8106        self.anchor = Some(self.caret_floor());
8107        self.caret = self.source.len();
8108        self.goal_col = None;
8109        self.last_edit_kind = None;
8110        self.status = None;
8111    }
8112
8113    /// Select the word (or whitespace / punctuation run) at `offset` — the
8114    /// double-click gesture. Anchors on the run's start with the caret at its
8115    /// end so a following Shift-motion extends from the far edge.
8116    pub fn select_word_at(&mut self, offset: usize) {
8117        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
8118        self.anchor = Some(s);
8119        self.caret = e;
8120        self.goal_col = None;
8121        self.last_edit_kind = None;
8122        self.status = None;
8123        self.clamp_caret();
8124    }
8125
8126    /// Select the whole enclosing text block (paragraph, heading, list item's
8127    /// text…) at `offset` — the triple-click gesture. Reads the range straight
8128    /// from the AST (twig's `content_span`), so it selects the entire *logical*
8129    /// paragraph even when that paragraph soft-wraps across several visual rows —
8130    /// where a visual-row-based select breaks down, because one source offset at
8131    /// a wrap boundary belongs to two rows at once.
8132    pub fn select_block_at(&mut self, offset: usize) {
8133        let off = offset.min(self.source.len());
8134        let range = self
8135            .editor
8136            .ancestors_at(off)
8137            .ok()
8138            .and_then(|chain| {
8139                // Ancestors run root → deepest; the deepest node that is neither
8140                // an inline span nor a multi-block container is the text block
8141                // the caret sits in (a paragraph, a heading, a code block…).
8142                chain
8143                    .into_iter()
8144                    .rev()
8145                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
8146                    .map(|m| m.content_span.unwrap_or(m.span))
8147            })
8148            .unwrap_or_else(|| source_line_range(&self.source, off));
8149        self.anchor = Some(range.start.min(self.source.len()));
8150        self.caret = range.end.min(self.source.len());
8151        self.goal_col = None;
8152        self.last_edit_kind = None;
8153        self.status = None;
8154        self.clamp_caret();
8155    }
8156
8157    /// Select the exact source range `[start, end)` — anchor at `start`, caret
8158    /// at `end` — without snapping either end to a visible caret stop.
8159    ///
8160    /// The one caret verb that takes a range it was *handed* rather than one it
8161    /// worked out, for a host that already knows the bytes it means: a search
8162    /// hit, an annotation's footprint, a quote re-anchored through
8163    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
8164    /// wrong tool for that, and not by a little — it snaps to the nearest
8165    /// *visible* stop, and where a range butts up against a hidden delimiter
8166    /// the nearest stop is the one before it, so selecting the "needle" of
8167    /// `**needle**` comes back with "needl" and an edit against it strands the
8168    /// "e".
8169    ///
8170    /// What `place_caret` does that is bookkeeping rather than snapping still
8171    /// happens here, because a host handing in a range is not asking to opt out
8172    /// of the invariants:
8173    ///
8174    /// - both ends are clamped into the document and up to
8175    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
8176    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
8177    ///   types into the metadata;
8178    /// - both land on character boundaries, so nothing slices a `é` in half;
8179    /// - the sticky vertical goal column is dropped, and any armed inline mark
8180    ///   disarmed, since a range from outside inherits neither.
8181    ///
8182    /// An empty range is a caret rather than a selection —
8183    /// [`selection`](Self::selection) reports `None` for it, as it does for any
8184    /// anchor that has met the caret.
8185    pub fn select_range(&mut self, start: usize, end: usize) {
8186        let floor = self.caret_floor();
8187        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
8188        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
8189        self.anchor = Some(anchor);
8190        self.caret = caret;
8191        self.goal_col = None;
8192        self.status = None;
8193        self.last_edit_kind = None;
8194        self.clear_pending();
8195    }
8196
8197    /// `offset` itself if it is a character boundary, else the boundary before
8198    /// it. An offset that isn't one draws nowhere real and panics the next time
8199    /// anything slices there.
8200    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
8201        let mut o = offset.min(self.source.len());
8202        while o > 0 && !self.source.is_char_boundary(o) {
8203            o -= 1;
8204        }
8205        o
8206    }
8207
8208    /// The lowest source offset the caret may occupy in the active view. In
8209    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
8210    /// the first rendered offset; the source view reaches everything, so it's 0.
8211    fn caret_floor(&self) -> usize {
8212        match self.view {
8213            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
8214            View::Source => 0,
8215        }
8216    }
8217
8218    /// Land in a table cell with its whole content selected — the anchor at the
8219    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
8220    /// like tabbing into a form field: the text comes up selected, so typing
8221    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
8222    /// end`) collapses to a plain caret home (an empty selection is no selection).
8223    fn select_cell(&mut self, start: usize, end: usize) {
8224        self.select_range(start, end);
8225    }
8226
8227    fn move_to(&mut self, offset: usize, extend: bool) {
8228        if extend {
8229            if self.anchor.is_none() {
8230                self.anchor = Some(self.caret);
8231            }
8232        } else {
8233            self.anchor = None;
8234        }
8235        self.caret = offset.min(self.source.len()).max(self.caret_floor());
8236        self.status = None;
8237        // A caret move ends the current typing/deletion run, so the next edit
8238        // starts a fresh undo group rather than coalescing across the gap.
8239        self.last_edit_kind = None;
8240        // Moving away disarms any sticky mark — "start bold" applies only where
8241        // it was asked for, not wherever the caret next lands.
8242        self.clear_pending();
8243    }
8244
8245    // In the source view, motion walks source bytes / source lines. In the
8246    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
8247    // what steps the caret cleanly over hidden delimiters.
8248
8249    pub fn move_left(&mut self, extend: bool) {
8250        self.goal_col = None;
8251        if !extend && let Some((s, _e)) = self.selection() {
8252            self.move_to(s, false);
8253            return;
8254        }
8255        let target = match self.view {
8256            View::Source => {
8257                if self.caret > 0 {
8258                    prev_boundary(&self.source, self.caret)
8259                } else {
8260                    0
8261                }
8262            }
8263            // Walks caret *stops*, not columns: decoration (a table border, a
8264            // cell's padding) is stepped over in one press, and a hidden
8265            // delimiter never holds the caret up — though the end of a mark's
8266            // content is a stop of its own (`VisualMap::mark_ends`), so
8267            // leaving `**bold**` from past its `**` is a press onto the end of
8268            // the bold and another onto the `d`.
8269            View::Wysiwyg => self
8270                .vmap
8271                .caret_stop_before(self.caret)
8272                .unwrap_or(self.caret),
8273        };
8274        let before = self.caret;
8275        self.move_to(target, extend);
8276        self.debug_assert_on_a_stop(before);
8277    }
8278
8279    pub fn move_right(&mut self, extend: bool) {
8280        self.goal_col = None;
8281        if !extend && let Some((_s, e)) = self.selection() {
8282            self.move_to(e, false);
8283            return;
8284        }
8285        let target = match self.view {
8286            View::Source => {
8287                if self.caret < self.source.len() {
8288                    next_boundary(&self.source, self.caret)
8289                } else {
8290                    self.caret
8291                }
8292            }
8293            View::Wysiwyg => self.vmap.caret_stop_after(self.caret).unwrap_or(self.caret),
8294        };
8295        let before = self.caret;
8296        self.move_to(target, extend);
8297        self.debug_assert_on_a_stop(before);
8298    }
8299
8300    /// Move to the start of the previous word (⌥← / Ctrl+←).
8301    pub fn move_word_left(&mut self, extend: bool) {
8302        self.goal_col = None;
8303        let before = self.caret;
8304        let target = self.word_left_from(self.caret);
8305        self.move_to(target, extend);
8306        self.debug_assert_on_a_stop(before);
8307    }
8308
8309    /// Move to the end of the next word (⌥→ / Ctrl+→).
8310    pub fn move_word_right(&mut self, extend: bool) {
8311        self.goal_col = None;
8312        let before = self.caret;
8313        let target = self.word_right_from(self.caret);
8314        self.move_to(target, extend);
8315        self.debug_assert_on_a_stop(before);
8316    }
8317
8318    // Word boundaries are found in the space the *view* is in. The source view
8319    // walks the source, because there the source is what's rendered. WYSIWYG
8320    // walks the rendered text instead: `**` is invisible to the user, so it has
8321    // to be invisible to word motion too — a caret parked inside one draws in
8322    // the column after `bold` and types two bytes earlier, and a word-delete
8323    // that stops there shreds the markup into `a ** c`.
8324
8325    /// The word boundary to the left of `off` in the active view's space.
8326    fn word_left_from(&self, off: usize) -> usize {
8327        match self.view {
8328            View::Source => prev_word(&self.source, off),
8329            View::Wysiwyg => self.glyph_word_left(off),
8330        }
8331    }
8332
8333    /// The word boundary to the right of `off` in the active view's space.
8334    fn word_right_from(&self, off: usize) -> usize {
8335        match self.view {
8336            View::Source => next_word(&self.source, off),
8337            View::Wysiwyg => self.glyph_word_right(off),
8338        }
8339    }
8340
8341    /// The character class of the glyph drawn at stop `off`.
8342    ///
8343    /// Read from the source, because a stop points at the source byte its glyph
8344    /// came from — the source *is* where the rendered character is written. What
8345    /// makes the walk glyph space rather than source space is that it only ever
8346    /// visits stops, and the hidden bytes between them have none.
8347    fn class_at(&self, off: usize) -> Class {
8348        self.source
8349            .get(off..)
8350            .and_then(|s| s.chars().next())
8351            .map_or(Class::Space, classify)
8352    }
8353
8354    /// [`next_word`] in glyph space: skip any leading separators, then consume
8355    /// the following word run, with the stop table standing in for the source's
8356    /// characters.
8357    fn glyph_word_right(&self, from: usize) -> usize {
8358        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
8359            return from;
8360        };
8361        let mut in_word = false;
8362        loop {
8363            match self.class_at(off) {
8364                Class::Word => in_word = true,
8365                _ if in_word => return off,
8366                _ => {}
8367            }
8368            match self.vmap.stop_after(off) {
8369                Some(next) => off = next,
8370                None => return off,
8371            }
8372        }
8373    }
8374
8375    /// [`prev_word`] in glyph space: skip separators walking left, then consume
8376    /// the preceding word run.
8377    fn glyph_word_left(&self, from: usize) -> usize {
8378        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
8379            return from;
8380        };
8381        let mut in_word = false;
8382        while let Some(prev) = self.vmap.stop_before(off) {
8383            match self.class_at(prev) {
8384                Class::Word => in_word = true,
8385                _ if in_word => return off,
8386                _ => {}
8387            }
8388            off = prev;
8389        }
8390        off
8391    }
8392
8393    /// After a motion that walks the visual map, the caret must be *on* the map.
8394    /// A stop is the only offset where the caret draws and edits in the same
8395    /// place, and it's the invariant both a caret parked inside an emoji and one
8396    /// parked inside a `**` were quietly breaking.
8397    ///
8398    /// Only when the caret actually moved: a walk with nowhere to go leaves it
8399    /// where it was, which is wherever the floor or a frontend put it rather
8400    /// than somewhere this motion chose.
8401    fn debug_assert_on_a_stop(&self, before: usize) {
8402        debug_assert!(
8403            self.view != View::Wysiwyg
8404                || self.vmap.num_rows() == 0
8405                || self.caret == before
8406                || self.vmap.is_stop(self.caret),
8407            "motion left the caret at {}, which is not a caret stop: it would draw in \
8408             one place and type in another",
8409            self.caret
8410        );
8411    }
8412
8413    // Up and Down run off the ends of the document rather than stopping dead at
8414    // them: Up from the first row lands at the document's start, Down from the
8415    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
8416    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
8417    // reaching the end of the text is what a reader means by it.
8418    //
8419    // The views used to disagree here by accident rather than by decision: the
8420    // source view fell into the edge behaviour through `row_col_to_offset`
8421    // clamping an out-of-range row to the end of the string, while WYSIWYG had
8422    // no row below to walk to and did nothing at all. They share the rule now,
8423    // each in its own space — the source view reaches every byte, WYSIWYG only
8424    // the offsets it draws.
8425
8426    pub fn move_up(&mut self, extend: bool) {
8427        let (row, col) = self.caret_pos();
8428        let goal = self.goal_col.unwrap_or(col);
8429        let target = match self.view {
8430            View::Source => match row.checked_sub(1) {
8431                Some(r) => row_col_to_offset(&self.source, r, goal),
8432                None => self.reachable_start(),
8433            },
8434            // A table's border rules are drawn but hold no caret, so Up steps
8435            // over them to the row that does.
8436            View::Wysiwyg => match self.vmap.navigable_above(row) {
8437                Some(r) => self.row_target(r, goal),
8438                None => self.reachable_start(),
8439            },
8440        };
8441        self.step_vertical(target, goal, extend);
8442    }
8443
8444    pub fn move_down(&mut self, extend: bool) {
8445        let (row, col) = self.caret_pos();
8446        let goal = self.goal_col.unwrap_or(col);
8447        let target = match self.view {
8448            View::Source => match self.source_row_below(row) {
8449                Some(r) => row_col_to_offset(&self.source, r, goal),
8450                None => self.reachable_end(),
8451            },
8452            View::Wysiwyg => match self.vmap.navigable_below(row) {
8453                Some(r) => self.row_target(r, goal),
8454                None => self.reachable_end(),
8455            },
8456        };
8457        self.step_vertical(target, goal, extend);
8458    }
8459
8460    /// Land a vertical motion at `target`, latching the `goal` column it aimed
8461    /// with so the rest of the run keeps aiming there.
8462    ///
8463    /// A motion with nowhere to go changes *nothing*, the goal column included:
8464    /// the latch used to run before the early return at the top of the document,
8465    /// so an Up that did nothing still armed a column, and the next Down aimed
8466    /// at one the caret had never been in.
8467    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
8468        let before = self.caret;
8469        if target == before {
8470            return;
8471        }
8472        self.goal_col = Some(goal);
8473        self.move_to(target, extend);
8474        self.debug_assert_on_a_stop(before);
8475    }
8476
8477    /// The source line below `row`, or `None` when `row` is the last one. Lines
8478    /// are counted by newline, so a trailing one leaves a real, empty last line
8479    /// for the caret to sit on — the document ends below it, not on it.
8480    fn source_row_below(&self, row: usize) -> Option<usize> {
8481        let last = self.source.bytes().filter(|&b| b == b'\n').count();
8482        (row < last).then_some(row + 1)
8483    }
8484
8485    /// Where a vertical motion aiming at the `goal` column lands on visual row
8486    /// `r`: the column clamped to the row, mapped to its offset, then held
8487    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
8488    /// column belongs to the row below, and a gutter's column 0 points at the
8489    /// block rather than at this row.
8490    fn row_target(&self, r: usize, goal: usize) -> usize {
8491        let (start, end) = self.row_bounds(r);
8492        self.vmap
8493            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
8494            .clamp(start, end)
8495    }
8496
8497    /// The first and last offsets the caret can reach in the active view.
8498    ///
8499    /// Not the same span in both: the source view shows every byte, so it can
8500    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
8501    /// sits below the first stop, and a document's trailing newline is drawn
8502    /// nowhere and so sits past the last.
8503    fn reachable_start(&self) -> usize {
8504        match self.view {
8505            View::Source => 0,
8506            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
8507        }
8508    }
8509
8510    fn reachable_end(&self) -> usize {
8511        match self.view {
8512            View::Source => self.source.len(),
8513            View::Wysiwyg => self
8514                .vmap
8515                .stop_at_or_before(self.source.len())
8516                .unwrap_or(self.caret),
8517        }
8518    }
8519
8520    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
8521    /// including the space a soft wrap ate off its end, which is drawn on this
8522    /// row however much the offset past it belongs to the next one.
8523    fn row_span(&self, r: usize) -> (usize, usize) {
8524        let start = self
8525            .vmap
8526            .row_start(r)
8527            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
8528        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
8529        (start.min(end), end)
8530    }
8531
8532    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
8533    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
8534    /// this row's last position is the one before it — the offset before the
8535    /// space the wrap ate, where the caret draws just past the row's last word
8536    /// and types there too.
8537    ///
8538    /// Aiming at the shared offset instead is what stalled End: it is the row's
8539    /// last *column*, so End pressed on the row reached it and then read back as
8540    /// the row below's start, where a second press ran on to that row's end and
8541    /// the next to the one after — End walking down the paragraph a row a press.
8542    fn row_bounds(&self, r: usize) -> (usize, usize) {
8543        let (start, end) = self.row_span(r);
8544        let wraps = self
8545            .vmap
8546            .navigable_below(r)
8547            .and_then(|b| self.vmap.row_start(b))
8548            .is_some_and(|off| off == end);
8549        match wraps {
8550            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
8551            false => (start, end),
8552        }
8553    }
8554
8555    /// The `[start, end]` of the line Home and End aim at: the visual row in
8556    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
8557    ///
8558    /// A soft-wrapped row is a line here, because it is one to the eye and the
8559    /// eye is what these keys are aimed by — a reader pressing End means the end
8560    /// of the line they can see. (`select_block_at` wants the opposite and reads
8561    /// the AST for it: a triple-click grabs the whole paragraph, however many
8562    /// rows it folds into.)
8563    fn line_bounds(&self) -> (usize, usize) {
8564        let (row, _) = self.caret_pos();
8565        match self.view {
8566            View::Source => {
8567                let start = line_start(&self.source, row);
8568                (start, line_end_from(&self.source, start))
8569            }
8570            View::Wysiwyg => self.row_bounds(row),
8571        }
8572    }
8573
8574    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
8575    /// *drawn* — what a kill takes.
8576    ///
8577    /// The two part only at a soft wrap, over the space the wrap ate: the caret
8578    /// can't stand after it (that offset opens the row below, and End stopping
8579    /// there would walk), but it is on this row, and a kill that spared it would
8580    /// leave a double space behind where the row's text had been. Deleting it
8581    /// joins nothing — a wrap is drawn, not written.
8582    fn line_span(&self) -> (usize, usize) {
8583        let (row, _) = self.caret_pos();
8584        match self.view {
8585            View::Source => self.line_bounds(),
8586            View::Wysiwyg => self.row_span(row),
8587        }
8588    }
8589
8590    /// The first offset in `[start, end]` holding something other than
8591    /// whitespace, or `end` when the line holds nothing else — where Home aims.
8592    ///
8593    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
8594    /// so a hidden delimiter is never taken for the line's first character (nor
8595    /// landed on), and the source view steps the source it is showing.
8596    fn first_non_space(&self, start: usize, end: usize) -> usize {
8597        let mut off = start;
8598        while off < end {
8599            if self.class_at(off) != Class::Space {
8600                return off;
8601            }
8602            off = match self.view {
8603                View::Source => next_boundary(&self.source, off),
8604                View::Wysiwyg => match self.vmap.stop_after(off) {
8605                    Some(next) => next,
8606                    None => return end,
8607                },
8608            };
8609        }
8610        end
8611    }
8612
8613    /// Home: to the first character on the line, or to column 0 when the caret
8614    /// is already on it — the two-press toggle every editor spells this way.
8615    /// The indentation is somewhere the caret has to be able to reach and almost
8616    /// never where a reader is headed, so it costs the second press.
8617    pub fn move_home(&mut self, extend: bool) {
8618        self.goal_col = None;
8619        let (start, end) = self.line_bounds();
8620        let text = self.first_non_space(start, end);
8621        let target = if self.caret == text { start } else { text };
8622        let before = self.caret;
8623        self.move_to(target, extend);
8624        self.debug_assert_on_a_stop(before);
8625    }
8626
8627    /// End: to the end of the line.
8628    pub fn move_end(&mut self, extend: bool) {
8629        self.goal_col = None;
8630        let (_, end) = self.line_bounds();
8631        let before = self.caret;
8632        self.move_to(end, extend);
8633        self.debug_assert_on_a_stop(before);
8634    }
8635
8636    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
8637    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
8638    /// when the caret isn't in a table, or is already in the last/first cell — the
8639    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
8640    /// meaning everywhere else.
8641    pub fn cell_hop(&mut self, forward: bool) -> bool {
8642        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8643            return false;
8644        };
8645        // Flatten to document (row-major) order and step one cell either way.
8646        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
8647        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
8648        let next = if forward {
8649            i.checked_add(1)
8650        } else {
8651            i.checked_sub(1)
8652        };
8653        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
8654            return false; // at the table's edge; leave Tab to the frontend
8655        };
8656        self.select_cell(start, end);
8657        true
8658    }
8659
8660    /// Move the caret to the cell directly above (`down == false`) or below in
8661    /// the same column, landing with the cell's whole content selected (see
8662    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
8663    /// when the caret isn't in a table), so the frontend can fall through — the
8664    /// vertical counterpart of [`Self::cell_hop`].
8665    ///
8666    /// A ragged row that is short a column clamps to its last cell, so Down never
8667    /// falls out of the table over a gap the row above happened to have.
8668    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
8669        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8670            return false;
8671        };
8672        let target = match down {
8673            true => r + 1,
8674            false if r == 0 => return false,
8675            false => r - 1,
8676        };
8677        let Some(row) = grid.get(target) else {
8678            return false;
8679        };
8680        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
8681            return false;
8682        };
8683        self.select_cell(start, end);
8684        true
8685    }
8686
8687    /// The table containing `off` as a row-major grid of `(start, end)` cell
8688    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
8689    /// isn't in a table. Read straight off the visual map's laid-out grid, so
8690    /// every cell (an empty one included, whose derived home twig gives no
8691    /// `content_span` for) is present and in the order Tab walks them.
8692    // Grid, row, column — three returns that only ever travel together, and a
8693    // named type for the pair of them would be read at one call site.
8694    #[allow(clippy::type_complexity)]
8695    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
8696        for t in &self.vmap.tables {
8697            let mut pos = None;
8698            let grid: Vec<Vec<(usize, usize)>> = t
8699                .grid
8700                .iter()
8701                .enumerate()
8702                .map(|(r, row)| {
8703                    row.cells
8704                        .iter()
8705                        .enumerate()
8706                        .map(|(c, cell)| {
8707                            if pos.is_none() && off >= cell.start && off <= cell.end {
8708                                pos = Some((r, c));
8709                            }
8710                            (cell.start, cell.end)
8711                        })
8712                        .collect()
8713                })
8714                .collect();
8715            if let Some((r, c)) = pos {
8716                return Some((grid, r, c));
8717            }
8718        }
8719        None
8720    }
8721
8722    // ── table key policy ──────────────────────────────────────────────────────
8723    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
8724    // as one policy every frontend shares, rather than each re-deriving it. Each
8725    // reports whether it acted *as a table key*; a `false` hands the key back to
8726    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
8727    // everywhere else.
8728
8729    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
8730    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
8731    /// back and simply stays put at the very first cell. `false` when the caret
8732    /// isn't in a table.
8733    pub fn cell_tab(&mut self, forward: bool) -> bool {
8734        if !self.caret_in_table() {
8735            return false;
8736        }
8737        if self.cell_hop(forward) {
8738            return true;
8739        }
8740        // Off the last cell: grow the table by a row and step into its first
8741        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
8742        if forward {
8743            self.append_row_and_enter(0);
8744        }
8745        true
8746    }
8747
8748    /// Return inside a table: drop to the cell below in the same column,
8749    /// appending a new row when the caret is already in the last one. `false`
8750    /// when the caret isn't in a table, so the frontend inserts a newline.
8751    pub fn cell_return(&mut self) -> bool {
8752        if !self.caret_in_table() {
8753            return false;
8754        }
8755        if self.cell_move_vertical(true) {
8756            return true;
8757        }
8758        // Already on the last row: grow one below and drop into the same column.
8759        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
8760        self.append_row_and_enter(col);
8761        true
8762    }
8763
8764    /// Append a row below the caret's (last) row and land in `col` of it. The
8765    /// caret is in the last row, so twig's "insert below" makes the fresh row the
8766    /// table's new last — but twig re-spells the whole table, moving every byte,
8767    /// so the destination is read back from the rebuilt grid by the table's
8768    /// position (stable across a row insert), not from the pre-edit caret.
8769    fn append_row_and_enter(&mut self, col: usize) {
8770        let table = self.caret_table_index();
8771        self.table_insert_row(true);
8772        self.rebuild_map();
8773        let Some((start, end)) = table
8774            .and_then(|ti| self.vmap.tables.get(ti))
8775            .and_then(|t| t.grid.last())
8776            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
8777            .map(|cell| (cell.start, cell.end))
8778        else {
8779            return;
8780        };
8781        self.select_cell(start, end);
8782    }
8783
8784    /// The index, among the document's tables, of the one the caret sits in —
8785    /// `None` when it's in none. Used to re-find a table after an edit re-spells
8786    /// it (a row insert leaves the table order unchanged).
8787    fn caret_table_index(&self) -> Option<usize> {
8788        let off = self.caret;
8789        self.vmap.tables.iter().position(|t| {
8790            t.grid
8791                .iter()
8792                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
8793        })
8794    }
8795
8796    /// Shift+Return inside a table: insert a hard line break *within* the current
8797    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
8798    /// table, so the frontend inserts an ordinary line break.
8799    ///
8800    /// A table row is a single source line, so the newline-spelled hard break
8801    /// can't live in a cell. twig spells the in-cell break the format's way
8802    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
8803    /// break round-trips as structure the renderer reads back as a line — not the
8804    /// opaque raw HTML the old raw-splice left behind.
8805    ///
8806    /// Djot has no idiomatic in-cell break, so twig refuses it
8807    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
8808    /// would render as the literal text `<br>`. The gesture is still *consumed*
8809    /// there — returning `false` would let the frontend insert a real newline,
8810    /// which splits the one-line row — it just leaves the cell unchanged and says
8811    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
8812    ///
8813    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
8814    /// have to be read together: djot is not the only `false`, and naming it in
8815    /// the message was already a guess that HTML — which spells the break as its
8816    /// own `<br>` — would have made wrong.
8817    pub fn cell_line_break(&mut self) -> bool {
8818        if self.read_only || !self.caret_in_table() {
8819            return false;
8820        }
8821        self.record_caret();
8822        match self.editor.insert_line_break(self.caret) {
8823            Ok(change) => {
8824                self.last_edit_kind = None;
8825                self.refresh();
8826                self.caret = change.new.end;
8827                self.anchor = None;
8828                self.goal_col = None;
8829                self.clamp_caret();
8830                self.dirty = self.source != self.clean_source;
8831                self.status = None;
8832                self.record_caret();
8833            }
8834            Err(twig::Error::UnsupportedFormat) => {
8835                self.status = Some(format!(
8836                    "in-cell line breaks aren't supported in {}",
8837                    self.format_name()
8838                ));
8839            }
8840            Err(_) => {}
8841        }
8842        true
8843    }
8844
8845    /// Rebuild the visual map at the width the last build used. A structural edit
8846    /// bumps the revision and swaps the source in, but leaves the *map* stale;
8847    /// when a single gesture edits and then moves over the result (Tab appending
8848    /// a row, then stepping into it), the move needs the map to already show the
8849    /// edit rather than waiting for the frontend's next frame.
8850    fn rebuild_map(&mut self) {
8851        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
8852        self.build_map(wrap);
8853    }
8854
8855    /// Move the caret to the very start of the document (⌘↑ on macOS,
8856    /// Ctrl+Home on Windows/Linux).
8857    pub fn move_doc_start(&mut self, extend: bool) {
8858        self.goal_col = None;
8859        self.move_to(0, extend);
8860    }
8861
8862    /// Move the caret to the very end of the document (⌘↓ on macOS,
8863    /// Ctrl+End on Windows/Linux).
8864    pub fn move_doc_end(&mut self, extend: bool) {
8865        self.goal_col = None;
8866        let end = self.source.len();
8867        self.move_to(end, extend);
8868    }
8869
8870    /// Point the caret at the body cell `(row, col)` the mouse landed on —
8871    /// `col` being a cell of the terminal grid, which is what a display column
8872    /// is. A click on the far cell of a wide character lands at that
8873    /// character's start; the mapping's own doc-comments carry the rule.
8874    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
8875        self.goal_col = None;
8876        let target = match self.view {
8877            View::Source => row_col_to_offset(&self.source, row, col),
8878            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
8879        };
8880        let before = self.caret;
8881        self.move_to(target, extend);
8882        self.debug_assert_on_a_stop(before);
8883    }
8884
8885    /// A click in the blank space under the document's last block.
8886    ///
8887    /// Not a click *on* anything, so it lands on nothing in particular: the
8888    /// caret goes onto an empty paragraph under the last block, wherever the
8889    /// pointer was horizontally — and if the document does not end with one,
8890    /// one is opened, which is the only way to get out from under a block Enter
8891    /// cannot leave. Enter inside a fenced code block is a literal newline (see
8892    /// [`newline`](Self::newline)), so a document that *ends* in a fence had no
8893    /// way out at all; and a click under any last block used to land at the
8894    /// pointer's x on the block's last line, which is what a click on that line
8895    /// means and not what a click under it does.
8896    ///
8897    /// "Ends with an empty paragraph" is two trailing newlines: the first closes
8898    /// the last line and the second opens the blank line the visual map lays
8899    /// out as a navigable empty row (see `emit_trailing_blank_lines`). A
8900    /// document ending inside an *unclosed* fence gets the fence closed first,
8901    /// since a newline written there would only be another line of code. An
8902    /// empty document has nothing to be under, and the caret simply goes to its
8903    /// start.
8904    ///
8905    /// In the source view the gesture is the ordinary one: the caret goes to the
8906    /// end of the source, and nothing is written. A read-only document likewise.
8907    pub fn click_past_end(&mut self) {
8908        self.goal_col = None;
8909        let len = self.source.len();
8910        if self.view == View::Source || self.read_only || self.source.trim().is_empty() {
8911            self.move_to(len, false);
8912            return;
8913        }
8914        let mut tail = String::new();
8915        if let Some(fence) = self.unclosed_fence_at_end() {
8916            if !self.source.ends_with('\n') {
8917                tail.push('\n');
8918            }
8919            tail.push_str(&fence);
8920            tail.push('\n');
8921        }
8922        let joined = format!("{}{tail}", self.source);
8923        let trailing = joined.len() - joined.trim_end_matches('\n').len();
8924        for _ in trailing..2 {
8925            tail.push('\n');
8926        }
8927        if !tail.is_empty() && !self.splice(len, len, &tail, EditKind::Other) {
8928            return;
8929        }
8930        let end = self.source.len();
8931        self.move_to(end, false);
8932    }
8933
8934    /// The closing fence a document ending inside an unclosed fenced code block
8935    /// needs — the opening fence's own run, behind the quote prefix the block
8936    /// wears — or `None` when the last block is closed, indented, or not a code
8937    /// block at all.
8938    ///
8939    /// Unclosed is when twig's content span reaches the block's end: a closing
8940    /// fence line would lie between the two. `code_info_span`'s read of the
8941    /// fence is not used because it starts at the block's span, which inside a
8942    /// quote is the quote marker rather than the fence.
8943    fn unclosed_fence_at_end(&mut self) -> Option<String> {
8944        let content_end = self.source.trim_end_matches('\n').len();
8945        let block = self
8946            .nodes()
8947            .into_iter()
8948            .filter(|n| n.kind == Kind::CodeBlock && n.span.end >= content_end)
8949            .max_by_key(|n| n.span.start)?;
8950        if block.content_span.as_ref()?.end < block.span.end {
8951            return None;
8952        }
8953        let line = self.source[block.span.start..].lines().next()?;
8954        let opening = line.trim_start_matches(['>', ' ', '\t']);
8955        let fence = opening.chars().next().filter(|c| matches!(c, '`' | '~'))?;
8956        let run: String = opening.chars().take_while(|&c| c == fence).collect();
8957        let prefix = self.quote_prefix_at(block.span.start);
8958        Some(format!("{prefix}{run}"))
8959    }
8960
8961    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
8962    /// screen if it has moved since the last frame, and never scroll past the
8963    /// last of `rows`.
8964    ///
8965    /// Only if it has *moved* — that's the whole point. Revealing the caret on
8966    /// every frame ties the viewport to it, and a scroll wheel that fights the
8967    /// caret for the viewport loses: the view snaps back the instant it tries to
8968    /// pass the caret's row, so the document can't be scrolled beyond what's
8969    /// already on screen. A caret move is the frontend's cue to follow; a scroll
8970    /// with the caret sitting still is the reader's cue to leave it alone.
8971    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
8972        if self.drawn_caret != Some(self.caret) {
8973            if caret_row < self.scroll {
8974                self.scroll = caret_row;
8975            } else if height > 0 && caret_row >= self.scroll + height {
8976                self.scroll = caret_row + 1 - height;
8977            }
8978            self.drawn_caret = Some(self.caret);
8979        }
8980        self.scroll = self.scroll.min(rows.saturating_sub(1));
8981    }
8982
8983    /// The caret's screen position `(row, col)` in the active view's grid, with
8984    /// `col` a display column: the cell to draw the caret in, which on a line of
8985    /// `你好` or emoji is not the count of characters before it.
8986    pub fn caret_pos(&self) -> (usize, usize) {
8987        match self.view {
8988            View::Source => offset_to_row_col(&self.source, self.caret),
8989            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
8990        }
8991    }
8992
8993    fn clamp_caret(&mut self) {
8994        if self.caret > self.source.len() {
8995            self.caret = self.source.len();
8996        }
8997        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
8998        // any selection anchor) to the first rendered offset.
8999        let floor = self.caret_floor();
9000        if self.caret < floor {
9001            self.caret = floor;
9002        }
9003        if let Some(a) = self.anchor
9004            && a < floor
9005        {
9006            self.anchor = Some(floor);
9007        }
9008        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
9009            self.caret -= 1;
9010        }
9011    }
9012}
9013
9014// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
9015
9016// Left/right motion and backspace/delete step by *grapheme cluster*, not
9017// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
9018// marks moves and deletes as the single character a user sees. Grapheme
9019// boundaries are a superset of char boundaries, so the caret stays valid for twig.
9020
9021/// How an insert of `text` groups for undo: a single typed character folds into
9022/// the run of typing around it, while a newline or a multi-character insert is a
9023/// step of its own.
9024fn typed_edit_kind(text: &str) -> EditKind {
9025    if text.chars().take(2).count() == 1 && text != "\n" {
9026        EditKind::Insert
9027    } else {
9028        EditKind::Other
9029    }
9030}
9031
9032fn prev_boundary(s: &str, i: usize) -> usize {
9033    let mut cursor = GraphemeCursor::new(i, s.len(), true);
9034    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
9035}
9036
9037fn next_boundary(s: &str, i: usize) -> usize {
9038    let mut cursor = GraphemeCursor::new(i, s.len(), true);
9039    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
9040}
9041
9042// ── word boundaries ──────────────────────────────────────────────────────────
9043// The shared primitive behind word-wise motion, word deletion, and
9044// double-click-to-select-a-word. A "word" is a maximal run of one character
9045// class; whitespace and punctuation are their own classes, so motion skips
9046// cleanly between them the way native text fields do.
9047
9048#[derive(PartialEq, Eq, Clone, Copy)]
9049enum Class {
9050    Word,
9051    Space,
9052    Other,
9053}
9054
9055/// The source range of an inline node's own visible text — the part of it a
9056/// WYSIWYG caret can reach, as against the delimiters that only spell it.
9057/// `None` for a node with no interior to empty (a `str`, a break).
9058///
9059/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
9060/// one delimiter in from the span — the same place the renderer maps it to. A
9061/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
9062/// against the source rather than trusted: a range guessed wrong here is text
9063/// deleted wrong.
9064fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
9065    if let Some(span) = n.content_span.clone() {
9066        return Some(span);
9067    }
9068    match n.kind.as_str() {
9069        "verbatim" | "inline_math" => {
9070            let text = n.text.as_ref()?;
9071            let start = n.span.start + 1;
9072            let range = start..start + text.len();
9073            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
9074        }
9075        _ => None,
9076    }
9077}
9078
9079/// The `id` a node declares, or `None` for one that declares none — the
9080/// attribute djot writes for a `{#v1}` and mints for a heading.
9081///
9082/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
9083/// names nothing, so it reads as absent rather than as the empty string.
9084fn declared_id(n: &FlatNode) -> Option<&str> {
9085    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
9086}
9087
9088/// A heading's words reduced to the form a link fragment spells them in:
9089/// lowercase, runs of anything else collapsed to a single `-`, with none left
9090/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
9091///
9092/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
9093/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
9094/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
9095/// any other language is still a heading someone will link to. Underscores
9096/// survive for the same reason they do on the web: they are word characters
9097/// wherever identifiers are written.
9098fn slug(text: &str) -> String {
9099    let mut out = String::new();
9100    let mut pending = false;
9101    for c in text.chars() {
9102        if c.is_alphanumeric() || c == '_' {
9103            if pending && !out.is_empty() {
9104                out.push('-');
9105            }
9106            pending = false;
9107            out.extend(c.to_lowercase());
9108        } else {
9109            pending = true;
9110        }
9111    }
9112    out
9113}
9114
9115/// The text of the inline run starting at `first` and its siblings, markup
9116/// stripped: each leaf's payload in order, a line break as a space. `nodes` is
9117/// the arena `Doc::nodes` returns, indexed by id.
9118fn inline_text(nodes: &[FlatNode], first: Option<NodeId>, out: &mut String) {
9119    let mut next = first;
9120    while let Some(id) = next {
9121        let Some(n) = nodes.get(id.0 as usize) else {
9122            return;
9123        };
9124        match (&n.text, &n.kind) {
9125            (Some(text), _) => out.push_str(text),
9126            (None, Kind::SoftBreak | Kind::HardBreak) => out.push(' '),
9127            (None, _) => inline_text(nodes, n.first_child, out),
9128        }
9129        next = n.next_sibling;
9130    }
9131}
9132
9133fn is_block_container(kind: &Kind) -> bool {
9134    matches!(
9135        kind,
9136        Kind::Doc
9137            | Kind::Section
9138            | Kind::BlockQuote
9139            | Kind::BulletList
9140            | Kind::OrderedList
9141            | Kind::TaskList
9142            | Kind::ListItem
9143            | Kind::TaskListItem
9144            // Every `container` — a directive in any of its three forms, or a
9145            // promoted HTML element. A *text* directive is really inline, so
9146            // claiming it here is a small overreach, and the deliberate one this
9147            // function's kind-only peer `is_inline_kind` documents: the pair is
9148            // consulted together, and answering "block container" for something
9149            // inline is what keeps an ancestor walk from stopping short of the
9150            // paragraph that actually holds it.
9151            | Kind::Container
9152    )
9153}
9154
9155/// The `[start, end)` byte range of the source line containing `off` (newline
9156/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
9157/// line between paragraphs).
9158fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
9159    let off = off.min(s.len());
9160    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
9161    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
9162    start..end
9163}
9164
9165/// How many leading bytes an outdent takes off `line`: a whole indent level
9166/// where the line has one, and whatever it has where it has less.
9167///
9168/// A leading tab counts as a level on its own. It's indentation some other
9169/// editor wrote, and one tab is one level everywhere it came from — measuring it
9170/// in spaces it doesn't contain would leave it untouchable.
9171fn outdent_width(line: &str, unit: usize) -> usize {
9172    if line.starts_with('\t') {
9173        return 1;
9174    }
9175    line.bytes().take(unit).take_while(|b| *b == b' ').count()
9176}
9177
9178/// A list marker found at the head of a line, together with everything before it
9179/// that a sibling line has to repeat.
9180///
9181/// The three offsets differ only inside a block quote, where `>   - b` opens with
9182/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
9183/// `line_start == marker_start`, and `text` is the plain `"  - "`.
9184#[derive(Clone, Debug)]
9185struct ListMarker {
9186    /// The line's first byte.
9187    line_start: usize,
9188    /// Where the marker proper begins, past any quote prefix. The offset to hand
9189    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
9190    marker_start: usize,
9191    /// `line_start` through the marker's trailing space — quote prefix, indent
9192    /// and bullet together, which is what the next item's line opens with.
9193    text: String,
9194}
9195
9196impl ListMarker {
9197    /// Where the item's content starts — one past the marker's trailing space.
9198    fn content_start(&self) -> usize {
9199        self.line_start + self.text.len()
9200    }
9201}
9202
9203fn classify(c: char) -> Class {
9204    if c == '_' || c.is_alphanumeric() {
9205        Class::Word
9206    } else if c.is_whitespace() {
9207        Class::Space
9208    } else {
9209        Class::Other
9210    }
9211}
9212
9213/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
9214/// skip any leading separators, then consume the following word run.
9215fn next_word(s: &str, i: usize) -> usize {
9216    let mut off = i;
9217    let mut in_word = false;
9218    for c in s[i..].chars() {
9219        if classify(c) == Class::Word {
9220            in_word = true;
9221        } else if in_word {
9222            break;
9223        }
9224        off += c.len_utf8();
9225    }
9226    off
9227}
9228
9229/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
9230/// skip separators walking left, then consume the preceding word run.
9231fn prev_word(s: &str, i: usize) -> usize {
9232    let mut off = i;
9233    let mut in_word = false;
9234    for c in s[..i].chars().rev() {
9235        if classify(c) == Class::Word {
9236            in_word = true;
9237        } else if in_word {
9238            break;
9239        }
9240        off -= c.len_utf8();
9241    }
9242    off
9243}
9244
9245/// The `[start, end)` run of same-class characters surrounding `off` — the
9246/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
9247/// the run ending there is used.
9248fn word_range_at(s: &str, off: usize) -> (usize, usize) {
9249    if s.is_empty() {
9250        return (0, 0);
9251    }
9252    let off = off.min(s.len());
9253    let reference = if off < s.len() {
9254        s[off..].chars().next()
9255    } else {
9256        s[..off].chars().next_back()
9257    };
9258    let Some(rc) = reference else {
9259        return (off, off);
9260    };
9261    let class = classify(rc);
9262
9263    let mut start = off;
9264    for c in s[..start].chars().rev() {
9265        if classify(c) == class {
9266            start -= c.len_utf8();
9267        } else {
9268            break;
9269        }
9270    }
9271    let mut end = off;
9272    for c in s[end..].chars() {
9273        if classify(c) == class {
9274            end += c.len_utf8();
9275        } else {
9276            break;
9277        }
9278    }
9279    (start, end)
9280}
9281
9282/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
9283/// the line's start — terminal cells, not characters, so the column names the
9284/// cell the caret is drawn in even on a line of `你好` or emoji.
9285fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
9286    let off = off.min(s.len());
9287    let mut row = 0;
9288    let mut line_start = 0;
9289    for (i, &b) in s.as_bytes().iter().enumerate() {
9290        if i >= off {
9291            break;
9292        }
9293        if b == b'\n' {
9294            row += 1;
9295            line_start = i + 1;
9296        }
9297    }
9298    (row, wysiwyg::text_width(&s[line_start..off]))
9299}
9300
9301/// The byte offset at display column `col` of `row` (clamped to that line's
9302/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
9303///
9304/// A column landing *inside* a character — the second cell of `你`, or any cell
9305/// but the first of an emoji — resolves to that character's start, which is the
9306/// column the caret would have been drawn at to begin with. So both cells of a
9307/// wide character mean the character, and every offset survives the round trip
9308/// out to a column and back. The walk steps by grapheme cluster for the same
9309/// reason the caret does: a cluster is the character, and the cells belong to it
9310/// rather than to the codepoints spelling it.
9311fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
9312    let start = line_start(s, row);
9313    let end = line_end_from(s, start);
9314    let mut off = start;
9315    let mut at = 0; // the display column `off` sits at
9316    while off < end {
9317        let next = next_boundary(s, off).min(end);
9318        let cells = wysiwyg::text_width(&s[off..next]);
9319        if at + cells > col {
9320            break; // `col` is one of this cluster's own cells
9321        }
9322        at += cells;
9323        off = next;
9324    }
9325    off
9326}
9327
9328fn line_start(s: &str, row: usize) -> usize {
9329    if row == 0 {
9330        return 0;
9331    }
9332    let mut r = 0;
9333    for (i, &b) in s.as_bytes().iter().enumerate() {
9334        if b == b'\n' {
9335            r += 1;
9336            if r == row {
9337                return i + 1;
9338            }
9339        }
9340    }
9341    s.len()
9342}
9343
9344fn line_end_from(s: &str, start: usize) -> usize {
9345    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
9346}
9347
9348/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
9349/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
9350/// twig applies writing the mark out, so the toolbar can light the same button
9351/// that made the node.
9352///
9353/// `None` for every other kind, including the inline nodes that aren't marks at
9354/// all (`str`, `link`, `image`, the math and break kinds): they're things a
9355/// caret stands in, not formatting a button toggles.
9356/// Whether a match from an ancestor chain is an inline run whose delimiters
9357/// the rich view draws nothing for — a mark (`**`, `_`, `==`), or an
9358/// attributed span: `<span data-size="large">…</span>`, djot's `[…]{…}`. The
9359/// span is a [`Kind::Container`], which the kind alone cannot tell from a
9360/// block `<div>`, so the chain's caller passes [`Doc::run_span_ids`] and the
9361/// answer is the node's own. Every delete and caret step that walks over a
9362/// `**` walks over a span's tags by this test; without it Backspace after
9363/// `</span>` took the `>` and left the paragraph unparseable.
9364fn hides_delims(m: &QueryMatch, run_spans: &[NodeId]) -> bool {
9365    inline_kind(&m.kind).is_some() || run_spans.contains(&NodeId(m.node_id))
9366}
9367
9368fn inline_kind(kind: &Kind) -> Option<InlineKind> {
9369    Some(match kind {
9370        Kind::Strong => InlineKind::Strong,
9371        Kind::Emph => InlineKind::Emph,
9372        Kind::Verbatim => InlineKind::Verbatim,
9373        Kind::Mark => InlineKind::Mark,
9374        Kind::Superscript => InlineKind::Superscript,
9375        Kind::Subscript => InlineKind::Subscript,
9376        Kind::Insert => InlineKind::Insert,
9377        Kind::Delete => InlineKind::Delete,
9378        _ => return None,
9379    })
9380}
9381
9382/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
9383/// a highlight's opening `==`.
9384///
9385/// Two enums for one closed vocabulary, and the duplication is the boundary
9386/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
9387/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
9388/// the editor writes. Spelled as a match rather than routed through the two
9389/// crates' name strings so that a colour added on either side is a compile
9390/// error here, where the pairing is decided, rather than a runtime `None` that
9391/// would read as "clear the colour".
9392fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
9393    match color {
9394        MarkColor::Red => twig::MarkColor::Red,
9395        MarkColor::Orange => twig::MarkColor::Orange,
9396        MarkColor::Yellow => twig::MarkColor::Yellow,
9397        MarkColor::Green => twig::MarkColor::Green,
9398        MarkColor::Blue => twig::MarkColor::Blue,
9399        MarkColor::Purple => twig::MarkColor::Purple,
9400        MarkColor::Brown => twig::MarkColor::Brown,
9401    }
9402}
9403
9404/// Where an offset lands after a splice it didn't make — twig's own rule, from
9405/// [`Change`]: shift anything at or past the replaced range's end by the length
9406/// the replacement gained or lost, and leave anything before it alone.
9407///
9408/// An offset *inside* the replaced range has no text of its own to ride any
9409/// more, and lands at the end of what replaced it: for
9410/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
9411/// the prefix is cleared, which then sits where the highlighted text begins.
9412/// One node's attribute list, twig's own `(key, value)` pairs owned — what
9413/// every presentation gesture reads, edits one key of, and passes back whole.
9414type Attrs = Vec<(String, Option<String>)>;
9415
9416/// The name of the leaf directive a page break is — [`Doc::insert_page_break`]
9417/// writes it and the walker draws it, and a frontend that paginates matches a
9418/// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) against it. One spelling,
9419/// stated once.
9420pub const PAGE_BREAK: &str = "page-break";
9421
9422/// `attrs` with `key` set to `value`, or removed when `value` is `None`, and
9423/// every other attribute kept in its place — the read-edit-write half of twig's
9424/// replace-not-merge contract for a `data-` key.
9425///
9426/// **A key that is already there is rewritten where it stands**, and only a key
9427/// the node did not have goes on the end. That is what makes the proposal's
9428/// worked example true: `class="lead center" id="intro"
9429/// data-line-height="1.5"`, right-aligned, is `class="lead right" id="intro"
9430/// data-line-height="1.5"` — the same document with one token changed, and a
9431/// one-line diff. Removing the key and pushing it back would reorder the
9432/// author's attributes on every press, so a document that passed through the
9433/// editor came out shuffled even where nothing about it had changed.
9434///
9435/// A duplicate key — which no format leaf opens can spell, but twig reports
9436/// verbatim — collapses onto the first of its copies, since twig is handed one
9437/// value for one key either way.
9438fn with_attr(attrs: &[(String, Option<String>)], key: &str, value: Option<&str>) -> Attrs {
9439    let mut out: Attrs = Vec::with_capacity(attrs.len() + 1);
9440    let mut written = false;
9441    for (k, v) in attrs {
9442        if k != key {
9443            out.push((k.clone(), v.clone()));
9444            continue;
9445        }
9446        if let Some(new) = value.filter(|_| !written) {
9447            out.push((k.clone(), Some(new.to_string())));
9448            written = true;
9449        }
9450    }
9451    if let Some(new) = value.filter(|_| !written) {
9452        out.push((key.to_string(), Some(new.to_string())));
9453    }
9454    out
9455}
9456
9457/// [`with_attr`] for a `class` token: every token `mine` claims is removed, and
9458/// `token` added, with the rest of the list kept in order.
9459///
9460/// `class` is a space-separated token list, and leaf owns three of the tokens in
9461/// it. A paragraph that arrives as `class="lead center"` and is right-aligned
9462/// goes out as `class="lead right"`; one whose last owned token goes and which
9463/// carried nothing else loses the key, so a block that has lost its whole
9464/// vocabulary is spelled bare again. `class` itself keeps its place among the
9465/// attributes, because [`with_attr`] does the writing.
9466fn with_class_token(
9467    attrs: &[(String, Option<String>)],
9468    mine: impl Fn(&str) -> bool,
9469    token: Option<&str>,
9470) -> Attrs {
9471    let kept: Vec<&str> = attrs
9472        .iter()
9473        .find(|(k, _)| k == "class")
9474        .and_then(|(_, v)| v.as_deref())
9475        .unwrap_or_default()
9476        .split_whitespace()
9477        .filter(|t| !mine(t))
9478        .collect();
9479    let class = kept.into_iter().chain(token).collect::<Vec<_>>().join(" ");
9480    with_attr(
9481        attrs,
9482        "class",
9483        (!class.is_empty()).then_some(class.as_str()),
9484    )
9485}
9486
9487/// An owned attribute list as the borrowed pairs twig's two attribute ops take.
9488///
9489/// A **bare** attribute — one twig reports with no value, such as HTML's `<p
9490/// hidden>` — is passed back as an empty one. Twig refuses a `None` outright
9491/// (djot has no bare attribute, so no format reads one back everywhere), and
9492/// `hidden=""` is the same document where `hidden` is; dropping it instead
9493/// would lose what the author wrote, which is the one thing these gestures
9494/// promise not to do.
9495fn attr_pairs(attrs: &[(String, Option<String>)]) -> Vec<(&str, Option<&str>)> {
9496    attrs
9497        .iter()
9498        .map(|(k, v)| (k.as_str(), Some(v.as_deref().unwrap_or_default())))
9499        .collect()
9500}
9501
9502fn reanchor(off: usize, change: &Change) -> usize {
9503    if off < change.old.start {
9504        return off;
9505    }
9506    if off < change.old.end {
9507        return change.new.end;
9508    }
9509    (off + change.new.end).saturating_sub(change.old.end)
9510}
9511
9512/// [`reanchor`] for an edit that respells the markup *around* a block and
9513/// leaves the block's own bytes alone — which is every attribute gesture.
9514///
9515/// `block` is that block's content span before and after the splice, so an
9516/// offset standing in the text keeps its distance from the text's start and how
9517/// many bytes twig wrote above it never enters the arithmetic. That is the whole
9518/// rule, and it is why nothing here knows how long a `<div …>` is: a second key
9519/// on the same div lengthens the attribute line, clearing the last one takes the
9520/// div away entirely, and both are the same sum. `None` where the splice named
9521/// no block at either end, which is every djot case — the `{…}` line is written
9522/// above the block, and the block itself only shifts past it.
9523///
9524/// Anywhere else it is `reanchor`'s own answer: untouched before the splice,
9525/// shifted by its delta after it, and at the splice's end for an offset that
9526/// stood in markup being rewritten — a caret inside djot's `{…}` line has no
9527/// text to keep.
9528fn reanchor_in_block(
9529    off: usize,
9530    change: &Change,
9531    block: Option<(&Range<usize>, &Range<usize>)>,
9532) -> usize {
9533    if let Some((was, now)) = block
9534        && was.start <= off
9535        && off <= was.end
9536    {
9537        return now.start + (off - was.start).min(now.end - now.start);
9538    }
9539    reanchor(off, change)
9540}
9541
9542/// A watermark for a file's contents (see `Doc::disk_hash`).
9543///
9544/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
9545/// watermark is compared only against one taken by the same process moments
9546/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
9547/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
9548fn hash_bytes(bytes: &[u8]) -> u64 {
9549    use std::hash::{Hash, Hasher};
9550    let mut h = std::collections::hash_map::DefaultHasher::new();
9551    bytes.hash(&mut h);
9552    h.finish()
9553}
9554
9555#[cfg(feature = "fs")]
9556fn detect_format(path: &Path) -> Result<Format> {
9557    let ext = path
9558        .extension()
9559        .and_then(|e| e.to_str())
9560        .unwrap_or("")
9561        .to_ascii_lowercase();
9562    Ok(match ext.as_str() {
9563        "dj" | "djot" => Format::Djot,
9564        "md" | "markdown" => Format::Markdown,
9565        "xml" => Format::Xml,
9566        "html" | "htm" => Format::Html,
9567        other => return Err(anyhow!("unknown document extension: .{other}")),
9568    })
9569}
9570
9571/// The one span `from` and `to` differ in: `[start, end)` of `from`, and
9572/// what `to` holds there. The longest shared prefix, then the longest shared
9573/// suffix of what is left — never overlapping it — each ended on a character
9574/// boundary of both.
9575fn differing_span<'a>(from: &str, to: &'a str) -> (usize, usize, &'a str) {
9576    let (a, b) = (from.as_bytes(), to.as_bytes());
9577    let mut prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
9578    while !(from.is_char_boundary(prefix) && to.is_char_boundary(prefix)) {
9579        prefix -= 1;
9580    }
9581    let most = a.len().min(b.len()) - prefix;
9582    let mut suffix = a
9583        .iter()
9584        .rev()
9585        .zip(b.iter().rev())
9586        .take(most)
9587        .take_while(|(x, y)| x == y)
9588        .count();
9589    while !(from.is_char_boundary(a.len() - suffix) && to.is_char_boundary(b.len() - suffix)) {
9590        suffix -= 1;
9591    }
9592    (prefix, a.len() - suffix, &to[prefix..b.len() - suffix])
9593}
9594
9595#[cfg(test)]
9596mod tests {
9597    use super::*;
9598    use crate::style::{FontFamily, LineSpacing, SizeStep};
9599
9600    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
9601    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
9602    /// without one is a view no user is ever in.
9603    fn doc_in(view: View, name: &str, body: &str) -> Doc {
9604        // The fixture name doubles as the temp file's, so two tests picking the
9605        // same one raced under the parallel runner and read each other's body —
9606        // a green suite proving the wrong thing. The counter makes that
9607        // unreachable rather than asking every future caller to notice.
9608        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
9609        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9610        let mut p = std::env::temp_dir();
9611        p.push(format!("leaf_test_{name}_{seq}.md"));
9612        std::fs::write(&p, body).unwrap();
9613        let mut d = Doc::open(p).unwrap();
9614        d.view = view;
9615        if view == View::Wysiwyg {
9616            d.build_visual(80);
9617        }
9618        d
9619    }
9620
9621    // Source-view document for the source-behaviour tests. `Doc::open` now
9622    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
9623    // `wysiwyg_doc` builds the rich-text variant on top of this.
9624    fn doc_with(name: &str, body: &str) -> Doc {
9625        doc_in(View::Source, name, body)
9626    }
9627
9628    /// Every visual row's drawn text — what the reader actually sees, which is
9629    /// the only thing the reveal preference is supposed to change.
9630    fn drawn_rows(d: &Doc) -> Vec<String> {
9631        d.vmap
9632            .rows
9633            .iter()
9634            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9635            .collect()
9636    }
9637
9638    /// Put the caret at the first byte of `needle` and rebuild, so the row under
9639    /// it becomes the revealed line.
9640    fn caret_at(d: &mut Doc, needle: &str) {
9641        d.caret = d.source.find(needle).expect("needle in source");
9642        d.build_visual(80);
9643    }
9644
9645    #[test]
9646    fn blockquote_after_a_list_is_not_bulleted() {
9647        // twig nests a following top-level block quote under the `bullet_list`
9648        // (a direct child, not a `list_item`). The map must render it de-nested —
9649        // `│ quote`, never `• │ quote` — with a blank separator, like any block
9650        // that follows a list. Regression for the "combined list + blockquote" bug.
9651        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
9652        d.build_visual(80);
9653        let rows: Vec<String> = d
9654            .vmap
9655            .rows
9656            .iter()
9657            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9658            .collect();
9659        assert!(
9660            rows.iter().any(|r| r == "│ quote"),
9661            "block quote should render on its own gutter, got rows: {rows:?}"
9662        );
9663        assert!(
9664            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
9665            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
9666        );
9667    }
9668
9669    // ── the map is built at most once per (revision, wrap) ───────────────────
9670    //
9671    // A frontend repaints for reasons that have nothing to do with the text — a
9672    // blinking caret, a scroll — and rebuilding the map is O(document). These
9673    // pin *that the cache fires*, which a passing suite can't tell you: a cache
9674    // that never hits is invisible to every other test in this file.
9675    //
9676    // The probe is to wreck the built map and ask for it again. A rebuild
9677    // repairs it; a cache hit hands the wreckage straight back. Nothing else
9678    // can distinguish the two from outside.
9679
9680    #[test]
9681    fn a_rebuild_with_nothing_changed_reuses_the_map() {
9682        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
9683        d.build_visual(80);
9684        assert!(!d.vmap.rows.is_empty());
9685        d.vmap.rows.clear(); // wreck it
9686        d.build_visual(80);
9687        assert!(
9688            d.vmap.rows.is_empty(),
9689            "the map was rebuilt though nothing changed — the cache never fired"
9690        );
9691    }
9692
9693    #[test]
9694    fn an_edit_rebuilds_the_map() {
9695        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
9696        d.build_visual(80);
9697        let before = d.revision();
9698        d.vmap.rows.clear();
9699        d.insert("x");
9700        d.build_visual(80);
9701        assert!(d.revision() > before, "an edit must move the revision");
9702        assert!(
9703            !d.vmap.rows.is_empty(),
9704            "an edited document must not paint from a stale map"
9705        );
9706    }
9707
9708    #[test]
9709    fn a_width_change_rebuilds_the_map() {
9710        // The map is a function of the wrap width too, so a resize is a miss
9711        // even though the text is untouched.
9712        let mut d = doc_in(
9713            View::Wysiwyg,
9714            "cache_width",
9715            "one two three four five six\n",
9716        );
9717        d.build_visual(80);
9718        d.vmap.rows.clear();
9719        d.build_visual(12);
9720        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
9721        // And the unwrapped map is its own key, not the same as any width.
9722        d.vmap.rows.clear();
9723        d.build_visual_unwrapped();
9724        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
9725    }
9726
9727    #[test]
9728    fn a_motion_does_not_rebuild_the_map() {
9729        // The whole point: moving the caret changes nothing the map is built
9730        // from. If a motion bumped the revision, every arrow key would cost a
9731        // full rebuild and the cache would be worthless.
9732        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
9733        d.build_visual(80);
9734        let rev = d.revision();
9735        d.move_right(false);
9736        d.move_right(true);
9737        d.move_down(false);
9738        assert_eq!(d.revision(), rev, "a motion must not move the revision");
9739        d.vmap.rows.clear();
9740        d.build_visual(80);
9741        assert!(
9742            d.vmap.rows.is_empty(),
9743            "a motion should not rebuild the map"
9744        );
9745    }
9746
9747    #[test]
9748    fn saving_does_not_rebuild_the_map() {
9749        // Saving changes `dirty`, not the text.
9750        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
9751        d.insert("x");
9752        d.build_visual(80);
9753        let rev = d.revision();
9754        d.save();
9755        assert_eq!(d.revision(), rev, "a save must not move the revision");
9756        assert!(!d.dirty, "the save should have cleaned the document");
9757    }
9758
9759    #[test]
9760    fn a_reload_rebuilds_the_map() {
9761        // Reload replaces the text without going through `refresh`, so it has to
9762        // move the revision itself — else the editor paints the old file.
9763        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
9764        d.build_visual(80);
9765        let rev = d.revision();
9766        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
9767        d.reload();
9768        assert!(d.revision() > rev, "a reload must move the revision");
9769        d.build_visual(80);
9770        let text: String = d
9771            .vmap
9772            .rows
9773            .iter()
9774            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
9775            .collect();
9776        assert!(
9777            text.contains("wholly new"),
9778            "the reloaded text should be on screen, got {text:?}"
9779        );
9780    }
9781
9782    // ── golden-case harness ──────────────────────────────────────────────────
9783    // The pattern the whole parity suite can reuse: write a fixture with the
9784    // caret marked by `|`, run one action, and compare the rendered result —
9785    // also caret-marked — against the expected string. One readable line per
9786    // behavior, and it exercises the exact `Doc` ops both frontends call.
9787
9788    /// Split a `|`-marked fixture into `(source, caret_offset)`.
9789    fn parse_caret(marked: &str) -> (String, usize) {
9790        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
9791        (marked.replacen('|', "", 1), caret)
9792    }
9793
9794    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
9795    /// selection) so a result reads like the fixtures.
9796    fn render_caret(d: &Doc) -> String {
9797        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
9798        // so the caret always renders inside its own selection.
9799        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
9800        if let Some((s, e)) = d.selection() {
9801            marks.push((s, 0, '['));
9802            marks.push((e, 2, ']'));
9803        }
9804        // Insert right-to-left: descending offset, then descending rank.
9805        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
9806        let mut out = d.source.clone();
9807        for (at, _, ch) in marks {
9808            out.insert(at, ch);
9809        }
9810        out
9811    }
9812
9813    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
9814    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9815        golden_in(View::Source, name, marked, action)
9816    }
9817
9818    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
9819    /// the same fixture has to read the same way in both.
9820    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9821        let (src, caret) = parse_caret(marked);
9822        let mut d = doc_in(view, name, &src);
9823        d.caret = caret;
9824        action(&mut d);
9825        render_caret(&d)
9826    }
9827
9828    #[test]
9829    fn word_motion_walks_word_by_word() {
9830        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
9831        assert_eq!(
9832            g("hello wor|ld", |d| d.move_word_left(false)),
9833            "hello |world"
9834        );
9835        assert_eq!(
9836            g("hello| world", |d| d.move_word_left(false)),
9837            "|hello world"
9838        );
9839        assert_eq!(
9840            g("hel|lo world", |d| d.move_word_right(false)),
9841            "hello| world"
9842        );
9843        assert_eq!(
9844            g("hello| world", |d| d.move_word_right(false)),
9845            "hello world|"
9846        );
9847        // Punctuation is its own class, so motion stops at the boundary.
9848        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
9849    }
9850
9851    #[test]
9852    fn word_motion_extends_the_selection_when_asked() {
9853        assert_eq!(
9854            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
9855            "hello [world|]"
9856        );
9857    }
9858
9859    #[test]
9860    fn delete_word_removes_a_whole_word() {
9861        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
9862        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
9863        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
9864        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
9865    }
9866
9867    // ── Home / End ───────────────────────────────────────────────────────────
9868
9869    #[test]
9870    fn home_toggles_between_the_line_s_text_and_its_margin() {
9871        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
9872        // indent to the markup it spells everywhere it means one, so the fixture
9873        // with whitespace left to walk is a code block, which is verbatim.
9874        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
9875        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
9876        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
9877        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
9878        // A line with no indentation has one place to go, so the toggle is a
9879        // no-op rather than a trip to nowhere.
9880        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
9881        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
9882
9883        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
9884        let indent = d.source.find("    indented").unwrap();
9885        d.caret = indent + 6; // inside "indented"
9886        d.move_home(false);
9887        assert_eq!(
9888            d.caret,
9889            indent + 4,
9890            "wysiwyg: Home aims at the code line's text"
9891        );
9892        d.move_home(false);
9893        assert_eq!(
9894            d.caret, indent,
9895            "wysiwyg: the second press takes the indent"
9896        );
9897        d.move_home(false);
9898        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
9899    }
9900
9901    #[test]
9902    fn end_takes_the_line_the_view_is_showing() {
9903        // The line differs by view for the same document, and that is the point:
9904        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
9905        // as a space on one row and the source view as two lines.
9906        let mut d = doc_with("end_src", "one two\nthree\n");
9907        d.caret = 1;
9908        d.move_end(false);
9909        assert_eq!(d.caret, 7, "source: the end of the source line");
9910
9911        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
9912        d.caret = 1;
9913        d.move_end(false);
9914        assert_eq!(
9915            d.caret, 13,
9916            "wysiwyg: the end of the row, soft break and all"
9917        );
9918    }
9919
9920    #[test]
9921    fn home_and_end_extend_the_selection_when_asked() {
9922        for (view, tag) in VIEWS {
9923            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
9924            d.caret = 6;
9925            d.move_end(true);
9926            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
9927            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
9928            d.caret = 6;
9929            d.move_home(true);
9930            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
9931        }
9932    }
9933
9934    // ── kill to the line's start / end ───────────────────────────────────────
9935
9936    #[test]
9937    fn kill_to_the_line_start_and_end_in_both_views() {
9938        for (view, tag) in VIEWS {
9939            // The gap that reads as a paragraph break in each view: the source
9940            // view's lines are the renderer's rows only where the source says so.
9941            let gap = if view == View::Source { "\n" } else { "\n\n" };
9942            let mut d = doc_in(
9943                view,
9944                &format!("kill_end_{tag}"),
9945                &format!("one two{gap}three\n"),
9946            );
9947            d.caret = 3;
9948            d.delete_to_line_end();
9949            assert_eq!(
9950                d.source,
9951                format!("one{gap}three\n"),
9952                "{tag}: ^K to the line's end"
9953            );
9954            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
9955
9956            let mut d = doc_in(
9957                view,
9958                &format!("kill_start_{tag}"),
9959                &format!("one two{gap}three\n"),
9960            );
9961            d.caret = 7; // the end of the first line
9962            d.delete_to_line_start();
9963            assert_eq!(
9964                d.source,
9965                format!("{gap}three\n"),
9966                "{tag}: ⌘⌫ to the line's start"
9967            );
9968            assert_eq!(d.caret, 0, "{tag}");
9969        }
9970    }
9971
9972    #[test]
9973    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
9974        // The decision: at the boundary both kills do nothing, rather than
9975        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
9976        // at a soft wrap as often as at a newline, where there is nothing
9977        // written to delete — and a source newline is only half of the blank
9978        // line between two paragraphs, so taking it leaves a soft break rather
9979        // than the join it looks like. Backspace and Delete are the keys for it.
9980        for (view, tag) in VIEWS {
9981            let gap = if view == View::Source { "\n" } else { "\n\n" };
9982            let src = format!("one{gap}three\n");
9983            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
9984            d.caret = 3; // the end of "one"
9985            d.delete_to_line_end();
9986            assert_eq!(
9987                d.source, src,
9988                "{tag}: ^K at the line's end joined it to the next"
9989            );
9990
9991            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
9992            d.caret = 3 + gap.len(); // the start of "three"
9993            d.delete_to_line_start();
9994            assert_eq!(
9995                d.source, src,
9996                "{tag}: ⌘⌫ at the line's start joined it to the last"
9997            );
9998        }
9999    }
10000
10001    #[test]
10002    fn a_kill_takes_the_selection_when_there_is_one() {
10003        // What every other delete here does with one, so these two as well.
10004        for (view, tag) in VIEWS {
10005            for (name, kill) in [
10006                (
10007                    "end",
10008                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
10009                ),
10010                ("start", |d: &mut Doc| d.delete_to_line_start()),
10011            ] {
10012                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
10013                d.anchor = Some(4);
10014                d.caret = 7; // "two"
10015                kill(&mut d);
10016                assert_eq!(
10017                    d.source, "one  three\n",
10018                    "{tag}: {name} ignored the selection"
10019                );
10020                assert_eq!(d.selection(), None, "{tag}: {name}");
10021            }
10022        }
10023    }
10024
10025    #[test]
10026    fn a_kill_takes_the_markup_it_empties_with_it() {
10027        // The same hazard a word-delete has: a WYSIWYG range covers what the
10028        // user can see, which for `**bold**` is the word and never the
10029        // delimiters, so a kill that stopped at the text would leave `a ****` —
10030        // markup wrapped around nothing.
10031        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
10032        d.caret = d.source.find("bold").unwrap();
10033        d.delete_to_line_end();
10034        assert_eq!(d.source, "a \n");
10035    }
10036
10037    #[test]
10038    fn a_kill_is_undone_in_one_step() {
10039        for (view, tag) in VIEWS {
10040            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
10041            d.caret = 3;
10042            d.delete_to_line_end();
10043            assert_eq!(d.source, "one\n", "{tag}");
10044            d.undo();
10045            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
10046        }
10047    }
10048
10049    #[test]
10050    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
10051        // Regression: triple-click used move_home/move_end over visual rows, so
10052        // it only worked on a paragraph's first row (a wrap-boundary offset maps
10053        // to the earlier row). select_block_at reads the AST, so every offset in
10054        // the paragraph selects the whole thing.
10055        let body = "one two three four five six seven eight\n";
10056        let mut d = doc_with("sel_block", body);
10057        d.view = View::Wysiwyg;
10058        d.build_visual(12); // force the paragraph to wrap into several rows
10059        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
10060        let para = (0, "one two three four five six seven eight".len());
10061        for off in [0usize, 8, 19, 28, 38] {
10062            d.caret = 0;
10063            d.anchor = None;
10064            d.select_block_at(off);
10065            assert_eq!(
10066                d.selection(),
10067                Some(para),
10068                "offset {off} should select the paragraph"
10069            );
10070        }
10071    }
10072
10073    #[test]
10074    fn select_block_uses_content_span_for_a_heading() {
10075        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
10076        d.select_block_at(4); // inside "Title"
10077        // content_span excludes the "# " marker.
10078        assert_eq!(d.selected_text(), Some("Title"));
10079        d.select_block_at(10); // inside "body"
10080        assert_eq!(d.selected_text(), Some("body"));
10081    }
10082
10083    #[test]
10084    fn select_all_spans_the_document() {
10085        let mut d = doc_with("sel_all", "abc\n\ndef\n");
10086        d.select_all();
10087        assert_eq!(d.selection(), Some((0, d.source.len())));
10088    }
10089
10090    #[test]
10091    fn select_word_at_picks_the_surrounding_word() {
10092        let mut d = doc_with("sel_word", "hello world\n");
10093        d.select_word_at(8); // inside "world"
10094        assert_eq!(d.selection(), Some((6, 11)));
10095        // Double-clicking at end-of-word still grabs the word to its left.
10096        d.select_word_at(5); // the space between the words
10097        assert_eq!(d.selection(), Some((5, 6)));
10098    }
10099
10100    #[test]
10101    fn word_helpers_respect_utf8_boundaries() {
10102        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
10103        assert_eq!(
10104            golden("utf8", "|café ok", |d| d.move_word_right(false)),
10105            "café| ok"
10106        );
10107        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
10108    }
10109
10110    #[test]
10111    fn typing_inserts_at_the_caret_and_advances_it() {
10112        let mut d = doc_with("type", "hello\n");
10113        d.insert("Hi ");
10114        assert_eq!(d.source, "Hi hello\n");
10115        assert_eq!(d.caret, 3);
10116        assert!(d.dirty);
10117    }
10118
10119    #[test]
10120    fn backspace_deletes_the_char_before_the_caret() {
10121        let mut d = doc_with("bs", "hello\n");
10122        d.caret = 3; // after "hel"
10123        d.backspace();
10124        assert_eq!(d.source, "helo\n");
10125        assert_eq!(d.caret, 2);
10126    }
10127
10128    #[test]
10129    fn typing_replaces_the_selection() {
10130        let mut d = doc_with("replace", "a word b\n");
10131        d.anchor = Some(2);
10132        d.caret = 6; // "word" selected
10133        d.insert("X");
10134        assert_eq!(d.source, "a X b\n");
10135        assert_eq!(d.caret, 3);
10136        assert_eq!(d.anchor, None);
10137    }
10138
10139    #[test]
10140    fn toggle_bold_wraps_then_unwraps_the_selection() {
10141        let mut d = doc_with("bold", "a word b\n");
10142        d.anchor = Some(2);
10143        d.caret = 6;
10144        d.toggle(InlineKind::Strong);
10145        assert_eq!(d.source, "a **word** b\n");
10146        // The toggled region stays selected, so a second toggle reverses it.
10147        d.toggle(InlineKind::Strong);
10148        assert_eq!(d.source, "a word b\n");
10149        d.toggle(InlineKind::Strong);
10150        assert_eq!(d.source, "a **word** b\n");
10151    }
10152
10153    #[test]
10154    fn toggle_code_wraps_then_unwraps_the_selection() {
10155        let mut d = doc_with("code_rt", "a word b\n");
10156        d.anchor = Some(2);
10157        d.caret = 6;
10158        d.toggle(InlineKind::Verbatim);
10159        assert_eq!(d.source, "a `word` b\n");
10160        d.toggle(InlineKind::Verbatim);
10161        assert_eq!(d.source, "a word b\n");
10162    }
10163
10164    #[test]
10165    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
10166        // ⌘b at a bare caret, then type: the text comes out bold with no
10167        // selection ever made — the word-processor "start bold here" gesture.
10168        let mut d = doc_with("sticky_wrap", "xy\n");
10169        d.caret = 1; // between x and y
10170        d.toggle(InlineKind::Strong);
10171        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
10172        d.insert("A");
10173        assert_eq!(d.source, "x**A**y\n");
10174    }
10175
10176    #[test]
10177    fn sticky_bold_lights_the_toolbar_before_any_typing() {
10178        // The button must light the instant ⌘b is pressed, or the mode is
10179        // invisible until the first character lands.
10180        let mut d = doc_with("sticky_light", "xy\n");
10181        d.caret = 1;
10182        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10183        d.toggle(InlineKind::Strong);
10184        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10185    }
10186
10187    #[test]
10188    fn sticky_bold_toggled_off_types_normally_again() {
10189        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
10190        // in the flow of typing, the exact sequence the user described.
10191        let mut d = doc_with("sticky_off", "\n");
10192        d.caret = 0;
10193        d.toggle(InlineKind::Strong);
10194        d.insert("a");
10195        d.insert("b"); // continues inside the run, no re-arming
10196        assert_eq!(d.source, "**ab**\n");
10197        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
10198        d.insert("c");
10199        assert_eq!(d.source, "**ab**c\n");
10200    }
10201
10202    #[test]
10203    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
10204        // Once a mark is realised the caret sits inside the run, so plain typing
10205        // extends it rather than starting a second, adjacent bold span.
10206        let mut d = doc_with("sticky_cont", "\n");
10207        d.caret = 0;
10208        d.toggle(InlineKind::Emph);
10209        d.insert("h");
10210        d.insert("i");
10211        assert_eq!(d.source, "*hi*\n");
10212    }
10213
10214    #[test]
10215    fn moving_the_caret_disarms_a_sticky_mark() {
10216        // Arming a mark and then moving away must not style text elsewhere.
10217        let mut d = doc_with("sticky_disarm", "xy\n");
10218        d.caret = 0;
10219        d.toggle(InlineKind::Strong);
10220        d.move_right(false); // caret 0 → 1, disarms
10221        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10222        d.insert("A");
10223        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
10224    }
10225
10226    #[test]
10227    fn stacked_sticky_marks_apply_together() {
10228        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
10229        let mut d = doc_with("sticky_stack", "\n");
10230        d.caret = 0;
10231        d.toggle(InlineKind::Strong);
10232        d.toggle(InlineKind::Emph);
10233        d.insert("x");
10234        // Land the caret on the styled character and confirm both marks are live.
10235        d.anchor = Some(d.source.find('x').unwrap());
10236        d.caret = d.anchor.unwrap() + 1;
10237        let marks = d.active_inline_marks();
10238        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
10239        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
10240    }
10241
10242    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
10243
10244    #[test]
10245    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
10246        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
10247        // The space inside the run made `**bold **`, which is *not* bold — four
10248        // literal asterisks — so the rich view drew them, correctly and
10249        // uselessly, until the next character happened to close the run again.
10250        let mut d = wysiwyg_doc("edge_typing", "a \n");
10251        d.caret = 2;
10252        d.toggle(InlineKind::Strong);
10253        for c in "bold".chars() {
10254            d.insert(&c.to_string());
10255        }
10256        assert_eq!(d.source, "a **bold**\n");
10257        d.insert(" ");
10258        assert_eq!(
10259            d.source, "a **bold** \n",
10260            "the space belongs outside the run"
10261        );
10262        assert!(
10263            d.active_inline_marks().contains(InlineKind::Strong),
10264            "bold is still what's being typed, so the button stays lit"
10265        );
10266        // What the writer is looking at while all this happens: their words.
10267        d.build_visual(80);
10268        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
10269        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
10270        for c in "hey".chars() {
10271            d.insert(&c.to_string());
10272        }
10273        assert_eq!(
10274            d.source, "a **bold hey**\n",
10275            "one bold phrase, not two runs"
10276        );
10277    }
10278
10279    #[test]
10280    fn typing_past_a_space_can_still_leave_the_bold_behind() {
10281        // The other half: the marks stay armed across the space, so ⌘b turns
10282        // them off again there and the next word is plain — the run isn't
10283        // rejoined by a caret that was told not to.
10284        let mut d = wysiwyg_doc("edge_shed", "\n");
10285        d.caret = 0;
10286        d.toggle(InlineKind::Strong);
10287        for c in "bold ".chars() {
10288            d.insert(&c.to_string());
10289        }
10290        assert_eq!(d.source, "**bold** \n");
10291        d.toggle(InlineKind::Strong);
10292        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10293        d.insert("x");
10294        assert_eq!(d.source, "**bold** x\n");
10295    }
10296
10297    #[test]
10298    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
10299        // ⌘b and then a space before any word: the space is not marked (nothing
10300        // is), and the word after it is.
10301        let mut d = wysiwyg_doc("edge_space_first", "a\n");
10302        d.caret = 1;
10303        d.toggle(InlineKind::Strong);
10304        d.insert(" ");
10305        assert_eq!(d.source, "a \n");
10306        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10307        d.insert("b");
10308        assert_eq!(d.source, "a **b**\n");
10309    }
10310
10311    #[test]
10312    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
10313        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
10314        d.caret = 8; // the caret's home at the end of the run's text
10315        d.insert(" ");
10316        assert_eq!(
10317            d.source, "x **bold** \n",
10318            "the space lands past the delimiters"
10319        );
10320        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
10321
10322        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
10323        d.caret = 4; // in front of the "b"
10324        d.insert(" ");
10325        assert_eq!(d.source, "x  **bold** y\n");
10326        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
10327    }
10328
10329    #[test]
10330    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
10331        // Backspace over the last letter of a bold phrase.
10332        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
10333        d.caret = 10; // past the "h"
10334        d.backspace();
10335        assert_eq!(d.source, "a **bold** \n");
10336        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
10337        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10338        d.insert("x");
10339        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
10340    }
10341
10342    #[test]
10343    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
10344        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
10345        // mark, which is only text. The marks live on in the caret instead.
10346        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
10347        d.caret = 5;
10348        d.backspace();
10349        assert_eq!(d.source, "a  c\n");
10350        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10351        d.insert("x");
10352        assert_eq!(d.source, "a **x** c\n");
10353    }
10354
10355    #[test]
10356    fn typing_over_a_whole_bold_word_keeps_it_bold() {
10357        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
10358        d.anchor = Some(4);
10359        d.caret = 8; // the word, not its delimiters
10360        d.insert("x");
10361        assert_eq!(d.source, "a **x** c\n");
10362    }
10363
10364    #[test]
10365    fn a_code_span_keeps_the_space_it_is_given() {
10366        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
10367        // is still verbatim, so nothing is re-spelt. The repair asks the parser
10368        // rather than a table of kinds, and this is the answer it gets.
10369        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
10370        d.caret = 7;
10371        d.insert(" ");
10372        assert_eq!(d.source, "a `code ` c\n");
10373    }
10374
10375    #[test]
10376    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
10377        // A run's closing delimiter has a caret home on each side of it, one
10378        // column apart on screen — and a plain ← off the space after a bold word
10379        // lands on the outer one. The character drawn behind the caret there is
10380        // still the last letter of the phrase, so that is what Backspace takes;
10381        // the byte behind it is a `*` nobody can see.
10382        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
10383        d.caret = 9;
10384        d.move_left(false);
10385        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
10386        d.backspace();
10387        assert_eq!(
10388            d.source, "**bol** x\n",
10389            "a letter of the phrase, not its `*`"
10390        );
10391        assert_eq!(d.caret, 5);
10392
10393        // And the mirror in front of the opening delimiter, where Delete's
10394        // character is the first letter of the run.
10395        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
10396        d.caret = 1;
10397        d.delete_forward();
10398        assert_eq!(d.source, "x**old**\n");
10399        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
10400    }
10401
10402    #[test]
10403    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
10404        // The byte beside the caret at either edge of a bold word is a `*` the
10405        // rich view draws nothing for. Taking it is not the character delete the
10406        // key was pressed for — it unspells the run and puts a literal asterisk
10407        // on screen (`a *bold** c`). The visible character is the one that goes.
10408        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
10409        d.caret = 4; // in front of the "b"
10410        d.backspace();
10411        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
10412
10413        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
10414        d.caret = 8; // past the "d"
10415        d.delete_forward();
10416        assert_eq!(d.source, "a **bold**c\n");
10417        assert_eq!(d.caret, 8, "and the caret stays inside the run");
10418        d.insert("x");
10419        assert_eq!(d.source, "a **boldx**c\n");
10420
10421        // A code span's backticks are hidden the same way, so they are covered
10422        // by the same rule and not by a list of kinds.
10423        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
10424        d.caret = 3;
10425        d.backspace();
10426        assert_eq!(d.source, "a`code` c\n");
10427    }
10428
10429    #[test]
10430    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
10431        // The asterisks are on the screen there and the caret can stand between
10432        // them, so a delete takes exactly the byte it is aimed at.
10433        let mut d = doc_with("edge_open_src", "a **bold** c\n");
10434        d.caret = 4;
10435        d.backspace();
10436        assert_eq!(d.source, "a *bold** c\n");
10437
10438        let mut d = doc_with("edge_close_src", "a **bold** c\n");
10439        d.caret = 8;
10440        d.delete_forward();
10441        assert_eq!(d.source, "a **bold* c\n");
10442    }
10443
10444    #[test]
10445    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
10446        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
10447        // The space had stepped outside the run (the mark-edge rule), taking the
10448        // caret with it, so the delete put it back down on the far side of the
10449        // closing `**` — one place on screen, and the wrong side of it. Typing
10450        // came out plain and the toolbar went dark, with nothing to see.
10451        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
10452        d.caret = 0;
10453        d.toggle(InlineKind::Strong);
10454        for c in "bold".chars() {
10455            d.insert(&c.to_string());
10456        }
10457        d.insert(" ");
10458        assert_eq!(d.source, "**bold** \n");
10459        d.backspace();
10460        assert_eq!(
10461            d.source, "**bold**\n",
10462            "the space goes, the delimiters stay"
10463        );
10464        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
10465        assert!(
10466            d.active_inline_marks().contains(InlineKind::Strong),
10467            "so the button is still lit"
10468        );
10469        d.insert("x");
10470        assert_eq!(
10471            d.source, "**boldx**\n",
10472            "and the next character is still bold"
10473        );
10474    }
10475
10476    #[test]
10477    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
10478        // What the stranded caret did next: the byte behind it was the closing
10479        // `*`, so a second press took that instead of a letter — `**bold*`, the
10480        // styling gone and an asterisk on the screen where the word had been.
10481        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
10482        d.caret = 0;
10483        d.toggle(InlineKind::Strong);
10484        for c in "bold ".chars() {
10485            d.insert(&c.to_string());
10486        }
10487        assert_eq!(d.source, "**bold** \n");
10488        d.backspace();
10489        d.backspace();
10490        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
10491        assert_eq!(d.caret, 5);
10492    }
10493
10494    #[test]
10495    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
10496        // `***both***` closes two runs with one stack of asterisks: the caret has
10497        // to walk in through all of them, or it lands between the emph and the
10498        // strong and types half-marked.
10499        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
10500        d.caret = 11;
10501        d.backspace();
10502        assert_eq!(d.source, "***both***\n");
10503        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
10504        d.insert("x");
10505        assert_eq!(d.source, "***bothx***\n");
10506    }
10507
10508    #[test]
10509    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
10510        // The settle only moves a caret a run actually closed over. Ordinary
10511        // deletes — inside a run, or in plain prose — are untouched.
10512        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
10513        d.caret = 8;
10514        d.backspace();
10515        assert_eq!(d.source, "a **bol** c\n");
10516        assert_eq!(d.caret, 7);
10517
10518        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
10519        d.caret = 5;
10520        d.backspace();
10521        assert_eq!(d.source, "plai\n");
10522        assert_eq!(d.caret, 4);
10523    }
10524
10525    #[test]
10526    fn the_source_view_leaves_a_delete_where_it_landed() {
10527        // The delimiters are on the screen there, so the offset past them is a
10528        // place the caret can be seen to be — nothing to settle.
10529        let mut d = doc_with("edge_bksp_src", "**bold** \n");
10530        d.caret = 9;
10531        d.backspace();
10532        assert_eq!(d.source, "**bold**\n");
10533        assert_eq!(d.caret, 8);
10534    }
10535
10536    #[test]
10537    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
10538        // `***both***` closes two runs with one stack of asterisks; a space that
10539        // clears only the inner one lands against the outer's and breaks that
10540        // instead.
10541        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
10542        d.caret = 9;
10543        d.insert(" ");
10544        assert_eq!(d.source, "a ***both*** \n");
10545        assert_eq!(d.caret, 13);
10546        d.insert("x");
10547        assert_eq!(d.source, "a ***both x***\n");
10548    }
10549
10550    #[test]
10551    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
10552        // The delimiter shuffle is not an edit the writer made, so it is not a
10553        // step they have to undo past.
10554        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
10555        d.caret = 8;
10556        d.insert(" ");
10557        assert_eq!(d.source, "a **bold** \n");
10558        d.undo();
10559        assert_eq!(d.source, "a **bold**\n");
10560    }
10561
10562    #[test]
10563    fn the_source_view_types_the_space_where_it_was_asked_to() {
10564        // The rule is a rich-view courtesy. In the source view the delimiters are
10565        // on the screen and the user is editing the bytes they can see.
10566        let mut d = doc_with("edge_src", "a **bold** c\n");
10567        d.caret = 8;
10568        d.insert(" ");
10569        assert_eq!(d.source, "a **bold ** c\n");
10570    }
10571
10572    #[test]
10573    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
10574        // Double-clicking a word takes the space after it; bolding that must not
10575        // spell `**word **`, which is not bold at all.
10576        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
10577        d.anchor = Some(2);
10578        d.caret = 7; // "word "
10579        d.toggle(InlineKind::Strong);
10580        assert_eq!(d.source, "a **word** b\n");
10581        d.toggle(InlineKind::Strong);
10582        assert_eq!(d.source, "a word b\n");
10583        d.toggle(InlineKind::Strong);
10584        assert_eq!(
10585            d.source, "a **word** b\n",
10586            "reapplying the mark must not wrap stale delimiter offsets"
10587        );
10588        // And a selection of nothing but whitespace has no word to mark.
10589        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
10590        d.anchor = Some(6);
10591        d.caret = 7;
10592        d.toggle(InlineKind::Strong);
10593        assert_eq!(d.source, "a word b\n");
10594        assert!(d.status.is_some());
10595    }
10596
10597    #[test]
10598    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
10599        let mut d = doc_with("head_set", "hello\n");
10600        d.caret = 2; // caret inside the paragraph, no selection
10601        d.set_block(BlockKind::Heading(1));
10602        assert_eq!(d.source, "# hello\n");
10603    }
10604
10605    #[test]
10606    fn set_block_heading_works_in_wysiwyg_view() {
10607        // The app defaults to WYSIWYG; the caret is a source offset either way.
10608        let mut d = wysiwyg_doc("head_wys", "hello\n");
10609        d.caret = 2;
10610        d.set_block(BlockKind::Heading(1));
10611        assert_eq!(d.source, "# hello\n");
10612    }
10613
10614    #[test]
10615    fn toggle_heading_applies_switches_and_reverts() {
10616        let mut d = doc_with("head_toggle", "hello\n");
10617        d.caret = 2;
10618        d.toggle_heading(1);
10619        assert_eq!(d.source, "# hello\n"); // paragraph → H1
10620        d.toggle_heading(2);
10621        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
10622        d.toggle_heading(2);
10623        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
10624    }
10625
10626    #[test]
10627    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
10628        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
10629        // the blank line but the caret rendered on the *next* line, because the
10630        // separator was a non-navigable decoration row. In Preserve flow that
10631        // blank line is a real caret home — the caret must resolve onto it, and
10632        // typing there makes the soft break that continues the paragraph.
10633        let src = "line one:\nsecond line\n";
10634        let mut d = wysiwyg_doc("pre_enter_lineend", src);
10635        d.set_line_flow(LineFlow::Preserve);
10636        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
10637        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
10638        d.newline();
10639        d.build_visual_unwrapped();
10640        assert_eq!(d.source, "line one:\n\nsecond line\n");
10641        assert_eq!(
10642            d.caret, 10,
10643            "caret sits on the new blank line, not the next line"
10644        );
10645        // The blank line is row 1, and the caret resolves onto it — not row 2.
10646        assert_eq!(
10647            d.vmap.pos_of_offset(10),
10648            (1, 0),
10649            "caret renders on the blank row"
10650        );
10651        assert!(
10652            !d.vmap.rows[1].decoration,
10653            "the blank line is navigable in Preserve"
10654        );
10655        // Typing there makes a soft break: one paragraph, three lines.
10656        d.insert("new clause,");
10657        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
10658    }
10659
10660    #[test]
10661    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
10662        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
10663        // that keeps it one paragraph — where Fold would open a second paragraph.
10664        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
10665        d.set_line_flow(LineFlow::Preserve);
10666        d.caret = 3;
10667        d.newline();
10668        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
10669
10670        // End-of-paragraph: Enter then typing continues the same paragraph on a
10671        // new line (a soft break), not a fresh paragraph.
10672        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
10673        d.set_line_flow(LineFlow::Preserve);
10674        d.caret = 3;
10675        d.newline();
10676        d.insert("def");
10677        assert_eq!(
10678            d.source, "abc\ndef\n",
10679            "end-of-line Enter + typing is a soft break"
10680        );
10681    }
10682
10683    #[test]
10684    fn preserve_double_enter_still_makes_a_paragraph() {
10685        // Two Enters in a row promote to a real paragraph break: the second lands
10686        // on the blank line the first opened and takes the empty-line branch.
10687        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
10688        d.set_line_flow(LineFlow::Preserve);
10689        d.caret = 3;
10690        d.newline();
10691        d.newline();
10692        d.insert("def");
10693        assert_eq!(
10694            d.source, "abc\n\ndef\n",
10695            "double Enter is a paragraph break"
10696        );
10697    }
10698
10699    #[test]
10700    fn preserve_backspace_joins_across_a_soft_break() {
10701        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
10702        // soft break it deletes the single newline and joins the two lines.
10703        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
10704        d.set_line_flow(LineFlow::Preserve);
10705        d.build_visual(80);
10706        d.caret = 4; // start of "def", just past the soft break
10707        d.backspace();
10708        assert_eq!(
10709            d.source, "abcdef\n",
10710            "Backspace joins across the soft break"
10711        );
10712        assert_eq!(d.caret, 3, "caret lands where the lines meet");
10713    }
10714
10715    #[test]
10716    fn fold_enter_still_starts_a_new_paragraph() {
10717        // The default flow is unchanged: a lone `\n` would render as an invisible
10718        // space, so Enter keeps opening the paragraph break that actually shows.
10719        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
10720        d.caret = 3;
10721        d.newline();
10722        assert_eq!(
10723            d.source, "abc\n\ndef\n",
10724            "Fold mid-line Enter is a paragraph break"
10725        );
10726    }
10727
10728    #[test]
10729    fn wysiwyg_one_enter_starts_a_new_paragraph() {
10730        // Regression: one Enter left the caret between the two newlines, so typing
10731        // made a soft break (one paragraph) and you needed a second Enter.
10732        let mut d = wysiwyg_doc("wys_enter", "abc\n");
10733        d.caret = 3;
10734        d.newline();
10735        d.insert("def");
10736        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
10737    }
10738
10739    #[test]
10740    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
10741        // Regression: Enter at the caret's natural End-of-line resting place
10742        // after a bold run with nothing following it (on screen: right after
10743        // "bold", before the hidden closing "**") spliced the paragraph break
10744        // at that very byte offset — which sits *before* the closing "**" in
10745        // the source, since the delimiter is hidden and emits no glyph of its
10746        // own for `push_row`'s "end of row" fallback to count. That severed the
10747        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
10748        // "**" alone on the new line instead of leaving "**bold**" intact with
10749        // a fresh empty paragraph after it.
10750        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
10751        d.move_end(false); // the WYSIWYG End key, from caret 0
10752        assert_eq!(
10753            d.caret, 6,
10754            "caret rests right after \"bold\", before the hidden \"**\""
10755        );
10756        d.newline();
10757        assert!(
10758            d.source.starts_with("**bold**"),
10759            "the closing ** must stay attached to \"bold\": got {:?}",
10760            d.source
10761        );
10762        assert_eq!(
10763            d.source, "**bold**\n\n\n",
10764            "a fresh empty paragraph follows the still-intact bold run"
10765        );
10766    }
10767
10768    #[test]
10769    fn source_view_enter_is_a_single_newline() {
10770        let mut d = doc_with("src_enter", "abc\n");
10771        d.caret = 3;
10772        d.newline();
10773        assert_eq!(d.source, "abc\n\n");
10774    }
10775
10776    #[test]
10777    fn heading_applies_at_the_end_of_a_paragraph() {
10778        // The caret at a line end sits at the doc level; set_block must still find
10779        // the block on that line.
10780        let mut d = doc_with("head_end", "abc\n");
10781        d.caret = 3; // end of "abc"
10782        d.toggle_heading(1);
10783        assert_eq!(d.source, "# abc\n");
10784    }
10785
10786    #[test]
10787    fn heading_on_an_empty_new_paragraph_creates_one() {
10788        let mut d = wysiwyg_doc("head_empty", "abc\n");
10789        d.caret = 3;
10790        d.newline(); // caret now on a fresh, empty paragraph
10791        d.toggle_heading(1);
10792        d.insert("Title");
10793        assert!(d.source.contains("# Title"), "got {:?}", d.source);
10794    }
10795
10796    #[test]
10797    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
10798        // The reported bug, end to end: click a blank line with another one under
10799        // it, press H1, type. The text landed in the heading and the caret's
10800        // offset was right (the source view drew it there), but the rich view
10801        // drew it two rows lower, on the trailing blank line — the empty `# `
10802        // heading had left every row below it short by the marker's two bytes,
10803        // and the blank line ended up claiming the heading's own end offset.
10804        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
10805        d.build_visual_unwrapped();
10806        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
10807        d.toggle_heading(1);
10808        for c in "title".chars() {
10809            d.insert(&c.to_string());
10810            d.build_visual_unwrapped(); // as a frontend does, one frame per key
10811        }
10812        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
10813        assert_eq!(
10814            d.caret_pos(),
10815            (4, 5),
10816            "the caret draws at the end of the heading"
10817        );
10818    }
10819
10820    #[test]
10821    fn clicking_an_empty_heading_types_after_its_marker() {
10822        // The same anchor from the other side: the empty heading's row is its own
10823        // caret home, so a click on it must land past the hidden `# `. Landing in
10824        // front of the hashes made the first keystroke un-heading the line.
10825        let mut d = wysiwyg_doc("head_click", "# \n");
10826        d.build_visual_unwrapped();
10827        d.caret = d.vmap.offset_of_pos(0, 0);
10828        d.insert("x");
10829        assert_eq!(d.source, "# x\n");
10830    }
10831
10832    #[test]
10833    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
10834        let mut d = wysiwyg_doc("head_enter", "# Title\n");
10835        d.caret = 7; // end of the heading
10836        d.newline();
10837        d.insert("body");
10838        assert_eq!(d.source, "# Title\n\nbody\n");
10839    }
10840
10841    #[test]
10842    fn wysiwyg_enter_continues_a_bullet_list() {
10843        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
10844        d.caret = 6; // end of "item"
10845        d.newline();
10846        d.insert("two");
10847        assert_eq!(d.source, "- item\n- two\n");
10848    }
10849
10850    #[test]
10851    fn wysiwyg_enter_increments_an_ordered_list() {
10852        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
10853        d.caret = 6; // end of "one"
10854        d.newline();
10855        d.insert("two");
10856        assert_eq!(d.source, "1. one\n2. two\n");
10857    }
10858
10859    #[test]
10860    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
10861        // Regression for the "extra newline" left between a list and the paragraph
10862        // below it. Enter, Enter leaves the list on a fresh empty paragraph
10863        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
10864        // Backspace should then take the caret cleanly back to the end of the list
10865        // item, `- item\n\nnext`, not delete a single newline and strand it on the
10866        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
10867        // no caret can land on. The map is rebuilt between keystrokes exactly as a
10868        // frontend does, since Backspace reads the stop table to place the delete.
10869        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
10870        d.caret = 6; // end of "item"
10871        d.newline();
10872        d.build_visual(80);
10873        d.newline(); // leave the list onto a fresh empty paragraph
10874        d.build_visual(80);
10875        assert_eq!(
10876            d.source, "- item\n\n\n\nnext\n",
10877            "double-Enter opens the empty paragraph"
10878        );
10879        d.backspace();
10880        assert_eq!(
10881            d.source, "- item\n\nnext\n",
10882            "one Backspace collapses the whole gap"
10883        );
10884        assert_eq!(
10885            d.caret, 6,
10886            "and lands the caret back at the end of the list item"
10887        );
10888    }
10889
10890    #[test]
10891    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
10892        // The stop-wise delete must not over-reach when there is no block boundary
10893        // to cross: two blank lines in a row are one caret stop apart, so pressing
10894        // Enter on an empty line and then Backspace removes exactly the one newline
10895        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
10896        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
10897        d.caret = 5; // the empty paragraph the first Enter already opened
10898        d.build_visual(80);
10899        d.newline();
10900        d.build_visual(80);
10901        assert_eq!(
10902            d.source, "abc\n\n\n\n",
10903            "Enter on the blank line adds one newline"
10904        );
10905        d.backspace();
10906        assert_eq!(
10907            d.source, "abc\n\n\n",
10908            "Backspace takes back exactly that one newline"
10909        );
10910    }
10911
10912    #[test]
10913    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
10914        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
10915        d.caret = 6; // end of the empty "- " item
10916        d.newline();
10917        d.insert("p");
10918        assert_eq!(d.source, "- a\n\np\n");
10919    }
10920
10921    #[test]
10922    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
10923        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
10924        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
10925        // not take the list-exit path (which would splice the `- ` away as if
10926        // leaving an empty item); the AST guard sends it to a normal break and
10927        // leaves the underline intact.
10928        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
10929        assert!(
10930            d.nodes().iter().any(|n| n.kind == Kind::Heading),
10931            "precondition: twig parses this as a heading, not a list",
10932        );
10933        d.caret = 7; // on the `- ` underline line
10934        d.newline();
10935        assert!(
10936            d.source.contains("- "),
10937            "the setext underline survives, not spliced away as a list item: {:?}",
10938            d.source,
10939        );
10940    }
10941
10942    #[test]
10943    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
10944        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
10945        d.caret = 7; // end of "abc" inside the fence
10946        d.newline();
10947        d.insert("def");
10948        assert_eq!(d.source, "```\nabc\ndef\n```\n");
10949    }
10950
10951    #[test]
10952    fn wysiwyg_enter_continues_a_block_quote() {
10953        // Enter opens a new *paragraph* inside the quote, not a second line of
10954        // the same one. `> quote\n> more` is a soft break, which under
10955        // `LineFlow::Fold` renders as a space — the keystroke would look like it
10956        // did nothing. The quoted blank line is what makes the break visible, and
10957        // it's the same thing Enter does in running prose.
10958        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
10959        d.caret = 7; // end of "quote"
10960        d.newline();
10961        d.insert("more");
10962        assert_eq!(d.source, "> quote\n>\n> more\n");
10963        // Still one quote, now holding two paragraphs — not a quote and a stray
10964        // line that fell out of it.
10965        let quotes = d
10966            .nodes()
10967            .iter()
10968            .filter(|n| n.kind == Kind::BlockQuote)
10969            .count();
10970        assert_eq!(quotes, 1);
10971    }
10972
10973    #[test]
10974    fn set_block_makes_a_heading_at_the_caret() {
10975        let mut d = doc_with("head", "Title\n\nbody\n");
10976        d.caret = 0;
10977        d.set_block(BlockKind::Heading(2));
10978        assert_eq!(d.source, "## Title\n\nbody\n");
10979        d.set_block(BlockKind::Paragraph);
10980        assert_eq!(d.source, "Title\n\nbody\n");
10981    }
10982
10983    // ── block containers (quote / list) ──────────────────────────────────────
10984
10985    #[test]
10986    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
10987        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
10988        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
10989        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
10990        // A caret at a line end sits at the doc level; the block is still found.
10991        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
10992    }
10993
10994    #[test]
10995    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
10996        // Every source line of the paragraph gets its own `> `, so a caret left
10997        // on its old byte offset falls one prefix per line above it too far
10998        // back — inside the markup it just asked for rather than in its word.
10999        assert_eq!(
11000            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
11001            "> aaa\n> b|bb\n> ccc\n"
11002        );
11003    }
11004
11005    #[test]
11006    fn toggle_blockquote_works_in_wysiwyg_view() {
11007        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
11008        assert_eq!(
11009            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
11010            "> hel|lo\n"
11011        );
11012        assert_eq!(
11013            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
11014            "hel|lo\n"
11015        );
11016    }
11017
11018    #[test]
11019    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
11020        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
11021        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
11022        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
11023        // The *other* kind converts in place instead of nesting, which is what
11024        // makes the two buttons one three-state control.
11025        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
11026        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
11027        // Its own kind, over the only item the list holds, takes it off.
11028        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
11029    }
11030
11031    #[test]
11032    fn toggle_list_works_in_wysiwyg_view() {
11033        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
11034        assert_eq!(
11035            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
11036            "1. hel|lo\n"
11037        );
11038        assert_eq!(
11039            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
11040            "- hel|lo\n"
11041        );
11042        assert_eq!(
11043            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
11044            "hel|lo\n"
11045        );
11046    }
11047
11048    #[test]
11049    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
11050        // The selection has to grow with the markup: twig takes a container off
11051        // only a range covering every block it holds, so the second press can
11052        // reverse the first only if the result is what's selected.
11053        let mut d = doc_with("list_sel", "abc\n\ndef\n");
11054        d.select_all();
11055        d.toggle_list(true);
11056        assert_eq!(d.source, "1. abc\n\n2. def\n");
11057        assert_eq!(d.selection(), Some((0, d.source.len())));
11058        d.toggle_list(true);
11059        assert_eq!(d.source, "abc\n\ndef\n");
11060    }
11061
11062    #[test]
11063    fn toggle_blockquote_nests_a_partly_covered_quote() {
11064        // twig's rule: covering only some of a container's blocks nests, because
11065        // taking the quote off would drag its uncovered siblings out with it.
11066        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
11067        d.caret = 2; // in the first quoted paragraph only
11068        d.toggle_blockquote();
11069        assert_eq!(d.source, "> > a\n>\n> b\n");
11070    }
11071
11072    #[test]
11073    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
11074        // A blank line used to be no block for twig to wrap —
11075        // `toggle_block_container` answered `NotFound` — so Quote and the list
11076        // buttons did nothing on the very line the H1 button works on, and leaf
11077        // lent twig a scratch paragraph to wrap and took it back out again.
11078        // twig 3.2.0 opens an empty container there itself, so what is left here
11079        // is where the caret lands: inside the marker that was just written.
11080        let mut d = doc_with("quote_blank", "\nabc\n");
11081        d.caret = 0;
11082        d.toggle_blockquote();
11083        assert_eq!(d.source, "> \nabc\n");
11084        assert_eq!(
11085            d.caret, 2,
11086            "the caret belongs inside the quote it just opened"
11087        );
11088        assert!(d.status.is_none(), "{:?}", d.status);
11089        assert!(d.dirty);
11090
11091        // And the paragraph below is still its own block: an empty container one
11092        // soft break from `abc` would take that paragraph into the quote with it.
11093        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
11094        d.caret = 0;
11095        d.toggle_blockquote();
11096        d.build_visual(80);
11097        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
11098
11099        // The same from the other side: a blank line directly under a paragraph
11100        // earns the blank line an empty block needs, rather than being read as a
11101        // soft break inside that paragraph.
11102        let mut d = doc_with("list_blank_below", "abc\n");
11103        d.caret = 4;
11104        d.toggle_list(false);
11105        assert_eq!(d.source, "abc\n\n- ");
11106        assert_eq!(d.caret, 7);
11107    }
11108
11109    #[test]
11110    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
11111        // The gesture the rendering fix is for. `newline` inside a quote already
11112        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
11113        // spelling — but the two marker lines it adds belonged to no node until
11114        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
11115        // just made drew as plain prose under the quote.
11116        let mut d = wysiwyg_doc("quote_enter", "> a\n");
11117        d.caret = 3; // past `a`, at the end of the quoted line
11118        d.newline();
11119        assert_eq!(d.source, "> a\n>\n> \n");
11120        d.build_visual(80);
11121        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
11122        // And the caret is on the new line, not stranded on the old one.
11123        assert_eq!(d.caret, 8);
11124    }
11125
11126    #[test]
11127    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
11128        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
11129        // now it is twig's single edit. Either way one ⌘z has to put the blank
11130        // line back rather than undoing into a half-built document.
11131        for open in [
11132            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
11133            &|d: &mut Doc| d.toggle_list(false),
11134            &|d: &mut Doc| d.toggle_list(true),
11135        ] {
11136            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
11137            d.caret = 3;
11138            open(&mut d);
11139            assert_ne!(d.source, "a\n\n\n\nb\n");
11140            d.undo();
11141            assert_eq!(d.source, "a\n\n\n\nb\n");
11142        }
11143    }
11144
11145    #[test]
11146    fn a_container_toggle_is_one_undo_step() {
11147        let mut d = doc_with("quote_undo", "hello\n");
11148        d.caret = 3;
11149        d.insert("X"); // a typing run the structural edit must not fold into
11150        d.toggle_blockquote();
11151        assert_eq!(d.source, "> helXlo\n");
11152        d.undo();
11153        assert_eq!(d.source, "helXlo\n");
11154    }
11155
11156    // ── links ────────────────────────────────────────────────────────────────
11157
11158    #[test]
11159    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
11160        let mut d = doc_with("link_sel", "word here\n");
11161        d.anchor = Some(0);
11162        d.caret = 4;
11163        d.insert_link("http://x.dev");
11164        assert_eq!(d.source, "[word](http://x.dev) here\n");
11165        // The text, not the destination — so a second press re-points the link
11166        // the first one made rather than nesting one inside it.
11167        assert_eq!(d.selected_text(), Some("word"));
11168        d.insert_link("http://y.dev");
11169        assert_eq!(d.source, "[word](http://y.dev) here\n");
11170        assert_eq!(d.selected_text(), Some("word"));
11171    }
11172
11173    #[test]
11174    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
11175        let mut d = doc_with("img_caret", "before after\n");
11176        d.caret = 7; // between "before " and "after"
11177        d.insert_image("cat.png", "a cat");
11178        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
11179        // The caret sits just past the inserted image, nothing selected.
11180        assert_eq!(d.selection(), None);
11181        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
11182    }
11183
11184    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
11185    /// destination at the first space, so the `format!` this used to be wrote
11186    /// something that was not an image at all — and the reader saw the markup as
11187    /// text. twig owns the spelling now, and moves it into the angle form.
11188    #[test]
11189    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
11190        let mut d = doc_with("img_space", "x\n");
11191        d.caret = 0;
11192        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
11193        assert_eq!(
11194            d.source,
11195            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
11196        );
11197        // And it reads back as an image pointing at the unescaped path — the angle
11198        // brackets are spelling, not part of the destination.
11199        d.caret = 2;
11200        assert_eq!(
11201            d.image_destination_at_caret(),
11202            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
11203        );
11204    }
11205
11206    /// A `)` in a caption or a filename must not close the image early.
11207    #[test]
11208    fn insert_image_escapes_a_paren_in_either_half() {
11209        let mut d = doc_with("img_paren", "x\n");
11210        d.caret = 0;
11211        d.insert_image("a)b.png", "");
11212        assert_eq!(d.source, "![](a\\)b.png)x\n");
11213        d.caret = 2;
11214        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
11215    }
11216
11217    #[test]
11218    fn insert_image_uses_the_selection_as_alt_text() {
11219        let mut d = doc_with("img_sel", "caption here\n");
11220        d.anchor = Some(0);
11221        d.caret = 7; // "caption"
11222        d.insert_image("p.png", "ignored fallback");
11223        assert_eq!(d.source, "![caption](p.png) here\n");
11224    }
11225
11226    #[test]
11227    fn insert_image_with_no_alt_leaves_empty_brackets() {
11228        let mut d = doc_with("img_noalt", "\n");
11229        d.caret = 0;
11230        d.insert_image("logo.svg", "");
11231        assert_eq!(d.source, "![](logo.svg)\n");
11232    }
11233
11234    // ── move_block ─────────────────────────────────────────────────────────────
11235
11236    /// A move, then its undo: one step takes the whole thing back.
11237    fn moved(name: &str, body: &str, from: usize, to: usize) -> (String, Doc) {
11238        let mut d = doc_with(name, body);
11239        d.caret = from;
11240        let steps = d.undo_steps;
11241        d.move_block(from, to);
11242        let after = d.source.clone();
11243        assert_eq!(d.undo_steps, steps + 1, "one undo step");
11244        assert!(d.dirty);
11245        d.undo();
11246        assert_eq!(d.source, body, "one undo restores the original");
11247        (after, d)
11248    }
11249
11250    #[test]
11251    fn move_block_carries_a_paragraph_between_two_paragraphs_and_to_the_end() {
11252        let body = "a\n\nb\n\nc\n";
11253        assert_eq!(moved("mv_p1", body, 6, 3).0, "a\n\nc\n\nb\n");
11254        assert_eq!(moved("mv_p2", body, 0, body.len()).0, "b\n\nc\n\na\n");
11255        assert_eq!(moved("mv_p3", body, 3, 0).0, "b\n\na\n\nc\n");
11256    }
11257
11258    #[test]
11259    fn move_block_carries_an_image_block() {
11260        let body = "a\n\n![p](x.png)\n\nc\n";
11261        assert_eq!(moved("mv_img1", body, 4, 0).0, "![p](x.png)\n\na\n\nc\n");
11262        assert_eq!(
11263            moved("mv_img2", body, 4, body.len()).0,
11264            "a\n\nc\n\n![p](x.png)\n"
11265        );
11266    }
11267
11268    #[test]
11269    fn move_block_carries_a_table() {
11270        let body = "a\n\n| h |\n|---|\n| c |\n\nc\n";
11271        assert_eq!(
11272            moved("mv_tbl1", body, 5, 0).0,
11273            "| h |\n|---|\n| c |\n\na\n\nc\n"
11274        );
11275        assert_eq!(
11276            moved("mv_tbl2", body, 5, body.len()).0,
11277            "a\n\nc\n\n| h |\n|---|\n| c |\n"
11278        );
11279    }
11280
11281    #[test]
11282    fn move_block_carries_a_code_block() {
11283        let body = "a\n\n```rs\nx\n```\n\nc\n";
11284        assert_eq!(moved("mv_code1", body, 8, 0).0, "```rs\nx\n```\n\na\n\nc\n");
11285        assert_eq!(
11286            moved("mv_code2", body, 8, body.len()).0,
11287            "a\n\nc\n\n```rs\nx\n```\n"
11288        );
11289    }
11290
11291    #[test]
11292    fn move_block_onto_its_own_boundary_is_a_quiet_no_op() {
11293        let mut d = doc_with("mv_noop", "a\n\nb\n");
11294        let steps = d.undo_steps;
11295        d.move_block(0, 0);
11296        d.move_block(0, 3);
11297        assert_eq!(d.source, "a\n\nb\n");
11298        assert_eq!(d.undo_steps, steps);
11299        assert_eq!(d.status, None);
11300        assert!(!d.dirty);
11301    }
11302
11303    #[test]
11304    fn move_block_into_a_fence_is_refused_with_a_status() {
11305        let mut d = doc_with("mv_fence", "a\n\n```\nx\ny\n```\n");
11306        d.move_block(0, 7);
11307        assert_eq!(d.source, "a\n\n```\nx\ny\n```\n");
11308        assert!(
11309            d.status
11310                .as_deref()
11311                .is_some_and(|s| s.starts_with("move block"))
11312        );
11313    }
11314
11315    #[test]
11316    fn move_block_rides_the_caret_with_the_block() {
11317        // Down: "second" is line 0 of its block, caret 3 bytes from its end.
11318        let mut d = doc_with("mv_caret1", "first\n\nsecond\n\nthird\n");
11319        d.caret = 10; // "sec|ond"
11320        d.move_block(10, d.source.len());
11321        assert_eq!(d.source, "first\n\nthird\n\nsecond\n");
11322        assert_eq!(&d.source[d.caret..], "ond\n");
11323        // Up, across a wrapped paragraph's second line.
11324        let mut d = doc_with("mv_caret2", "first\n\nsecond\nline two\n");
11325        d.caret = 16; // "li|ne two"
11326        d.move_block(16, 0);
11327        assert_eq!(d.source, "second\nline two\n\nfirst\n");
11328        assert_eq!(&d.source[d.caret..], "ne two\n\nfirst\n");
11329        assert_eq!(d.selection(), None);
11330    }
11331
11332    #[test]
11333    fn move_block_keeps_the_caret_on_its_line_through_a_quotes_prefix() {
11334        let mut d = doc_with("mv_quote_caret", "para\n\n> a\n");
11335        d.caret = 2; // "pa|ra"
11336        d.move_block(2, 9); // after a, inside the quote
11337        assert_eq!(d.source, "> a\n>\n> para\n");
11338        assert_eq!(&d.source[d.caret..], "ra\n");
11339    }
11340
11341    #[test]
11342    fn move_block_up_and_down_step_over_siblings() {
11343        let mut d = doc_with("mv_updown", "a\n\nb\n\nc\n");
11344        d.caret = 3;
11345        d.move_block_down();
11346        assert_eq!(d.source, "a\n\nc\n\nb\n");
11347        assert_eq!(&d.source[d.caret..], "b\n");
11348        d.move_block_down();
11349        assert_eq!(d.source, "a\n\nc\n\nb\n", "nothing below the last block");
11350        assert_eq!(d.status.as_deref(), Some("move block: nothing below"));
11351        d.move_block_up();
11352        d.move_block_up();
11353        assert_eq!(d.source, "b\n\na\n\nc\n");
11354        assert_eq!(&d.source[d.caret..], "b\n\na\n\nc\n");
11355        d.move_block_up();
11356        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11357    }
11358
11359    #[test]
11360    fn move_block_up_and_down_reorder_list_items_with_their_children() {
11361        let mut d = doc_with("mv_items", "- a\n  - x\n- b\n- c\n");
11362        d.caret = 12; // in "b"
11363        d.move_block_up();
11364        assert_eq!(d.source, "- b\n- a\n  - x\n- c\n");
11365        assert_eq!(&d.source[d.caret..], "b\n- a\n  - x\n- c\n");
11366        d.caret = 6; // in "a"
11367        d.move_block_down();
11368        assert_eq!(d.source, "- b\n- c\n- a\n  - x\n");
11369        assert_eq!(&d.source[d.caret..], "a\n  - x\n");
11370        // A nested item leaves its list upward, as an item of the outer one.
11371        d.caret = 16; // in "x"
11372        d.move_block_up();
11373        assert_eq!(d.source, "- b\n- c\n- x\n- a\n");
11374    }
11375
11376    #[test]
11377    fn move_block_on_a_lone_item_that_stays_a_bullet_is_no_step() {
11378        let mut d = doc_with("mv_lone_item", "x\n\n- b\n\ny\n");
11379        d.caret = 5;
11380        let steps = d.undo_steps;
11381        d.move_block_up();
11382        assert_eq!(d.source, "x\n\n- b\n\ny\n");
11383        assert_eq!(
11384            d.undo_steps, steps,
11385            "a move that rewrote nothing is no undo step"
11386        );
11387        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11388    }
11389
11390    #[test]
11391    fn move_block_up_leaves_a_container_at_its_first_block_and_down_at_its_last() {
11392        let mut d = doc_with("mv_leave", "x\n\n> a\n>\n> b\n\ny\n");
11393        d.caret = 5; // "a"
11394        d.move_block_up();
11395        assert_eq!(d.source, "x\n\na\n\n> b\n\ny\n");
11396        d.caret = 8; // "b"
11397        d.move_block_down();
11398        assert_eq!(d.source, "x\n\na\n\nb\n\ny\n");
11399        // A tail block leaves its item into the next item's tail, then the list.
11400        let mut d = doc_with("mv_tail", "- a\n\n  t\n- b\n");
11401        d.caret = 7;
11402        d.move_block_down();
11403        assert_eq!(d.source, "- a\n- b\n\n  t\n");
11404        d.move_block_down();
11405        assert_eq!(d.source, "- a\n- b\n\nt\n");
11406        // And a paragraph after a quote steps over the whole quote, not into it.
11407        let mut d = doc_with("mv_over", "x\n\n> a\n>\n> b\n\ny\n");
11408        d.caret = 14;
11409        d.move_block_up();
11410        assert_eq!(d.source, "x\n\ny\n\n> a\n>\n> b\n");
11411        assert_eq!(d.caret, 3);
11412        d.move_block_down();
11413        assert_eq!(d.status, None);
11414        assert_eq!(d.source, "x\n\n> a\n>\n> b\n\ny\n");
11415        // Above a quote that opens the document is offset 0 — before the
11416        // quote, not inside it.
11417        let mut d = doc_with("mv_over_top", "> a\n\ny\n");
11418        d.caret = 5;
11419        d.move_block_up();
11420        assert_eq!(d.source, "y\n\n> a\n");
11421        assert_eq!(d.caret, 0);
11422    }
11423
11424    #[test]
11425    fn move_block_up_from_the_first_block_of_a_quote_that_opens_the_document_leaves_it() {
11426        let mut d = doc_with("mv_top_quote", "> a\n>\n> b\n");
11427        d.caret = 2;
11428        d.move_block_up();
11429        assert_eq!(d.source, "a\n\n> b\n");
11430        assert_eq!(d.caret, 0);
11431        assert_eq!(d.status, None);
11432    }
11433
11434    #[test]
11435    fn move_block_on_a_blank_line_or_read_only_does_nothing() {
11436        let mut d = doc_with("mv_blank", "a\n\nb\n");
11437        d.caret = 2;
11438        d.move_block_down();
11439        assert_eq!(d.source, "a\n\nb\n");
11440        assert_eq!(d.status.as_deref(), Some("move block: no block here"));
11441        d.read_only = true;
11442        d.caret = 0;
11443        d.move_block_down();
11444        d.move_block(0, 5);
11445        assert_eq!(d.source, "a\n\nb\n");
11446    }
11447
11448    #[test]
11449    fn move_block_never_lands_above_hidden_frontmatter() {
11450        let mut d = wysiwyg_doc("mv_fm", "---\nt: x\n---\n\na\n\nb\n");
11451        let b = d.source.find('b').unwrap();
11452        d.move_block(b, 0);
11453        assert_eq!(d.source, "---\nt: x\n---\n\nb\n\na\n");
11454    }
11455
11456    #[test]
11457    fn block_range_at_is_the_block_a_move_picks_up() {
11458        let mut d = doc_with("mv_range", "a\n\n- b\n  - c\n\nd\n");
11459        assert_eq!(d.block_range_at(0), Some(0..1));
11460        assert_eq!(d.block_range_at(5), Some(3..12), "the item with its child");
11461        assert_eq!(d.block_range_at(10), Some(7..12), "the nested item alone");
11462        assert_eq!(d.block_range_at(2), None, "a blank line");
11463    }
11464
11465    #[test]
11466    fn drop_target_at_splits_a_block_at_its_middle_row_and_ends_below_everything() {
11467        let long = "two ".repeat(40).trim_end().to_string(); // wraps to three rows at 80
11468        let mut d = wysiwyg_doc("drop", &format!("one\n\n{long} four\n\nfive\n"));
11469        let rows = d.vmap.rows.len();
11470        assert_eq!(rows, 7, "one, gap, three wrapped rows, gap, five");
11471        assert_eq!(d.drop_target_at(0), Some(DropTarget { offset: 0, row: 0 }));
11472        let two = d.source.find("two").unwrap();
11473        assert_eq!(
11474            d.drop_target_at(1),
11475            Some(DropTarget {
11476                offset: two,
11477                row: 2
11478            }),
11479            "the gap resolves to the block under it"
11480        );
11481        assert_eq!(
11482            d.drop_target_at(2),
11483            Some(DropTarget {
11484                offset: two,
11485                row: 2
11486            })
11487        );
11488        assert_eq!(
11489            d.drop_target_at(3),
11490            Some(DropTarget {
11491                offset: two,
11492                row: 2
11493            })
11494        );
11495        let four_end = d.source.find("four").unwrap() + 4;
11496        assert_eq!(
11497            d.drop_target_at(4),
11498            Some(DropTarget {
11499                offset: four_end,
11500                row: 5
11501            })
11502        );
11503        assert_eq!(
11504            d.drop_target_at(rows + 3),
11505            Some(DropTarget {
11506                offset: d.source.len(),
11507                row: rows
11508            })
11509        );
11510        // And the offsets are ones move_block takes.
11511        let five = d.source.find("five").unwrap();
11512        let t = d.drop_target_at(2).unwrap();
11513        d.move_block(five, t.offset);
11514        assert_eq!(d.source, format!("one\n\nfive\n\n{long} four\n"));
11515    }
11516
11517    #[test]
11518    fn append_media_lands_at_the_end_as_its_own_block() {
11519        let mut d = doc_with("append_mid", "first word and more\n");
11520        d.caret = 0; // an editor nobody has tapped: the caret is at the start
11521        d.append_media(MediaKind::Image, "cat.png", "");
11522        assert_eq!(d.source, "first word and more\n\n![](cat.png)");
11523        assert_eq!(d.selection(), None);
11524        assert_eq!(d.caret, "first word and more\n\n![](cat.png)".len());
11525    }
11526
11527    #[test]
11528    fn append_media_needs_no_separator_after_a_blank_line_or_in_an_empty_document() {
11529        let mut d = doc_with("append_blank", "para\n\n");
11530        d.append_media(MediaKind::Image, "a.png", "");
11531        assert_eq!(d.source, "para\n\n![](a.png)");
11532
11533        let mut e = doc_with("append_empty", "");
11534        e.append_media(MediaKind::Image, "b.png", "");
11535        assert_eq!(e.source, "![](b.png)");
11536
11537        let mut f = doc_with("append_noeol", "no newline at end");
11538        f.anchor = Some(0);
11539        f.caret = 2; // a selection, which the verb ignores
11540        f.append_media(MediaKind::Video, "clip.mp4", "");
11541        assert_eq!(
11542            f.source,
11543            "no newline at end\n\n<video src=\"clip.mp4\" controls></video>"
11544        );
11545    }
11546
11547    #[test]
11548    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
11549        // The round trip is the point: it's no use writing markup the reader
11550        // can't pick up again. This is the pair that only holds from twig 2.5.1
11551        // on — before it, the one-line form went in fine and came back as a
11552        // paragraph of raw tags, publishing no media at all.
11553        let mut d = doc_with("vid_rt", "\n");
11554        d.caret = 0;
11555        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
11556        assert_eq!(
11557            d.source,
11558            "<video src=\"clip.mp4\" controls>a clip</video>\n"
11559        );
11560
11561        d.build_visual(80);
11562        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
11563        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
11564        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
11565        assert_eq!(d.vmap.media[0].alt, "a clip");
11566    }
11567
11568    #[test]
11569    fn insert_media_spells_audio_with_its_own_tag() {
11570        let mut d = doc_with("aud_rt", "\n");
11571        d.caret = 0;
11572        d.insert_media(MediaKind::Audio, "take.mp3", "");
11573        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
11574        d.build_visual(80);
11575        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
11576    }
11577
11578    #[test]
11579    fn insert_media_uses_the_selection_as_fallback_text() {
11580        // The same courtesy `insert_image` does with alt: select a caption,
11581        // insert, and the caption labels the thing rather than being replaced.
11582        let mut d = doc_with("vid_sel", "the talk here\n");
11583        d.anchor = Some(0);
11584        d.caret = 8; // "the talk"
11585        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
11586        assert_eq!(
11587            d.source,
11588            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
11589        );
11590    }
11591
11592    #[test]
11593    fn insert_media_with_an_image_kind_is_just_insert_image() {
11594        let mut d = doc_with("img_via_media", "\n");
11595        d.caret = 0;
11596        d.insert_media(MediaKind::Image, "logo.svg", "x");
11597        assert_eq!(d.source, "![x](logo.svg)\n");
11598    }
11599
11600    // ── thematic breaks ─────────────────────────────────────────────────────
11601
11602    /// The node the source parses as at `caret` — what confirms an inserted
11603    /// `---` actually reads back as a rule, not stray text or a setext heading.
11604    ///
11605    /// The *narrowest* node covering the offset. Every ancestor covers it too,
11606    /// and since twig 2.8 that includes the `doc` root, which now carries a real
11607    /// span (it reported none before, so taking the first match used to land on
11608    /// the block by luck and now always answers `"doc"`).
11609    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
11610        d.nodes()
11611            .into_iter()
11612            .filter(|n| n.span.start <= caret && caret < n.span.end)
11613            .min_by_key(|n| n.span.end - n.span.start)
11614            .map(|n| n.kind)
11615    }
11616
11617    #[test]
11618    fn a_task_box_toggles_at_the_caret_and_reads_back() {
11619        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
11620        d.caret = 8; // inside "todo"
11621        assert_eq!(d.task_checked_at_caret(), Some(false));
11622        d.toggle_task_checked();
11623        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
11624        assert_eq!(d.task_checked_at_caret(), Some(true));
11625        d.toggle_task_checked();
11626        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
11627    }
11628
11629    #[test]
11630    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
11631        // The whole reason `toggle_task_at` exists apart from the caret form:
11632        // ticking a box elsewhere must not move the cursor out of what's being
11633        // typed.
11634        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
11635        d.caret = 8; // inside "first"
11636        let second = d.source.find("second").unwrap();
11637        d.toggle_task_at(second);
11638        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
11639        assert_eq!(d.caret, 8, "the caret stayed in the first item");
11640    }
11641
11642    #[test]
11643    fn a_paragraph_becomes_a_task_item_in_one_undo_step() {
11644        let mut d = doc_with("task_para", "first\n\nplain para\n");
11645        d.caret = d.source.find("para").unwrap();
11646        d.toggle_task_item();
11647        assert_eq!(d.source, "first\n\n- [ ] plain para\n");
11648        assert_eq!(d.task_checked_at_caret(), Some(false));
11649        assert_eq!(d.status, None);
11650        d.undo();
11651        assert_eq!(
11652            d.source, "first\n\nplain para\n",
11653            "one step takes both back"
11654        );
11655    }
11656
11657    #[test]
11658    fn a_blank_line_becomes_an_empty_task_item() {
11659        let mut d = doc_with("task_blank", "first\n\n");
11660        d.caret = d.source.len();
11661        d.toggle_task_item();
11662        assert_eq!(d.task_checked_at_caret(), Some(false), "{:?}", d.source);
11663        assert_eq!(d.status, None);
11664    }
11665
11666    #[test]
11667    fn a_plain_item_gains_and_loses_a_box() {
11668        let mut d = doc_with("task_mint", "- plain\n");
11669        d.caret = 4;
11670        assert_eq!(d.task_checked_at_caret(), None);
11671        d.toggle_task_item();
11672        assert_eq!(d.source, "- [ ] plain\n");
11673        assert_eq!(
11674            d.task_checked_at_caret(),
11675            Some(false),
11676            "a new box arrives unticked"
11677        );
11678        d.toggle_task_item();
11679        assert_eq!(d.source, "- plain\n");
11680    }
11681
11682    #[test]
11683    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
11684        // `set checked` must not silently convert a bullet into a task — that is
11685        // `toggle_task_item`'s job, and twig refuses it here.
11686        let mut d = doc_with("task_none", "- plain\n");
11687        d.caret = 4;
11688        d.toggle_task_checked();
11689        assert_eq!(d.source, "- plain\n", "nothing written");
11690        assert!(
11691            d.status.is_some(),
11692            "the refusal should reach the status line"
11693        );
11694    }
11695
11696    #[test]
11697    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
11698        let mut d = doc_with("task_quote", "> - [ ] nested\n");
11699        d.caret = d.source.find("nested").unwrap();
11700        assert_eq!(d.task_checked_at_caret(), Some(false));
11701        d.toggle_task_checked();
11702        assert_eq!(d.source, "> - [x] nested\n");
11703    }
11704
11705    #[test]
11706    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
11707        // A rule is a block, so twig's `insert_thematic_break` alone lands it
11708        // after the whole paragraph. `split_block` parts the paragraph first and
11709        // the rule is aimed at the *first* half, which is what a rule button is
11710        // understood to do — and what leaf spelled by hand until twig grew both
11711        // halves of the gesture.
11712        let mut d = doc_with("hr_mid", "before after\n");
11713        d.caret = 7; // between "before " and "after"
11714        d.insert_thematic_break();
11715        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11716        assert_eq!(d.selection(), None);
11717        assert_eq!(
11718            kind_at(&mut d, "before \n\n".len()),
11719            Some(Kind::ThematicBreak)
11720        );
11721    }
11722
11723    #[test]
11724    fn insert_thematic_break_at_a_paragraph_s_end_splits_nothing() {
11725        // At the end there is nothing to part, and a split there writes the
11726        // separator anyway — a blank line and the empty slot the next paragraph
11727        // would fill — which the rule then landed above: `para\n\n* * *\n\n\n`,
11728        // two blank lines nothing fills. Now the rule lands after the paragraph,
11729        // where the split-and-aim was sending it regardless. Both formats, and
11730        // both shapes of a last line — terminated, and still being typed —
11731        // because the two reach the split through different doors: Markdown's
11732        // paragraph span stops before its newline, so `para\n` at 4 never split
11733        // there, but `para` at 4 did.
11734        //
11735        // What stands under the rule is the line the caret goes on to, not a
11736        // slot: nothing above the rule but the one blank line, and the caret on
11737        // the line beneath it.
11738        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11739            for src in ["para\n", "para"] {
11740                let mut d = Doc::from_source(src.into(), fmt).unwrap();
11741                d.caret = 4;
11742                d.insert_thematic_break();
11743                assert_eq!(d.source, format!("para\n\n{rule}\n\n"), "{fmt:?} {src:?}");
11744                assert_eq!(d.caret, d.source.len());
11745            }
11746            // Mid-document the slot sat between the rule and the next block;
11747            // the caret's line does now, a blank line either side of it.
11748            let mut d = Doc::from_source("para\n\nnext\n".into(), fmt).unwrap();
11749            d.caret = 4;
11750            d.insert_thematic_break();
11751            assert_eq!(d.source, format!("para\n\n{rule}\n\n\n\nnext\n"), "{fmt:?}");
11752            // Trailing whitespace is nothing to part either.
11753            let mut d = Doc::from_source("para  \n".into(), fmt).unwrap();
11754            d.caret = 4;
11755            d.insert_thematic_break();
11756            assert_eq!(d.source, format!("para  \n\n{rule}\n\n"), "{fmt:?}");
11757        }
11758    }
11759
11760    #[test]
11761    fn insert_thematic_break_at_a_paragraph_s_start_lands_before_it() {
11762        // The split at the start parts nothing, but it is kept on purpose:
11763        // `|para` becomes `\npara` with the caret on a blank line, and twig
11764        // (3.5.2) writes a rule aimed at a blank line ON that line — the only
11765        // way "before the paragraph" is reachable through a gesture that only
11766        // places after. Before 3.5.2 this came out as `\n\n---\n\npara`.
11767        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11768            let mut d = Doc::from_source("para\n".into(), fmt).unwrap();
11769            d.caret = 0;
11770            d.insert_thematic_break();
11771            assert_eq!(d.source, format!("{rule}\n\npara\n"), "{fmt:?}");
11772            let mut d = Doc::from_source("prev\n\npara\n".into(), fmt).unwrap();
11773            d.caret = 6;
11774            d.insert_thematic_break();
11775            assert_eq!(d.source, format!("prev\n\n{rule}\n\npara\n"), "{fmt:?}");
11776        }
11777    }
11778
11779    #[test]
11780    fn insert_thematic_break_on_a_blank_line_takes_that_line() {
11781        // The gap between two blocks is where a click lands the caret; the
11782        // rule goes on the blank, one blank each side, and the caret on the
11783        // line opened under it.
11784        let mut d = doc_with("hr_gap", "a\n\nb\n");
11785        d.caret = 2;
11786        d.insert_thematic_break();
11787        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11788        assert_eq!(d.caret, "a\n\n---\n\n".len());
11789    }
11790
11791    #[test]
11792    fn insert_thematic_break_leaves_the_caret_on_a_line_under_the_rule() {
11793        // The caret used to be left where twig's splice ended, the home past
11794        // the rule, which is drawn on the rule's own row: the writer saw the
11795        // caret beside the rule, and mid-document what they typed next ran
11796        // into the block below. Now it goes on to an empty row under the
11797        // rule's gap from every place a rule is asked for — the end of a
11798        // paragraph, the empty paragraph Enter opened, a list and the line
11799        // Enter leaves a list for, closing the document and before another
11800        // block — and what is typed there is a paragraph of its own.
11801        for (body, caret, typed) in [
11802            ("para\n", 4, "para\n\n---\n\nX"),
11803            ("para\n\n\n", 6, "para\n\n---\n\nX"),
11804            ("- one\n- two\n", 11, "- one\n- two\n\n---\n\nX"),
11805            ("- one\n- two\n\n\n", 13, "- one\n- two\n\n---\n\nX"),
11806            ("a\n\nb\n", 1, "a\n\n---\n\nX\n\nb\n"),
11807            ("a\n\n\n\nb\n", 3, "a\n\n---\n\nX\n\nb\n"),
11808        ] {
11809            let mut d = wysiwyg_doc("hr_caret", body);
11810            d.build_visual(80);
11811            d.caret = caret;
11812            d.insert_thematic_break();
11813            d.build_visual(80);
11814            let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11815            let (row, col) = d.vmap.pos_of_offset(d.caret);
11816            assert_eq!((row, col), (rule + 2, 0), "{body:?} → {:?}", d.source);
11817            assert!(d.vmap.rows[rule + 1].decoration, "the gap under the rule");
11818            assert!(d.vmap.rows[row].glyphs.is_empty(), "an empty line");
11819            d.insert("X");
11820            assert_eq!(d.source, typed, "{body:?}");
11821            let rule_at = d.source.find("---").unwrap();
11822            assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
11823        }
11824        // djot's rule takes in its newline; the line under it is the same.
11825        let mut d = Doc::from_source("a\n\nb\n".into(), Format::Djot).unwrap();
11826        d.view = View::Wysiwyg;
11827        d.caret = 1;
11828        d.insert_thematic_break();
11829        d.build_visual(80);
11830        assert_eq!(d.source, "a\n\n* * *\n\n\n\nb\n");
11831        assert_eq!(d.vmap.pos_of_offset(d.caret), (4, 0));
11832    }
11833
11834    #[test]
11835    fn a_rule_parting_a_paragraph_leaves_the_caret_before_its_second_half() {
11836        // The line under the rule is the paragraph's second half, so that is
11837        // where the caret goes: the text it was standing in front of is still
11838        // in front of it.
11839        let mut d = wysiwyg_doc("hr_parted", "before after\n");
11840        d.caret = 7;
11841        d.insert_thematic_break();
11842        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11843        assert_eq!(d.caret, d.source.find("after").unwrap());
11844        // At the start of a paragraph too, the rule landing above it.
11845        let mut d = wysiwyg_doc("hr_parted_start", "prev\n\npara\n");
11846        d.caret = 6;
11847        d.insert_thematic_break();
11848        assert_eq!(d.caret, d.source.find("para").unwrap());
11849    }
11850
11851    #[test]
11852    fn the_line_under_a_new_rule_is_one_undo_step_with_it() {
11853        let mut d = wysiwyg_doc("hr_undo", "a\n\nb\n");
11854        d.caret = 1;
11855        d.insert_thematic_break();
11856        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11857        d.undo();
11858        assert_eq!(d.source, "a\n\nb\n");
11859        assert!(!d.can_undo());
11860        d.redo();
11861        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11862    }
11863
11864    #[test]
11865    fn a_rule_in_preserve_flow_leaves_the_caret_on_the_first_line_under_it() {
11866        // Preserve draws every blank line as somewhere to type, the first under
11867        // the rule included, so that is the caret's line and the one written.
11868        let mut d = wysiwyg_doc("hr_preserve", "para\n");
11869        d.set_line_flow(LineFlow::Preserve);
11870        d.caret = 4;
11871        d.insert_thematic_break();
11872        assert_eq!(d.source, "para\n\n---\n\n");
11873        assert_eq!(d.caret, "para\n\n---\n".len());
11874        d.build_visual(80);
11875        let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11876        assert_eq!(d.vmap.pos_of_offset(d.caret), (rule + 1, 0));
11877        // Before another block, one blank line more keeps it off that block.
11878        let mut d = wysiwyg_doc("hr_preserve_mid", "a\n\nb\n");
11879        d.set_line_flow(LineFlow::Preserve);
11880        d.caret = 1;
11881        d.insert_thematic_break();
11882        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
11883        assert_eq!(d.caret, "a\n\n---\n".len());
11884    }
11885
11886    #[test]
11887    fn insert_page_break_leaves_the_caret_on_a_line_under_it() {
11888        // The rule button's placement, for the other block the toolbar writes:
11889        // the caret was left at the end of twig's splice, beside the break at
11890        // the end of the document and on the next block's first letter before
11891        // one. djot spells the break as a fence of two lines; the line under
11892        // it is under the closing `:::`.
11893        for (fmt, body, want, typed) in [
11894            (
11895                Format::Markdown,
11896                "a\n\nb\n",
11897                "a\n\n::page-break\n\n\n\nb\n",
11898                "a\n\n::page-break\n\nX\n\nb\n",
11899            ),
11900            (
11901                Format::Markdown,
11902                "a\n",
11903                "a\n\n::page-break\n\n",
11904                "a\n\n::page-break\n\nX",
11905            ),
11906            (
11907                Format::Djot,
11908                "a\n\nb\n",
11909                "a\n\n::: page-break\n:::\n\n\n\nb\n",
11910                "a\n\n::: page-break\n:::\n\nX\n\nb\n",
11911            ),
11912        ] {
11913            let mut d = Doc::from_source(body.into(), fmt).unwrap();
11914            d.view = View::Wysiwyg;
11915            d.caret = 1;
11916            d.insert_page_break();
11917            assert_eq!(d.source, want, "{fmt:?}");
11918            d.build_visual(80);
11919            let (row, col) = d.vmap.pos_of_offset(d.caret);
11920            assert_eq!(col, 0);
11921            assert!(d.vmap.rows[row].glyphs.is_empty(), "{fmt:?}: an empty line");
11922            assert!(
11923                d.vmap.rows[row - 2].leaf_directive.is_some(),
11924                "{fmt:?}: under the break"
11925            );
11926            d.insert("X");
11927            assert_eq!(d.source, typed, "{fmt:?}");
11928            d.undo();
11929            d.undo();
11930            assert_eq!(
11931                d.source, body,
11932                "{fmt:?}: the break and its line are one step"
11933            );
11934        }
11935    }
11936
11937    #[test]
11938    fn a_block_parting_a_paragraph_is_one_undo_step() {
11939        // The split went to twig without leaf counting it, so the first Undo
11940        // took back the block, left the paragraph parted, and reported nothing
11941        // more to undo.
11942        let mut rule = wysiwyg_doc("part_undo_rule", "before after\n");
11943        rule.caret = 7;
11944        rule.insert_thematic_break();
11945        let mut table = wysiwyg_doc("part_undo_table", "before after\n");
11946        table.caret = 7;
11947        table.insert_table(1, 1);
11948        let mut page = wysiwyg_doc("part_undo_page", "before after\n");
11949        page.caret = 7;
11950        page.insert_page_break();
11951        for (name, d) in [
11952            ("rule", &mut rule),
11953            ("table", &mut table),
11954            ("page break", &mut page),
11955        ] {
11956            assert_ne!(d.source, "before after\n", "{name}");
11957            d.undo();
11958            assert_eq!(d.source, "before after\n", "{name}: one Undo");
11959            assert_eq!(d.caret, 7, "{name}: the caret back where it was");
11960            assert!(!d.can_undo(), "{name}");
11961            assert!(d.can_redo(), "{name}");
11962            d.redo();
11963            assert!(!d.source.starts_with("before after"), "{name}: one Redo");
11964            assert!(!d.can_redo(), "{name}");
11965        }
11966        // A table twig would refuse parts nothing: the refusal comes first.
11967        let mut d = wysiwyg_doc("part_undo_zero", "before after\n");
11968        d.caret = 7;
11969        d.insert_table(0, 1);
11970        assert_eq!(d.source, "before after\n");
11971        assert!(!d.can_undo());
11972    }
11973
11974    #[test]
11975    fn enter_at_a_paragraph_s_start_opens_an_empty_paragraph_above_it() {
11976        // twig's split at a paragraph's start writes one newline ahead of it,
11977        // which Fold draws as one more gap, so the first Enter showed nothing.
11978        // A paragraph break opens a line above, the caret staying before the
11979        // text. Past a mark's opening delimiters — where a tap before the
11980        // first letter lands — the split used to cut the mark in two
11981        // (`**\n\nb**`); the break goes in front of them, as it goes in
11982        // front of a heading's `#`, where the heading's own Enter left an
11983        // empty heading over its text as a paragraph. A paragraph that
11984        // opens a div gets its line outside the div, where it draws.
11985        for (body, caret, want, want_caret) in [
11986            ("a\n\nb\n", 3, "a\n\n\n\nb\n", 5),
11987            ("# H\n\nb\n", 5, "# H\n\n\n\nb\n", 7),
11988            ("a\n\n# H\n", 5, "a\n\n\n\n# H\n", 7),
11989            ("a\n\n**b** c\n", 3, "a\n\n\n\n**b** c\n", 5),
11990            ("a\n\n**b** c\n", 5, "a\n\n\n\n**b** c\n", 7),
11991            (
11992                "a\n\n<span data-color=\"orange\">b</span>\n",
11993                29,
11994                "a\n\n\n\n<span data-color=\"orange\">b</span>\n",
11995                31,
11996            ),
11997            (
11998                "a\n\n<div class=\"center\">\n\nb\n\n</div>\n",
11999                25,
12000                "a\n\n\n\n<div class=\"center\">\n\nb\n\n</div>\n",
12001                27,
12002            ),
12003        ] {
12004            let mut d = wysiwyg_doc("enter_para_start", body);
12005            d.build_visual(80);
12006            d.caret = caret;
12007            d.newline();
12008            assert_eq!(d.source, want, "{body:?}");
12009            assert_eq!(d.caret, want_caret, "{body:?}");
12010            d.build_visual(80);
12011            let (row, _) = d.vmap.pos_of_offset(d.caret);
12012            assert!(
12013                d.vmap.rows[row - 2].glyphs.is_empty(),
12014                "{body:?}: an empty line above"
12015            );
12016            assert!(
12017                !d.vmap.rows[row - 2].decoration,
12018                "{body:?}: one the caret can stand on"
12019            );
12020        }
12021        // Past the first letter it is an ordinary split.
12022        let mut d = wysiwyg_doc("enter_para_mid", "a\n\n**b** c\n");
12023        d.caret = 8;
12024        d.newline();
12025        assert_eq!(d.source, "a\n\n**b**\n\nc\n");
12026    }
12027
12028    #[test]
12029    fn enter_again_at_a_paragraph_s_start_opens_one_more_line() {
12030        // The first Enter's paragraph break leaves a gap either side of the
12031        // empty line. A second break drew two lines more; a newline draws one.
12032        let mut d = wysiwyg_doc("enter_para_again", "a\n\nb\n");
12033        d.build_visual(80);
12034        d.caret = 3;
12035        for (want, lines) in [("a\n\n\n\nb\n", 1), ("a\n\n\n\n\nb\n", 2)] {
12036            d.newline();
12037            assert_eq!(d.source, want);
12038            assert_eq!(&d.source[d.caret..], "b\n");
12039            d.build_visual(80);
12040            let empty = d
12041                .vmap
12042                .rows
12043                .iter()
12044                .filter(|r| r.glyphs.is_empty() && !r.decoration)
12045                .count();
12046            assert_eq!(empty, lines, "{want:?}");
12047        }
12048    }
12049
12050    #[test]
12051    fn enter_at_the_first_block_s_start_pushes_it_down() {
12052        // No row was drawn for a blank line above the first block, so Enter
12053        // there wrote a line and the text stayed where it was. Each Enter now
12054        // draws one empty line above it, the caret staying with the text;
12055        // past frontmatter, the line conventionally under it still draws
12056        // nothing until Enter adds to it.
12057        for (body, caret, wants) in [
12058            ("b\n", 0, ["\n\nb\n", "\n\n\nb\n"]),
12059            ("**b** c\n", 2, ["\n\n**b** c\n", "\n\n\n**b** c\n"]),
12060            ("# H\n", 2, ["\n\n# H\n", "\n\n\n# H\n"]),
12061            (
12062                "---\nt: x\n---\n\nb\n",
12063                14,
12064                ["---\nt: x\n---\n\n\nb\n", "---\nt: x\n---\n\n\n\nb\n"],
12065            ),
12066        ] {
12067            let mut d = wysiwyg_doc("enter_first_block", body);
12068            d.build_visual(80);
12069            let empty = |d: &Doc| {
12070                d.vmap
12071                    .rows
12072                    .iter()
12073                    .filter(|r| r.glyphs.is_empty() && !r.decoration)
12074                    .count()
12075            };
12076            assert_eq!(empty(&d), 0, "{body:?}: nothing above the text yet");
12077            d.caret = caret;
12078            for (lines, want) in wants.into_iter().enumerate() {
12079                d.newline();
12080                assert_eq!(d.source, want, "{body:?}");
12081                assert!(d.source[d.caret..].starts_with(&body[caret..]), "{body:?}");
12082                d.build_visual(80);
12083                assert_eq!(empty(&d), lines + 1, "{want:?}");
12084            }
12085            // The caret can go up onto the lines it opened.
12086            d.move_up(false);
12087            let (row, _) = d.vmap.pos_of_offset(d.caret);
12088            assert!(d.vmap.rows[row].glyphs.is_empty(), "{body:?}");
12089            assert!(!d.vmap.rows[row].decoration, "{body:?}");
12090        }
12091    }
12092
12093    /// What a reader sees of a map: each row's text, whether it is a gap,
12094    /// and the presentation it is drawn with. Offsets are left out, since an
12095    /// edit shifts them without anything on screen changing.
12096    fn drawn(d: &Doc) -> Vec<String> {
12097        d.vmap
12098            .rows
12099            .iter()
12100            .map(|r| {
12101                let text: String = r.glyphs.iter().map(|g| g.ch).collect();
12102                format!(
12103                    "{}{text:?} h={:?} lh={:?} a={:?}",
12104                    if r.decoration { "~" } else { "" },
12105                    r.heading,
12106                    r.line_height,
12107                    r.align
12108                )
12109            })
12110            .collect()
12111    }
12112
12113    #[test]
12114    fn enter_and_backspace_anywhere_show_what_they_write_and_undo_in_one_step() {
12115        // Enter that writes what the view does not draw looks like a key that
12116        // did nothing, so it gets pressed again, and the lines pile up unseen
12117        // until something redraws them all at once. The rule, the page break,
12118        // a paragraph's start, the first block's start and the blank page
12119        // were each that bug once. So: at every place the caret can stand, in
12120        // both flows, Enter either changes what is drawn or writes nothing,
12121        // and one Undo takes back whatever it wrote. Enter and Backspace both
12122        // leave the view a fresh open of the text would draw, so nothing
12123        // moves when the view is next rebuilt from scratch.
12124        let cases: &[(Format, &str)] = &[
12125            (
12126                Format::Markdown,
12127                "I talk to myself\n\nI laugh\n\nI cry\n\nknees to nose\n\nlet me go\n",
12128            ),
12129            (Format::Markdown, "I talk to myself\nI laugh\nI cry\n"),
12130            (
12131                Format::Markdown,
12132                "<div data-line-height=\"1.5\">\n\nI laugh\n\nI cry\n\nknees to nose\n\n</div>\n",
12133            ),
12134            (
12135                Format::Markdown,
12136                "<div data-line-height=\"1.15\">\n\nI cry\n\n</div>\n\n<div data-line-height=\"1.15\">\n\nknees\n\n</div>\n",
12137            ),
12138            (
12139                Format::Markdown,
12140                "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n",
12141            ),
12142            (
12143                Format::Markdown,
12144                "---\ntitle: x\n---\n\n# Title\n\nbody **bold** and <span data-color=\"red\">red</span>\n",
12145            ),
12146            (Format::Markdown, "\n\n\nafter blank lines\n\n\n\nmid\n\n\n"),
12147            (
12148                Format::Markdown,
12149                "- one\n- two\n\n1. a\n2. b\n\n- [ ] task\n",
12150            ),
12151            (Format::Markdown, "> quoted\n> more\n\n> - in a quote\n"),
12152            (Format::Markdown, "a\n\n---\n\nb\n\n::page-break\n\nc\n"),
12153            (Format::Markdown, "Title\n=====\n\nSub\n---\n\ntext\n"),
12154            (
12155                Format::Markdown,
12156                "```\ncode\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n",
12157            ),
12158            (Format::Djot, "I laugh\n\nI cry\n\nknees to nose\n"),
12159            (
12160                Format::Djot,
12161                "{data-line-height=\"2\"}\nI cry\n\n{data-line-height=\"2\"}\nknees to nose\n",
12162            ),
12163            (Format::Djot, "# Title\n\na\n\n* * *\n\nb\n"),
12164            // HTML is not here: Enter writes blank lines there, which the
12165            // view draws and HTML does not keep. See
12166            // docs/tasks/enter-in-html-writes-whitespace.md.
12167        ];
12168        let mut failures = Vec::new();
12169        for &(format, body) in cases {
12170            for flow in [LineFlow::Fold, LineFlow::Preserve] {
12171                let open = || {
12172                    let mut d = Doc::from_source(body.into(), format).unwrap();
12173                    d.view = View::Wysiwyg;
12174                    d.set_line_flow(flow);
12175                    d.build_visual_unwrapped();
12176                    d
12177                };
12178                // The map a fresh open of the same text would draw. The
12179                // edited map differing from it is a view that changes on the
12180                // next full rebuild, seconds after the key, with no key.
12181                let fresh = |source: &str| {
12182                    let mut ed =
12183                        twig::Editor::new_ext(source.as_bytes(), format, parse_extensions())
12184                            .unwrap();
12185                    let nodes = ed.nodes().unwrap();
12186                    crate::wysiwyg::build(
12187                        &nodes,
12188                        source,
12189                        None,
12190                        flow == LineFlow::Preserve,
12191                        &wysiwyg::Surface::default(),
12192                        None,
12193                    )
12194                };
12195                let probe = open();
12196                let stops: Vec<usize> = (0..=body.len())
12197                    .filter(|&o| probe.vmap.is_stop(o))
12198                    .collect();
12199                for at in stops {
12200                    for enter in [true, false] {
12201                        let mut d = open();
12202                        d.caret = at;
12203                        d.anchor = None;
12204                        let before = drawn(&d);
12205                        if enter {
12206                            d.newline();
12207                        } else {
12208                            d.backspace();
12209                        }
12210                        d.build_visual_unwrapped();
12211                        let key = if enter { "enter" } else { "backspace" };
12212                        let what = format!(
12213                            "{key} {format:?} {flow:?} caret {at} in {body:?} -> {:?}",
12214                            d.source
12215                        );
12216                        if maps_differ(&d.vmap, &fresh(&d.source)) {
12217                            failures.push(format!("redraws differently: {what}"));
12218                        }
12219                        if d.source == body {
12220                            continue;
12221                        }
12222                        if enter && drawn(&d) == before {
12223                            failures.push(format!("drew nothing: {what}"));
12224                        }
12225                        d.undo();
12226                        if d.source != body {
12227                            failures.push(format!("undo left {:?}: {what}", d.source));
12228                        }
12229                    }
12230                }
12231            }
12232        }
12233        assert!(
12234            failures.is_empty(),
12235            "{} failures:\n{}",
12236            failures.len(),
12237            failures.join("\n")
12238        );
12239    }
12240
12241    #[test]
12242    fn enter_opens_a_line_that_draws_inside_a_div_a_quote_and_preserve_flow() {
12243        // Each of these wrote a line the view did not draw, so Enter looked
12244        // dead and every press left one more.
12245        let enter = |format, flow, body: &str, at: usize| {
12246            let mut d = Doc::from_source(body.into(), format).unwrap();
12247            d.view = View::Wysiwyg;
12248            d.set_line_flow(flow);
12249            d.build_visual(80);
12250            d.caret = at;
12251            d.newline();
12252            d.build_visual(80);
12253            d
12254        };
12255        let div = "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n</div>\n";
12256        let end = div.find("knees").unwrap() + "knees".len();
12257
12258        // At the end of a div's last paragraph, the empty paragraph opens
12259        // inside the div, drawn with its line height, and what is typed
12260        // there stays in it.
12261        let mut d = enter(Format::Markdown, LineFlow::Fold, div, end);
12262        let (row, _) = d.vmap.pos_of_offset(d.caret);
12263        let r = &d.vmap.rows[row];
12264        assert!(r.glyphs.is_empty() && !r.decoration, "{:?}", drawn(&d));
12265        assert!(
12266            r.line_height.is_some(),
12267            "the new line keeps the div's spacing"
12268        );
12269        d.insert("x");
12270        assert_eq!(
12271            d.source,
12272            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\nx\n\n</div>\n"
12273        );
12274        // Preserve flow's soft line there draws too.
12275        let d = enter(Format::Markdown, LineFlow::Preserve, div, end);
12276        assert_eq!(
12277            d.source,
12278            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n\n</div>\n"
12279        );
12280        assert_eq!(d.vmap.rows.len(), 4, "{:?}", drawn(&d));
12281        // Between two of the div's paragraphs, the empty line takes its
12282        // spacing as well.
12283        let d = enter(
12284            Format::Markdown,
12285            LineFlow::Fold,
12286            div,
12287            div.find("knees").unwrap(),
12288        );
12289        let (row, _) = d.vmap.pos_of_offset(d.caret);
12290        assert!(
12291            d.vmap.rows[row - 2].line_height.is_some(),
12292            "{:?}",
12293            drawn(&d)
12294        );
12295
12296        // Under `</div>` the blank line is the one Markdown needs to end the
12297        // div. Preserve flow drew it as a line to type on, and Backspace
12298        // there glued the next paragraph to the tag (`</div>after`).
12299        let below = "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n";
12300        let mut d = Doc::from_source(below.into(), Format::Markdown).unwrap();
12301        d.view = View::Wysiwyg;
12302        d.set_line_flow(LineFlow::Preserve);
12303        d.build_visual(80);
12304        assert_eq!(d.vmap.rows.len(), 2, "{:?}", drawn(&d));
12305        d.caret = below.find("after").unwrap();
12306        d.backspace();
12307        assert!(!d.source.contains("</div>after"), "{:?}", d.source);
12308
12309        // At a quote's first line, the line opens above the quote; twig's
12310        // split wrote a quoted blank line above the text, which drew nothing.
12311        let d = enter(
12312            Format::Markdown,
12313            LineFlow::Fold,
12314            "a\n\n> quoted\n> more\n",
12315            5,
12316        );
12317        assert_eq!(d.source, "a\n\n\n\n> quoted\n> more\n");
12318        assert_eq!(&d.source[d.caret..], "quoted\n> more\n");
12319
12320        // Preserve flow at a paragraph's start: past a mark's delimiters its
12321        // newline cut the mark (`**\nb**`), and in djot a heading ran on
12322        // over it unseen.
12323        let d = enter(Format::Markdown, LineFlow::Preserve, "a\n\n**b** c\n", 5);
12324        assert_eq!(d.source, "a\n\n\n**b** c\n");
12325        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 5);
12326        assert_eq!(d.source, "a\n\n\n# Title\n");
12327        // Inside a heading it parts the heading, as in Fold flow.
12328        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 7);
12329        assert_eq!(d.source, "a\n\n# Ti\n\ntle\n");
12330    }
12331
12332    #[test]
12333    fn enter_on_a_blank_page_writes_nothing() {
12334        // With no block to push down, Fold flow draws no line for Enter to
12335        // open, and the newline it wrote was an edit and an undo step that
12336        // showed nothing. Preserve flow draws every line, so there it writes.
12337        for body in ["", "\n", "\n\n  \n", "---\nt: x\n---\n"] {
12338            let mut d = wysiwyg_doc("enter_blank_page", body);
12339            d.build_visual(80);
12340            d.caret = d.source.len();
12341            d.newline();
12342            assert_eq!(d.source, body);
12343            assert!(!d.can_undo(), "{body:?}");
12344            assert!(!d.dirty, "{body:?}");
12345        }
12346        let mut d = wysiwyg_doc("enter_blank_page_preserve", "");
12347        d.set_line_flow(LineFlow::Preserve);
12348        d.build_visual(80);
12349        d.newline();
12350        assert_eq!(d.source, "\n");
12351    }
12352
12353    #[test]
12354    fn enter_beside_a_rule_opens_a_line_under_it() {
12355        // Beside a rule the caret stands at the home past it, which in source is
12356        // the start of the blank line under the rule, and Enter took it for an
12357        // empty paragraph: a lone newline, drawn as one more gap, and the caret
12358        // put on the next block's first line — where typing joined that block.
12359        // It goes on under the rule instead, as the rule button leaves it.
12360        let mut d = wysiwyg_doc("enter_rule", "a\n\n---\n\nb\n");
12361        d.build_visual(80);
12362        d.caret = "a\n\n---\n".len();
12363        d.newline();
12364        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
12365        assert_eq!(d.caret, "a\n\n---\n\n".len());
12366        d.insert("X");
12367        assert_eq!(d.source, "a\n\n---\n\nX\n\nb\n");
12368
12369        // Closing the document.
12370        let mut d = wysiwyg_doc("enter_rule_end", "a\n\n---\n");
12371        d.caret = d.source.len();
12372        d.newline();
12373        assert_eq!(d.source, "a\n\n---\n\n");
12374        assert_eq!(d.caret, d.source.len());
12375
12376        // In a quote, where the lines it writes keep the quote's prefix.
12377        let mut d = wysiwyg_doc("enter_rule_quote", "> a\n>\n> ---\n>\n> b\n");
12378        d.caret = "> a\n>\n> ---\n".len();
12379        d.newline();
12380        assert_eq!(d.source, "> a\n>\n> ---\n>\n> \n>\n> b\n");
12381        d.insert("X");
12382        assert_eq!(d.source, "> a\n>\n> ---\n>\n> X\n>\n> b\n");
12383
12384        // Preserve draws the blank line under a rule as a line, and the caret
12385        // on it: Enter there is a blank line's, one line down.
12386        let mut d = wysiwyg_doc("enter_rule_preserve", "a\n\n---\n\nb\n");
12387        d.set_line_flow(LineFlow::Preserve);
12388        d.caret = "a\n\n---\n".len();
12389        d.newline();
12390        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
12391        assert_eq!(d.caret, "a\n\n---\n\n".len());
12392    }
12393
12394    #[test]
12395    fn insert_table_at_a_paragraph_s_end_splits_nothing() {
12396        // The same door as the rule's, through the placement they share.
12397        let mut d = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12398        d.caret = 4;
12399        d.insert_table(1, 1);
12400        assert_eq!(d.source, "para\n\n|  |\n|---|\n|  |\n");
12401        let mut d = doc_with("table_end_typed", "para");
12402        d.caret = 4;
12403        d.insert_table(1, 1);
12404        assert_eq!(d.source, "para\n\n|  |\n| --- |\n|  |\n");
12405        assert!(d.caret_in_table());
12406    }
12407
12408    #[test]
12409    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
12410        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
12411        // and leaf wrote the first into both until twig started spelling it.
12412        let mut md = doc_with("hr_md", "para\n");
12413        md.caret = 2;
12414        md.insert_thematic_break();
12415        assert_eq!(md.source, "pa\n\n---\n\nra\n");
12416
12417        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12418        dj.caret = 2;
12419        dj.insert_thematic_break();
12420        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
12421    }
12422
12423    #[test]
12424    fn insert_table_parts_the_paragraph_and_lands_in_the_first_header_cell() {
12425        // The table goes *at* the caret the way the rule does: the paragraph is
12426        // parted first, and twig writes the grid after its first half. The
12427        // caret then sits in the first header cell — selected, as Tab would
12428        // leave it — so the next keystroke is the heading.
12429        let mut d = doc_with("table_mid", "before after\n");
12430        d.caret = 7;
12431        d.insert_table(2, 3);
12432        assert_eq!(
12433            d.source,
12434            "before \n\n|  |  |  |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |\n\nafter\n"
12435        );
12436        assert!(d.caret_in_table());
12437        let first_bar = d.source.find('|').unwrap();
12438        assert!(
12439            d.caret > first_bar && d.caret < d.source.find("| ---").unwrap(),
12440            "caret {} is not in the header row",
12441            d.caret
12442        );
12443        d.insert("Name");
12444        assert!(d.source.starts_with("before \n\n| Name |  |  |\n"));
12445        // And the grid the table was written into is one the table keys walk
12446        // (over the map a frontend rebuilds after every edit).
12447        d.build_visual(80);
12448        assert!(d.cell_tab(true));
12449        d.insert("Qty");
12450        assert!(d.source.starts_with("before \n\n| Name | Qty |  |\n"));
12451    }
12452
12453    #[test]
12454    fn insert_table_spells_the_grid_the_format_s_own_way() {
12455        // Djot's delimiter row is unpadded, and leaf never has to know that.
12456        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12457        dj.caret = 2;
12458        dj.insert_table(1, 2);
12459        assert_eq!(dj.source, "pa\n\n|  |  |\n|---|---|\n|  |  |\n\nra\n");
12460        assert!(dj.caret_in_table());
12461    }
12462
12463    #[test]
12464    fn insert_table_refuses_where_the_format_spells_no_table() {
12465        let mut d = Doc::from_source("<p>ab</p>\n".into(), Format::Html).unwrap();
12466        d.caret = 4;
12467        d.insert_table(1, 1);
12468        assert_eq!(d.source, "<p>ab</p>\n");
12469        assert!(d.status.as_deref().unwrap_or("").contains("not supported"));
12470        assert!(!d.capabilities().table);
12471    }
12472
12473    #[test]
12474    fn insert_table_reports_a_zero_shape_and_writes_nothing() {
12475        let mut d = doc_with("table_zero", "para\n");
12476        d.caret = 2;
12477        d.insert_table(0, 2);
12478        assert_eq!(d.source, "para\n");
12479        assert!(d.status.as_deref().unwrap_or("").starts_with("table:"));
12480    }
12481
12482    #[test]
12483    fn clicking_below_a_final_thematic_break_can_type_after_it() {
12484        let mut d = wysiwyg_doc("hr_final_click", "---\n");
12485        d.build_visual(80);
12486        d.click(d.vmap.num_rows() + 2, 0, false);
12487        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
12488        d.insert("after");
12489        assert_eq!(d.source, "---\nafter");
12490    }
12491
12492    #[test]
12493    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
12494        // The same bytes are two documents. In Markdown `  - b` is a nested item
12495        // and the next one belongs beside it, at its indent. In Djot a list
12496        // marker can't interrupt a paragraph, so those bytes are literal text in
12497        // item `a` and there is only one item — writing `  - ` under it would add
12498        // no item at all, just more text, and the new sibling has to go to
12499        // column zero. Both spellings come out of the *enclosing item's* line.
12500        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
12501        md.caret = "- a\n  - b".len();
12502        md.newline();
12503        assert_eq!(md.source, "- a\n  - b\n  - \n");
12504        assert_eq!(list_items(&mut md), 3);
12505
12506        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
12507        dj.view = View::Wysiwyg;
12508        dj.build_visual(80);
12509        dj.caret = "- a\n  - b".len();
12510        dj.newline();
12511        assert_eq!(dj.source, "- a\n  - b\n- \n");
12512        assert_eq!(list_items(&mut dj), 2);
12513
12514        // Where Djot's nesting is real — opened by a blank line — the indent is
12515        // reproduced there too, and the two formats agree again.
12516        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
12517        dj.view = View::Wysiwyg;
12518        dj.build_visual(80);
12519        dj.caret = "- a\n\n  - b".len();
12520        dj.newline();
12521        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
12522        assert_eq!(list_items(&mut dj), 3);
12523    }
12524
12525    #[test]
12526    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
12527        // Tab replaces the line's whole prefix with the one twig spells, so the
12528        // quote markers, the parent's indent and an ordered marker's extra
12529        // column are all its answer rather than leaf's arithmetic.
12530        for (name, body, caret, want) in [
12531            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
12532            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
12533            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
12534            // A checkbox is markup the item's own text wraps past, but a nested
12535            // list may only open at the *list* marker's column — four in from
12536            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
12537            // parses as one item, not two.
12538            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
12539            (
12540                "quoted task",
12541                "> - [ ] a\n> - [ ] b\n",
12542                18,
12543                "> - [ ] a\n>   - [ ] b\n",
12544            ),
12545        ] {
12546            let mut doc = wysiwyg_doc(name, body);
12547            doc.caret = caret;
12548            doc.indent();
12549            assert_eq!(doc.source, want, "{name}");
12550            // The nesting is real, not just indented text.
12551            assert_eq!(list_items(&mut doc), 2, "{name}");
12552        }
12553    }
12554
12555    #[test]
12556    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
12557        // The same bytes, the two formats disagreeing, and a gesture that used
12558        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
12559        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
12560        // so those bytes are literal text inside item `a` — there is nothing to
12561        // outdent, and treating them as a marker turned one item into two, a
12562        // structural edit from a keystroke that should delete one character.
12563        //
12564        // twig's `line_prefix` is what tells them apart: it reports the marker
12565        // on the Markdown line and nothing on the Djot one, which is a
12566        // continuation. No byte scan can reach that answer.
12567        let src = "- a\n  - b\n";
12568        let at = "- a\n  - ".len();
12569
12570        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
12571        md.view = View::Wysiwyg;
12572        md.build_visual(80);
12573        md.caret = at;
12574        md.backspace();
12575        assert_eq!(md.source, "- a\n- b\n");
12576        assert_eq!(list_items(&mut md), 2);
12577
12578        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
12579        dj.view = View::Wysiwyg;
12580        dj.build_visual(80);
12581        dj.caret = at;
12582        dj.backspace();
12583        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
12584        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
12585    }
12586
12587    #[test]
12588    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
12589        // Leaf used to spell the next item from the marker bytes it scanned, and
12590        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
12591        // and dropped out of the checklist. twig reproduces the whole
12592        // continuation, and a fresh item is always unticked however the one above
12593        // it stands.
12594        for (name, body, want) in [
12595            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
12596            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
12597        ] {
12598            let mut doc = wysiwyg_doc(name, body);
12599            doc.caret = body.trim_end_matches('\n').len();
12600            doc.newline();
12601            assert_eq!(doc.source, want, "{name}");
12602            // Both items are checklist items — the new one is a box, not the
12603            // plain bullet the old marker scan left behind — and it is unticked
12604            // whichever way the one above it faces.
12605            let boxes: Vec<Option<bool>> = doc
12606                .nodes()
12607                .iter()
12608                .filter(|n| n.kind == Kind::TaskListItem)
12609                .map(|n| n.checked)
12610                .collect();
12611            assert_eq!(boxes.len(), 2, "{name}");
12612            assert_eq!(boxes[1], Some(false), "{name}");
12613        }
12614    }
12615
12616    #[test]
12617    fn a_split_takes_the_space_the_caret_was_in_front_of() {
12618        // Splicing a break at the caret strands the space the words were parted
12619        // at on the head of the second block, where it reads as an indent nobody
12620        // typed. twig's split consumes it.
12621        for (name, body, caret, want) in [
12622            ("para", "one two\n", 3, "one\n\ntwo\n"),
12623            ("item", "- one two\n", 5, "- one\n- two\n"),
12624            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
12625            // A heading takes leaf's own path, which has to match.
12626            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
12627        ] {
12628            let mut doc = wysiwyg_doc(name, body);
12629            doc.caret = caret;
12630            doc.newline();
12631            assert_eq!(doc.source, want, "{name}");
12632        }
12633    }
12634
12635    #[test]
12636    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
12637        // The one place leaf keeps its own break: `split_block` repeats the `#`,
12638        // and Enter after a title is how the body under it is asked for.
12639        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
12640        doc.caret = "# Title".len();
12641        doc.newline();
12642        doc.insert("body");
12643        assert_eq!(doc.source, "# Title\n\nbody\n");
12644        assert_eq!(
12645            doc.nodes()
12646                .iter()
12647                .filter(|n| n.kind == Kind::Heading)
12648                .count(),
12649            1
12650        );
12651    }
12652
12653    #[test]
12654    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
12655        // A quoted item's marker doesn't open its line, so a scan that starts at
12656        // column zero finds a `>` where it wanted a bullet, calls the line "not a
12657        // list" and hands Enter to the plain-quote branch — which writes `> ` and
12658        // drops the list. The next item has to carry the whole prefix.
12659        for (name, body, want) in [
12660            ("flat", "> - a\n", "> - a\n> - \n"),
12661            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
12662            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
12663            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
12664            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
12665        ] {
12666            let mut doc = wysiwyg_doc(name, body);
12667            doc.caret = body.trim_end_matches('\n').len();
12668            doc.newline();
12669            assert_eq!(doc.source, want, "{name}");
12670            // The marker isn't just spelled right, it parses as an item.
12671            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
12672        }
12673    }
12674
12675    #[test]
12676    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
12677        // Double-Enter exits the list. Unquoted that means a blank line, but a
12678        // *bare* blank line would end the quote too and drop the caret out of it,
12679        // so the separator keeps its `>` and the caret's line keeps its `> `.
12680        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
12681        doc.caret = "> - a\n> - ".len();
12682        doc.newline();
12683        assert_eq!(doc.source, "> - a\n>\n> \n");
12684        assert_eq!(list_items(&mut doc), 1);
12685        // What "still in the quote" means for the next keystroke: the caret sits
12686        // behind the prefix, and what's typed there lands inside the quote as a
12687        // paragraph of its own — not as more of item `a`.
12688        doc.insert("x");
12689        assert_eq!(doc.source, "> - a\n>\n> x\n");
12690        assert!(
12691            doc.editor
12692                .ancestors_at(doc.caret - 1)
12693                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
12694        );
12695    }
12696
12697    #[test]
12698    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
12699        // The marker is hidden block markup, so Backspace over it is structural —
12700        // but only the marker is the list's. Splicing from the line start would
12701        // take the `>` with it and silently unquote the line.
12702        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
12703        doc.caret = "> - ".len();
12704        doc.backspace();
12705        assert_eq!(doc.source, "> a\n");
12706        assert_eq!(list_items(&mut doc), 0);
12707
12708        // A nested one outdents instead, moving the bullet within the quote
12709        // rather than moving the quote.
12710        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
12711        doc.caret = "> - a\n>   - ".len();
12712        doc.backspace();
12713        assert_eq!(doc.source, "> - a\n> - b\n");
12714        assert_eq!(list_items(&mut doc), 2);
12715    }
12716
12717    #[test]
12718    fn only_a_bare_paragraph_is_parted_around_the_caret() {
12719        // The split is deliberately narrow. Parting a fenced block would leave
12720        // two fences with a rule between them, and parting a list item would
12721        // mint an item nobody asked for on the way to a rule that lands after
12722        // the list either way — so both keep the whole block intact and take the
12723        // rule after it. A caret in a quote is likewise left alone.
12724        for (name, body, caret, want) in [
12725            (
12726                "code",
12727                "```\nfn x() {}\n```\n",
12728                8,
12729                "```\nfn x() {}\n```\n\n---\n\n",
12730            ),
12731            ("list", "- one two\n", 6, "- one two\n\n---\n\n"),
12732            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n>\n> \n"),
12733        ] {
12734            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
12735            d.caret = caret;
12736            d.insert_thematic_break();
12737            assert_eq!(d.source, want, "{name}: the block should stay whole");
12738        }
12739    }
12740
12741    #[test]
12742    fn insert_thematic_break_replaces_the_selection() {
12743        // Now that the rule lands *at* the caret again, replacing the selection
12744        // is coherent once more: the text goes, and the rule takes its place.
12745        // The space the deletion left leading the second half is consumed by the
12746        // split rather than opening the new paragraph with it.
12747        let mut d = doc_with("hr_sel", "one two three\n");
12748        d.anchor = Some(4);
12749        d.caret = 7; // "two"
12750        d.insert_thematic_break();
12751        assert_eq!(d.source, "one \n\n---\n\nthree\n");
12752        assert_eq!(d.selection(), None);
12753    }
12754
12755    #[test]
12756    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
12757        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
12758        // because writing `---` into one is code, not a rule — twig now walks out
12759        // to the block that owns the caret's line, so there is nothing to refuse.
12760        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
12761        code.caret = 5; // inside the fenced code
12762        code.insert_thematic_break();
12763        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n\n");
12764        assert_eq!(code.status, None, "no refusal to report any more");
12765
12766        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
12767        table.caret = 3; // in the header row
12768        table.insert_thematic_break();
12769        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n\n");
12770    }
12771
12772    #[test]
12773    fn insert_thematic_break_in_a_list_item_ends_the_list() {
12774        // The un-indented rule cannot continue the list, so it closes the list
12775        // and lands at the top level rather than nested inside it.
12776        let mut d = doc_with("hr_list", "- one\n- two\n");
12777        d.caret = "- one\n- tw".len(); // mid "two"
12778        d.insert_thematic_break();
12779        d.build_visual(80);
12780        let rule_at = d.source.find("---").unwrap();
12781        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12782        assert!(
12783            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
12784                && n.span.start <= rule_at
12785                && rule_at < n.span.end),
12786            "the rule must not be nested inside the list"
12787        );
12788    }
12789
12790    #[test]
12791    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
12792        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
12793        // which is the document the gesture was actually asked for — and the
12794        // line the caret goes on to under it wears the prefix too, as the line
12795        // Enter opens in a quote does.
12796        let mut d = doc_with("hr_quote", "> hello\n");
12797        d.caret = 4; // inside the quoted text
12798        d.insert_thematic_break();
12799        assert_eq!(d.source, "> hello\n>\n> ---\n>\n> \n");
12800        assert_eq!(d.caret, "> hello\n>\n> ---\n>\n> ".len());
12801        d.build_visual(80);
12802        let rule_at = d.source.find("---").unwrap();
12803        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12804        assert!(
12805            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
12806                && n.span.start <= rule_at
12807                && rule_at < n.span.end),
12808            "the rule belongs to the quote it was asked for"
12809        );
12810    }
12811
12812    // ── typing against a block picture ────────────────────────────────────────
12813
12814    /// A rendered-view document with the caret parked on one of the picture's two
12815    /// stops, and the map already built — the state a frontend is in between
12816    /// drawing a frame and the next keystroke.
12817    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
12818        let mut d = doc_in(View::Wysiwyg, name, src);
12819        d.build_visual_unwrapped();
12820        let start = src.find("![").unwrap();
12821        d.caret = match side {
12822            MediaStop::Before => start,
12823            MediaStop::After => start + "![](p.png)".len(),
12824        };
12825        d
12826    }
12827
12828    /// The block media the map publishes, after rebuilding it — "is this still a
12829    /// picture, or has it become a line of text with an image in it?"
12830    fn media_count(d: &mut Doc) -> usize {
12831        d.build_visual_unwrapped();
12832        d.vmap.media.len()
12833    }
12834
12835    #[test]
12836    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
12837        // The accident this prevents: tap the blank page under a photo (which
12838        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
12839        // paragraph with an *inline* image — the photo stops being drawn.
12840        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
12841        d.insert("xy");
12842        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
12843        assert_eq!(media_count(&mut d), 1, "still a picture");
12844    }
12845
12846    #[test]
12847    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
12848        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12849        d.insert("xy");
12850        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
12851        assert_eq!(media_count(&mut d), 1);
12852    }
12853
12854    #[test]
12855    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
12856        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
12857        d.insert("x");
12858        assert_eq!(d.source, "x\n\n![](p.png)\n");
12859        assert_eq!(media_count(&mut d), 1);
12860    }
12861
12862    #[test]
12863    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
12864        // The opened paragraph is part of the keystroke, not an edit the writer
12865        // made — so it undoes with the character, not a step later.
12866        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
12867        d.insert("x");
12868        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
12869        d.undo();
12870        assert_eq!(d.source, "hi\n\n![](p.png)\n");
12871    }
12872
12873    #[test]
12874    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
12875        // ⌘V dissolves the picture exactly as a keystroke does.
12876        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
12877        d.paste("pasted");
12878        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
12879        assert_eq!(media_count(&mut d), 1);
12880    }
12881
12882    #[test]
12883    fn typing_beside_an_inline_image_is_ordinary_editing() {
12884        // An inline image has no placeholder row and no stops of its own. Opening
12885        // a paragraph mid-sentence would be the bug, not the fix.
12886        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
12887        d.build_visual_unwrapped();
12888        d.caret = "see ![](p.png)".len();
12889        d.insert("!");
12890        assert_eq!(d.source, "see ![](p.png)! here\n");
12891    }
12892
12893    #[test]
12894    fn source_view_types_raw_markup_against_an_image_untouched() {
12895        // Source view is for writing the markup itself; a break inserted behind
12896        // the writer's back there would be the editor arguing with them.
12897        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
12898        d.caret = "![](p.png)".len();
12899        d.insert("x");
12900        assert_eq!(d.source, "![](p.png)x\n");
12901    }
12902
12903    #[test]
12904    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
12905        // A selection is replaced, not joined into, so there is nothing to
12906        // protect: the range takes the picture with it.
12907        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
12908        d.anchor = Some(d.caret);
12909        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
12910        d.insert("x");
12911        assert_eq!(d.source, "hi\n\nx\n");
12912    }
12913
12914    #[test]
12915    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
12916        // What this actually cost: a real vault's photo, to one stray Backspace.
12917        // The caret past `![](p.png)` was deleting the closing paren — invisible
12918        // in the rendered view — and the photo became the text `![](p.png`.
12919        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
12920        d.backspace();
12921        assert_eq!(d.source, "hi\n");
12922        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
12923        d.undo();
12924        assert_eq!(
12925            d.source, "hi\n\n![](p.png)\n",
12926            "and comes back in one piece"
12927        );
12928    }
12929
12930    #[test]
12931    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
12932        // Deleting the break here would join the picture to the paragraph above,
12933        // where it is an *inline* image and stops being drawn. Step over the
12934        // boundary; the next press deletes in the paragraph the caret reached.
12935        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12936        d.backspace();
12937        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
12938        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
12939        d.backspace();
12940        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
12941        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
12942    }
12943
12944    #[test]
12945    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
12946        // The mirror. A byte-step here eats the `!` and leaves a link.
12947        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
12948        d.delete_forward();
12949        assert_eq!(d.source, "hi\n\nbye\n");
12950        assert_eq!(media_count(&mut d), 0);
12951    }
12952
12953    #[test]
12954    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
12955        let mut d = doc_at_picture(
12956            "pic_del_after",
12957            "hi\n\n![](p.png)\n\nbye\n",
12958            MediaStop::After,
12959        );
12960        d.delete_forward();
12961        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
12962        assert_eq!(
12963            d.caret,
12964            d.source.find("bye").unwrap(),
12965            "the caret stepped down to `bye`"
12966        );
12967    }
12968
12969    #[test]
12970    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
12971        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
12972        d.backspace();
12973        assert_eq!(d.source, "\n");
12974        assert_eq!(media_count(&mut d), 0);
12975    }
12976
12977    #[test]
12978    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
12979        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
12980        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
12981        d.delete_word_back();
12982        assert_eq!(d.source, "hi there\n");
12983
12984        // And in front of one it runs *through* the paragraph break into the
12985        // prose above, which merges the picture inline — so it steps out first,
12986        // and the second press deletes the word it was aimed at.
12987        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
12988        d.delete_word_back();
12989        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
12990        d.delete_word_back();
12991        assert_eq!(
12992            d.source, "hi \n\n![](p.png)\n",
12993            "the word above went, the picture stayed"
12994        );
12995        assert_eq!(media_count(&mut d), 1);
12996    }
12997
12998    #[test]
12999    fn source_view_deletes_raw_markup_against_an_image_untouched() {
13000        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
13001        d.caret = "![](p.png)".len();
13002        d.backspace();
13003        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
13004    }
13005
13006    #[test]
13007    fn image_destination_at_caret_reads_the_image_under_the_caret() {
13008        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
13009        d.caret = 3; // inside the image markup
13010        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
13011        // Past the image, the caret is in no image.
13012        d.caret = "![a cat](cat.png)".len();
13013        assert_eq!(d.image_destination_at_caret(), None);
13014    }
13015
13016    #[test]
13017    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
13018        // The image is one placeholder row by default, and `set_media_rows` grows
13019        // it to the height the frontend measured: the label row plus blank
13020        // `decoration` fillers that hold the vertical space a raster is drawn into.
13021        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
13022        assert_eq!(d.vmap.media.len(), 1);
13023        let img_row = d.vmap.media[0].rows_span.start;
13024        assert_eq!(
13025            d.vmap.media[0].rows_span,
13026            img_row..img_row + 1,
13027            "default is one row"
13028        );
13029
13030        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
13031        d.build_visual(80);
13032        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
13033        let span = d.vmap.media[0].rows_span.clone();
13034        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
13035        // The label row carries the mark and its glyphs; the three below are blank
13036        // decoration — drawn, but no caret and no text.
13037        assert!(
13038            d.vmap.rows[span.start].media.is_some(),
13039            "mark rides the first row"
13040        );
13041        for r in (span.start + 1)..span.end {
13042            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
13043            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
13044            assert!(
13045                d.vmap.rows[r].media.is_none(),
13046                "only the first row is marked"
13047            );
13048        }
13049    }
13050
13051    #[test]
13052    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
13053        // The extra rows are pure spacers: the caret's only homes stay the stop in
13054        // front of the image and the one just past it, so walking the document top
13055        // to bottom visits the same offsets whether the image is 1 row or 5.
13056        let body = "ab\n\n![x](p.png)\n\ncd\n";
13057        let stops_at = |rows: usize| -> Vec<usize> {
13058            let mut d = wysiwyg_doc("img_stops", body);
13059            if rows > 1 {
13060                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
13061                d.build_visual(80);
13062            }
13063            d.caret = 0;
13064            let mut seen = vec![d.caret];
13065            loop {
13066                d.move_right(false);
13067                if *seen.last().unwrap() == d.caret {
13068                    break;
13069                }
13070                seen.push(d.caret);
13071            }
13072            seen
13073        };
13074        assert_eq!(
13075            stops_at(1),
13076            stops_at(5),
13077            "reserving rows must not add stops"
13078        );
13079    }
13080
13081    #[test]
13082    fn insert_link_repoints_the_link_at_a_bare_caret() {
13083        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
13084        d.caret = 3; // in the link's text, nothing selected
13085        d.insert_link("http://y.dev");
13086        assert_eq!(d.source, "[word](http://y.dev)\n");
13087        assert_eq!(d.selected_text(), Some("word"));
13088    }
13089
13090    #[test]
13091    fn insert_link_on_an_empty_range_autolinks_a_url() {
13092        // A link with no text of its own is an autolink, and twig spells it —
13093        // `<…>` is the canonical form and needs no text typed into it, so the
13094        // caret lands after it rather than selecting a finished link.
13095        let mut d = doc_with("link_empty", "\n");
13096        d.caret = 0;
13097        d.insert_link("http://x.dev");
13098        assert_eq!(d.source, "<http://x.dev>\n");
13099        assert_eq!(d.selection(), None);
13100        assert_eq!(d.caret, 14);
13101    }
13102
13103    #[test]
13104    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
13105        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
13106        // in Markdown, so a destination that can't autolink doubles as the text
13107        // instead — which is then selected, ready to be typed over.
13108        let mut d = doc_with("link_rel", "\n");
13109        d.caret = 0;
13110        d.insert_link("./notes.md");
13111        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
13112        assert_eq!(d.selection(), Some((1, 11)));
13113        d.insert("Notes");
13114        assert_eq!(d.source, "[Notes](./notes.md)\n");
13115    }
13116
13117    #[test]
13118    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
13119        // The autolink's text is its URL, so re-pointing replaces the whole
13120        // node — the caret must not splice a second link inside the first.
13121        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
13122        d.caret = 10;
13123        d.insert_link("https://y.dev");
13124        assert_eq!(d.source, "see <https://y.dev> ok\n");
13125    }
13126
13127    #[test]
13128    fn code_language_reads_and_edits_through_the_fence() {
13129        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
13130        d.caret = 10; // inside the code body
13131        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13132        assert!(d.caret_in_fenced_code());
13133
13134        d.set_code_language("python");
13135        assert!(
13136            d.source.starts_with("```python\n"),
13137            "source: {:?}",
13138            d.source
13139        );
13140        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13141
13142        // Clearing it leaves a bare fence and no label.
13143        d.set_code_language("");
13144        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
13145        assert_eq!(d.code_language_at_caret(), None);
13146
13147        // A caret outside any code block edits nothing.
13148        let mut p = doc_with("code_lang_none", "just prose\n");
13149        assert!(!p.caret_in_fenced_code());
13150        p.set_code_language("rust");
13151        assert_eq!(p.source, "just prose\n");
13152    }
13153
13154    #[test]
13155    fn code_language_reads_and_edits_through_a_quoted_fence() {
13156        let mut d = doc_with("code_lang_quote", "> ```rust\n> let x = 1;\n> ```\n");
13157        d.caret = d.source.find("let").unwrap();
13158        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13159        assert!(d.caret_in_fenced_code());
13160        d.set_code_language("python");
13161        assert!(
13162            d.source.starts_with("> ```python\n"),
13163            "source: {:?}",
13164            d.source
13165        );
13166        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13167    }
13168
13169    #[test]
13170    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
13171        // Markdown's info string ends at whitespace, so `two words` would write
13172        // a fence that reads back with a different language than the one asked
13173        // for. twig refuses it; leaf reports that and leaves the source alone.
13174        // The old splice trimmed the ends and wrote whatever was left.
13175        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
13176        d.caret = 10;
13177        d.set_code_language("two words");
13178        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
13179        assert!(d.status.is_some(), "the refusal should be reported");
13180        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13181    }
13182
13183    #[test]
13184    fn link_destination_at_caret_reads_both_spellings() {
13185        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
13186        d.caret = 5;
13187        assert_eq!(
13188            d.link_destination_at_caret().as_deref(),
13189            Some("https://x.dev")
13190        );
13191        d.caret = 0;
13192        assert_eq!(d.link_destination_at_caret(), None);
13193
13194        // An autolink has no `destination`; its text is the URL.
13195        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
13196        a.caret = 10;
13197        assert_eq!(
13198            a.link_destination_at_caret().as_deref(),
13199            Some("https://x.dev")
13200        );
13201        a.caret = 21;
13202        assert_eq!(a.link_destination_at_caret(), None);
13203    }
13204
13205    #[test]
13206    fn heading_at_caret_is_the_nearest_heading_above() {
13207        let src = "intro\n\n# Title\n\n## The *Second* Part\n\nbody here\n";
13208        let mut d = doc_with("heading_at", src);
13209        // Under no heading at all.
13210        d.caret = 2;
13211        assert_eq!(d.heading_at_caret(), None);
13212        // In a paragraph under a level-2 heading: that heading, its markup
13213        // stripped for the slug, and its own span.
13214        d.caret = src.find("body").unwrap() + 2;
13215        let h = d.heading_at_caret().expect("under `## The Second Part`");
13216        assert_eq!(h.text, "The Second Part");
13217        assert_eq!(h.level, 2);
13218        assert_eq!(&src[h.span.clone()].trim_end(), &"## The *Second* Part");
13219        // Standing in a heading answers with that heading.
13220        let h = d.heading_at(src.find("Title").unwrap()).unwrap();
13221        assert_eq!((h.text.as_str(), h.level), ("Title", 1));
13222        // And the text is what `locate` lands a slug of.
13223        let landing = d.locate("the-second-part").unwrap();
13224        assert_eq!(landing.start, d.heading_at_caret().unwrap().span.start);
13225    }
13226
13227    #[test]
13228    fn locate_finds_the_block_a_declared_id_names() {
13229        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
13230        // verse. The locator has to land on the *verse*, which is the whole
13231        // reason a link carries one.
13232        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
13233                   {#v2}\nYea, I make a record in the language of my father.\n";
13234        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13235        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
13236        assert_eq!(
13237            d.source[v2.start..v2.end].trim_end(),
13238            "Yea, I make a record in the language of my father."
13239        );
13240        // The attribute line is not part of it: `start` is a place to put a
13241        // caret, and `{#v2}` is markup the caret has no business landing in.
13242        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
13243        assert_eq!(d.locate("v99"), None);
13244    }
13245
13246    #[test]
13247    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
13248        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
13249        // Markdown heading is literal text. So `#the-second-part` can only be
13250        // the heading's own words, which is the rule every Markdown renderer
13251        // already follows and therefore the one a link was authored against.
13252        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
13253        let mut d = doc_with("locate_md", src);
13254        let hit = d.locate("the-second-part").expect("the heading's slug");
13255        assert!(d.source[hit.start..].starts_with("## The Second Part"));
13256        // Bounded by the next heading that isn't under it, so a peek shows the
13257        // section rather than only its title.
13258        assert_eq!(
13259            &d.source[hit.start..hit.end],
13260            "## The Second Part\n\nbody\n\n"
13261        );
13262
13263        // A subsection does not end its parent: `# Title` runs to `## Third`'s
13264        // sibling only because there is no other `#`, so it covers the lot.
13265        let title = d.locate("title").expect("the top heading");
13266        assert_eq!(title.end, d.source.len());
13267    }
13268
13269    #[test]
13270    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
13271        // djot mints `Some-Heading-Here`; a link to it is written
13272        // `#some-heading-here` by nearly everything that writes links. Both
13273        // spellings are one question.
13274        let src = "## Some Heading Here\n\nbody\n";
13275        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13276        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
13277        let slugged = d.locate("some-heading-here").expect("the link's spelling");
13278        assert_eq!(exact, slugged);
13279        // The section, not the heading line — there is more to show than a title.
13280        assert_eq!(&d.source[exact.start..exact.end], src);
13281    }
13282
13283    #[test]
13284    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
13285        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
13286        assert_eq!(d.locate(""), None);
13287        assert_eq!(d.locate("   "), None);
13288        // All punctuation: it names nothing, and must not be read as "match the
13289        // first heading whose slug is also empty".
13290        assert_eq!(d.locate("!!!"), None);
13291    }
13292
13293    #[test]
13294    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
13295        // The document's mistake, and the answer every other anchor
13296        // implementation gives — the alternative is for a link to mean whichever
13297        // of the two a walk happened to reach first.
13298        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
13299        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13300        let hit = d.locate("dup").expect("the first `{#dup}`");
13301        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
13302    }
13303
13304    #[test]
13305    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
13306        // The button's whole job: a reference where the caret was, a definition
13307        // to give it meaning, and the caret waiting in the empty note so the
13308        // next keystroke is the note's first word.
13309        let mut d = doc_with("fn_insert", "A claim and more.\n");
13310        d.caret = 7; // just past "A claim"
13311        d.insert_footnote();
13312        assert!(
13313            d.source.starts_with("A claim[^1] and more."),
13314            "{:?}",
13315            d.source
13316        );
13317        assert!(
13318            d.source.contains("[^1]:"),
13319            "the definition too: {:?}",
13320            d.source
13321        );
13322        assert_eq!(d.status, None);
13323
13324        let reference = d.source.find("[^1]").unwrap();
13325        let note = d
13326            .footnote_at(reference + 2)
13327            .expect("the reference just written");
13328        assert_eq!(note.label, "1");
13329        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
13330        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
13331        // …and typing there is typing into the note, not near it.
13332        d.insert("the note");
13333        assert_eq!(
13334            d.footnote_at(reference + 2).and_then(|f| f.text),
13335            Some("the note".to_string())
13336        );
13337    }
13338
13339    #[test]
13340    fn insert_footnote_numbers_past_the_notes_already_written() {
13341        // A second press must not hand back a label somebody else is using: twig
13342        // reuses a defined label rather than appending a rival definition, so a
13343        // repeat of `1` would quietly point the new reference at the old note.
13344        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
13345        d.caret = 7; // past `[^1]`, before " two."
13346        d.insert_footnote();
13347        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
13348        assert_eq!(d.source.matches("[^2]:").count(), 1);
13349    }
13350
13351    #[test]
13352    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
13353        // `[^2]` with no definition is still a 2 that means something to whoever
13354        // wrote it — stepping over it would mint a note for their reference. A
13355        // word label takes no number, so it blocks none.
13356        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
13357        d.caret = d.source.find(" c").unwrap();
13358        d.insert_footnote();
13359        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
13360        assert!(
13361            d.source.starts_with("a[^2] b[^why][^1] c"),
13362            "{:?}",
13363            d.source
13364        );
13365    }
13366
13367    #[test]
13368    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
13369        // A reference annotates the words before it. Consuming the selection —
13370        // which is what an insert normally does — would delete the very claim
13371        // the author selected in order to footnote.
13372        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
13373        d.anchor = Some(2);
13374        d.caret = 7; // "claim" selected
13375        d.insert_footnote();
13376        assert!(
13377            d.source.starts_with("A claim[^1] and more."),
13378            "{:?}",
13379            d.source
13380        );
13381    }
13382
13383    #[test]
13384    fn a_note_just_written_still_knows_where_its_reference_is() {
13385        // The authoring loop in one test: press the button, type the note, ask to
13386        // go back. The caret ends at the note's last byte — which is the *end* of
13387        // the definition's span, the one offset the query used to exclude — so
13388        // this is where the round trip either works or doesn't.
13389        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
13390        d.caret = 7;
13391        d.insert_footnote();
13392        d.insert("the note");
13393        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
13394        let back = d
13395            .footnote_definition_at_caret()
13396            .expect("still in the note we just typed");
13397        assert_eq!(back.label, "1");
13398        // …and following it lands on the reference's label, where a reader's
13399        // return leg lands.
13400        assert_eq!(back.offset, Some(9));
13401        assert_eq!(&d.source[9..10], "1");
13402    }
13403
13404    #[test]
13405    fn insert_footnote_takes_one_undo_for_both_halves() {
13406        // twig writes the pair as a single edit; the point of that is here.
13407        let before = "A claim and more.\n";
13408        let mut d = doc_with("fn_insert_undo", before);
13409        d.caret = 7;
13410        d.insert_footnote();
13411        assert_ne!(d.source, before);
13412        d.undo();
13413        assert_eq!(d.source, before, "one undo takes back both halves");
13414    }
13415
13416    #[test]
13417    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
13418        // HTML is authorable — it spells the inline marks — and has no footnote.
13419        // The refusal says so rather than writing brackets that would render as
13420        // brackets.
13421        let src = "<p>A claim.</p>\n";
13422        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
13423        assert!(!Capabilities::of(Format::Html).footnote);
13424        d.caret = 5;
13425        d.insert_footnote();
13426        assert_eq!(d.source, src, "nothing written");
13427        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
13428    }
13429
13430    #[test]
13431    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
13432        // The empty body is the one place this could go wrong: the definition
13433        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
13434        // byte early would draw up in the paragraph above the note it belongs to.
13435        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
13436        d.place_caret(7, false);
13437        d.insert_footnote();
13438        d.build_visual(80); // the frame a frontend draws after the edit
13439        assert_eq!(
13440            d.vmap.snap_to_stop(d.caret),
13441            d.caret,
13442            "the caret sits on a stop"
13443        );
13444        let (row, _) = d.caret_pos();
13445        assert!(
13446            drawn_rows(&d)[row].contains("[1]"),
13447            "the caret is on the note's row, not above it: {:?}",
13448            drawn_rows(&d)
13449        );
13450    }
13451
13452    #[test]
13453    fn footnote_at_caret_resolves_a_reference_to_its_note() {
13454        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
13455        // blank line, as one has to.
13456        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
13457        d.caret = 9;
13458        let f = d
13459            .footnote_at_caret()
13460            .expect("the caret stands in a reference");
13461        assert_eq!(f.label, "1");
13462        assert_eq!(f.text.as_deref(), Some("the note"));
13463        // The offset points at the note's first word, not at the definition's
13464        // `[` — the marker is decoration with no caret stop on it.
13465        assert_eq!(f.offset, Some(29));
13466        assert_eq!(&d.source[29..37], "the note");
13467        // …and `end` closes the range, so a frontend can ask which rendered rows
13468        // the note occupies rather than re-deriving them from the text.
13469        assert_eq!(f.end, Some(37));
13470        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
13471    }
13472
13473    /// Two definitions in a row: each is its own note, and neither reaches into
13474    /// the other.
13475    ///
13476    /// A djot definition's span used to run past the blank line into the first
13477    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
13478    /// offsets named the *next* note's rows too, showing a reader two footnotes
13479    /// when they had asked about one. twig 3.1 ends the span after the block's
13480    /// own last line; the test outlives the workaround leaf carried for it.
13481    #[test]
13482    fn footnote_at_stops_a_note_at_the_definition_after_it() {
13483        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
13484        for format in [Format::Markdown, Format::Djot] {
13485            let mut d = Doc::from_source(src.to_string(), format).unwrap();
13486            d.caret = 7;
13487            let f = d.footnote_at_caret().expect("a reference");
13488            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
13489            assert_eq!(
13490                &src[f.offset.unwrap()..f.end.unwrap()],
13491                "first note.",
13492                "in {format:?}"
13493            );
13494        }
13495    }
13496
13497    /// The other side of that boundary: a blank line *inside* a definition is
13498    /// interior to it, and the note keeps its second paragraph.
13499    ///
13500    /// This is what the old body scan cost. It stopped at the first line not
13501    /// indented under the note — a blank line is not — so a two-paragraph note
13502    /// came back as its first paragraph, and "go to note" framed half of it.
13503    /// Reading the span twig gives is both simpler and right.
13504    #[test]
13505    fn footnote_at_keeps_a_notes_second_paragraph() {
13506        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
13507        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13508        d.caret = 7;
13509        let f = d.footnote_at_caret().expect("a reference");
13510        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
13511        // And it stops there — `After.` is the next block, not more note.
13512        assert_eq!(
13513            &src[f.offset.unwrap()..f.end.unwrap()],
13514            f.text.as_deref().unwrap()
13515        );
13516        assert!(!f.text.as_deref().unwrap().contains("After"));
13517    }
13518
13519    #[test]
13520    fn footnote_at_bounds_a_note_whose_body_is_empty() {
13521        // `[^1]:` with nothing after it. The range is empty rather than
13522        // inverted, and still points inside the definition — which is what keeps
13523        // a frontend's row lookup from walking off into the block above.
13524        let src = "A claim[^1].\n\n[^1]:\n";
13525        let mut d = doc_with("fn_empty_body", src);
13526        d.caret = 9;
13527        let f = d.footnote_at_caret().expect("a reference");
13528        assert_eq!(f.text.as_deref(), Some(""));
13529        assert_eq!(f.offset, f.end, "an empty note is an empty range");
13530        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
13531    }
13532
13533    #[test]
13534    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
13535        let mut d = doc_with(
13536            "fn_at_caret_none",
13537            "A claim[^1] and more.\n\n[^1]: the note\n",
13538        );
13539        d.caret = 2; // in the prose
13540        assert_eq!(d.footnote_at_caret(), None);
13541    }
13542
13543    #[test]
13544    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
13545        // The two are deliberately separate: a reference names a note in this
13546        // document, a link names somewhere to leave for, and answering one with
13547        // the other is what made a reference click do nothing at all.
13548        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
13549        d.caret = 3; // the `1` of `[^1]`
13550        assert!(d.footnote_at_caret().is_some());
13551        assert_eq!(
13552            d.link_destination_at_caret(),
13553            None,
13554            "a reference is not a link"
13555        );
13556
13557        d.caret = 10; // inside the link's label
13558        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
13559        assert_eq!(
13560            d.link_destination_at_caret().as_deref(),
13561            Some("https://x.dev")
13562        );
13563    }
13564
13565    #[test]
13566    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
13567        // A `[^99]` the document never defines is a real state — a note deleted
13568        // out from under its reference — and the label is what lets a frontend
13569        // say so. `None` here would be indistinguishable from "not on a
13570        // reference", which is the wrong thing to tell a reader.
13571        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
13572        d.caret = 9;
13573        let f = d
13574            .footnote_at_caret()
13575            .expect("the reference is still a reference");
13576        assert_eq!(f.label, "99");
13577        assert_eq!(f.text, None);
13578        assert_eq!(f.offset, None);
13579    }
13580
13581    #[test]
13582    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
13583        // Labels are not always numbers, and a note's body runs past its first
13584        // line — the indented continuation belongs to the note, so it comes back
13585        // with it (source bytes, verbatim, as documented).
13586        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
13587        let mut d = doc_with("fn_word_label", src);
13588        d.caret = 6;
13589        let f = d
13590            .footnote_at_caret()
13591            .expect("the caret stands in a reference");
13592        assert_eq!(f.label, "note");
13593        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
13594    }
13595
13596    #[test]
13597    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
13598        // The point of the offset form: a pointer hovering a reference asks what
13599        // note it names, and must not drag the caret along to ask.
13600        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
13601        d.caret = 0;
13602        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
13603        assert_eq!(f.label, "1");
13604        assert_eq!(f.text.as_deref(), Some("the note"));
13605        assert_eq!(d.caret, 0, "asking must not move the caret");
13606        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
13607    }
13608
13609    #[test]
13610    fn footnote_definition_at_caret_points_back_at_the_reference() {
13611        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
13612        // the caret can rest on — is at 9.
13613        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
13614        d.caret = 30; // inside the note's body
13615        let f = d
13616            .footnote_definition_at_caret()
13617            .expect("the caret stands in a definition");
13618        assert_eq!(f.label, "1");
13619        assert_eq!(f.offset, Some(9));
13620        assert_eq!(&d.source[7..11], "[^1]");
13621    }
13622
13623    #[test]
13624    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
13625        // The two legs have to meet: wherever `footnote_at` sends the caret, the
13626        // definition query must answer for — otherwise arriving at a note leaves
13627        // the reader somewhere the way back isn't offered.
13628        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
13629        let mut d = doc_with("fn_def_marker", src);
13630        let landed = d.footnote_at(9).unwrap().offset.unwrap();
13631        assert_eq!(
13632            d.footnote_definition_at(landed).and_then(|f| f.offset),
13633            Some(9),
13634            "the note a reference sends you to offers the way back"
13635        );
13636    }
13637
13638    #[test]
13639    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
13640        // The two queries answer for disjoint places, which is what lets one
13641        // gesture mean "down to the note" in one and "back up" in the other
13642        // without either having to remember which way the reader is going.
13643        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
13644        d.caret = 2; // prose
13645        assert_eq!(d.footnote_definition_at_caret(), None);
13646        d.caret = 9; // the reference
13647        assert_eq!(d.footnote_definition_at_caret(), None);
13648        assert!(
13649            d.footnote_at_caret().is_some(),
13650            "which is the reference's own query"
13651        );
13652    }
13653
13654    #[test]
13655    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
13656        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
13657        // note", which is false and leaves a frontend unable to explain why the
13658        // way back is missing.
13659        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
13660        let mut d = doc_with("fn_def_orphan", src);
13661        d.caret = src.find("orphan").unwrap();
13662        let f = d
13663            .footnote_definition_at_caret()
13664            .expect("an orphan is still a definition");
13665        assert_eq!(f.label, "2");
13666        assert_eq!(f.offset, None);
13667    }
13668
13669    #[test]
13670    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
13671        // One label, cited twice. The first is where the reader most likely came
13672        // from, and the only answer that doesn't depend on how they got here.
13673        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
13674        let mut d = doc_with("fn_def_repeat", src);
13675        d.caret = src.find("the note").unwrap();
13676        let f = d.footnote_definition_at_caret().expect("a definition");
13677        assert_eq!(
13678            f.offset,
13679            Some(5),
13680            "the first `[^a]`'s label, not the second's"
13681        );
13682        assert_eq!(&src[3..7], "[^a]");
13683    }
13684
13685    #[test]
13686    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
13687        // Down and back up, each leg found from the document rather than from a
13688        // memory of the other — so it still works for a reader who scrolled to
13689        // the notes instead of jumping there.
13690        //
13691        // `place_caret` rather than assigning `caret`, because that is what a
13692        // frontend calls: it snaps to a real caret stop, and a jump that lands
13693        // on a byte the caret can't rest on would arrive somewhere the return
13694        // leg no longer answers for. `build_map` first, since snapping is a
13695        // no-op until the map exists — which is exactly how this went unnoticed
13696        // when the offsets pointed at the `[^` markers.
13697        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
13698        d.build_map(None);
13699        d.place_caret(9, false);
13700        let down = d
13701            .footnote_at_caret()
13702            .expect("a reference")
13703            .offset
13704            .expect("a note");
13705        d.place_caret(down, false);
13706        let up = d
13707            .footnote_definition_at_caret()
13708            .expect("a definition")
13709            .offset
13710            .expect("a reference");
13711        d.place_caret(up, false);
13712        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
13713        assert_eq!(
13714            d.footnote_at_caret().expect("back on the reference").label,
13715            "1"
13716        );
13717    }
13718
13719    #[test]
13720    fn insert_link_hands_the_destination_to_twig_raw() {
13721        // Escaping is twig's, and format-specific: Markdown ends a destination
13722        // at the first space and needs the `<…>` form, where djot would read
13723        // those angle brackets as part of the URL.
13724        let mut d = doc_with("link_space", "word\n");
13725        d.anchor = Some(0);
13726        d.caret = 4;
13727        d.insert_link("a b");
13728        assert_eq!(d.source, "[word](<a b>)\n");
13729    }
13730
13731    #[test]
13732    fn insert_link_reports_a_destination_no_format_can_carry() {
13733        let mut d = doc_with("link_bad", "word\n");
13734        d.anchor = Some(0);
13735        d.caret = 4;
13736        d.insert_link("a\nb");
13737        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
13738        assert!(
13739            d.status.is_some(),
13740            "InvalidArgument should reach the status line"
13741        );
13742        assert!(!d.dirty);
13743    }
13744
13745    #[test]
13746    fn insert_link_works_in_wysiwyg_view() {
13747        let mut d = wysiwyg_doc("link_wys", "word here\n");
13748        d.anchor = Some(0);
13749        d.caret = 4;
13750        d.insert_link("http://x.dev");
13751        assert_eq!(d.source, "[word](http://x.dev) here\n");
13752        assert_eq!(d.selected_text(), Some("word"));
13753        // The map the caret has to keep riding is rebuilt each frame; motion
13754        // over the fresh one must still land on a real stop (the debug_assert).
13755        d.build_visual(80);
13756        d.move_right(false);
13757        d.move_left(false);
13758    }
13759
13760    #[test]
13761    fn click_maps_a_row_col_to_a_byte_offset() {
13762        let mut d = doc_with("click", "ab\ncd\n");
13763        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
13764        assert_eq!(d.caret, 4);
13765    }
13766
13767    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
13768    // stop just as the `(row, col)` click path does, so the caret can never come
13769    // to rest in the blank gap between two paragraphs — where it would draw in one
13770    // place and type in another.
13771    #[test]
13772    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
13773        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
13774        // caret stop (stops are 0,1,3,4).
13775        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
13776        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
13777        d.place_caret(2, false);
13778        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13779        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
13780    }
13781
13782    #[test]
13783    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
13784        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
13785        d.place_caret(0, false); // anchor at the start of "A"
13786        d.place_caret(2, true); // drag into the gap
13787        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13788        let (s, e) = d.selection().expect("a selection");
13789        assert!(
13790            d.vmap.is_stop(s) && d.vmap.is_stop(e),
13791            "selection {s}..{e} off a stop"
13792        );
13793    }
13794
13795    #[test]
13796    fn place_caret_on_a_real_stop_is_left_untouched() {
13797        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
13798        d.place_caret(3, false); // the start of "B" — a genuine stop
13799        assert_eq!(d.caret, 3);
13800    }
13801
13802    // An *empty paragraph* (two blank lines, an intentional blank line the user
13803    // opened) is a real caret stop, unlike the gap — a click into it must stay.
13804    #[test]
13805    fn place_caret_rests_in_an_empty_paragraph() {
13806        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
13807        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
13808        assert!(d.vmap.is_stop(empty));
13809        d.place_caret(empty, false);
13810        assert_eq!(d.caret, empty);
13811    }
13812
13813    // The content end of a hidden mark is a home too (`VisualMap::mark_ends`):
13814    // a drag over the word `bold` ends there, and a caret placed there stays.
13815    #[test]
13816    fn place_caret_rests_at_the_end_of_a_hidden_marks_content() {
13817        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
13818        let mut d = wysiwyg_doc("place_mark_end", src);
13819        let start = src.find("bold").unwrap();
13820        d.place_caret(start, false);
13821        d.place_caret(start + 4, true);
13822        assert_eq!(d.selection(), Some((start, start + 4)), "the whole word");
13823        d.toggle(InlineKind::Strong);
13824        assert_eq!(d.source, src.replace("**bold**", "bold"));
13825    }
13826
13827    #[test]
13828    fn right_steps_onto_the_end_of_a_mark_and_then_past_its_delimiter() {
13829        let mut d = wysiwyg_doc("right_mark_end", "a **bold** b");
13830        d.caret = 7; // before the `d`
13831        d.move_right(false);
13832        assert_eq!(d.caret, 8, "onto the end of the bold");
13833        assert!(d.active_inline_marks().contains(InlineKind::Strong));
13834        d.move_right(false);
13835        assert_eq!(d.caret, 10, "past the closing `**`");
13836        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
13837        d.move_left(false);
13838        assert_eq!(d.caret, 8);
13839        d.move_left(false);
13840        assert_eq!(d.caret, 7);
13841        // Typing at the inner home extends the bold.
13842        d.caret = 8;
13843        d.insert("!");
13844        assert_eq!(d.source, "a **bold!** b");
13845    }
13846
13847    #[test]
13848    fn a_marks_end_home_follows_an_edit_through_the_incremental_map() {
13849        // The splice path shifts the home with the block it is in, and the
13850        // re-rendered block finds its own again.
13851        let mut d = wysiwyg_doc("mark_end_splice", "x\n\na **bold** b\n\ny\n");
13852        d.build_visual_unwrapped();
13853        d.edit(0, 0, "zz");
13854        d.build_visual_unwrapped();
13855        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a shift");
13856        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13857        let at = d.source.find("bold").unwrap();
13858        d.edit(at, at, "very ");
13859        d.build_visual_unwrapped();
13860        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a re-render");
13861        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13862    }
13863
13864    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
13865        doc_in(View::Wysiwyg, name, body)
13866    }
13867
13868    /// How many list items the source actually parses into — the check that a
13869    /// marker Leaf wrote is a marker the format agrees is one.
13870    fn list_items(doc: &mut Doc) -> usize {
13871        doc.editor
13872            .nodes()
13873            .unwrap()
13874            .iter()
13875            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
13876            .count()
13877    }
13878
13879    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
13880    /// incremental (`build_spliced` / `build_cached`) path must always match.
13881    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
13882        reference_map_revealing(source, None)
13883    }
13884
13885    /// [`reference_map`] with a reveal line — the ground truth for the
13886    /// `MarkupMode::Full` builds, where the map is a function of the caret's
13887    /// line as well as the text.
13888    fn reference_map_revealing(source: &str, reveal: Option<Reveal>) -> crate::wysiwyg::VisualMap {
13889        // The same parse `Doc` uses. With twig's plain defaults instead, the two
13890        // sides disagree on what the *document* is before the renderer is even
13891        // reached — a bare `:word` is a text directive to one and prose to the
13892        // other — and the mismatch reads as a splice bug that isn't one.
13893        let mut ed =
13894            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
13895        let nodes = ed.nodes().unwrap();
13896        crate::wysiwyg::build(
13897            &nodes,
13898            source,
13899            None,
13900            false,
13901            &wysiwyg::Surface::default(),
13902            reveal,
13903        )
13904    }
13905
13906    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
13907        if a.rows.len() != b.rows.len() {
13908            return true;
13909        }
13910        for (ra, rb) in a.rows.iter().zip(&b.rows) {
13911            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
13912                return true;
13913            }
13914            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
13915                if ga.ch != gb.ch || ga.src != gb.src {
13916                    return true;
13917                }
13918            }
13919        }
13920        false
13921    }
13922
13923    #[test]
13924    fn incremental_build_matches_a_fresh_build_across_edits() {
13925        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
13926        // fast path, gated on twig's `dirty_range`) or falls back to
13927        // `build_cached`. After each edit the map must be byte-identical to a
13928        // from-scratch build — this is the correctness net under the splice.
13929        let docs = [
13930            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
13931            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
13932            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
13933            // A footnote definition is a root beside `doc`, merged back into the
13934            // top-level list by `wysiwyg::top_blocks`. The random edits below
13935            // make and unmake definitions as they go (a deleted `:` turns one
13936            // back into a paragraph, and vice versa), which is exactly the
13937            // structural churn the splice path has to notice and bail out of.
13938            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
13939            // A comment is a top-level block that draws no rows — a layout entry
13940            // at zero rows either side of blocks that do. The edits below type
13941            // into the blocks around it (a splice past a hidden block), and
13942            // break the comment open into prose and back (a structural change).
13943            "intro\n\n<!-- exec -->\n```\ncode\n```\n\nafter the comment\n\n<!-- trail -->\n",
13944            // Link reference definitions: a hidden block that an edit can turn
13945            // into a paragraph (a deleted `:`) and back, and whose own bytes an
13946            // edit can land in.
13947            "see [a] and [b]\n\n[a]: /a\n\nmid text\n\n[b]: /b\n",
13948            // Blank lines above the first block draw as rows, counted as its
13949            // separator; above it past frontmatter and past a comment too.
13950            "\n\nfirst pushed down\n\nsecond\n",
13951            "---\ntitle: x\n---\n\n\nafter frontmatter\n\nmore\n",
13952            "<!-- lead -->\n\n\nafter a comment\n\nmore\n",
13953            // No `<div>` here yet: an edit that takes the blank line under
13954            // `</div>` leaves a map no fresh build draws. See
13955            // docs/tasks/text-glued-under-a-closing-div.md.
13956        ];
13957        // A deterministic mix: mostly single characters (which stay inside one
13958        // block → splice), plus edits that reshape structure (a paragraph break,
13959        // a heading marker, a code fence → fallback), so both paths are exercised.
13960        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
13961        for src in docs {
13962            let mut d = wysiwyg_doc("diff", src);
13963            d.build_visual_unwrapped();
13964            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
13965
13966            for step in 0..60usize {
13967                let len = d.source.len();
13968                let raw = (step * 13 + 5) % (len + 1);
13969                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
13970                let pre = d.source.clone();
13971                let action;
13972                if step % 3 == 0 && pos < len {
13973                    let end = (pos + 1..=len)
13974                        .find(|&i| d.source.is_char_boundary(i))
13975                        .unwrap();
13976                    action = format!("delete [{pos},{end})");
13977                    d.edit(pos, end, "");
13978                } else {
13979                    let ins = inserts[step % inserts.len()];
13980                    action = format!("insert {ins:?} @ {pos}");
13981                    d.edit(pos, pos, ins);
13982                }
13983                d.build_visual_unwrapped();
13984                if maps_differ(&d.vmap, &reference_map(&d.source)) {
13985                    panic!(
13986                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
13987                        d.source
13988                    );
13989                }
13990            }
13991        }
13992    }
13993
13994    /// A frontend is handed [`Doc::vmap`] and may present it differently:
13995    /// leaf-ratatui splices blank filler rows under an oversized heading so the
13996    /// raster it paints there has somewhere to stand, and leaves them in the map
13997    /// because the caret and the mouse both read it between frames. The splice
13998    /// path addresses that map by *row index*, against the block layout the last
13999    /// build recorded — so handed a map with rows in it that no block owns, it
14000    /// laid the re-rendered block over one of the fillers and carried the rows
14001    /// the block really occupied into the suffix. One stranded copy of the
14002    /// edited line, and everything below it a row further down, per keystroke.
14003    ///
14004    /// A map that isn't the one the layout describes is a map this path can't
14005    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
14006    #[test]
14007    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
14008        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
14009        d.build_visual_unwrapped();
14010
14011        // Stand in for the heading filler rows: two blank rows past the heading
14012        // that no block accounts for. Cloning a real row keeps every field
14013        // plausible — it is the row *count* the splice can't survive.
14014        let filler = d.vmap.rows[0].clone();
14015        d.vmap.rows.insert(1, filler.clone());
14016        d.vmap.rows.insert(1, filler);
14017
14018        // An edit inside the last block: the single-block case the splice path
14019        // is for, and the one the frontend hits on every keystroke.
14020        let at = d.source.len() - 1;
14021        d.edit(at, at, "!");
14022        d.build_visual_unwrapped();
14023
14024        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
14025    }
14026
14027    /// A glyph's [`FaceId`] has to mean the same thing however its row was
14028    /// built. A row comes three ways — a fresh walk, a [`BlockCache`] hit
14029    /// cloned at a shifted offset, and a previous map's rows a splice kept
14030    /// untouched — and only the first of those walks a `data-font` at all. An
14031    /// index into a per-build table would have had the same glyph naming two
14032    /// families the moment a second one appeared; the id is the name's own
14033    /// hash, so nothing is remapped and the table is merged rather than rebuilt.
14034    ///
14035    /// Two families, because one cannot tell a wrong id from a right one.
14036    ///
14037    /// [`FaceId`]: crate::style::FaceId
14038    /// [`BlockCache`]: crate::wysiwyg::BlockCache
14039    #[test]
14040    fn a_spliced_rebuild_still_says_which_family_each_glyph_is_set_in() {
14041        use crate::style::{FaceId, FaceRef};
14042        let garamond = FaceId::of("Garamond");
14043        let futura = FaceId::of("Futura");
14044        let mut d = wysiwyg_doc(
14045            "two_faces",
14046            "x <span data-font=\"Garamond\">alpha</span>\n\ny <span data-font=\"Futura\">beta</span>\n",
14047        );
14048        d.build_visual_unwrapped();
14049
14050        // What the map has to keep saying, whichever path built it.
14051        let check = |d: &Doc, ctx: &str| {
14052            let face_of = |ch: char| {
14053                d.vmap
14054                    .rows
14055                    .iter()
14056                    .flat_map(|r| r.glyphs.iter())
14057                    .find(|g| g.ch == ch)
14058                    .map(|g| g.style.font)
14059            };
14060            assert_eq!(face_of('a'), Some(Some(FaceRef::Named(garamond))), "{ctx}");
14061            assert_eq!(face_of('b'), Some(Some(FaceRef::Named(futura))), "{ctx}");
14062            assert_eq!(d.vmap.face_name(garamond), Some("Garamond"), "{ctx}");
14063            assert_eq!(d.vmap.face_name(futura), Some("Futura"), "{ctx}");
14064            assert_eq!(d.vmap.face_name(FaceId::of("Bodoni")), None, "{ctx}");
14065        };
14066        check(&d, "fresh");
14067
14068        // An edit inside the second block: the single-block case the splice
14069        // path is for. The first block's rows are carried over untouched, so
14070        // its glyphs' ids are the previous build's and the table has to be too.
14071        let at = d.source.find("beta").unwrap();
14072        d.edit(at, at, "z");
14073        d.build_visual_unwrapped();
14074        check(&d, "after an edit in the second block");
14075        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced");
14076
14077        // And the other way round, so the block that was kept is the one that
14078        // is now re-rendered.
14079        let at = d.source.find("alpha").unwrap();
14080        d.edit(at, at, "z");
14081        d.build_visual_unwrapped();
14082        check(&d, "after an edit in the first block");
14083        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced again");
14084
14085        // A structural edit is one the splice bails out of, so the map is
14086        // reassembled by `build_cached` — where an untouched block is a *cache
14087        // hit* and its rows are cloned without a `data-font` being walked
14088        // again. The names the entry stored are what keeps the table honest
14089        // there.
14090        let at = d.source.find("\n\ny ").unwrap();
14091        d.edit(at, at, "\n\nmiddle");
14092        d.build_visual_unwrapped();
14093        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached");
14094        // Twice, because that first `build_cached` is what stores the entries:
14095        // this one is the build where the Garamond block is a *hit*, its rows
14096        // cloned with their ids and no attribute walked to explain them.
14097        let at = d.source.len() - 1;
14098        d.edit(at, at, "\n\ntail");
14099        d.build_visual_unwrapped();
14100        check(&d, "after a structural edit, through the block cache");
14101        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached again");
14102
14103        // A family the edit took the last glyph of leaves the glyphs with no
14104        // face and the table with a name nothing asks for — harmless, and the
14105        // price of not walking the rows the splice exists to avoid walking.
14106        let span = d.source.find("<span data-font=\"Futura\">").unwrap();
14107        let end = d.source.rfind("</span>").unwrap() + "</span>".len();
14108        d.edit(span, end, "beta");
14109        d.build_visual_unwrapped();
14110        assert!(!d.source.contains("Futura"), "{:?}", d.source);
14111        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "the face removed");
14112    }
14113
14114    #[test]
14115    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
14116        // The same correctness net as `incremental_build_matches_a_fresh_build_
14117        // across_edits`, under `MarkupMode::Full` — where the map depends on
14118        // the caret's *line* as well as the text, so the two caches have a new
14119        // way to be wrong. Both are exercised: the block cache can hand back
14120        // rows built for a line that is no longer the revealed one, and the
14121        // splice path can reuse a suffix that still has yesterday's line raw.
14122        //
14123        // Caret motion is interleaved with the edits deliberately, because a
14124        // caret that only ever moved with the edit would never cross a line
14125        // without also dirtying it — the case where a stale reveal survives.
14126        let docs = [
14127            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
14128            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
14129        ];
14130        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
14131        for src in docs {
14132            let mut d = wysiwyg_doc("reveal_diff", src);
14133            d.set_markup_mode(MarkupMode::Full);
14134
14135            for step in 0..60usize {
14136                let len = d.source.len();
14137                let raw = (step * 13 + 5) % (len + 1);
14138                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
14139                let pre = d.source.clone();
14140                let action;
14141                if step % 3 == 0 && pos < len {
14142                    let end = (pos + 1..=len)
14143                        .find(|&i| d.source.is_char_boundary(i))
14144                        .unwrap();
14145                    action = format!("delete [{pos},{end})");
14146                    d.edit(pos, end, "");
14147                } else {
14148                    let ins = inserts[step % inserts.len()];
14149                    action = format!("insert {ins:?} @ {pos}");
14150                    d.edit(pos, pos, ins);
14151                }
14152                // Walk the caret somewhere else in the document, independently
14153                // of where the edit landed.
14154                let want = (step * 29 + 11) % (d.source.len() + 1);
14155                d.caret = (want..=d.source.len())
14156                    .find(|&i| d.source.is_char_boundary(i))
14157                    .unwrap();
14158                d.build_visual_unwrapped();
14159
14160                let want = reference_map_revealing(&d.source, d.reveal_line());
14161                if maps_differ(&d.vmap, &want) {
14162                    panic!(
14163                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
14164                        d.caret, d.source
14165                    );
14166                }
14167            }
14168        }
14169    }
14170
14171    #[test]
14172    fn caret_motion_across_lines_rebuilds_only_under_full() {
14173        // The cache-key change has to earn its keep in both directions: `Full`
14174        // must rebuild when the caret changes line (or the reveal would never
14175        // move), and the hidden modes must *not* (or every arrow key would pay
14176        // for a feature they don't use). The existing `cache_motion` test pins
14177        // the second for the default mode; this pins the pair against a mode
14178        // change alone.
14179        let body = "*one* here\n\n*two* there\n";
14180
14181        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
14182        full.set_markup_mode(MarkupMode::Full);
14183        caret_at(&mut full, "one");
14184        let before = full.revision();
14185        caret_at(&mut full, "two");
14186        assert_eq!(full.revision(), before, "motion is not an edit");
14187        assert!(
14188            drawn_rows(&full).iter().any(|r| r == "*two* there"),
14189            "the map followed the caret: {:?}",
14190            drawn_rows(&full)
14191        );
14192
14193        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
14194        caret_at(&mut hidden, "one");
14195        let key = hidden.vmap_key.clone();
14196        caret_at(&mut hidden, "two");
14197        assert_eq!(
14198            hidden.vmap_key, key,
14199            "a hidden mode rebuilds nothing on motion"
14200        );
14201    }
14202
14203    #[test]
14204    fn wysiwyg_down_crosses_a_paragraph_boundary() {
14205        // Regression: the blank separator row used to share the previous
14206        // paragraph's end offset, so Down got pinned at the boundary (while Up
14207        // still crossed). Both directions must step through it symmetrically.
14208        //
14209        // It's now stepped *over* rather than onto: the blank line between two
14210        // paragraphs is the boundary being drawn, not a line of the document, so
14211        // one press of Down crosses it. The goal column survives the crossing —
14212        // col 3 at the end of "abc" is col 3 at the end of "def".
14213        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
14214        d.caret = 3; // end of "abc" (row 0)
14215        d.move_down(false);
14216        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
14217        assert_eq!(d.caret, 8); // end of "def", col 3 kept
14218        d.move_up(false);
14219        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
14220        assert_eq!(d.caret, 3);
14221    }
14222
14223    #[test]
14224    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
14225        // The second Up and the second Down here run off the ends of the
14226        // document, which is no longer a place a press is swallowed: they carry
14227        // the caret to the start and the end of the text. The claim in the
14228        // middle — that a Down retraces the Up that crossed the paragraph gap —
14229        // is the one this test is for, and it is asserted where it is made.
14230        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
14231        d.caret = 5; // start of "def"
14232        let start = d.caret_pos();
14233        d.move_up(false);
14234        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
14235        d.move_up(false);
14236        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
14237        d.move_down(false);
14238        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
14239        d.move_down(false);
14240        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
14241    }
14242
14243    #[test]
14244    fn wysiwyg_new_paragraph_shows_before_typing() {
14245        // Regression: two Enters at the end of a paragraph produced trailing
14246        // newlines with no AST node, so the caret appeared stuck on the old line
14247        // until a character was typed. It must ride down onto the new line now.
14248        let mut d = doc_with("wys_newpara", "abc\n");
14249        d.view = View::Wysiwyg;
14250        d.caret = 3;
14251        d.insert("\n");
14252        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
14253        assert_eq!(d.source, "abc\n\n\n");
14254        d.build_visual(80);
14255        let (row, _) = d.caret_pos();
14256        assert!(
14257            row >= 2,
14258            "caret should have moved down to the new line, got row {row}"
14259        );
14260        assert!(
14261            d.vmap.num_rows() >= 3,
14262            "the blank lines should render as rows"
14263        );
14264    }
14265
14266    #[test]
14267    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
14268        // The reported bug: Enter at the end of a paragraph that has another
14269        // paragraph below put the caret at the *start of the next paragraph* —
14270        // the empty paragraph it opened had no row, so the caret snapped onto
14271        // "World". It must now sit on its own empty line, with a blank spacer
14272        // above it (the paragraph gap).
14273        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
14274        d.caret = 5; // end of "Hello"
14275        d.newline();
14276        d.build_visual(80);
14277        let (row, col) = d.caret_pos();
14278        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
14279        assert_eq!(
14280            d.vmap.row_width(row),
14281            0,
14282            "caret's row must be empty, not 'World'"
14283        );
14284        assert!(
14285            row >= 2,
14286            "a blank spacer row should sit above the caret, got row {row}"
14287        );
14288        // The row above the caret is a real (empty) gap, and "Hello" stays put.
14289        assert_eq!(
14290            d.vmap.row_width(row - 1),
14291            0,
14292            "the row above the caret is a gap"
14293        );
14294        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
14295        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
14296    }
14297
14298    #[test]
14299    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
14300        // At the document end a single Enter must also show the paragraph gap —
14301        // a blank spacer row above the caret — so the layout already matches how
14302        // it will look once the new paragraph has text.
14303        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
14304        d.caret = 5; // end of "Hello", no trailing newline
14305        d.newline(); // source becomes "Hello\n\n"
14306        d.build_visual(80);
14307        let (row, col) = d.caret_pos();
14308        assert_eq!(col, 0);
14309        assert!(
14310            row >= 2,
14311            "caret should sit below a blank spacer, got row {row}"
14312        );
14313        assert_eq!(
14314            d.vmap.row_width(row - 1),
14315            0,
14316            "the row above the caret is a gap"
14317        );
14318    }
14319
14320    #[test]
14321    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
14322        // The spacer is view-only: typing the new paragraph must not reflow the
14323        // caret onto a different row — the transient view already matched the
14324        // settled one.
14325        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
14326        d.caret = 5;
14327        d.newline();
14328        d.build_visual(80);
14329        let before = d.caret_pos();
14330        d.insert("New");
14331        d.build_visual(80);
14332        let after = d.caret_pos();
14333        assert_eq!(
14334            after.0, before.0,
14335            "typing must not move the caret to another row ({before:?} -> {after:?})"
14336        );
14337    }
14338
14339    #[test]
14340    fn wysiwyg_return_on_the_last_code_line_keeps_the_caret_in_the_block() {
14341        // Return at the end of the block's last line writes an empty line the
14342        // map used to drop, so the caret landed on `after` and the next
14343        // keystroke went into the paragraph below instead of into the code.
14344        let mut d = wysiwyg_doc("code_return", "prose\n\n```\nalpha\nbeta\n```\n\nafter\n");
14345        d.caret = d.source.find("beta").unwrap() + "beta".len();
14346        d.build_visual(80);
14347        let before = d.caret_pos().0;
14348
14349        d.newline();
14350        d.build_visual(80);
14351        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n");
14352
14353        let (row, col) = d.caret_pos();
14354        assert_eq!(row, before + 1, "the caret moves down one row");
14355        assert_eq!(col, 0, "onto the head of the empty line");
14356        let span = d.vmap.code_blocks[0].rows_span.clone();
14357        assert!(
14358            span.contains(&row),
14359            "caret row {row} is outside the block's rows {span:?}"
14360        );
14361
14362        // The whole point: what is typed next is code.
14363        d.insert("gamma");
14364        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\ngamma\n```\n\nafter\n");
14365    }
14366
14367    #[test]
14368    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
14369        let fm = "---\ntitle: hi\n---\n";
14370        let body = format!("{fm}# leaf\n\nbody\n");
14371        let mut d = wysiwyg_doc("wys_fm", &body);
14372        // Opening lifts the caret out of the now-hidden frontmatter.
14373        assert_eq!(
14374            d.caret,
14375            fm.len(),
14376            "caret should start at the first real block"
14377        );
14378        // Left at the content start can't step back into frontmatter.
14379        d.move_left(false);
14380        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
14381        // Doc-start lands on the content floor, not offset 0.
14382        d.move_doc_start(false);
14383        assert_eq!(d.caret, fm.len());
14384        // Select-all + copy never include the frontmatter bytes.
14385        d.select_all();
14386        let sel = d.selected_text().unwrap().to_string();
14387        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
14388        assert!(
14389            sel.starts_with("# leaf"),
14390            "selection should begin at content: {sel:?}"
14391        );
14392    }
14393
14394    #[test]
14395    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
14396        // A fresh note is frontmatter and nothing else. With no rendered block
14397        // to floor the caret it opened at offset 0 — before the opening `---` —
14398        // so the first keystroke wrote itself in front of the metadata and the
14399        // file came out as `This---\ntitle: …`.
14400        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
14401        let mut d = wysiwyg_doc("wys_fm_only", fm);
14402        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
14403        // Nothing is rendered, so the caret draws at the origin of an empty view
14404        // — the same place an empty document puts it.
14405        assert_eq!(d.caret_pos(), (0, 0));
14406        d.insert("This");
14407        assert_eq!(d.source, format!("{fm}This"));
14408    }
14409
14410    /// `select_range` is the verb for a range a host already knows the bytes of,
14411    /// so it must not snap — and must still hold every invariant `place_caret`
14412    /// holds, the frontmatter floor above all.
14413    #[test]
14414    fn select_range_takes_the_range_as_given_but_still_floors_it() {
14415        let fm = "---\ntitle: foo\n---\n\n";
14416        let body = format!("{fm}body foo here\n");
14417        let mut d = wysiwyg_doc("wys_select_range", &body);
14418
14419        // The `foo` in the body: taken exactly, not snapped to a caret stop.
14420        let at = body.rfind("foo").unwrap();
14421        d.select_range(at, at + 3);
14422        assert_eq!(d.selection(), Some((at, at + 3)));
14423        assert_eq!(d.selected_text(), Some("foo"));
14424
14425        // The `foo` in the hidden frontmatter: below the floor, so both ends
14426        // come up to it rather than parking the caret in the metadata, where a
14427        // later keystroke would rewrite `title:`.
14428        let hidden = body.find("foo").unwrap();
14429        assert!(hidden < d.vmap.content_start);
14430        d.select_range(hidden, hidden + 3);
14431        assert!(
14432            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
14433            "a range under the floor must not leave the caret in the frontmatter"
14434        );
14435
14436        // Past the end, and mid-character, are both brought back to something
14437        // sliceable rather than panicking the next reader of the range.
14438        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
14439        let mut d = multi;
14440        d.select_range(2, 9_999);
14441        assert_eq!(d.caret, d.source.len());
14442        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
14443        assert!(d.source.is_char_boundary(d.caret));
14444    }
14445
14446    /// The bug `select_range` exists for: a match butting up against a hidden
14447    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
14448    /// the one before the `**`.
14449    #[test]
14450    fn select_range_does_not_snap_off_a_hidden_delimiter() {
14451        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
14452        let at = d.source.find("needle").unwrap();
14453        d.select_range(at, at + 6);
14454        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
14455    }
14456
14457    #[test]
14458    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
14459        // Backspace deletes `prev_boundary..caret` directly; at the first real
14460        // block that boundary is inside the hidden frontmatter, so it must be a
14461        // no-op rather than eating the closing `---`.
14462        let fm = "---\ntitle: hi\n---\n";
14463        let body = format!("{fm}leaf\n");
14464        let mut d = wysiwyg_doc("wys_fm_bs", &body);
14465        assert_eq!(d.caret, fm.len());
14466        d.backspace();
14467        assert_eq!(d.source, body, "backspace must not touch frontmatter");
14468        d.delete_word_back();
14469        assert_eq!(
14470            d.source, body,
14471            "word-delete must not touch frontmatter either"
14472        );
14473    }
14474
14475    #[test]
14476    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
14477        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
14478        // fenced div, really, since core parses these on for every document
14479        // now (`parse_extensions`). The container is a `directive` node, an
14480        // `is_block_container` kind like `block_quote`, so the caret works
14481        // inside its child paragraph exactly as it would inside a quote: typing
14482        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
14483        // untouched.
14484        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
14485        let mut d = wysiwyg_doc("wys_vis", body);
14486        d.caret = body.find("hello").unwrap() + "hello".len();
14487        d.insert("!");
14488        assert_eq!(
14489            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
14490            "typing inside the block edits its content in place"
14491        );
14492        assert!(
14493            d.source.contains(":::vis{.public .family}"),
14494            "opening fence survives"
14495        );
14496        assert!(d.source.contains(":::\nafter"), "closing fence survives");
14497    }
14498
14499    #[test]
14500    fn source_view_still_reaches_frontmatter() {
14501        // The metadata is only *hidden*, never lost: the source view edits and
14502        // selects it in full, and it's always preserved on save.
14503        let fm = "---\ntitle: hi\n---\n";
14504        let body = format!("{fm}# leaf\n");
14505        let mut d = doc_with("src_fm", &body);
14506        d.select_all();
14507        let sel = d.selected_text().unwrap();
14508        assert!(
14509            sel.contains("title"),
14510            "source view should select everything"
14511        );
14512        d.move_doc_start(false);
14513        assert_eq!(d.caret, 0, "source view can reach offset 0");
14514    }
14515
14516    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
14517
14518    #[test]
14519    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
14520        // The border and padding between two cells all share one source offset,
14521        // so a column-stepping caret would sit on `│` and then stall there
14522        // forever. Right must step: end of "Name" -> start of "Qty".
14523        let mut d = wysiwyg_doc("tbl_right", TABLE);
14524        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
14525        d.move_right(false);
14526        assert_eq!(
14527            d.caret,
14528            TABLE.find("Qty").unwrap(),
14529            "should land in the next cell"
14530        );
14531        let (r, c) = d.caret_pos();
14532        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
14533    }
14534
14535    #[test]
14536    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
14537        let mut d = wysiwyg_doc("tbl_left", TABLE);
14538        d.caret = TABLE.find("Qty").unwrap();
14539        d.move_left(false);
14540        assert_eq!(
14541            d.caret,
14542            TABLE.find("Name").unwrap() + 4,
14543            "end of the previous cell"
14544        );
14545    }
14546
14547    #[test]
14548    fn wysiwyg_down_steps_over_a_table_rule() {
14549        // Between the header and the first body row sits a `├───┼───┤` rule.
14550        // It's drawn but holds no caret, so one Down must reach "Pear".
14551        let mut d = wysiwyg_doc("tbl_down", TABLE);
14552        d.caret = TABLE.find("Name").unwrap();
14553        d.move_down(false);
14554        assert_eq!(
14555            d.caret,
14556            TABLE.find("Pear").unwrap(),
14557            "one Down reaches the body row"
14558        );
14559        d.move_down(false);
14560        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
14561    }
14562
14563    #[test]
14564    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
14565        let mut d = wysiwyg_doc("tbl_tab", TABLE);
14566        d.caret = TABLE.find("Name").unwrap();
14567        // A hop lands with the destination cell's whole content selected, the
14568        // caret at its end — so typing replaces the cell like a form field.
14569        assert!(d.cell_hop(true));
14570        assert_eq!(
14571            d.selected_text(),
14572            Some("Qty"),
14573            "the target cell comes up selected"
14574        );
14575        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
14576        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
14577        assert_eq!(d.selected_text(), Some("Pear"));
14578        assert!(d.cell_hop(false));
14579        assert_eq!(d.selected_text(), Some("Qty"));
14580    }
14581
14582    #[test]
14583    fn tab_outside_a_table_is_not_a_cell_hop() {
14584        // `cell_hop` reports false so the frontend can indent as usual.
14585        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
14586        d.caret = 4;
14587        assert!(!d.cell_hop(true));
14588        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
14589    }
14590
14591    #[test]
14592    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
14593        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14594        d.caret = TABLE.rfind("12").unwrap(); // the final cell
14595        assert!(!d.cell_hop(true), "no cell after the last one");
14596        d.caret = TABLE.find("Name").unwrap();
14597        assert!(!d.cell_hop(false), "no cell before the first one");
14598    }
14599
14600    #[test]
14601    fn wysiwyg_vertical_cell_motion_holds_the_column() {
14602        // Down/Up step to the cell above/below in the *same column*, not back to
14603        // the top-left the way a naive row/col motion over the picture would.
14604        let mut d = wysiwyg_doc("tbl_vert", TABLE);
14605        d.caret = TABLE.find("Qty").unwrap();
14606        // Each vertical hop selects the destination cell, holding the column.
14607        assert!(d.cell_move_vertical(true));
14608        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
14609        assert!(d.cell_move_vertical(true));
14610        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
14611        assert!(!d.cell_move_vertical(true), "no row below the last");
14612        assert!(d.cell_move_vertical(false));
14613        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
14614        assert!(d.cell_move_vertical(false));
14615        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
14616        assert!(!d.cell_move_vertical(false), "no row above the header");
14617    }
14618
14619    #[test]
14620    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
14621        let mut d = wysiwyg_doc("tbl_grow", TABLE);
14622        d.caret = TABLE.rfind("12").unwrap();
14623        let rows_before = d.source.matches('\n').count();
14624        assert!(d.cell_tab(true), "acts as a table key");
14625        assert_eq!(
14626            d.source.matches('\n').count(),
14627            rows_before + 1,
14628            "a fresh row was appended"
14629        );
14630        assert!(d.caret_in_table(), "the caret entered the new row");
14631        // The caret sits in the new row's first cell — past the old last cell.
14632        assert!(d.caret > TABLE.rfind("12").unwrap());
14633    }
14634
14635    #[test]
14636    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
14637        let mut d = wysiwyg_doc("tbl_ret", TABLE);
14638        d.caret = TABLE.find("Name").unwrap();
14639        assert!(d.cell_return(), "acts as a table key");
14640        assert_eq!(
14641            d.selected_text(),
14642            Some("Pear"),
14643            "Return drops one cell, selecting it"
14644        );
14645        // From the last row, Return appends a row and enters it.
14646        d.caret = TABLE.rfind("Fig").unwrap();
14647        let rows_before = d.source.matches('\n').count();
14648        assert!(d.cell_return());
14649        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
14650        assert!(d.caret_in_table());
14651    }
14652
14653    #[test]
14654    fn return_and_tab_outside_a_table_decline() {
14655        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
14656        d.caret = 4;
14657        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
14658        assert!(!d.cell_tab(true), "no table: the frontend indents");
14659        assert!(
14660            !d.cell_line_break(),
14661            "no table: the frontend breaks the line"
14662        );
14663    }
14664
14665    #[test]
14666    fn a_click_under_a_trailing_table_lands_past_it_and_enter_opens_a_line() {
14667        // A document that ends in a table used to end *inside* it: nothing
14668        // past the last cell was a caret stop, so a click in the blank space
14669        // under the grid snapped back into the table and there was no way to
14670        // write a line after it. The bottom border's end is that stop now.
14671        let mut d = wysiwyg_doc("tbl_trail", TABLE);
14672        let rows = d.vmap.num_rows();
14673        d.click(rows + 3, 0, false);
14674        let end = TABLE.trim_end_matches('\n').len();
14675        assert_eq!(d.caret, end, "the caret stands just past the table");
14676        assert!(!d.caret_in_table(), "past the table is outside it");
14677        assert!(!d.cell_return(), "Return there is the frontend's newline");
14678        d.newline();
14679        d.insert("after");
14680        assert_eq!(
14681            d.source,
14682            format!("{TABLE}\nafter\n"),
14683            "Enter opens a paragraph under the table"
14684        );
14685    }
14686
14687    #[test]
14688    fn typing_at_a_table_s_trailing_stop_opens_a_paragraph_first() {
14689        // The stop sits at the end of the table's last source line, and a
14690        // line glued under a table is a row of it — `| Fig | 12 |x` would be a
14691        // three-cell row. So the text gets a paragraph of its own, as it does
14692        // beside a block picture.
14693        let mut d = wysiwyg_doc("tbl_type", TABLE);
14694        d.caret = TABLE.trim_end_matches('\n').len();
14695        d.insert("x");
14696        assert_eq!(d.source, format!("{TABLE}\nx\n"));
14697        assert_eq!(d.caret, TABLE.len() + 2, "the caret follows the text");
14698        // And a paste, which joins the block exactly as typing would.
14699        let mut d = wysiwyg_doc("tbl_paste", TABLE);
14700        d.caret = TABLE.trim_end_matches('\n').len();
14701        d.paste("pasted");
14702        assert_eq!(d.source, format!("{TABLE}\npasted\n"));
14703    }
14704
14705    #[test]
14706    fn right_leaves_a_table_by_its_trailing_stop_and_backspace_steps_back_in() {
14707        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14708        let last_cell_end = TABLE.rfind("12").unwrap() + 2;
14709        let end = TABLE.trim_end_matches('\n').len();
14710        d.caret = last_cell_end;
14711        d.move_right(false);
14712        assert_eq!(d.caret, end, "Right from the last cell leaves the table");
14713        // Backspace there takes no byte: the one behind the caret is the row's
14714        // closing `|`, which the rich view never drew. It steps back instead.
14715        d.backspace();
14716        assert_eq!(d.source, TABLE, "nothing deleted");
14717        assert_eq!(d.caret, last_cell_end, "back into the last cell");
14718        // Down from the last row lands on the same stop, and Up returns.
14719        d.move_down(false);
14720        assert_eq!(d.caret, end, "Down from the last row leaves the table");
14721        d.move_up(false);
14722        assert_eq!(d.caret, last_cell_end);
14723    }
14724
14725    #[test]
14726    fn a_table_s_trailing_stop_sits_between_it_and_the_text_below() {
14727        // With prose under the table, the stop is one hop between the last
14728        // cell and the paragraph — the shape a block picture's second stop has.
14729        let src = format!("{TABLE}\nafter\n");
14730        let mut d = wysiwyg_doc("tbl_mid", &src);
14731        d.caret = TABLE.rfind("12").unwrap() + 2;
14732        d.move_right(false);
14733        assert_eq!(d.caret, TABLE.trim_end_matches('\n').len());
14734        d.move_right(false);
14735        assert_eq!(d.caret, src.find("after").unwrap());
14736        // Typing at the stop still opens a paragraph, and the text below keeps
14737        // its own.
14738        d.move_left(false);
14739        d.insert("x");
14740        assert_eq!(d.source, format!("{TABLE}\nx\n\nafter\n"));
14741    }
14742
14743    #[test]
14744    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
14745        let mut d = wysiwyg_doc("tbl_break", TABLE);
14746        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
14747        assert!(d.cell_line_break(), "acts as a table key");
14748        assert!(
14749            d.source.contains("Pear<br>"),
14750            "spelled as an inline <br>: {}",
14751            d.source
14752        );
14753        assert!(d.caret_in_table(), "still in the cell, past the break");
14754        // The break renders as a real line: the "Pear" cell now draws two lines,
14755        // so the table's picture is one row taller than a single-line table.
14756        d.build_visual(80);
14757        let table = &d.vmap.tables[0];
14758        let cell = &table.grid[1].cells[0]; // first body row, first column
14759        assert!(
14760            cell.glyphs.iter().any(|g| g.ch == '\n'),
14761            "the cell carries the break as a newline glyph for the frontend to split"
14762        );
14763    }
14764
14765    #[test]
14766    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
14767        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
14768        // back as structure — the whole point of routing through insert_line_break
14769        // instead of splicing raw `<br>` bytes.
14770        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
14771        d.caret = TABLE.find("Pear").unwrap() + 4;
14772        assert!(d.cell_line_break());
14773        let kinds: Vec<Kind> = d
14774            .editor
14775            .nodes()
14776            .unwrap()
14777            .iter()
14778            .map(|n| n.kind.clone())
14779            .collect();
14780        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
14781        assert!(
14782            !kinds.contains(&Kind::RawInline),
14783            "still raw HTML: {kinds:?}"
14784        );
14785    }
14786
14787    #[test]
14788    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
14789        // The `<br>` draws as one newline glyph, so Backspace over it must take
14790        // all four bytes — a one-byte delete would strand a visible `<br` in the
14791        // cell (the reported bug).
14792        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
14793        d.caret = TABLE.find("Pear").unwrap() + 4;
14794        assert!(d.cell_line_break());
14795        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
14796        d.backspace(); // caret sits just past the break
14797        assert!(
14798            !d.source.contains("<br"),
14799            "no half-deleted <br left: {}",
14800            d.source
14801        );
14802        assert!(
14803            d.source.contains("| Pear |"),
14804            "the cell is back to one line: {}",
14805            d.source
14806        );
14807    }
14808
14809    #[test]
14810    fn backspace_at_a_cell_start_is_a_wall() {
14811        // The task's repro: two presses used to take the padding and then the
14812        // `|`, merging `d` into `c`'s cell and leaving the row a column short.
14813        let src = "| a | b |\n| - | - |\n| c | d |\n";
14814        let mut d = wysiwyg_doc("tbl_wall_bs", src);
14815        d.place_caret(src.find("d |").unwrap(), false);
14816        for _ in 0..3 {
14817            d.backspace();
14818        }
14819        assert_eq!(d.source, src);
14820        // Inside the padding too — right after the `|`, before the space. Set
14821        // directly: `place_caret` would snap it onto the stop past the space.
14822        d.caret = src.find("| d").unwrap() + 1;
14823        d.backspace();
14824        assert_eq!(d.source, src);
14825        // The row's first cell, and an empty one, are walls the same.
14826        d.place_caret(src.find("c |").unwrap(), false);
14827        d.backspace();
14828        assert_eq!(d.source, src);
14829        // A cell that opens on hidden markup: the wall is the first letter
14830        // drawn, not the `**` in front of it.
14831        let bold = "| a | b |\n| - | - |\n| c | **d** |\n";
14832        let mut d = wysiwyg_doc("tbl_wall_bs_bold", bold);
14833        d.place_caret(bold.find("d**").unwrap(), false);
14834        d.backspace();
14835        assert_eq!(d.source, bold);
14836        let empty = "| a | b |\n| - | - |\n| c |   |\n";
14837        let mut d = wysiwyg_doc("tbl_wall_bs_empty", empty);
14838        d.place_caret(empty.find("|   |").unwrap() + 2, false);
14839        d.backspace();
14840        assert_eq!(d.source, empty);
14841    }
14842
14843    #[test]
14844    fn backspace_inside_a_cell_still_deletes_a_character() {
14845        let src = "| a | b |\n| - | - |\n| c | de |\n";
14846        let mut d = wysiwyg_doc("tbl_wall_bs_mid", src);
14847        d.place_caret(src.find("e |").unwrap(), false);
14848        d.backspace();
14849        assert_eq!(d.source, "| a | b |\n| - | - |\n| c | e |\n");
14850    }
14851
14852    #[test]
14853    fn delete_at_a_cell_end_is_a_wall() {
14854        // The mirror: Delete at `c`'s end would take the padding, then the `|`.
14855        let src = "| a | b |\n| - | - |\n| c | d |\n";
14856        let mut d = wysiwyg_doc("tbl_wall_del", src);
14857        d.place_caret(src.find("c |").unwrap() + 1, false);
14858        for _ in 0..3 {
14859            d.delete_forward();
14860        }
14861        assert_eq!(d.source, src);
14862        // And inside the trailing padding, set directly past the snap.
14863        d.caret = src.find("c |").unwrap() + 2;
14864        d.delete_forward();
14865        assert_eq!(d.source, src);
14866        // The row's last cell is a wall on its closing `|` as well.
14867        d.place_caret(src.find("d |").unwrap() + 1, false);
14868        d.delete_forward();
14869        assert_eq!(d.source, src);
14870        // Mid-cell Delete is untouched.
14871        d.place_caret(src.find("c |").unwrap(), false);
14872        d.delete_forward();
14873        assert_eq!(d.source, "| a | b |\n| - | - |\n|  | d |\n");
14874    }
14875
14876    #[test]
14877    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
14878        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
14879        d.caret = TABLE.find("Pear").unwrap() + 4;
14880        assert!(d.cell_line_break());
14881        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
14882        d.delete_forward();
14883        assert!(
14884            !d.source.contains("<br"),
14885            "no half-deleted <br: {}",
14886            d.source
14887        );
14888        assert!(
14889            d.source.contains("| Pear |"),
14890            "cell back to one line: {}",
14891            d.source
14892        );
14893    }
14894
14895    #[test]
14896    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
14897        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
14898        // still consumed (a real newline would split the one-line row), but the
14899        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
14900        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
14901        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
14902        d.caret = src.find("Pear").unwrap() + 4;
14903        assert!(d.caret_in_table(), "caret should be inside the djot table");
14904        assert!(
14905            d.cell_line_break(),
14906            "the key is consumed, not passed to the frontend"
14907        );
14908        assert_eq!(d.source, src, "the djot cell is left untouched");
14909        assert!(
14910            !d.source.contains("<br>"),
14911            "no non-idiomatic <br> spliced into djot"
14912        );
14913        assert!(
14914            d.status.is_some(),
14915            "the refusal is surfaced on the status line"
14916        );
14917    }
14918
14919    #[test]
14920    fn typing_in_a_cell_edits_that_cell() {
14921        // Editing comes free once offsets map correctly: the caret is a source
14922        // offset, so a normal splice lands inside the pipe table.
14923        let mut d = wysiwyg_doc("tbl_type", TABLE);
14924        d.caret = TABLE.find("Pear").unwrap() + 4;
14925        d.insert("s");
14926        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
14927    }
14928
14929    #[test]
14930    fn motion_and_delete_treat_an_emoji_as_one_character() {
14931        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
14932        // bytes, several codepoints. Right-arrow must clear it in one step, and
14933        // backspace must remove the whole cluster, not a stray joiner.
14934        let family = "👨‍👩‍👧";
14935        let mut d = doc_with("emoji", &format!("a{family}b\n"));
14936        d.caret = 1; // just after 'a', before the emoji
14937        d.move_right(false);
14938        assert_eq!(
14939            d.caret,
14940            1 + family.len(),
14941            "one step clears the whole cluster"
14942        );
14943        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
14944
14945        d.backspace(); // delete the emoji as a unit
14946        assert_eq!(d.source, "ab\n");
14947        assert_eq!(d.caret, 1);
14948    }
14949
14950    #[test]
14951    fn motion_handles_a_combining_accent_as_one_character() {
14952        // "e" + U+0301 (combining acute) renders as one é.
14953        let mut d = doc_with("combining", "e\u{0301}x\n");
14954        d.caret = 0;
14955        d.move_right(false);
14956        assert_eq!(
14957            d.caret,
14958            "e\u{0301}".len(),
14959            "steps past base + combining mark"
14960        );
14961    }
14962
14963    #[test]
14964    fn undo_then_redo_round_trips_an_edit() {
14965        let mut d = doc_with("undo", "hello\n");
14966        d.caret = 5;
14967        d.insert("!");
14968        assert_eq!(d.source, "hello!\n");
14969        d.undo();
14970        assert_eq!(d.source, "hello\n");
14971        assert_eq!(d.caret, 5, "undo restores the caret");
14972        d.redo();
14973        assert_eq!(d.source, "hello!\n");
14974    }
14975
14976    #[test]
14977    fn a_run_of_typing_undoes_as_one_step() {
14978        let mut d = doc_with("coalesce", "\n");
14979        d.caret = 0;
14980        d.insert("a");
14981        d.insert("b");
14982        d.insert("c");
14983        assert_eq!(d.source, "abc\n");
14984        d.undo(); // the whole typed run, not just "c"
14985        assert_eq!(d.source, "\n");
14986        d.undo(); // nothing left — the run was one step
14987        assert_eq!(d.source, "\n");
14988        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
14989    }
14990
14991    // ── IME composition ──────────────────────────────────────────────────────
14992
14993    #[test]
14994    fn a_composition_run_undoes_as_one_step() {
14995        let mut d = doc_with("compose", "\n");
14996        d.caret = 0;
14997        // What an IME does: each step replaces the last one's provisional bytes.
14998        d.edit_composing(0, 0, "k");
14999        d.edit_composing(0, 1, "か");
15000        d.edit_composing(0, 3, "かん");
15001        d.edit_composing(0, 6, "感"); // the commit
15002        d.end_composition();
15003        assert_eq!(d.source, "感\n");
15004        d.undo(); // the whole composition, not its last keystroke
15005        assert_eq!(d.source, "\n");
15006        assert_eq!(d.status.as_deref(), None, "the run was a single step");
15007    }
15008
15009    /// A Replace All the way a host does one: every match, last to first so
15010    /// the offsets still to go stay put, each a selection replaced by an
15011    /// insert, inside one undo group. `select_range` rather than the host's
15012    /// snapping `place_caret`, which would snap against a map these tests do
15013    /// not rebuild between edits.
15014    fn replace_all_in(d: &mut Doc, needle: &str, with: &str) {
15015        let hits: Vec<usize> = d.source.match_indices(needle).map(|(i, _)| i).collect();
15016        d.begin_undo_group();
15017        for at in hits.into_iter().rev() {
15018            d.select_range(at, at + needle.len());
15019            d.insert(with);
15020        }
15021        d.end_undo_group();
15022    }
15023
15024    #[test]
15025    fn a_replace_all_undoes_and_redoes_as_one_step() {
15026        let mut d = wysiwyg_doc("group", "a cat, a **cat**, a cat\n");
15027        d.caret = 0;
15028        d.insert("x");
15029        replace_all_in(&mut d, "cat", "dog");
15030        assert_eq!(d.source, "xa dog, a **dog**, a dog\n");
15031        assert!(d.undo(), "one undo");
15032        assert_eq!(
15033            d.source, "xa cat, a **cat**, a cat\n",
15034            "puts back every match"
15035        );
15036        assert!(d.redo(), "one redo");
15037        assert_eq!(
15038            d.source, "xa dog, a **dog**, a dog\n",
15039            "replaces them all again"
15040        );
15041        assert!(d.undo());
15042        assert!(d.undo(), "the typing before is its own step");
15043        assert_eq!(d.source, "a cat, a **cat**, a cat\n");
15044        assert!(!d.can_undo());
15045    }
15046
15047    #[test]
15048    fn typing_after_a_group_is_a_step_of_its_own() {
15049        // A one-character replacement is an insert like a keystroke, and a
15050        // keystroke after it would coalesce with it outside a group.
15051        let mut d = wysiwyg_doc("group", "a b a\n");
15052        replace_all_in(&mut d, "a", "c");
15053        d.caret = d.source.len() - 1;
15054        d.insert("d");
15055        assert_eq!(d.source, "c b cd\n");
15056        assert!(d.undo());
15057        assert_eq!(d.source, "c b c\n", "the typing alone");
15058        assert!(d.undo());
15059        assert_eq!(d.source, "a b a\n", "then the replacement, whole");
15060    }
15061
15062    #[test]
15063    fn a_group_of_more_edits_than_the_history_holds_is_still_one_step() {
15064        // twig keeps 200 steps; a group folds as it goes, so it never holds
15065        // more than one of them.
15066        let src = format!("start\n{}\n", "x ".repeat(300));
15067        let mut d = wysiwyg_doc("group", &src);
15068        d.caret = 5;
15069        d.insert("!");
15070        replace_all_in(&mut d, "x", "yy");
15071        assert_eq!(d.undo_steps, 2);
15072        assert!(d.undo());
15073        assert_eq!(d.source, src.replacen("start", "start!", 1));
15074        assert!(d.undo());
15075        assert_eq!(d.source, src);
15076        assert!(!d.can_undo());
15077    }
15078
15079    #[test]
15080    fn an_undo_closes_an_open_group() {
15081        let mut d = wysiwyg_doc("group", "one\n");
15082        d.caret = 3;
15083        d.begin_undo_group();
15084        d.begin_undo_group();
15085        d.insert("x");
15086        assert!(d.in_undo_group());
15087        assert!(d.undo());
15088        assert!(
15089            !d.in_undo_group(),
15090            "the history moved, so the group is over"
15091        );
15092        d.end_undo_group();
15093        d.end_undo_group();
15094        assert_eq!(d.source, "one\n");
15095        assert!(d.redo());
15096        assert_eq!(d.source, "onex\n");
15097    }
15098
15099    #[test]
15100    fn replacing_the_source_keeps_the_caret_on_its_characters() {
15101        let mut d = wysiwyg_doc("replace", "One.\n\nTwo.\n\nThree.\n");
15102        let on = d.source.find("Three").unwrap() + 2;
15103        d.caret = on;
15104        // Another device's edit, before the caret: the caret moves along.
15105        assert!(d.replace_source("One, and more.\n\nTwo.\n\nThree.\n"));
15106        assert_eq!(d.source, "One, and more.\n\nTwo.\n\nThree.\n");
15107        assert_eq!(&d.source[d.caret..], "ree.\n", "still inside Three");
15108        // After the caret: it stays.
15109        let at = d.caret;
15110        assert!(d.replace_source("One, and more.\n\nTwo.\n\nThree.\n\nFour.\n"));
15111        assert_eq!(d.caret, at);
15112        assert!(d.selection().is_none());
15113        // One undo step, the caret where it stood.
15114        assert!(d.undo());
15115        assert_eq!(d.source, "One, and more.\n\nTwo.\n\nThree.\n");
15116        assert_eq!(d.caret, at);
15117    }
15118
15119    #[test]
15120    fn replacing_the_source_writes_markup_as_markup() {
15121        let mut d = wysiwyg_doc("replace-markup", "plain\n");
15122        assert!(d.replace_source("**bold** and *it*\n"));
15123        assert_eq!(
15124            d.source, "**bold** and *it*\n",
15125            "source, not typing: nothing escaped"
15126        );
15127        assert!(d.replace_source("**bold** and *it*\n"), "already there");
15128    }
15129
15130    #[test]
15131    fn the_differing_span_ends_on_characters() {
15132        assert_eq!(differing_span("abc", "abc"), (3, 3, ""));
15133        assert_eq!(differing_span("abXc", "abYc"), (2, 3, "Y"));
15134        assert_eq!(differing_span("aaa", "aaaa"), (3, 3, "a"));
15135        assert_eq!(differing_span("aaaa", "aa"), (2, 4, ""));
15136        // é and è share their first byte; the span must not split it.
15137        assert_eq!(differing_span("café", "cafè"), (3, 5, "è"));
15138        assert_eq!(differing_span("", "x"), (0, 0, "x"));
15139    }
15140
15141    #[test]
15142    fn a_substitution_behind_the_caret_leaves_the_caret_and_is_its_own_step() {
15143        let mut d = wysiwyg_doc("substitute", "\n");
15144        d.caret = 0;
15145        for c in ["I", " ", "s", "a", "w", " ", "t", "e", "h", " "] {
15146            d.insert(c);
15147        }
15148        assert_eq!(d.source, "I saw teh \n");
15149        let at = d.source.find("teh").unwrap();
15150        assert!(d.substitute(at, at + 3, "the"));
15151        assert_eq!(d.source, "I saw the \n");
15152        assert_eq!(d.caret, 10, "still after the space");
15153        assert!(d.selection().is_none());
15154        d.insert("c");
15155        assert_eq!(d.source, "I saw the c\n");
15156        assert!(d.undo(), "the typing after it is a step of its own");
15157        assert_eq!(d.source, "I saw the \n");
15158        assert!(d.undo(), "the correction is one step");
15159        assert_eq!(d.source, "I saw teh \n", "what was typed");
15160        assert_eq!(d.caret, 10, "with the caret where it stood");
15161        assert!(d.redo());
15162        assert_eq!(d.source, "I saw the \n");
15163        assert!(d.undo());
15164        assert!(d.undo(), "and the typing before it is its own");
15165        assert_eq!(d.source, "\n");
15166        assert!(!d.can_undo());
15167    }
15168
15169    #[test]
15170    fn a_substitution_keeps_the_markup_it_stands_beside() {
15171        // A quote typed just past a bold run: only its own byte changes.
15172        let mut d = wysiwyg_doc("substitute", "A **bold** word\n");
15173        let at = d.source.find(" word").unwrap();
15174        d.caret = at;
15175        d.insert("\"");
15176        assert_eq!(d.source, "A **bold**\" word\n");
15177        assert!(d.substitute(at, at + 1, "\u{201d}"));
15178        assert_eq!(d.source, "A **bold**\u{201d} word\n");
15179        assert_eq!(d.caret, at + "\u{201d}".len());
15180        assert!(
15181            d.marks_at(d.source.find("bold").unwrap())
15182                .iter()
15183                .any(|(k, _)| *k == InlineKind::Strong)
15184        );
15185        // A range that is not one is refused, and changes nothing.
15186        let src = d.source.clone();
15187        assert!(!d.substitute(3, 2, "x"));
15188        assert!(!d.substitute(0, src.len() + 1, "x"));
15189        assert!(!d.substitute(d.source.find('\u{201d}').unwrap() + 1, d.source.len(), "x"));
15190        assert_eq!(d.source, src);
15191    }
15192
15193    #[test]
15194    fn a_substitution_that_half_lands_takes_back_only_its_own_deletion() {
15195        // The deletion lands and twig refuses the literal text: the deleted
15196        // bytes go back, and nothing else moves — not an earlier substitution
15197        // of the same keystroke, not the group it is in, and no redo is left
15198        // to delete them again.
15199        let mut d = wysiwyg_doc("substitute", "\n");
15200        d.set_markup_mode(MarkupMode::None);
15201        d.caret = 0;
15202        for c in ["a", "\"", "b", " ", "\""] {
15203            d.insert(c);
15204        }
15205        assert_eq!(d.source, "a\"b \"\n");
15206
15207        d.refuse_next_literal = true;
15208        assert!(!d.substitute(1, 2, "\u{201c}"));
15209        assert_eq!(d.source, "a\"b \"\n");
15210        assert_eq!(d.caret, 5, "the caret where it stood");
15211        assert!(!d.can_redo(), "no redo step left behind");
15212
15213        d.begin_undo_group();
15214        assert!(d.substitute(4, 5, "\u{201d}"));
15215        d.refuse_next_literal = true;
15216        assert!(!d.substitute(1, 2, "\u{201c}"));
15217        assert!(d.in_undo_group(), "the group is still open");
15218        assert_eq!(d.source, "a\"b \u{201d}\n", "the first substitution stands");
15219        d.end_undo_group();
15220        assert!(!d.can_redo());
15221        assert!(d.undo());
15222        assert_eq!(d.source, "a\"b \"\n", "one step takes the group back");
15223        assert!(d.undo());
15224        assert_eq!(d.source, "\n", "and the typing is still one step");
15225        assert!(!d.can_undo());
15226
15227        // A group whose first edit is the one that half lands has no step.
15228        let mut d = wysiwyg_doc("substitute", "\n");
15229        d.set_markup_mode(MarkupMode::None);
15230        d.caret = 0;
15231        d.insert("\"");
15232        d.begin_undo_group();
15233        d.refuse_next_literal = true;
15234        assert!(!d.substitute(0, 1, "\u{201c}"));
15235        assert!(d.substitute(0, 1, "\u{201c}"));
15236        d.end_undo_group();
15237        assert!(d.undo());
15238        assert_eq!(
15239            d.source, "\"\n",
15240            "the substitution that landed is the group's step"
15241        );
15242        assert!(d.undo());
15243        assert_eq!(d.source, "\n");
15244    }
15245
15246    #[test]
15247    fn a_substitution_is_written_the_way_typing_writes() {
15248        // Where typing is literal, so is a replacement's text.
15249        let mut d = wysiwyg_doc("substitute", "say hi\n");
15250        d.set_markup_mode(MarkupMode::None);
15251        assert!(d.substitute(4, 6, "*hi*"));
15252        assert_eq!(d.source, "say \\*hi\\*\n");
15253        assert!(d.undo());
15254        assert_eq!(d.source, "say hi\n", "one step, escapes and all");
15255    }
15256
15257    #[test]
15258    fn can_undo_is_false_once_a_coalesced_run_is_undone() {
15259        // The task's repro: five characters typed are one twig step, and the
15260        // counter used to say five.
15261        let mut d = wysiwyg_doc("undo_truth", "\n");
15262        d.caret = 0;
15263        for c in ["h", "e", "l", "l", "o"] {
15264            d.insert(c);
15265        }
15266        assert!(d.can_undo());
15267        assert!(d.undo(), "the run undoes");
15268        assert_eq!(d.source, "\n");
15269        assert!(!d.can_undo(), "and nothing is left behind it");
15270        let rev = d.revision();
15271        assert!(!d.undo(), "an undo that does not move says so");
15272        assert_eq!(d.revision(), rev);
15273        assert!(d.can_redo());
15274        assert!(d.redo());
15275        assert_eq!(d.source, "hello\n");
15276        assert!(!d.can_redo());
15277        assert!(!d.redo());
15278    }
15279
15280    #[test]
15281    fn can_undo_is_exact_across_the_gestures_that_coalesce() {
15282        // Each gesture below folds, or may fold, one twig step into another.
15283        // After it, the mirror must name exactly the number of undos twig
15284        // takes — and the same number of redos back.
15285        type Gesture = fn(&mut Doc);
15286        let cases: &[(&str, &str, Gesture)] = &[
15287            ("typing", "\n", |d| {
15288                d.caret = 0;
15289                d.insert("ab");
15290                d.insert("c");
15291                d.move_left(false);
15292                d.insert("x");
15293            }),
15294            ("backspaces", "abcdef\n", |d| {
15295                d.caret = 6;
15296                d.backspace();
15297                d.backspace();
15298                d.insert("z");
15299                d.backspace();
15300            }),
15301            ("ordered list item", "1. one\n2. two\n", |d| {
15302                d.caret = 6;
15303                d.newline();
15304                d.insert("x");
15305            }),
15306            ("list indent", "- one\n- two\n", |d| {
15307                d.caret = d.source.find("two").unwrap();
15308                d.indent();
15309                d.outdent();
15310            }),
15311            ("bold then type", "one two\n", |d| {
15312                d.select_range(0, 3);
15313                d.toggle(InlineKind::Strong);
15314                d.caret = d.source.len() - 1;
15315                d.insert("!");
15316            }),
15317            ("highlight", "one two\n", |d| {
15318                d.select_range(0, 3);
15319                d.highlight(None);
15320                d.highlight(Some(MarkColor::Green));
15321            }),
15322            ("heading and quote", "one\n", |d| {
15323                d.caret = 1;
15324                d.toggle_heading(2);
15325                d.toggle_blockquote();
15326            }),
15327            ("footnote", "one\n", |d| {
15328                d.caret = 3;
15329                d.insert_footnote();
15330                d.insert("note");
15331            }),
15332            ("blocks", "one\n\ntwo\n\nthree\n", |d| {
15333                d.caret = 1;
15334                d.move_block_down();
15335                d.toggle_list(true);
15336                d.set_alignment(Some(Align::Center));
15337                d.insert_page_break();
15338                d.insert_table(2, 2);
15339            }),
15340            ("paste and compose", "\n", |d| {
15341                d.caret = 0;
15342                d.paste("one two");
15343                d.delete_word_back();
15344                d.edit_composing(d.caret, d.caret, "か");
15345                d.edit_composing(d.caret - 3, d.caret, "蚊");
15346                d.end_composition();
15347                d.insert("z");
15348            }),
15349            ("table", "| a | b |\n| - | - |\n| c | d |\n", |d| {
15350                d.place_caret(d.source.find("d |").unwrap(), false);
15351                d.cell_tab(true);
15352                d.insert("e");
15353                d.cell_return();
15354            }),
15355            ("replace all", "cat cat cat\n", |d| {
15356                d.caret = 0;
15357                d.insert("a ");
15358                replace_all_in(d, "cat", "dog");
15359                d.insert("!");
15360            }),
15361            ("nested group", "one\n\ntwo\n", |d| {
15362                d.begin_undo_group();
15363                d.caret = 3;
15364                d.insert("x");
15365                d.begin_undo_group();
15366                d.toggle_heading(1);
15367                d.end_undo_group();
15368                d.insert("y");
15369                d.end_undo_group();
15370                d.backspace();
15371            }),
15372            ("group around a list", "1. one\n2. two\n", |d| {
15373                d.begin_undo_group();
15374                d.caret = 6;
15375                d.newline();
15376                d.insert("x");
15377                d.end_undo_group();
15378            }),
15379            ("substitution", "\n", |d| {
15380                d.caret = 0;
15381                d.insert("t");
15382                d.insert("e");
15383                d.insert("h");
15384                d.insert(" ");
15385                d.substitute(0, 3, "the");
15386                d.insert("c");
15387            }),
15388            ("empty group", "one\n", |d| {
15389                d.caret = 3;
15390                d.insert("x");
15391                d.begin_undo_group();
15392                d.end_undo_group();
15393                d.insert("y");
15394            }),
15395            ("undo inside a group", "one\n", |d| {
15396                d.caret = 3;
15397                d.begin_undo_group();
15398                d.insert("x");
15399                d.undo();
15400                d.insert("y");
15401                d.insert("z");
15402                d.end_undo_group();
15403            }),
15404        ];
15405        for (name, src, gesture) in cases {
15406            let mut d = wysiwyg_doc("undo_exact", src);
15407            gesture(&mut d);
15408            let (steps, after) = (d.undo_steps, d.source.clone());
15409            let mut undone = 0;
15410            while d.can_undo() {
15411                assert!(d.undo(), "{name}: can_undo said yes, undo moved nothing");
15412                undone += 1;
15413            }
15414            assert!(!d.undo(), "{name}: can_undo said no, undo moved");
15415            assert_eq!(undone, steps, "{name}");
15416            assert_eq!(d.source, *src, "{name}: back to the start");
15417            let mut redone = 0;
15418            while d.can_redo() {
15419                assert!(d.redo(), "{name}: can_redo said yes, redo moved nothing");
15420                redone += 1;
15421            }
15422            assert!(!d.redo(), "{name}: can_redo said no, redo moved");
15423            assert_eq!(redone, steps, "{name}");
15424            assert_eq!(d.source, after, "{name}: forward to the end");
15425        }
15426    }
15427
15428    #[test]
15429    fn two_compositions_are_two_undo_steps() {
15430        let mut d = doc_with("compose_two", "\n");
15431        d.caret = 0;
15432        d.edit_composing(0, 0, "か");
15433        d.edit_composing(0, 3, "蚊");
15434        d.end_composition();
15435        d.edit_composing(3, 3, "き");
15436        d.edit_composing(3, 6, "木");
15437        d.end_composition();
15438        assert_eq!(d.source, "蚊木\n");
15439        d.undo();
15440        assert_eq!(d.source, "蚊\n", "only the second composition");
15441        d.undo();
15442        assert_eq!(d.source, "\n");
15443    }
15444
15445    #[test]
15446    fn a_composition_does_not_fold_into_the_typing_around_it() {
15447        let mut d = doc_with("compose_typing", "\n");
15448        d.caret = 0;
15449        d.insert("a");
15450        d.insert("b");
15451        d.edit_composing(2, 2, "か");
15452        d.edit_composing(2, 5, "蚊");
15453        d.end_composition();
15454        d.insert("c");
15455        assert_eq!(d.source, "ab蚊c\n");
15456        d.undo();
15457        assert_eq!(d.source, "ab蚊\n");
15458        d.undo();
15459        assert_eq!(d.source, "ab\n");
15460        d.undo();
15461        assert_eq!(d.source, "\n");
15462    }
15463
15464    #[test]
15465    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
15466        let mut d = doc_with("compose_spurious", "\n");
15467        d.caret = 0;
15468        d.insert("a");
15469        d.end_composition(); // an IME unmarking unprompted
15470        d.insert("b");
15471        assert_eq!(d.source, "ab\n");
15472        d.undo();
15473        assert_eq!(d.source, "\n", "still one typed run");
15474    }
15475
15476    // ── the clipboard's rich flavor ──────────────────────────────────────────
15477
15478    #[test]
15479    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
15480        let mut d = doc_with("sel_inline", "a **bold** c\n");
15481        d.anchor = Some(2);
15482        d.caret = 10; // `**bold**`, inside the paragraph
15483        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
15484    }
15485
15486    #[test]
15487    fn a_whole_block_selection_keeps_its_paragraph() {
15488        let mut d = doc_with("sel_block", "a **bold** c\n");
15489        d.anchor = Some(0);
15490        d.caret = 12; // the entire paragraph
15491        assert_eq!(
15492            d.selection_html().as_deref(),
15493            Some("<p>a <strong>bold</strong> c</p>")
15494        );
15495    }
15496
15497    #[test]
15498    fn a_multi_block_selection_keeps_its_structure() {
15499        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
15500        d.select_all();
15501        let html = d.selection_html().expect("renders");
15502        assert!(html.contains("<p>para</p>"), "{html:?}");
15503        assert!(html.contains("<li>one</li>"), "{html:?}");
15504    }
15505
15506    #[test]
15507    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
15508        // The fragment `Head` is a paragraph standalone; the *document* says it
15509        // sits inside one block, so the wrapper is an artifact either way.
15510        let mut d = doc_with("sel_heading", "# Head line\n");
15511        d.anchor = Some(2);
15512        d.caret = 6;
15513        assert_eq!(d.selection_html().as_deref(), Some("Head"));
15514    }
15515
15516    #[test]
15517    fn no_selection_publishes_no_html() {
15518        let mut d = doc_with("sel_none", "a b\n");
15519        d.caret = 1;
15520        assert_eq!(d.selection_html(), None);
15521    }
15522
15523    #[test]
15524    fn pasting_html_converts_it_and_is_one_undo_step() {
15525        let mut d = doc_with("paste_html", "x\n");
15526        d.caret = 1;
15527        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
15528        assert_eq!(d.source, "xa **b** c\n");
15529        d.undo();
15530        assert_eq!(d.source, "x\n", "the whole paste, in one step");
15531    }
15532
15533    #[test]
15534    fn pasting_html_replaces_the_selection() {
15535        let mut d = doc_with("paste_html_sel", "keep drop\n");
15536        d.anchor = Some(5);
15537        d.caret = 9;
15538        assert!(d.paste_html("<em>new</em>"));
15539        assert_eq!(d.source, "keep *new*\n");
15540    }
15541
15542    #[test]
15543    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
15544        let mut d = doc_with("paste_html_bad", "x\n");
15545        d.caret = 1;
15546        // twig builds no table from HTML; raw `<table>` in prose is worse than
15547        // the plain flavor the caller still holds.
15548        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
15549        assert_eq!(d.source, "x\n", "declined edits nothing");
15550    }
15551
15552    #[test]
15553    fn copy_then_paste_round_trips_through_the_html_flavor() {
15554        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
15555        d.select_all();
15556        let html = d.selection_html().expect("renders");
15557        let mut into = doc_with("clip_round_dst", "\n");
15558        into.caret = 0;
15559        assert!(into.paste_html(&html));
15560        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
15561    }
15562
15563    #[test]
15564    fn moving_the_caret_starts_a_new_undo_group() {
15565        let mut d = doc_with("break", "\n");
15566        d.caret = 0;
15567        d.insert("a");
15568        d.insert("b"); // "ab\n", caret at 2
15569        d.move_left(false); // breaks the run
15570        d.insert("X"); // "aXb\n"
15571        assert_eq!(d.source, "aXb\n");
15572        d.undo();
15573        assert_eq!(
15574            d.source, "ab\n",
15575            "first undo removes only the post-move insert"
15576        );
15577        d.undo();
15578        assert_eq!(d.source, "\n", "second undo removes the earlier run");
15579    }
15580
15581    #[test]
15582    fn undo_reverses_a_format_toggle() {
15583        let mut d = doc_with("fmt_undo", "a word b\n");
15584        d.anchor = Some(2);
15585        d.caret = 6;
15586        d.toggle(InlineKind::Strong);
15587        assert_eq!(d.source, "a **word** b\n");
15588        d.undo();
15589        assert_eq!(d.source, "a word b\n");
15590    }
15591
15592    #[test]
15593    fn undo_back_to_the_saved_state_clears_dirty() {
15594        let mut d = doc_with("dirty_undo", "hello\n");
15595        assert!(!d.dirty);
15596        d.caret = 5;
15597        d.insert("!");
15598        assert!(d.dirty);
15599        d.undo();
15600        assert!(
15601            !d.dirty,
15602            "undoing to the saved source is not a modification"
15603        );
15604    }
15605
15606    #[test]
15607    fn marking_saved_as_what_was_written_keeps_later_typing_dirty() {
15608        let mut d = doc_with("saved_as", "Does this\n");
15609        d.caret = 9;
15610        d.insert(" ");
15611        // The host reads the source, and its write takes a while…
15612        let written = d.source.clone();
15613        // …during which the rest of the sentence is typed.
15614        d.insert("work?");
15615        d.mark_saved_as(&written);
15616        assert!(d.dirty, "what was typed during the write is not saved");
15617        d.undo();
15618        assert!(!d.dirty, "undoing to what was written is the saved state");
15619
15620        d.redo();
15621        let written = d.source.clone();
15622        d.mark_saved_as(&written);
15623        assert!(!d.dirty, "nothing typed meanwhile: saved");
15624    }
15625
15626    #[test]
15627    fn a_new_edit_invalidates_redo() {
15628        let mut d = doc_with("redo_inv", "\n");
15629        d.caret = 0;
15630        d.insert("a");
15631        d.undo();
15632        d.insert("b"); // diverges — the redo of "a" is now gone
15633        d.redo();
15634        assert_eq!(d.source, "b\n");
15635    }
15636
15637    #[test]
15638    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
15639        let mut d = doc_with("can_undo", "hello\n");
15640        assert!(
15641            !d.can_undo() && !d.can_redo(),
15642            "a fresh document has no history"
15643        );
15644        d.caret = 5;
15645        d.insert("!");
15646        assert!(
15647            d.can_undo() && !d.can_redo(),
15648            "an edit is a step to take back"
15649        );
15650        d.undo();
15651        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
15652        d.redo();
15653        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
15654        d.undo();
15655        d.insert("?");
15656        assert!(
15657            d.can_undo() && !d.can_redo(),
15658            "a fresh edit ends the redo chain"
15659        );
15660        // A coalesced run over-counts steps — the bound is what a menu needs,
15661        // and it reconciles the moment twig reports the history empty.
15662        d.insert("a");
15663        d.insert("b");
15664        while d.can_undo() {
15665            d.undo();
15666        }
15667        assert_eq!(d.source, "hello\n");
15668        assert!(!d.can_undo());
15669        // A reading surface has nothing to undo, whatever the history holds.
15670        d.redo();
15671        d.set_read_only(true);
15672        assert!(!d.can_undo() && !d.can_redo());
15673    }
15674
15675    #[test]
15676    fn undo_on_empty_history_is_a_no_op() {
15677        let mut d = doc_with("undo_empty", "hi\n");
15678        d.undo();
15679        assert_eq!(d.source, "hi\n");
15680        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
15681    }
15682
15683    #[test]
15684    fn a_one_character_paste_is_its_own_undo_step() {
15685        for view in [View::Source, View::Wysiwyg] {
15686            let mut d = doc_in(view, "paste_step", "ab\n");
15687            d.caret = 0;
15688            d.insert("x");
15689            d.insert("y"); // a run of typing
15690            d.paste("z"); // one character, but pasted — not part of that run
15691            assert_eq!(d.source, "xyzab\n");
15692            d.undo();
15693            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
15694            assert_eq!(d.caret, 2, "and hands back the caret it found");
15695            d.undo();
15696            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
15697        }
15698    }
15699
15700    #[test]
15701    fn the_same_character_typed_still_joins_the_run() {
15702        // The other half of the pair: `z` is a keystroke here and a paste above,
15703        // and the two undo differently. Nothing about the *string* says which —
15704        // which is why provenance has to come from the door the caller uses.
15705        for view in [View::Source, View::Wysiwyg] {
15706            let mut d = doc_in(view, "typed_run", "ab\n");
15707            d.caret = 0;
15708            d.insert("x");
15709            d.insert("y");
15710            d.insert("z");
15711            d.undo();
15712            assert_eq!(d.source, "ab\n", "one run, one step");
15713        }
15714    }
15715
15716    #[test]
15717    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
15718        for view in [View::Source, View::Wysiwyg] {
15719            let mut d = doc_in(view, "undo_caret", "hello world\n");
15720            d.caret = 11; // standing at the end of "world", away from the edit
15721            d.edit(0, 5, "goodbye");
15722            assert_eq!(d.source, "goodbye world\n");
15723            d.undo();
15724            assert_eq!(d.source, "hello world\n");
15725            // The undone edit ends at offset 5; the user was at 11.
15726            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
15727        }
15728    }
15729
15730    #[test]
15731    fn undo_restores_the_selection_the_edit_replaced() {
15732        for view in [View::Source, View::Wysiwyg] {
15733            let mut d = doc_in(view, "undo_sel", "a word b\n");
15734            d.anchor = Some(2);
15735            d.caret = 6; // "word" selected
15736            d.insert("X");
15737            assert_eq!(d.source, "a X b\n");
15738            d.undo();
15739            assert_eq!(d.source, "a word b\n");
15740            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
15741        }
15742    }
15743
15744    #[test]
15745    fn redo_restores_the_caret_the_edit_left_behind() {
15746        for view in [View::Source, View::Wysiwyg] {
15747            let mut d = doc_in(view, "redo_caret", "hello world\n");
15748            d.caret = 11;
15749            d.edit(0, 5, "goodbye");
15750            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
15751            d.undo();
15752            d.redo();
15753            assert_eq!(d.source, "goodbye world\n");
15754            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
15755        }
15756    }
15757
15758    #[test]
15759    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
15760        for view in [View::Source, View::Wysiwyg] {
15761            let mut d = doc_in(view, "run_caret", "hi\n");
15762            d.caret = 2;
15763            d.insert("a");
15764            d.insert("b");
15765            d.insert("c");
15766            assert_eq!(d.source, "hiabc\n");
15767            d.undo();
15768            assert_eq!(d.source, "hi\n");
15769            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
15770            d.redo();
15771            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
15772        }
15773    }
15774
15775    #[test]
15776    fn undo_restores_the_caret_across_a_format_toggle() {
15777        // A toggle reaches twig without going through `splice`, so it has to
15778        // record its own step — miss it and every stack depth below it is off by
15779        // one, and undo starts handing back another edit's caret.
15780        for view in [View::Source, View::Wysiwyg] {
15781            let mut d = doc_in(view, "fmt_caret", "a word b\n");
15782            d.caret = 8;
15783            d.anchor = Some(2);
15784            d.caret = 6;
15785            d.toggle(InlineKind::Strong);
15786            assert_eq!(d.source, "a **word** b\n");
15787            d.undo();
15788            assert_eq!(d.source, "a word b\n");
15789            assert_eq!(
15790                d.selection(),
15791                Some((2, 6)),
15792                "the toggled selection comes back"
15793            );
15794        }
15795    }
15796
15797    #[test]
15798    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
15799        // The drift that would never announce itself: twig drops its redo stack
15800        // on any fresh edit, so a leaf redo entry that outlives it would restore
15801        // a caret from the timeline that edit abandoned.
15802        for view in [View::Source, View::Wysiwyg] {
15803            let mut d = doc_in(view, "redo_trunc", "hello world\n");
15804            d.caret = 11;
15805            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
15806            d.undo();
15807            assert_eq!(d.caret, 11);
15808            d.caret = 0;
15809            d.insert("X"); // diverges: A's redo is gone from twig
15810            assert_eq!(d.source, "Xhello world\n");
15811
15812            d.redo();
15813            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
15814            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
15815            d.undo();
15816            assert_eq!(d.source, "hello world\n");
15817            assert_eq!(
15818                d.caret, 0,
15819                "the surviving step's caret, not the dropped one"
15820            );
15821        }
15822    }
15823
15824    #[test]
15825    fn indent_and_outdent_move_the_caret_line_with_its_text() {
15826        for view in [View::Source, View::Wysiwyg] {
15827            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
15828            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
15829            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
15830            // Indentation the caret is standing *in* collapses to the line start
15831            // rather than dragging the caret into the text.
15832            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
15833            // A line with none to give back is left exactly as it was.
15834            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
15835            // Less than a full level gives back what it has.
15836            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
15837            // A tab is one level however many spaces it isn't.
15838            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
15839        }
15840    }
15841
15842    #[test]
15843    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
15844        // Why the level is two spaces and not the four both frontends type
15845        // today. Four is markdown's indented-code-block marker, so a Tab on a
15846        // paragraph would silently restyle it as code — a width that changes
15847        // what the document *means* isn't an indent. Pinned because the number
15848        // is the kind of thing a later list-aware pass would reach for.
15849        let mut d = doc_with("indent_kind", "hello\n");
15850        d.caret = 2;
15851        d.indent();
15852        assert_eq!(d.source, "  hello\n");
15853        assert!(
15854            d.nodes().iter().any(|n| n.kind == Kind::Para),
15855            "still prose after a Tab"
15856        );
15857        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
15858
15859        // The four-space level this replaces, for contrast: same text, and twig
15860        // reparses the paragraph into a code block.
15861        let mut wide = doc_with("indent_kind_4", "    hello\n");
15862        wide.build_visual(80);
15863        assert!(
15864            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
15865            "four spaces is a code block, not an indented paragraph"
15866        );
15867    }
15868
15869    #[test]
15870    fn indent_nests_a_list_item_under_its_parent() {
15871        // Tab indents a list item by its own marker width, landing its marker at
15872        // the parent's content column so twig reparses it as a nested list.
15873        for view in [View::Source, View::Wysiwyg] {
15874            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
15875            d.caret = 6; // on the second item
15876            d.indent();
15877            assert_eq!(d.source, "- a\n  - b\n");
15878            let lists = d
15879                .nodes()
15880                .iter()
15881                .filter(|n| n.kind == Kind::BulletList)
15882                .count();
15883            assert_eq!(lists, 2, "the indented item is a nested list");
15884        }
15885    }
15886
15887    #[test]
15888    fn indent_nests_an_ordered_item_at_its_marker_width() {
15889        // An ordered marker `1. ` is three columns wide, so a two-space step
15890        // (which nests a bullet) leaves it flat. Regression: Tab must use the
15891        // marker width, three, so the item actually nests — and the source
15892        // renumbers so the sub-list restarts at 1 and the outer list resumes.
15893        for view in [View::Source, View::Wysiwyg] {
15894            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
15895            d.caret = d.source.find('b').unwrap();
15896            d.indent();
15897            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
15898            let lists = d
15899                .nodes()
15900                .iter()
15901                .filter(|n| n.kind == Kind::OrderedList)
15902                .count();
15903            assert_eq!(lists, 2, "the indented item is a nested ordered list");
15904        }
15905    }
15906
15907    #[test]
15908    fn indent_leaves_a_lists_first_item_put() {
15909        // The first item of a list has no sibling above it to nest under, so Tab
15910        // is a no-op there — the marker stays at column zero rather than being
15911        // shoved into indentation twig can't read as a sub-list.
15912        for view in [View::Source, View::Wysiwyg] {
15913            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
15914            d.caret = 1; // on the FIRST item
15915            d.indent();
15916            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
15917            // The sibling below still nests, proving the guard is per-item.
15918            d.caret = d.source.find('b').unwrap();
15919            d.indent();
15920            assert_eq!(d.source, "- a\n  - b\n");
15921        }
15922    }
15923
15924    #[test]
15925    fn hidden_mode_keeps_typed_markup_literal() {
15926        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
15927        // twig escapes what would open markup, so the source is `\*hi\*` and the
15928        // AST is a plain string. Formatting is the commands' job in this mode.
15929        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
15930        d.insert("*hi*");
15931        assert_eq!(d.source, "\\*hi\\*");
15932        assert!(
15933            d.nodes()
15934                .iter()
15935                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
15936        );
15937    }
15938
15939    #[test]
15940    fn hidden_mode_escapes_a_line_start_block_marker() {
15941        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
15942        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
15943        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
15944        d.insert("# hi");
15945        assert_eq!(d.source, "\\# hi");
15946        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
15947    }
15948
15949    #[test]
15950    fn authoring_modes_keep_typed_markup_live() {
15951        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
15952        // (no escape), the same as source view — escaping is `None`'s alone, and
15953        // it's the axis, not the reveal, that decides.
15954        for (view, mode) in [
15955            (View::Wysiwyg, MarkupMode::Shortcuts),
15956            (View::Wysiwyg, MarkupMode::Full),
15957            (View::Source, MarkupMode::None),
15958        ] {
15959            let mut d = doc_in(view, "live_markup", "");
15960            d.set_markup_mode(mode);
15961            d.insert("*hi*");
15962            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
15963        }
15964    }
15965
15966    #[test]
15967    fn hidden_mode_overwrite_undoes_in_one_step() {
15968        // Typing over a selection escapes the replacement *and* stays a single
15969        // undo — the selection-delete and the literal insert fold together, so
15970        // one undo brings the whole selection back, like a plain overwrite.
15971        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
15972        d.anchor = Some(2);
15973        d.caret = 6; // "word"
15974        d.insert("*");
15975        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
15976        d.undo();
15977        assert_eq!(d.source, "a word b\n");
15978        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
15979    }
15980
15981    #[test]
15982    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
15983        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
15984        // the whole visual character, never stranding the hidden `\`.
15985        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
15986        d.insert("*");
15987        assert_eq!(d.source, "\\*");
15988        d.backspace();
15989        assert_eq!(d.source, "", "the escape backslash went with the *");
15990        // A *literal* backslash (source view, no escape) is an ordinary char.
15991        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
15992        s.caret = 3; // after `b`
15993        s.backspace();
15994        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
15995    }
15996
15997    #[test]
15998    fn hidden_mode_leaves_structural_markup_alone() {
15999        // Enter continues a bullet list by writing a real `- ` marker (an
16000        // `insert_raw`, not the typing path), so Hidden mode's escaping never
16001        // touches it — the list keeps working.
16002        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
16003        d.caret = 6;
16004        d.newline();
16005        d.insert("two");
16006        assert_eq!(d.source, "- item\n- two\n");
16007    }
16008
16009    #[test]
16010    fn markup_mode_defaults_to_none_and_round_trips() {
16011        // Diaryx's default is the clean `None` surface; a markup-fluent
16012        // frontend can climb the ladder, and the choice sticks.
16013        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
16014        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
16015        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
16016            d.set_markup_mode(mode);
16017            assert_eq!(d.markup_mode(), mode);
16018        }
16019    }
16020
16021    #[test]
16022    fn full_mode_reveals_only_the_caret_line() {
16023        // The mode's whole claim: the caret's line shows its raw delimiters and
16024        // every other line stays resolved. Two paragraphs with identical markup
16025        // so the only difference between the rows is where the caret is.
16026        let mut d = doc_in(
16027            View::Wysiwyg,
16028            "reveal_caret_line",
16029            "*one* here\n\n*two* there\n",
16030        );
16031        d.set_markup_mode(MarkupMode::Full);
16032
16033        caret_at(&mut d, "one");
16034        let rows = drawn_rows(&d);
16035        assert!(
16036            rows.iter().any(|r| r == "*one* here"),
16037            "caret's line raw: {rows:?}"
16038        );
16039        assert!(
16040            rows.iter().any(|r| r == "two there"),
16041            "other line resolved: {rows:?}"
16042        );
16043
16044        // Move to the other paragraph: the reveal follows, and the line just
16045        // left goes back to being resolved.
16046        caret_at(&mut d, "two");
16047        let rows = drawn_rows(&d);
16048        assert!(
16049            rows.iter().any(|r| r == "*two* there"),
16050            "caret's line raw: {rows:?}"
16051        );
16052        assert!(
16053            rows.iter().any(|r| r == "one here"),
16054            "left line resolved: {rows:?}"
16055        );
16056    }
16057
16058    #[test]
16059    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
16060        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
16061        // the same treatment as an emphasis's `*`: hidden while the caret is
16062        // elsewhere, shown in full where the caret lands. That falls out of
16063        // `delims` reading the bytes between the mark's span and its content
16064        // span, which is exactly `==🔴 ` and `==`, rather than from a table
16065        // of spellings — so the no-space form `==🟢green==` reveals right too.
16066        let mut d = doc_in(
16067            View::Wysiwyg,
16068            "reveal_coloured_mark",
16069            "a ==🔴 red== one\n\nb ==plain== two\n",
16070        );
16071        d.set_markup_mode(MarkupMode::Full);
16072
16073        caret_at(&mut d, "red");
16074        let rows = drawn_rows(&d);
16075        assert!(
16076            rows.iter().any(|r| r == "a ==🔴 red== one"),
16077            "the caret's line shows the colour it was written with: {rows:?}"
16078        );
16079        assert!(
16080            rows.iter().any(|r| r == "b plain two"),
16081            "and every other line stays resolved: {rows:?}"
16082        );
16083
16084        // Away from it, the emoji goes back to being markup — the reader sees
16085        // the words and the wash.
16086        caret_at(&mut d, "two");
16087        let rows = drawn_rows(&d);
16088        assert!(
16089            rows.iter().any(|r| r == "a red one"),
16090            "resolved again: {rows:?}"
16091        );
16092    }
16093
16094    #[test]
16095    fn hidden_modes_never_reveal_wherever_the_caret_is() {
16096        // The two rungs below `Full` share a rendering: delimiters stay hidden
16097        // even under the caret. `Shortcuts` differing from `None` only in what
16098        // typing does is exactly the point of splitting the axes.
16099        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
16100            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
16101            d.set_markup_mode(mode);
16102            caret_at(&mut d, "one");
16103            let rows = drawn_rows(&d);
16104            assert!(
16105                rows.iter().any(|r| r == "one here"),
16106                "{mode:?} hides: {rows:?}"
16107            );
16108            assert!(
16109                !rows.iter().any(|r| r.contains('*')),
16110                "{mode:?} shows no `*`: {rows:?}"
16111            );
16112        }
16113    }
16114
16115    #[test]
16116    fn revealed_delimiters_are_the_authors_own_spelling() {
16117        // Delimiters are re-read from the source rather than synthesized per
16118        // kind, so a line comes back spelled the way it was written: `_em_` does
16119        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
16120        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
16121        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
16122        d.set_markup_mode(MarkupMode::Full);
16123        caret_at(&mut d, "em");
16124        let rows = drawn_rows(&d);
16125        assert!(
16126            rows.iter().any(|r| r == body.trim_end()),
16127            "the revealed line is its own source: {rows:?}"
16128        );
16129    }
16130
16131    #[test]
16132    fn revealed_heading_shows_its_hashes() {
16133        // The `# ` marker is a block-level prefix, not an inline delimiter, so
16134        // it takes its own path — but it reveals on the same rule.
16135        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
16136        d.set_markup_mode(MarkupMode::Full);
16137
16138        caret_at(&mut d, "Title");
16139        assert!(
16140            drawn_rows(&d).iter().any(|r| r == "# Title"),
16141            "{:?}",
16142            drawn_rows(&d)
16143        );
16144
16145        caret_at(&mut d, "body");
16146        let rows = drawn_rows(&d);
16147        assert!(
16148            rows.iter().any(|r| r == "Title"),
16149            "hashes hidden again: {rows:?}"
16150        );
16151    }
16152
16153    #[test]
16154    fn revealed_delimiters_are_caret_stops() {
16155        // A delimiter that is drawn but can't be reached is worse than one
16156        // that's hidden: the mode exists so the markup can be *edited*. Every
16157        // revealed byte must be somewhere the caret can stand.
16158        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
16159        d.set_markup_mode(MarkupMode::Full);
16160        caret_at(&mut d, "em");
16161        let opener = d.source.find('*').unwrap();
16162        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
16163        assert!(
16164            d.vmap.is_stop(opener + 3),
16165            "the closing `*` is a caret stop"
16166        );
16167    }
16168
16169    #[test]
16170    fn setext_heading_reveals_nothing_across_its_newline() {
16171        // A setext heading's underline is on another line, so it is not the
16172        // caret line's to reveal — and emitting it would inject a `\n` glyph
16173        // that splits the row where the author wrote no break.
16174        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
16175        d.set_markup_mode(MarkupMode::Full);
16176        caret_at(&mut d, "Title");
16177        let rows = drawn_rows(&d);
16178        assert!(
16179            rows.iter().any(|r| r == "Title"),
16180            "title renders alone: {rows:?}"
16181        );
16182        assert!(
16183            !rows.iter().any(|r| r.contains('=')),
16184            "no underline leaks in: {rows:?}"
16185        );
16186    }
16187
16188    #[test]
16189    fn markup_mode_axes_split_the_ladder() {
16190        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
16191        // that authors markup but still hides it, and it's the only rung where
16192        // the two axes disagree.
16193        assert!(!MarkupMode::None.authors());
16194        assert!(!MarkupMode::None.reveals_caret_line());
16195        assert!(MarkupMode::Shortcuts.authors());
16196        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
16197        assert!(MarkupMode::Full.authors());
16198        assert!(MarkupMode::Full.reveals_caret_line());
16199    }
16200
16201    #[test]
16202    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
16203        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
16204        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
16205        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
16206        // nested bullet and `hello` stays prose: the file round-trips instead of
16207        // hiding a heading the user never asked for.
16208        for view in [View::Source, View::Wysiwyg] {
16209            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
16210            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
16211            d.indent();
16212            assert_eq!(d.source, "- hello\n  * \n");
16213            assert!(
16214                d.nodes().iter().all(|n| n.kind != Kind::Heading),
16215                "no heading"
16216            );
16217            // And it's genuinely a nested list, not a flat one.
16218            assert_eq!(
16219                d.nodes()
16220                    .iter()
16221                    .filter(|n| n.kind == Kind::BulletList)
16222                    .count(),
16223                2
16224            );
16225        }
16226    }
16227
16228    #[test]
16229    fn indenting_a_dash_item_with_content_keeps_its_dash() {
16230        // With content, `- x` can't be a setext underline, so there's nothing to
16231        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
16232        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
16233        d.caret = d.source.find('x').unwrap();
16234        d.indent();
16235        assert_eq!(d.source, "- hello\n  - x\n");
16236    }
16237
16238    #[test]
16239    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
16240        // The dash→`*` repair coalesces into the Tab, so a single undo restores
16241        // the whole pre-Tab state rather than stranding a half-collapsed doc.
16242        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
16243        d.caret = d.source.find("- \n").unwrap() + 2;
16244        d.indent();
16245        assert_eq!(d.source, "- hello\n  * \n");
16246        d.undo();
16247        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
16248    }
16249
16250    #[test]
16251    fn indent_leaves_a_nested_lists_first_item_put_too() {
16252        // The guard is about siblings, not depth: the first item of an *inner*
16253        // list (already nested under `a`) still has nothing before it at its own
16254        // level, so Tab can't take it deeper.
16255        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
16256        d.caret = d.source.find('b').unwrap();
16257        d.indent();
16258        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
16259        // But `c` (a sibling of `b`) nests under `b`.
16260        d.caret = d.source.find('c').unwrap();
16261        d.indent();
16262        assert_eq!(d.source, "- a\n  - b\n    - c\n");
16263    }
16264
16265    #[test]
16266    fn backspace_at_a_nested_item_start_outdents_it() {
16267        // Backspace with the caret right after a nested item's marker gives back
16268        // one level of nesting, the mirror of Tab — and renumbers the flattened
16269        // ordered list back to a clean run.
16270        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
16271        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
16272        d.backspace();
16273        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16274    }
16275
16276    #[test]
16277    fn backspace_at_a_top_level_item_start_strips_the_marker() {
16278        // At the outermost level there's no nesting left to give back, so the same
16279        // keystroke drops the bullet and leaves a plain paragraph.
16280        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
16281        d.caret = d.source.find('b').unwrap(); // right after `- `
16282        d.backspace();
16283        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
16284    }
16285
16286    #[test]
16287    fn backspace_mid_item_still_deletes_a_character() {
16288        // The list behaviour is armed only at the item's content start; anywhere
16289        // else Backspace is the ordinary character delete.
16290        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
16291        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
16292        d.backspace();
16293        assert_eq!(d.source, "- b\n");
16294    }
16295
16296    #[test]
16297    fn backspace_at_a_heading_start_strips_the_marker() {
16298        // The `# ` is markup the rich view hides, so Backspace over it takes the
16299        // whole marker and leaves a paragraph. Deleting a byte of it instead left
16300        // `#Title` — no longer a heading, with the hash now literal text the user
16301        // never typed and has to delete again.
16302        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
16303        d.caret = d.source.find('T').unwrap(); // right after `## `
16304        d.backspace();
16305        assert_eq!(d.source, "Title\n");
16306        assert_eq!(
16307            d.caret, 0,
16308            "the caret stays with the text it was in front of"
16309        );
16310    }
16311
16312    #[test]
16313    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
16314        // Only the heading's own marker goes — the quote (or list) it sits in is
16315        // untouched, exactly as un-heading it should be.
16316        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
16317        d.caret = d.source.find('T').unwrap();
16318        d.backspace();
16319        assert_eq!(d.source, "> Title\n");
16320    }
16321
16322    #[test]
16323    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
16324        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
16325        // behind would surface the same stray hash the marker delete just avoided.
16326        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
16327        d.caret = d.source.find('T').unwrap();
16328        d.backspace();
16329        assert_eq!(d.source, "Title\n");
16330        // And it's one edit: a single undo puts the whole heading back.
16331        d.undo();
16332        assert_eq!(d.source, "# Title #\n");
16333    }
16334
16335    #[test]
16336    fn backspace_mid_heading_still_deletes_a_character() {
16337        // The heading behaviour is armed only at the content's start; anywhere
16338        // else Backspace is the ordinary character delete.
16339        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
16340        d.caret = d.source.find('b').unwrap();
16341        d.backspace();
16342        assert_eq!(d.source, "# b\n");
16343    }
16344
16345    #[test]
16346    fn source_view_backspace_still_edits_the_heading_marker_literally() {
16347        // In source view the `# ` is text on the screen the user is deleting a
16348        // byte of, so it keeps its literal meaning — the same split the list
16349        // ladder and Enter draw between the two views.
16350        let mut d = doc_with("bsp_head_src", "# Title\n");
16351        d.caret = d.source.find('T').unwrap();
16352        d.backspace();
16353        assert_eq!(d.source, "#Title\n");
16354    }
16355
16356    #[test]
16357    fn outdent_unnests_an_ordered_item_in_one_press() {
16358        // Shift+Tab gives back exactly the marker width the indent added, so a
16359        // nested ordered item unnests in a single press, and the flattened list
16360        // renumbers back to a clean 1, 2, 3.
16361        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
16362        d.caret = d.source.find('b').unwrap();
16363        d.outdent();
16364        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16365        let lists = d
16366            .nodes()
16367            .iter()
16368            .filter(|n| n.kind == Kind::OrderedList)
16369            .count();
16370        assert_eq!(lists, 1, "back to one flat list");
16371    }
16372
16373    #[test]
16374    fn table_insert_row_adds_a_row_below_the_caret() {
16375        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16376        d.caret = d.source.find('1').unwrap(); // in the body row
16377        d.table_insert_row(true);
16378        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
16379    }
16380
16381    #[test]
16382    fn table_insert_and_delete_column_at_the_caret() {
16383        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16384        d.caret = d.source.find('a').unwrap(); // column 0
16385        d.table_insert_column(true); // add a column to the right of `a`
16386        assert_eq!(
16387            d.source,
16388            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
16389        );
16390        d.caret = d.source.find('b').unwrap(); // now the third column
16391        d.table_delete_column();
16392        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
16393    }
16394
16395    // ── ragged formats ───────────────────────────────────────────────────────
16396    // No format spells every gesture. HTML writes the inline marks as a tag pair
16397    // and no heading, list, quote or link; Markdown spells five of the eight
16398    // marks — the highlight only because leaf parses with `highlight`, which is
16399    // why the question is asked with the extensions; djot spells all eight and
16400    // no in-cell break. leaf asks twig per
16401    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
16402    // op discover the fact on its own — one of them didn't.
16403
16404    /// An HTML document in the rich view, ready for a gesture.
16405    fn html_doc(body: &str) -> Doc {
16406        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
16407        d.view = View::Wysiwyg;
16408        d.build_visual(80);
16409        d
16410    }
16411
16412    #[test]
16413    fn a_table_gesture_leaves_an_html_table_alone() {
16414        // The regression this guard exists for. twig's table editor consults no
16415        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
16416        // HTML `<table>` as a *pipe table* and reported success: the whole
16417        // element replaced by `| a | b |`, silently, on one press of a toolbar
16418        // button. Every grid op went the same way.
16419        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
16420        // A table of named operations, which is what it looks like.
16421        #[allow(clippy::type_complexity)]
16422        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
16423            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
16424            ("delete row", &|d: &mut Doc| d.table_delete_row()),
16425            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
16426            ("delete column", &|d: &mut Doc| d.table_delete_column()),
16427            ("align", &|d: &mut Doc| {
16428                d.table_set_alignment(Alignment::Right)
16429            }),
16430            ("move row", &|d: &mut Doc| d.table_move_row(true)),
16431            ("move column", &|d: &mut Doc| d.table_move_column(true)),
16432        ];
16433        for (name, op) in ops {
16434            let mut d = html_doc(src);
16435            d.caret = d.source.find('a').unwrap();
16436            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
16437            op(&mut d);
16438            assert_eq!(d.source, src, "{name} rewrote an HTML table");
16439            assert!(
16440                !d.dirty,
16441                "{name} marked the document dirty without editing it"
16442            );
16443            assert!(d.status.is_some(), "{name} refused without saying why");
16444        }
16445    }
16446
16447    #[test]
16448    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
16449        // A task box is a form control in HTML and a footnote has no native
16450        // spelling at all — the two gestures twig 3.5 still spells nothing
16451        // for, now that a quote, a list, a link and an image print through
16452        // its renderer (see the test below).
16453        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16454        // A table of named operations, which is what it looks like.
16455        #[allow(clippy::type_complexity)]
16456        let ops: [(&str, &dyn Fn(&mut Doc)); 3] = [
16457            ("task item", &|d: &mut Doc| d.toggle_task_item()),
16458            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
16459            ("footnote", &|d: &mut Doc| d.insert_footnote()),
16460        ];
16461        for (name, op) in ops {
16462            let mut d = html_doc(src);
16463            let at = d.source.find("Hello").unwrap();
16464            d.caret = at;
16465            d.anchor = Some(at + 5); // a selection, for the ops that want one
16466            op(&mut d);
16467            assert_eq!(d.source, src, "{name} edited an HTML document");
16468            assert!(
16469                !d.dirty,
16470                "{name} marked the document dirty without editing it"
16471            );
16472            let status = d.status.as_deref().unwrap_or("");
16473            assert!(
16474                status.contains("html"),
16475                "{name}: the refusal should name the format, got {status:?}"
16476            );
16477        }
16478    }
16479
16480    #[test]
16481    fn html_spells_a_quote_a_list_a_link_and_an_image_through_the_renderer() {
16482        // twig 3.5: where HTML has no marker alphabet it prints the fresh
16483        // node — a `<blockquote>` around the paragraph, a `<ul>`/`<ol>` with
16484        // the paragraph as its item, an `<a>` or `<img>` over the selection.
16485        // Until then every one of these was a refusal; now each is a real
16486        // edit, which is what the toolbar's capability flags say too.
16487        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16488        #[allow(clippy::type_complexity)]
16489        let ops: [(&str, &dyn Fn(&mut Doc), &str); 5] = [
16490            (
16491                "quote",
16492                &|d: &mut Doc| d.toggle_blockquote(),
16493                "<blockquote>",
16494            ),
16495            ("list", &|d: &mut Doc| d.toggle_list(false), "<ul>\n<li>"),
16496            (
16497                "ordered list",
16498                &|d: &mut Doc| d.toggle_list(true),
16499                "<ol>\n<li>",
16500            ),
16501            (
16502                "link",
16503                &|d: &mut Doc| d.insert_link("https://example.dev"),
16504                "<a href=\"https://example.dev\">Hello</a>",
16505            ),
16506            (
16507                "image",
16508                &|d: &mut Doc| d.insert_image("pic.png", "alt"),
16509                "<img alt=\"Hello\" src=\"pic.png\">",
16510            ),
16511        ];
16512        for (name, op, expect) in ops {
16513            let mut d = html_doc(src);
16514            let at = d.source.find("Hello").unwrap();
16515            d.caret = at;
16516            d.anchor = Some(at + 5);
16517            op(&mut d);
16518            assert!(d.source.contains(expect), "{name}: got {:?}", d.source);
16519            assert!(d.dirty, "{name}: a real edit");
16520            assert_eq!(
16521                d.status, None,
16522                "{name}: a supported gesture reports nothing"
16523            );
16524        }
16525    }
16526
16527    #[test]
16528    fn html_spells_a_heading_as_its_tag_pair() {
16529        // twig 3.4 rebuilds a heading or paragraph as its tag pair, attributes
16530        // along — the one block gesture whose HTML shape it can write. So ⌘2
16531        // in an HTML document is a real edit, and ⌘0 takes it back.
16532        let src = "<h1>Title</h1>\n<p>Hello world</p>\n";
16533        let mut d = html_doc(src);
16534        d.caret = d.source.find("Hello").unwrap();
16535        d.toggle_heading(2);
16536        assert_eq!(d.source, "<h1>Title</h1>\n<h2>Hello world</h2>\n");
16537        assert!(d.dirty);
16538        assert_eq!(d.status, None, "a supported gesture reports nothing");
16539        d.toggle_heading(2);
16540        assert_eq!(d.source, src, "the same level again is back to a paragraph");
16541    }
16542
16543    #[test]
16544    fn html_spells_the_inline_marks_and_the_rule() {
16545        // The other half, and why one per-document flag stopped being enough:
16546        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
16547        // already emits and the parser reads straight back as the same mark —
16548        // and the rule button writes an `<hr>`. Refusing these on the old
16549        // "HTML is parse-only" reading would now be leaf's own limitation.
16550        let mut d = html_doc("<p>Hello world</p>\n");
16551        let at = d.source.find("world").unwrap();
16552        d.caret = at;
16553        d.anchor = Some(at + 5);
16554        d.toggle(InlineKind::Strong);
16555        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
16556        assert!(d.dirty);
16557        assert_eq!(d.status, None, "a supported gesture reports nothing");
16558
16559        // And off again — the toggle reverses, which is the property that makes
16560        // authoring in HTML worth offering rather than a one-way trip.
16561        d.toggle(InlineKind::Strong);
16562        assert_eq!(d.source, "<p>Hello world</p>\n");
16563
16564        let mut d = html_doc("<p>Hello world</p>\n");
16565        d.caret = d.source.find("world").unwrap();
16566        d.insert_thematic_break();
16567        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
16568    }
16569
16570    #[test]
16571    fn a_mark_the_format_cannot_spell_arms_nothing() {
16572        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
16573        // sticky mark for the next text typed. Guarding only the twig call
16574        // leaves that path live, promising a mark the gesture will not write and
16575        // then swallowing the error inside `insert`.
16576        //
16577        // Markdown carries this, on the superscript now rather than on the
16578        // highlight: `^x^` is text there in any configuration, whereas twig
16579        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
16580        // which every leaf document does.
16581        let mut d = doc_with("mark", "Hello world\n");
16582        d.view = View::Wysiwyg;
16583        d.build_visual(80);
16584        d.caret = d.source.find("world").unwrap();
16585        d.toggle(InlineKind::Superscript);
16586        assert!(d.pending_marks.is_empty(), "no mark should be armed");
16587        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
16588        d.insert("X");
16589        assert_eq!(d.source, "Hello Xworld\n");
16590    }
16591
16592    #[test]
16593    fn markdown_authors_a_highlight_and_a_strikethrough() {
16594        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
16595        // write. `==x==` is authorable because leaf's own `parse_extensions`
16596        // turns `highlight` on — twig will only mint bytes this editor's reparse
16597        // reads back — and `~~x~~` because GFM strikethrough is parsed by
16598        // default, so the refusal there was never right for any leaf document.
16599        // twig 3.10 adds the underline, spelled `<u>x</u>` and paired back into
16600        // an `insert` under the `html_elements` leaf parses with.
16601        for (kind, marked) in [
16602            (InlineKind::Mark, "a ==word== b\n"),
16603            (InlineKind::Delete, "a ~~word~~ b\n"),
16604            (InlineKind::Insert, "a <u>word</u> b\n"),
16605        ] {
16606            let mut d = doc_with("author_mark", "a word b\n");
16607            d.anchor = Some(2);
16608            d.caret = 6;
16609            d.toggle(kind);
16610            assert_eq!(d.source, marked, "{kind:?}");
16611            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
16612            assert!(d.dirty, "{kind:?}");
16613            // The region stays selected, so the second press reverses it — the
16614            // property that separates authoring from a one-way trip.
16615            d.toggle(kind);
16616            assert_eq!(d.source, "a word b\n", "{kind:?}");
16617        }
16618    }
16619
16620    #[test]
16621    fn an_authored_highlight_reads_back_as_a_mark() {
16622        // The round trip the extension gate exists to protect: what the toggle
16623        // writes, the reparse must read back as a `mark` rather than as two
16624        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
16625        // rebuilt map rather than from the source text.
16626        let mut d = doc_with("mark_roundtrip", "a word b\n");
16627        d.view = View::Wysiwyg;
16628        d.build_visual(80);
16629        d.anchor = Some(2);
16630        d.caret = 6;
16631        d.toggle(InlineKind::Mark);
16632        assert_eq!(d.source, "a ==word== b\n");
16633        d.build_visual(80);
16634        let w = d
16635            .vmap
16636            .rows
16637            .iter()
16638            .flat_map(|r| r.glyphs.iter())
16639            .find(|g| g.ch == 'w')
16640            .expect("the highlighted word");
16641        assert_eq!(w.style.role, crate::Role::Mark(None));
16642    }
16643
16644    #[test]
16645    fn an_authored_underline_reads_back_as_an_insert() {
16646        // The same round trip for `<u>…</u>`: under `html_elements` the tag pair
16647        // is one `insert`, so the word is underlined and the tags are markup the
16648        // caret-off line hides — not two `raw_inline` runs drawn as literal
16649        // HTML around plain text.
16650        let mut d = doc_with("underline_roundtrip", "a word b\nnext\n");
16651        d.view = View::Wysiwyg;
16652        d.build_visual(80);
16653        d.anchor = Some(2);
16654        d.caret = 6;
16655        d.toggle(InlineKind::Insert);
16656        assert_eq!(d.source, "a <u>word</u> b\nnext\n");
16657        d.anchor = None;
16658        d.caret = d.source.find("next").unwrap();
16659        d.build_visual(80);
16660        let glyphs: Vec<_> = d.vmap.rows.iter().flat_map(|r| r.glyphs.iter()).collect();
16661        let w = glyphs
16662            .iter()
16663            .find(|g| g.ch == 'w')
16664            .expect("the underlined word");
16665        assert!(w.style.underline);
16666        assert!(!glyphs.iter().any(|g| g.ch == '<'), "the tags are hidden");
16667    }
16668
16669    #[test]
16670    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
16671        // The three states of one gesture, in the order a palette is pressed:
16672        // an uncoloured highlight takes the prefix, a coloured one has it
16673        // replaced, and `None` takes it away with the space that was part of the
16674        // spelling.
16675        let mut d = doc_with("mark_colour", "a ==word== b\n");
16676        d.caret = d.source.find("word").unwrap();
16677        d.set_mark_color(Some(MarkColor::Red));
16678        assert_eq!(d.source, "a ==🔴 word== b\n");
16679        assert_eq!(d.status, None);
16680        assert!(d.dirty);
16681
16682        d.set_mark_color(Some(MarkColor::Blue));
16683        assert_eq!(d.source, "a ==🔵 word== b\n");
16684
16685        d.set_mark_color(None);
16686        assert_eq!(d.source, "a ==word== b\n");
16687    }
16688
16689    #[test]
16690    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
16691        // The prefix is written *before* the word, so an offset in the word has
16692        // to ride its width — a caret that stayed put would be a caret that
16693        // walked backwards through the text it was standing in.
16694        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
16695        let word = d.source.find("word").unwrap();
16696        d.caret = word + 2; // between `wo` and `rd`
16697        d.set_mark_color(Some(MarkColor::Red));
16698        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
16699
16700        // And back the other way when the prefix goes.
16701        d.set_mark_color(None);
16702        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
16703    }
16704
16705    #[test]
16706    fn the_colour_at_the_caret_is_what_the_palette_lights() {
16707        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
16708        d.caret = d.source.find("red").unwrap();
16709        assert!(d.caret_in_mark());
16710        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
16711
16712        d.caret = d.source.find("plain").unwrap();
16713        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
16714        assert_eq!(d.mark_color_at_caret(), None);
16715
16716        d.caret = d.source.find(" and ").unwrap() + 2;
16717        assert!(!d.caret_in_mark());
16718        assert_eq!(d.mark_color_at_caret(), None);
16719    }
16720
16721    #[test]
16722    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
16723        // The gesture colours a highlight that exists; it does not make one.
16724        // Two presses is the price of a coloured highlight from bare text, and
16725        // the reason is undo — one press that spliced twice would take two
16726        // presses to take back.
16727        let mut d = doc_with("mark_colour_none", "a word b\n");
16728        d.caret = d.source.find("word").unwrap();
16729        d.set_mark_color(Some(MarkColor::Red));
16730        assert_eq!(d.source, "a word b\n");
16731        assert!(d.status.is_some(), "it should say why");
16732        assert!(!d.dirty);
16733
16734        // Clearing where there is nothing to clear is the same refusal, not a
16735        // quiet success — the caret is in no highlight either way.
16736        d.status = None;
16737        d.set_mark_color(None);
16738        assert_eq!(d.source, "a word b\n");
16739        assert!(d.status.is_some());
16740    }
16741
16742    #[test]
16743    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
16744        // twig answers this one *successfully* with a `Change` describing some
16745        // earlier edit, so a caller that trusted the change would jump the caret
16746        // to wherever that was. Core answers it before asking.
16747        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
16748        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
16749        d.caret = d.source.find("word").unwrap();
16750        let (source, caret) = (d.source.clone(), d.caret);
16751        d.set_mark_color(None);
16752        assert_eq!(d.source, source);
16753        assert_eq!(
16754            d.caret, caret,
16755            "the caret must not ride a change that isn't one"
16756        );
16757        assert_eq!(d.status, None, "and it is not an error either");
16758    }
16759
16760    #[test]
16761    fn djot_spells_the_highlight_and_not_its_colour() {
16762        // The reason the palette is its own capability rather than the Highlight
16763        // button's: `{=word=}` is a highlight djot writes happily, and there is
16764        // no djot spelling for a colour on it.
16765        assert!(Capabilities::of(Format::Djot).mark);
16766        assert!(!Capabilities::of(Format::Djot).mark_color);
16767        assert!(Capabilities::of(Format::Markdown).mark_color);
16768
16769        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
16770        d.caret = d.source.find("word").unwrap();
16771        assert!(
16772            d.caret_in_mark(),
16773            "the caret is in a highlight all the same"
16774        );
16775        d.set_mark_color(Some(MarkColor::Red));
16776        assert_eq!(d.source, "a {=word=} b\n");
16777        assert!(
16778            d.status.as_deref().unwrap_or("").contains("djot"),
16779            "and the refusal names the document's format: {:?}",
16780            d.status
16781        );
16782    }
16783
16784    #[test]
16785    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
16786        // The round trip that matters for a palette: the bytes twig writes are
16787        // bytes its own reparse reads back as a colour, so the swatch that was
16788        // pressed is the swatch that lights afterwards.
16789        let mut d = doc_with("mark_colour_undo", "a word b\n");
16790        d.anchor = Some(2);
16791        d.caret = 6;
16792        d.toggle(InlineKind::Mark);
16793        d.caret = d.source.find("word").unwrap();
16794        d.set_mark_color(Some(MarkColor::Green));
16795        assert_eq!(d.source, "a ==🟢 word== b\n");
16796        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
16797
16798        // One splice, one step: the colour comes off and the highlight stays.
16799        d.undo();
16800        assert_eq!(d.source, "a ==word== b\n");
16801        d.undo();
16802        assert_eq!(d.source, "a word b\n");
16803    }
16804
16805    #[test]
16806    fn every_colour_leaf_names_is_one_twig_writes() {
16807        // The two enums are one vocabulary, and this is what says so: each of
16808        // leaf's colours writes an emoji twig's reparse reads back as *that*
16809        // colour, so `twig_mark_color`'s table cannot quietly pair red with
16810        // orange.
16811        for color in MarkColor::ALL {
16812            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
16813            d.caret = d.source.find("word").unwrap();
16814            d.set_mark_color(Some(color));
16815            assert_eq!(d.status, None, "{color:?}");
16816            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
16817        }
16818    }
16819
16820    #[test]
16821    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
16822        // The two presses a coloured highlight is made of, in the state the
16823        // first one leaves: `toggle` selects the whole `==word==` and puts the
16824        // caret one past the closing `==`, which is *not* in the mark. Asking at
16825        // the caret alone would refuse to colour the highlight just written —
16826        // the selection's start is what answers.
16827        let mut d = doc_with("mark_colour_fresh", "a word b\n");
16828        d.anchor = Some(2);
16829        d.caret = 6;
16830        d.toggle(InlineKind::Mark);
16831        assert_eq!(d.source, "a ==word== b\n");
16832        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
16833
16834        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
16835        d.set_mark_color(Some(MarkColor::Yellow));
16836        assert_eq!(d.source, "a ==🟡 word== b\n");
16837        assert_eq!(d.status, None);
16838    }
16839
16840    #[test]
16841    fn one_press_highlights_a_selection_and_colours_it() {
16842        // What a toolbar swatch means over a plain selection, and the undo it
16843        // has to have: one press, one step. Two steps would leave an uncoloured
16844        // highlight behind on the way back, which is a state the author never
16845        // asked for and never saw.
16846        let mut d = doc_with("highlight_one", "a word b\n");
16847        d.anchor = Some(2);
16848        d.caret = 6;
16849        d.highlight(Some(MarkColor::Purple));
16850        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
16851        assert_eq!(d.status, None);
16852
16853        d.undo();
16854        assert_eq!(d.source, "a word b\n", "one press, one undo");
16855    }
16856
16857    #[test]
16858    fn one_press_on_an_existing_highlight_only_recolours_it() {
16859        // The other half: inside a highlight there is nothing to make, so the
16860        // compound is the plain gesture and the text is untouched.
16861        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
16862        d.caret = d.source.find("word").unwrap();
16863        d.highlight(Some(MarkColor::Blue));
16864        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
16865        d.undo();
16866        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
16867    }
16868
16869    #[test]
16870    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
16871        // `None` means "no colour", and over bare text that is the Highlight
16872        // button's own job. The fold must not happen here — there is no second
16873        // splice, and folding would take the *previous* edit into this one.
16874        let mut d = doc_with("highlight_none", "a word b and more\n");
16875        d.caret = d.source.find("more").unwrap() + 4; // after "more"
16876        d.insert("!"); // an earlier edit for a wrong fold to swallow
16877        d.anchor = Some(2);
16878        d.caret = 6;
16879        d.highlight(None);
16880        assert_eq!(d.source, "a ==word== b and more!\n");
16881
16882        d.undo();
16883        assert_eq!(
16884            d.source, "a word b and more!\n",
16885            "only the highlight came off"
16886        );
16887        d.undo();
16888        assert_eq!(
16889            d.source, "a word b and more\n",
16890            "and the edit before it survived"
16891        );
16892    }
16893
16894    #[test]
16895    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
16896        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
16897        // a colour cannot be armed with it — so the compound declines rather
16898        // than leaving half a promise.
16899        let mut d = doc_with("highlight_bare", "a word b\n");
16900        d.caret = 4;
16901        d.highlight(Some(MarkColor::Red));
16902        assert_eq!(d.source, "a word b\n");
16903        assert!(d.pending_marks.is_empty(), "and nothing armed");
16904        assert!(d.status.is_some());
16905    }
16906
16907    #[test]
16908    fn a_read_only_document_takes_no_colour() {
16909        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
16910        d.caret = d.source.find("word").unwrap();
16911        d.set_read_only(true);
16912        d.set_mark_color(Some(MarkColor::Red));
16913        assert_eq!(d.source, "a ==word== b\n");
16914    }
16915
16916    #[test]
16917    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
16918        // The other door into `toggle`: no selection, so nothing reaches twig
16919        // until `insert` realises the armed mark. It is armed now — the guard
16920        // above asks `Doc::supports`, which asks with the extensions — and what
16921        // it writes is the same `==…==`.
16922        let mut d = doc_with("sticky_mark", "xy\n");
16923        d.caret = 1;
16924        d.toggle(InlineKind::Mark);
16925        assert!(d.pending_marks.contains(InlineKind::Mark));
16926        d.insert("Z");
16927        assert_eq!(d.source, "x==Z==y\n");
16928    }
16929
16930    #[test]
16931    fn html_documents_still_take_typed_text() {
16932        // The guard covers *markup* gestures and must not touch plain editing:
16933        // twig's splicer is language-neutral, and typing into an HTML document
16934        // is the thing that does work today.
16935        let mut d = html_doc("<p>Hello world</p>\n");
16936        d.caret = d.source.find("world").unwrap();
16937        d.insert("big ");
16938        assert_eq!(d.source, "<p>Hello big world</p>\n");
16939        assert!(d.dirty);
16940        d.backspace();
16941        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
16942        d.undo();
16943        d.undo();
16944        assert_eq!(d.source, "<p>Hello world</p>\n");
16945    }
16946
16947    #[test]
16948    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
16949        // `authorable` only separates "there is a door in" from "there is not",
16950        // and HTML is on the near side of that line — which is exactly why a
16951        // toolbar must not be built from it.
16952        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
16953        assert!(html.authorable());
16954        assert!(
16955            !Doc::from_source("<r>x</r>".into(), Format::Xml)
16956                .unwrap()
16957                .authorable()
16958        );
16959
16960        let caps = html.capabilities();
16961        assert!(caps.bold && caps.italic && caps.code && caps.mark);
16962        assert!(caps.thematic_break && caps.cell_line_break);
16963        // A heading is a tag pair twig rebuilds (3.4), and since 3.5 so are a
16964        // quote, a list, a code block's language, a link and an image — each
16965        // printed as a fresh node where HTML has no marker to rewrite. A task
16966        // box is a form control and a footnote has no spelling, so those two
16967        // are what keeps the record ragged.
16968        assert!(caps.heading && caps.blockquote && caps.bullet_list);
16969        assert!(caps.link && caps.image && caps.code_language);
16970        assert!(!caps.task && !caps.footnote);
16971        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
16972        // twig's table editor would happily re-emit as `| a | b |`.
16973        assert!(!caps.table);
16974
16975        // The two lightweight formats spell everything leaf offers — and still
16976        // differ from each other, which is the other half of why one boolean
16977        // can't serve.
16978        for fmt in [Format::Markdown, Format::Djot] {
16979            let caps = Capabilities::of(fmt);
16980            assert!(
16981                caps.heading && caps.blockquote && caps.ordered_list,
16982                "{fmt:?}"
16983            );
16984            assert!(
16985                caps.task && caps.link && caps.image && caps.table,
16986                "{fmt:?}"
16987            );
16988        }
16989        // Both spell the highlight, the strikethrough and the underline: djot
16990        // natively, and Markdown because `Capabilities` asks with
16991        // `parse_extensions` rather than with twig's defaults — `==x==` is text
16992        // under those, and a mark under the `highlight` leaf always parses
16993        // with; `<u>x</u>` likewise pairs into an `insert` only under
16994        // `html_elements`.
16995        for fmt in [Format::Markdown, Format::Djot] {
16996            let caps = Capabilities::of(fmt);
16997            assert!(caps.mark && caps.strike && caps.underline, "{fmt:?}");
16998        }
16999        // What still separates them, now that the highlight doesn't: djot has
17000        // no in-cell break, and Markdown spells neither of the scripts.
17001        assert!(Capabilities::of(Format::Djot).superscript);
17002        assert!(!Capabilities::of(Format::Markdown).superscript);
17003        assert!(Capabilities::of(Format::Markdown).cell_line_break);
17004        assert!(!Capabilities::of(Format::Djot).cell_line_break);
17005
17006        // A parse-only format answers no to every one of them, so the coarse
17007        // predicate and the record agree there.
17008        let caps = Capabilities::of(Format::Xml);
17009        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
17010    }
17011
17012    #[test]
17013    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
17014        // The guard exists to name the *document's* format rather than twig's
17015        // internals, so the message has to survive being one leaf writes itself.
17016        // Checked against a gesture twig also refuses, since that is the pair
17017        // most at risk of drifting apart — the task box, once the code
17018        // language stopped being one (twig 3.5).
17019        let mut d = html_doc("<p>Hello</p>\n");
17020        d.caret = d.source.find("Hello").unwrap();
17021        d.toggle_task_item();
17022        assert_eq!(d.status.as_deref(), Some("task: not supported in html"));
17023        assert!(!d.dirty);
17024    }
17025
17026    #[test]
17027    fn table_set_alignment_respells_the_delimiter() {
17028        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
17029        d.caret = d.source.find('b').unwrap();
17030        d.table_set_alignment(Alignment::Right);
17031        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
17032    }
17033
17034    #[test]
17035    fn each_empty_table_cell_has_its_own_editable_home() {
17036        // Regression: an empty cell has no twig content_span, so both cells of a
17037        // `|  |  |` row collapsed onto the row's start (before the first `│`).
17038        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
17039        // tell the cells apart. Each empty cell must now have a distinct home
17040        // inside it.
17041        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
17042        let (c0, c1) = {
17043            let cells = &d.vmap.tables[0].grid[1].cells;
17044            (cells[0].start, cells[1].start)
17045        };
17046        assert!(
17047            c0 < c1,
17048            "the two empty cells have distinct homes: {c0} < {c1}"
17049        );
17050        d.caret = c0;
17051        d.insert("x");
17052        assert_eq!(
17053            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
17054            "typed inside the cell"
17055        );
17056    }
17057
17058    #[test]
17059    fn arrows_step_into_each_empty_table_cell() {
17060        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
17061        let (c0, c1) = {
17062            let cells = &d.vmap.tables[0].grid[1].cells;
17063            (cells[0].start, cells[1].start)
17064        };
17065        d.caret = d.source.find('b').unwrap(); // in the header's second cell
17066        let mut seen = std::collections::HashSet::new();
17067        for _ in 0..6 {
17068            d.move_right(false);
17069            seen.insert(d.caret);
17070        }
17071        assert!(
17072            seen.contains(&c0),
17073            "right arrow reaches the first empty cell"
17074        );
17075        assert!(
17076            seen.contains(&c1),
17077            "right arrow reaches the second empty cell"
17078        );
17079    }
17080
17081    #[test]
17082    fn table_op_off_a_table_is_a_no_op_with_a_status() {
17083        let mut d = doc_with("tbl_none", "just text\n");
17084        d.caret = 3;
17085        d.table_insert_row(true);
17086        assert_eq!(d.source, "just text\n", "nothing changed");
17087        assert!(d.status.is_some(), "a status explains why");
17088        assert!(!d.caret_in_table());
17089    }
17090
17091    #[test]
17092    fn enter_in_an_ordered_list_renumbers_the_following_items() {
17093        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
17094        // the renumber pass keeps them sequential, matching what the view draws.
17095        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
17096        d.caret = d.source.find('a').unwrap() + 1; // end of item a
17097        d.newline();
17098        d.insert("x");
17099        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
17100    }
17101
17102    #[test]
17103    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
17104        for view in [View::Source, View::Wysiwyg] {
17105            let mut d = doc_in(view, "outdent_noop", "hello\n");
17106            d.caret = 2;
17107            d.outdent();
17108            assert_eq!(d.source, "hello\n");
17109            assert!(!d.dirty, "a no-op is not a modification");
17110            d.undo();
17111            assert_eq!(
17112                d.status.as_deref(),
17113                Some("nothing to undo"),
17114                "spends no undo step"
17115            );
17116            assert_eq!(d.source, "hello\n");
17117        }
17118    }
17119
17120    #[test]
17121    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
17122        for view in [View::Source, View::Wysiwyg] {
17123            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
17124            d.anchor = Some(0);
17125            d.caret = 7; // through "two"
17126            d.indent();
17127            assert_eq!(
17128                d.source, "  one\n\n  two\n",
17129                "the blank line keeps no trailing pad"
17130            );
17131            // Selected, so a second Tab lands on the same lines rather than on
17132            // whatever the shifted offsets now cover.
17133            assert_eq!(d.selection(), Some((0, 12)));
17134            d.indent();
17135            assert_eq!(d.source, "    one\n\n    two\n");
17136        }
17137    }
17138
17139    #[test]
17140    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
17141        for view in [View::Source, View::Wysiwyg] {
17142            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
17143            d.anchor = Some(0);
17144            d.caret = 15;
17145            d.outdent();
17146            assert_eq!(d.source, "two\none\nnone\n");
17147        }
17148    }
17149
17150    #[test]
17151    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
17152        for view in [View::Source, View::Wysiwyg] {
17153            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
17154            d.anchor = Some(0);
17155            d.caret = 7;
17156            d.indent();
17157            assert_eq!(d.source, "  one\n\n  two\n");
17158            d.undo();
17159            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
17160            assert_eq!(
17161                d.selection(),
17162                Some((0, 7)),
17163                "with the selection it was aimed at"
17164            );
17165            d.redo();
17166            assert_eq!(d.source, "  one\n\n  two\n");
17167            assert_eq!(
17168                d.selection(),
17169                Some((0, 12)),
17170                "redo replays the caret the indent placed, not the one splice left"
17171            );
17172        }
17173    }
17174
17175    #[test]
17176    fn vertical_motion_keeps_the_column() {
17177        let mut d = doc_with("move", "abcd\nef\n");
17178        d.caret = 3; // "abc|d" on row 0, col 3
17179        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
17180        assert_eq!(d.caret, 7); // just after "ef"
17181    }
17182
17183    // ── goal column ──────────────────────────────────────────────────────────
17184
17185    #[test]
17186    fn vertical_motion_goal_column_survives_a_short_line() {
17187        // Regression: re-deriving the column from the clamped position on
17188        // every step permanently forgets it once a short line clamps it.
17189        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
17190        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
17191        assert_eq!(
17192            g("abcd|ef\nxy\nghijkl\n", |d| {
17193                d.move_down(false); // clamps to end of "xy"
17194                d.move_down(false); // restores col 4 on the long line
17195            }),
17196            "abcdef\nxy\nghij|kl\n"
17197        );
17198    }
17199
17200    #[test]
17201    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
17202        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
17203        assert_eq!(d.goal_col, None);
17204        d.caret = 4; // row 0, col 4
17205        d.move_down(false); // clamps into "xy"; goal stays the original col
17206        assert_eq!(d.goal_col, Some(4));
17207        assert_eq!(d.caret_pos(), (1, 2));
17208
17209        // A horizontal motion drops the goal column...
17210        d.move_left(false);
17211        assert_eq!(d.goal_col, None);
17212
17213        // ...so the next vertical motion picks up the *new* column (1), not
17214        // the stale one (4).
17215        d.move_down(false);
17216        assert_eq!(d.goal_col, Some(1));
17217        assert_eq!(d.caret_pos(), (2, 1));
17218    }
17219
17220    #[test]
17221    fn editing_clears_the_goal_column() {
17222        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
17223        d.caret = 4;
17224        d.move_down(false);
17225        assert_eq!(d.goal_col, Some(4));
17226        d.insert("Z");
17227        assert_eq!(d.goal_col, None);
17228    }
17229
17230    #[test]
17231    fn vertical_motion_on_an_empty_document_is_a_no_op() {
17232        let mut d = doc_with("empty_vert", "");
17233        d.move_down(false);
17234        assert_eq!(d.caret, 0);
17235        d.move_up(false);
17236        assert_eq!(d.caret, 0);
17237    }
17238
17239    // ── the document's edges ─────────────────────────────────────────────────
17240
17241    #[test]
17242    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
17243        // The reproduction, and the disagreement: Down on the last line ran to
17244        // the end of the document in the source view — by accident, an
17245        // out-of-range row clamping to the end of the string — and did nothing
17246        // whatever in the view leaf opens in. One rule now, in both.
17247        for (view, tag) in VIEWS {
17248            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
17249            d.caret = 1;
17250            d.move_down(false);
17251            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
17252            d.move_up(false);
17253            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
17254        }
17255    }
17256
17257    #[test]
17258    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
17259        // Down off the bottom is a motion like any other, so it latches a goal
17260        // column — and Up comes back to the column the caret left, not to the
17261        // one the document's end happened to be in.
17262        for (view, tag) in VIEWS {
17263            let gap = if view == View::Source { "\n" } else { "\n\n" };
17264            let src = format!("abcdef{gap}ghijkl");
17265            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
17266            d.caret = 2; // row 0, col 2
17267            d.move_down(false);
17268            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
17269            d.move_down(false);
17270            assert_eq!(
17271                d.caret,
17272                src.len(),
17273                "{tag}: Down off the bottom reaches the end"
17274            );
17275            d.move_up(false);
17276            assert_eq!(
17277                d.caret_pos().1,
17278                2,
17279                "{tag}: Up returns to the column Down left"
17280            );
17281        }
17282    }
17283
17284    #[test]
17285    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
17286        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
17287        // Up that did nothing still armed a goal column, and the next Down aimed
17288        // at a column the caret had never been in.
17289        for (view, tag) in VIEWS {
17290            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
17291            d.caret = 0;
17292            d.move_up(false);
17293            assert_eq!(d.caret, 0, "{tag}: already at the start");
17294            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
17295
17296            d.caret = d.source.len();
17297            d.move_down(false);
17298            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
17299            assert_eq!(
17300                d.goal_col, None,
17301                "{tag}: a no-op Down latched a goal column"
17302            );
17303        }
17304    }
17305
17306    // ── soft wrap ────────────────────────────────────────────────────────────
17307    // Every other test here builds the map at 80 columns, where no fixture is
17308    // long enough to fold. A wrap is where one offset belongs to two rows at
17309    // once, and it broke everything that asks the caret what row it is on.
17310
17311    /// The wrapped fixture these cases share, folded at 12 columns into
17312    /// `one two ` / `three four ` / `five six ` / `seven eight`.
17313    fn wrapped_doc(name: &str) -> Doc {
17314        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
17315        d.build_visual(12);
17316        d
17317    }
17318
17319    #[test]
17320    fn home_and_end_work_from_a_wrapped_row() {
17321        // The reproduction: offset 19 is the `f` of "five", the first character
17322        // of the third row — and also the offset the second row ends at. It
17323        // resolved to the *second* row, so End aimed at a place the caret was
17324        // already in and did nothing, while Home walked backwards onto a row the
17325        // caret had left.
17326        let mut d = wrapped_doc("wrap_home_end");
17327        d.caret = 19;
17328        assert_eq!(
17329            d.caret_pos(),
17330            (2, 0),
17331            "the wrap boundary opens the third row"
17332        );
17333        d.move_end(false);
17334        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
17335        d.move_home(false);
17336        assert_eq!(d.caret, 19, "Home left the row the caret was on");
17337    }
17338
17339    #[test]
17340    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
17341        // The row's end is the last offset that is only ever its own: the offset
17342        // past it opens the row below, and aiming there would send a second
17343        // press on to *that* row's end, and a third to the next — End walking
17344        // down the paragraph rather than sitting where it landed.
17345        let mut d = wrapped_doc("wrap_end_twice");
17346        d.caret = 12; // inside "three", on the second row
17347        d.move_end(false);
17348        assert_eq!(
17349            d.caret, 18,
17350            "the end of `three four`, before the space the wrap ate"
17351        );
17352        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
17353        d.move_end(false);
17354        assert_eq!(d.caret, 18, "a second End moved the caret");
17355        d.move_home(false);
17356        assert_eq!(d.caret, 8, "Home takes the row's own start");
17357    }
17358
17359    #[test]
17360    fn vertical_motion_crosses_a_soft_wrap() {
17361        // Down aimed at the row below's column 0, an offset that resolved *up*
17362        // to the row above's end — so it landed on the offset it already had and
17363        // the caret could never leave a paragraph's first row.
17364        let mut d = wrapped_doc("wrap_down");
17365        d.caret = 0;
17366        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
17367            d.move_down(false);
17368            assert_eq!(d.caret, want, "Down stalled");
17369            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
17370        }
17371        d.move_down(false);
17372        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
17373
17374        // ...and back up, one row per press. The goal column is the end of the
17375        // last row, past every other row's width, so each press clamps to the
17376        // row's own last offset rather than to the one that opens the next.
17377        let mut d = wrapped_doc("wrap_up");
17378        d.caret = 39;
17379        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
17380            d.move_up(false);
17381            assert_eq!(d.caret, want, "Up stalled");
17382            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
17383        }
17384    }
17385
17386    #[test]
17387    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
17388        // The kills take the same line Home and End do, so in WYSIWYG they take
17389        // the visual row — and a soft wrap has no newline in it to delete, so
17390        // nothing is joined by reaching the end of one.
17391        let mut d = wrapped_doc("wrap_kill");
17392        d.caret = 19; // the `f` of "five", opening the third row
17393        d.delete_to_line_end();
17394        // The space the wrap ate goes with the row it was drawn on: sparing it
17395        // would leave "four  seven", two spaces where the row had been.
17396        assert_eq!(d.source, "one two three four seven eight");
17397
17398        // Backwards from the row's last caret position — which is *before* that
17399        // space, so this one survives, being on the far side of the caret.
17400        let mut d = wrapped_doc("wrap_kill_back");
17401        d.caret = 27;
17402        d.delete_to_line_start();
17403        assert_eq!(d.source, "one two three four  seven eight");
17404    }
17405
17406    // ── document start / end ────────────────────────────────────────────────
17407
17408    #[test]
17409    fn move_doc_start_and_end_jump_to_the_edges() {
17410        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
17411        assert_eq!(
17412            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
17413            "|hello\nworld\n"
17414        );
17415        assert_eq!(
17416            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
17417            "hello\nworld\n|"
17418        );
17419        // Already at the edge: a no-op.
17420        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
17421        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
17422    }
17423
17424    #[test]
17425    fn move_doc_start_and_end_extend_the_selection() {
17426        assert_eq!(
17427            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
17428                .move_doc_end(true)),
17429            "hello wor[ld\n|]"
17430        );
17431        assert_eq!(
17432            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
17433                .move_doc_start(true)),
17434            "[|hello wor]ld\n"
17435        );
17436    }
17437
17438    #[test]
17439    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
17440        let mut d = doc_with("empty_edges", "");
17441        d.move_doc_end(false);
17442        assert_eq!(d.caret, 0);
17443        d.move_doc_start(false);
17444        assert_eq!(d.caret, 0);
17445    }
17446
17447    // ── arrow collapses an active selection ─────────────────────────────────
17448
17449    #[test]
17450    fn arrow_collapses_selection_to_its_near_edge() {
17451        let mut d = doc_with("collapse", "hello world\n");
17452
17453        // Forward selection (anchor before caret): Right -> end, Left -> start.
17454        d.anchor = Some(2);
17455        d.caret = 7;
17456        d.move_right(false);
17457        assert_eq!((d.caret, d.anchor), (7, None));
17458
17459        d.anchor = Some(2);
17460        d.caret = 7;
17461        d.move_left(false);
17462        assert_eq!((d.caret, d.anchor), (2, None));
17463
17464        // Backward selection (anchor after caret): edges are the same
17465        // regardless of which end the caret started on.
17466        d.anchor = Some(7);
17467        d.caret = 2;
17468        d.move_right(false);
17469        assert_eq!((d.caret, d.anchor), (7, None));
17470
17471        d.anchor = Some(7);
17472        d.caret = 2;
17473        d.move_left(false);
17474        assert_eq!((d.caret, d.anchor), (2, None));
17475    }
17476
17477    #[test]
17478    fn arrow_with_extend_keeps_growing_the_selection() {
17479        let mut d = doc_with("collapse_extend", "hello world\n");
17480        d.anchor = Some(2);
17481        d.caret = 7;
17482        d.move_right(true); // extend: no collapse, caret steps one further
17483        assert_eq!((d.caret, d.anchor), (8, Some(2)));
17484    }
17485
17486    #[test]
17487    fn arrow_without_a_selection_moves_one_character_as_before() {
17488        let mut d = doc_with("no_collapse", "hello\n");
17489        d.caret = 2;
17490        d.move_right(false);
17491        assert_eq!(d.caret, 3);
17492        d.move_left(false);
17493        assert_eq!(d.caret, 2);
17494    }
17495
17496    /// Press Right until it stops, collecting the offsets walked through. Every
17497    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
17498    /// two stops sharing one source offset can't be moved between, so the caret
17499    /// stalls on the first of them and the walk never reaches the rest.
17500    fn walk_right(d: &mut Doc) -> Vec<usize> {
17501        let mut seen = vec![d.caret];
17502        for _ in 0..2000 {
17503            let before = d.caret;
17504            d.move_right(false);
17505            if d.caret == before {
17506                break;
17507            }
17508            seen.push(d.caret);
17509        }
17510        seen
17511    }
17512
17513    #[test]
17514    fn the_caret_crosses_a_soft_break() {
17515        // A newline inside a paragraph is a `soft_break`, which twig gives no
17516        // span of its own — the space it renders as used to borrow the offset of
17517        // the character before it, and a caret can't move without changing
17518        // offset. Right must walk clean off the end of the first line.
17519        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
17520        d.caret = 0;
17521        let seen = walk_right(&mut d);
17522        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17523    }
17524
17525    #[test]
17526    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
17527        // The paragraph holds one soft break. Folded (the default) it lays out as
17528        // a single reflowed row; Preserve re-lays it as a row per source line.
17529        // The setter must invalidate the cached map for the change to show, and
17530        // again on the way back — so a round trip returns to the folded layout.
17531        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
17532        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
17533        d.build_visual(80);
17534        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
17535
17536        d.set_line_flow(LineFlow::Preserve);
17537        d.build_visual(80);
17538        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
17539
17540        d.set_line_flow(LineFlow::Fold);
17541        d.build_visual(80);
17542        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
17543    }
17544
17545    #[test]
17546    fn the_caret_still_crosses_a_preserved_soft_break() {
17547        // Preserve renders the soft break as a row boundary rather than a space,
17548        // but the caret must still reach every offset — the break's own offset is
17549        // the first row's end stop, so Right walks clean off the end of line one
17550        // onto line two, exactly as it does when the break is folded.
17551        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
17552        d.set_line_flow(LineFlow::Preserve);
17553        d.build_visual(80);
17554        d.caret = 0;
17555        let seen = walk_right(&mut d);
17556        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17557    }
17558
17559    #[test]
17560    fn the_caret_walks_a_code_block() {
17561        // Every glyph of a code block used to map to the block's start, so the
17562        // whole block was a single offset and the caret couldn't move inside it.
17563        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
17564        let mut d = wysiwyg_doc("code_walk", src);
17565        d.caret = 0;
17566        let seen = walk_right(&mut d);
17567        // The fences are markup: hidden, and no caret stop. The code between
17568        // them is reached a character at a time.
17569        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
17570        for off in code.clone() {
17571            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
17572        }
17573        assert!(seen.contains(&code.end), "no stop after the last line");
17574    }
17575
17576    #[test]
17577    fn the_caret_walks_an_indented_code_block() {
17578        // An indented block's text has the four-space indent stripped, so it
17579        // isn't a verbatim slice and its lines have to be re-found. The caret
17580        // lands on the code, never in the indent.
17581        let src = "    indented\n    code\n";
17582        let mut d = wysiwyg_doc("indent_code_walk", src);
17583        d.caret = 0;
17584        let seen = walk_right(&mut d);
17585        assert!(seen.contains(&src.find("indented").unwrap()));
17586        assert!(seen.contains(&src.find("code").unwrap()));
17587        assert!(
17588            !seen.contains(&0) || seen[0] == 0,
17589            "the caret starts where it was put"
17590        );
17591        // Nothing in the stripped indent is a stop.
17592        for off in [1, 2, 3] {
17593            assert!(!seen.contains(&off), "landed in the indent at {off}");
17594        }
17595    }
17596
17597    #[test]
17598    fn the_caret_leaves_a_tight_heading() {
17599        // "# H" with text directly under it: the heading row's end and the
17600        // separator row's end are the same offset. Right used to find the
17601        // separator's copy, set the caret to where it already was, and stop.
17602        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
17603        d.caret = 2; // the "H"
17604        let seen = walk_right(&mut d);
17605        assert!(
17606            seen.len() > 2,
17607            "Right stalled at the heading's end: {seen:?}"
17608        );
17609        assert!(
17610            seen.contains(&8),
17611            "never reached the end of \"text\": {seen:?}"
17612        );
17613    }
17614
17615    #[test]
17616    fn the_caret_skips_the_gap_between_two_paragraphs() {
17617        // The blank line between two paragraphs is the boundary itself. The
17618        // caret used to be able to sit on it, and typing there landed in the
17619        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
17620        // soft break, so the text visibly snapped back up.
17621        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
17622        d.caret = 1; // the end of "A"
17623        d.move_right(false);
17624        assert_eq!(d.caret, 3, "Right stopped in the gap");
17625        d.insert("x");
17626        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
17627    }
17628
17629    #[test]
17630    fn down_from_a_paragraph_lands_on_the_next_one() {
17631        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
17632        d.caret = 0;
17633        d.move_down(false);
17634        assert_eq!(d.caret, 3, "Down stopped in the gap");
17635    }
17636
17637    #[test]
17638    fn clicking_the_gap_lands_on_real_text() {
17639        // A click can still *reach* the gap — it's drawn, so it's clickable.
17640        // It has to resolve to somewhere the caret can be.
17641        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
17642        d.click(1, 0, false); // the gap row
17643        assert!(
17644            d.caret == 1 || d.caret == 3,
17645            "click left the caret in the gap at {}",
17646            d.caret
17647        );
17648        d.insert("x");
17649        // Either edge of the boundary is a fair place to land; inside it isn't.
17650        assert!(
17651            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
17652            "click in the gap typed into the boundary: {:?}",
17653            d.source
17654        );
17655    }
17656
17657    #[test]
17658    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
17659        // Enter inserts a paragraph break, which leaves a blank line spare on
17660        // either side of a new one. That middle line is a real empty paragraph:
17661        // the caret lands there, and typing makes a paragraph rather than
17662        // extending a neighbour.
17663        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
17664        d.caret = 1;
17665        d.newline();
17666        assert_eq!(d.source, "A\n\n\n\nB\n");
17667        d.build_visual(80);
17668        let (row, _) = d.caret_pos();
17669        assert!(
17670            d.vmap.row_is_navigable(row),
17671            "the caret landed on a gap row"
17672        );
17673        d.insert("x");
17674        assert_eq!(
17675            d.source, "A\n\nx\n\nB\n",
17676            "the new paragraph merged into a neighbour"
17677        );
17678    }
17679
17680    #[test]
17681    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
17682        let mut d = wysiwyg_doc("gap_eof", "A\n");
17683        d.caret = 1;
17684        d.newline();
17685        d.build_visual(80);
17686        let (row, _) = d.caret_pos();
17687        assert!(
17688            d.vmap.row_is_navigable(row),
17689            "the caret landed on a gap row"
17690        );
17691        d.insert("x");
17692        assert!(
17693            d.source.starts_with("A\n\n") && d.source.contains('x'),
17694            "typing at the end merged into A: {:?}",
17695            d.source
17696        );
17697    }
17698
17699    // ── click_past_end ───────────────────────────────────────────────────────
17700
17701    /// [`Doc::click_past_end`] on `body`, and the source it left, with the caret
17702    /// rendered as `|`.
17703    fn past_end(name: &str, body: &str) -> (Doc, String) {
17704        let mut d = wysiwyg_doc(name, body);
17705        d.click_past_end();
17706        let out = render_caret(&d);
17707        (d, out)
17708    }
17709
17710    #[test]
17711    fn click_past_end_opens_an_empty_paragraph_under_the_last_block() {
17712        let (mut d, out) = past_end("pe_para", "A\n");
17713        assert_eq!(out, "A\n\n|");
17714        d.build_visual(80);
17715        let (row, _) = d.caret_pos();
17716        assert!(
17717            d.vmap.row_is_navigable(row),
17718            "the caret landed on a gap row"
17719        );
17720        d.insert("x");
17721        assert_eq!(d.source, "A\n\nx", "typing merged into A");
17722    }
17723
17724    #[test]
17725    fn click_past_end_writes_both_newlines_when_the_file_has_none() {
17726        assert_eq!(past_end("pe_bare", "A").1, "A\n\n|");
17727    }
17728
17729    #[test]
17730    fn click_past_end_is_only_a_caret_move_when_the_paragraph_is_already_there() {
17731        let (d, out) = past_end("pe_there", "A\n\n");
17732        assert_eq!(out, "A\n\n|");
17733        assert!(!d.dirty, "a click wrote to a document it did not need to");
17734        assert!(
17735            !d.can_undo(),
17736            "a click that changed nothing left an undo step"
17737        );
17738    }
17739
17740    #[test]
17741    fn click_past_end_leaves_a_closed_fence() {
17742        let (mut d, out) = past_end("pe_fence", "```\ncode\n```\n");
17743        assert_eq!(out, "```\ncode\n```\n\n|");
17744        d.build_visual(80);
17745        let (row, _) = d.caret_pos();
17746        assert!(!d.vmap.rows[row].code, "the caret is still on a code row");
17747        d.insert("x");
17748        assert_eq!(d.source, "```\ncode\n```\n\nx");
17749    }
17750
17751    #[test]
17752    fn click_past_end_closes_an_unclosed_fence_first() {
17753        assert_eq!(past_end("pe_open", "```\ncode\n").1, "```\ncode\n```\n\n|");
17754        assert_eq!(
17755            past_end("pe_open2", "````\ncode").1,
17756            "````\ncode\n````\n\n|"
17757        );
17758        assert_eq!(past_end("pe_tilde", "~~~\ncode\n").1, "~~~\ncode\n~~~\n\n|");
17759        assert_eq!(
17760            past_end("pe_quoted", "> ```\n> code\n").1,
17761            "> ```\n> code\n> ```\n\n|"
17762        );
17763    }
17764
17765    #[test]
17766    fn click_past_end_does_not_close_an_indented_block() {
17767        assert_eq!(past_end("pe_indent", "    code\n").1, "    code\n\n|");
17768    }
17769
17770    #[test]
17771    fn click_past_end_under_a_list_and_a_table_leaves_them() {
17772        let (mut d, out) = past_end("pe_list", "- a\n- b\n");
17773        assert_eq!(out, "- a\n- b\n\n|");
17774        d.insert("x");
17775        assert_eq!(d.source, "- a\n- b\n\nx", "typed into the list");
17776        assert_eq!(
17777            past_end("pe_table", "| a |\n|---|\n| b |\n").1,
17778            "| a |\n|---|\n| b |\n\n|"
17779        );
17780    }
17781
17782    #[test]
17783    fn click_past_end_on_an_empty_document_writes_nothing() {
17784        let (d, out) = past_end("pe_empty", "");
17785        assert_eq!(out, "|");
17786        assert!(!d.dirty);
17787    }
17788
17789    #[test]
17790    fn click_past_end_is_one_undo_step() {
17791        let (mut d, _) = past_end("pe_undo", "A\n");
17792        d.undo();
17793        assert_eq!(d.source, "A\n");
17794    }
17795
17796    #[test]
17797    fn click_past_end_in_the_source_view_only_moves_the_caret() {
17798        let mut d = doc_with("pe_source", "A\n");
17799        d.click_past_end();
17800        assert_eq!(render_caret(&d), "A\n|");
17801        assert!(!d.dirty);
17802    }
17803
17804    #[test]
17805    fn click_past_end_on_a_read_only_document_only_moves_the_caret() {
17806        let mut d = wysiwyg_doc("pe_ro", "A\n");
17807        d.set_read_only(true);
17808        d.click_past_end();
17809        assert_eq!(render_caret(&d), "A\n|");
17810    }
17811
17812    // ── toggle_code_block ────────────────────────────────────────────────────
17813
17814    #[test]
17815    fn toggle_code_block_fences_the_paragraph_at_the_caret_and_reverses() {
17816        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17817        assert_eq!(g("cb_on", "hel|lo\n"), "```\nhel|lo\n```\n");
17818        assert_eq!(g("cb_off", "```\nhel|lo\n```\n"), "hel|lo\n");
17819        assert_eq!(g("cb_end", "hello|\n"), "```\nhello|\n```\n");
17820        assert_eq!(
17821            g("cb_wrap", "aaa\nb|bb\nccc\n"),
17822            "```\naaa\nb|bb\nccc\n```\n"
17823        );
17824        assert_eq!(
17825            g("cb_unwrap", "```\naaa\nb|bb\nccc\n```\n"),
17826            "aaa\nb|bb\nccc\n"
17827        );
17828        // An indented block dedents, and the lines stay one-to-one.
17829        assert_eq!(g("cb_indent", "    co|de\n"), "co|de\n");
17830        // A quote's marker is kept on every line, the fence's included.
17831        assert_eq!(g("cb_quote", "> hel|lo\n"), "> ```\n> hel|lo\n> ```\n");
17832    }
17833
17834    #[test]
17835    fn toggle_code_block_on_a_blank_line_opens_an_empty_fence() {
17836        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17837        assert_eq!(g("cb_blank", "A\n\n|"), "A\n\n```\n|\n```");
17838        assert_eq!(
17839            g("cb_blank_mid", "A\n\n|\n\nB\n"),
17840            "A\n\n```\n|\n```\n\nB\n"
17841        );
17842        // Tight against a neighbour, a blank line goes in on that side.
17843        assert_eq!(g("cb_blank_tight", "A\n|\nB\n"), "A\n\n```\n|\n```\n\nB\n");
17844        // Inside a quote, on a quoted blank line.
17845        assert_eq!(
17846            g("cb_blank_quote", "> A\n>\n> |\n"),
17847            "> A\n>\n> ```\n> |\n> ```\n"
17848        );
17849    }
17850
17851    #[test]
17852    fn toggle_code_block_from_a_blank_line_is_a_block_the_caret_can_type_into() {
17853        let mut d = wysiwyg_doc("cb_type", "A\n\n");
17854        d.click_past_end();
17855        d.toggle_code_block();
17856        assert!(
17857            d.caret_in_code_block(),
17858            "the caret is not in the block it opened"
17859        );
17860        d.insert("let x = 1;");
17861        d.newline();
17862        d.insert("x");
17863        assert_eq!(d.source, "A\n\n```\nlet x = 1;\nx\n```");
17864        d.build_visual(80);
17865        let (row, _) = d.caret_pos();
17866        assert!(d.vmap.rows[row].code, "typed text is not on a code row");
17867        // And back out: the button reverses what it did, text kept.
17868        d.toggle_code_block();
17869        assert_eq!(d.source, "A\n\nlet x = 1;\nx\n");
17870        assert!(!d.caret_in_code_block());
17871    }
17872
17873    #[test]
17874    fn toggle_code_block_over_a_selection_fences_it_whole_and_keeps_it_selected() {
17875        let mut d = wysiwyg_doc("cb_sel", "one\n\ntwo\n\nthree\n");
17876        d.anchor = Some(1);
17877        d.caret = 7;
17878        d.toggle_code_block();
17879        assert_eq!(d.source, "```\none\n\ntwo\n```\n\nthree\n");
17880        assert!(d.selection().is_some(), "the block came back unselected");
17881        d.toggle_code_block();
17882        assert_eq!(
17883            d.source, "one\n\ntwo\n\nthree\n",
17884            "a second press did not reverse the first"
17885        );
17886    }
17887
17888    #[test]
17889    fn toggle_code_block_inside_a_list_item_fences_and_unfences_in_place() {
17890        for (name, before, fenced) in [
17891            ("cb_list", "- it|em\n", "- ```\n  it|em\n  ```\n"),
17892            ("cb_olist", "1. it|em\n", "1. ```\n   it|em\n   ```\n"),
17893            ("cb_task", "- [ ] it|em\n", "- [ ] ```\n  it|em\n  ```\n"),
17894            (
17895                "cb_nested",
17896                "- a\n  - it|em\n",
17897                "- a\n  - ```\n    it|em\n    ```\n",
17898            ),
17899        ] {
17900            let mut d = wysiwyg_doc(name, &before.replace('|', ""));
17901            d.caret = before.find('|').unwrap();
17902            d.toggle_code_block();
17903            assert_eq!(render_caret(&d), fenced, "{name}: fencing");
17904            assert!(
17905                d.caret_in_code_block(),
17906                "{name}: the caret is in the new block"
17907            );
17908            d.toggle_code_block();
17909            assert_eq!(
17910                render_caret(&d),
17911                before,
17912                "{name}: a second press reverses the first"
17913            );
17914        }
17915    }
17916
17917    #[test]
17918    fn toggle_code_block_in_a_list_item_is_one_undo_step() {
17919        let mut d = wysiwyg_doc("cb_list_undo", "- item\n");
17920        d.caret = 4;
17921        d.toggle_code_block();
17922        d.undo();
17923        assert_eq!(render_caret(&d), "- it|em\n");
17924    }
17925
17926    #[test]
17927    fn caret_in_code_block_reads_fenced_and_indented_blocks() {
17928        let mut d = wysiwyg_doc("cb_in", "para\n\n```\ncode\n```\n\n    more\n");
17929        d.caret = 2;
17930        assert!(!d.caret_in_code_block());
17931        d.caret = 11;
17932        assert!(d.caret_in_code_block());
17933        d.caret = 25;
17934        assert!(d.caret_in_code_block(), "an indented block is a code block");
17935    }
17936
17937    #[test]
17938    fn caret_in_blockquote_reads_every_line_of_a_quote_and_nothing_after() {
17939        let src = "para\n\n> # Head\n> body|\n\nafter\n";
17940        let mut d = wysiwyg_doc("bq_in", &src.replace('|', ""));
17941        let quote_start = src.find('>').unwrap();
17942        let body_end = src.find('|').unwrap();
17943        let after = src.find("after").unwrap() - 1;
17944        for (at, inside) in [
17945            (2, false),
17946            (quote_start + 4, true),
17947            (body_end - 2, true),
17948            (body_end, true),
17949            (after, false),
17950            (after + 2, false),
17951        ] {
17952            d.caret = at;
17953            assert_eq!(d.caret_in_blockquote(), inside, "caret at {at}");
17954        }
17955        // A heading in a quote is both: the quote is a layer over the style.
17956        d.caret = quote_start + 4;
17957        assert_eq!(d.current_heading_level(), Some(1));
17958    }
17959
17960    #[test]
17961    fn caret_in_blockquote_follows_the_toggle() {
17962        let mut d = wysiwyg_doc("bq_toggle", "hello\n");
17963        d.caret = 2;
17964        assert!(!d.caret_in_blockquote());
17965        d.toggle_blockquote();
17966        assert!(d.caret_in_blockquote());
17967        d.toggle_blockquote();
17968        assert!(!d.caret_in_blockquote());
17969    }
17970
17971    #[test]
17972    fn toggle_code_block_is_one_undo_step() {
17973        let mut d = wysiwyg_doc("cb_undo", "hello\n");
17974        d.caret = 2;
17975        d.toggle_code_block();
17976        d.undo();
17977        assert_eq!(render_caret(&d), "he|llo\n");
17978    }
17979
17980    #[test]
17981    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
17982        // A paragraph broken over two source lines is one paragraph. Selecting
17983        // it must not stop at the newline inside it — that newline is markup the
17984        // rich-text view exists to hide.
17985        let src = "one two\nthree four\n\nnext\n";
17986        let mut d = wysiwyg_doc("triple_para", src);
17987        d.select_block_at(2);
17988        assert_eq!(
17989            d.selected_text(),
17990            Some("one two\nthree four"),
17991            "stopped at the soft break"
17992        );
17993    }
17994
17995    #[test]
17996    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
17997        // The reader scrolls down past the caret's row. Nothing moved the
17998        // caret, so the view must stay where it was put — the old code revealed
17999        // the caret every frame, which dragged the view straight back and made
18000        // the document unscrollable past the caret.
18001        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
18002        d.caret = 0;
18003        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
18004        d.scroll = 4; // the wheel
18005        d.follow_caret(0, 3, 9);
18006        assert_eq!(
18007            d.scroll, 4,
18008            "the wheel was overruled by a caret that never moved"
18009        );
18010    }
18011
18012    #[test]
18013    fn moving_the_caret_brings_the_view_back_to_it() {
18014        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
18015        d.caret = 0;
18016        d.follow_caret(0, 3, 9);
18017        d.scroll = 6; // scrolled away
18018        d.move_right(false); // ...and now the caret moves
18019        let (row, _) = d.caret_pos();
18020        d.follow_caret(row, 3, 9);
18021        assert!(
18022            d.scroll <= row && row < d.scroll + 3,
18023            "caret row {row} off screen at scroll {}",
18024            d.scroll
18025        );
18026    }
18027
18028    #[test]
18029    fn scrolling_stops_at_the_last_row() {
18030        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
18031        d.caret = 0;
18032        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
18033        d.scroll = 999; // the wheel, spun hard
18034        d.follow_caret(0, 3, 3);
18035        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
18036    }
18037
18038    #[test]
18039    fn every_cell_of_a_wide_table_is_reachable() {
18040        // A table whose cells are far wider than the surface: the columns are
18041        // cut to fit and the text wraps inside them, so no cell hangs off the
18042        // right edge where the caret can never go.
18043        let src = "| Ingredient | Notes |\n|---|---|\n\
18044                   | flour milled coarse | sift it twice before folding it in |\n";
18045        let mut d = wysiwyg_doc("wide_table_walk", src);
18046        d.build_visual(30);
18047        d.caret = 0;
18048        let seen = walk_right(&mut d);
18049        for word in ["Ingredient", "Notes", "coarse", "folding"] {
18050            let at = src.find(word).unwrap();
18051            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
18052        }
18053    }
18054
18055    // ── view parity ──────────────────────────────────────────────────────────
18056    // `doc_with` pins the source view, so everything above tests a view users
18057    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
18058    // deletion golden cases through *both*, plus the WYSIWYG cases the two
18059    // can't share: where the source carries markup the rendered text is a
18060    // different string, and the views agreeing would itself be the bug.
18061
18062    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
18063
18064    /// Run `action` in both views on one `|`-marked fixture and assert they
18065    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
18066    /// source verbatim, so the two views are looking at the same text and any
18067    /// disagreement is one of them having lost the plot.
18068    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
18069        let (src, caret) = parse_caret(marked);
18070        let run = |view: View, tag: &str| {
18071            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
18072            d.caret = caret;
18073            action(&mut d);
18074            render_caret(&d)
18075        };
18076        let source = run(VIEWS[0].0, VIEWS[0].1);
18077        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
18078        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
18079        source
18080    }
18081
18082    #[test]
18083    fn word_motion_agrees_across_the_views_on_plain_prose() {
18084        let g = both_views;
18085        assert_eq!(
18086            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
18087            "hello |world"
18088        );
18089        assert_eq!(
18090            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
18091            "|hello world"
18092        );
18093        assert_eq!(
18094            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
18095            "hello| world"
18096        );
18097        assert_eq!(
18098            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
18099            "hello world|"
18100        );
18101        assert_eq!(
18102            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
18103            "foo|.bar"
18104        );
18105        assert_eq!(
18106            g("par_ext", "hello |world", |d| d.move_word_right(true)),
18107            "hello [world|]"
18108        );
18109    }
18110
18111    #[test]
18112    fn word_deletion_agrees_across_the_views_on_plain_prose() {
18113        let g = both_views;
18114        assert_eq!(
18115            g("par_db", "hello world|", |d| d.delete_word_back()),
18116            "hello |"
18117        );
18118        assert_eq!(
18119            g("par_df", "hello |world", |d| d.delete_word_forward()),
18120            "hello |"
18121        );
18122        assert_eq!(
18123            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
18124            "|bar baz"
18125        );
18126        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
18127    }
18128
18129    #[test]
18130    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
18131        let g = both_views;
18132        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
18133        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
18134        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
18135        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
18136    }
18137
18138    #[test]
18139    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
18140        // The reproduction: the stop table was built one stop per `char`, so
18141        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
18142        // source view, which steps by grapheme, can't reach and backspace can't
18143        // survive. The two views must land on the same offset.
18144        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
18145        for (view, tag) in VIEWS {
18146            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
18147            d.caret = 1;
18148            d.move_right(false);
18149            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
18150
18151            // ...and the edit that used to sever a joiner off the front of it.
18152            d.backspace();
18153            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
18154            assert_eq!(d.caret, 1);
18155        }
18156    }
18157
18158    #[test]
18159    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
18160        for (view, tag) in VIEWS {
18161            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
18162            d.caret = 0;
18163            d.move_right(false);
18164            assert_eq!(
18165                d.caret,
18166                "e\u{0301}".len(),
18167                "{tag} stopped on the combining mark"
18168            );
18169        }
18170    }
18171
18172    #[test]
18173    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
18174        // The general form: whatever route the caret takes through a document
18175        // full of clusters, it never lands between the codepoints of one — so no
18176        // motion-then-backspace sequence can leave a dangling joiner behind.
18177        use unicode_segmentation::UnicodeSegmentation;
18178
18179        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
18180        let mut d = wysiwyg_doc("cluster_walk", src);
18181        d.caret = 0;
18182        let boundaries: Vec<usize> = src
18183            .grapheme_indices(true)
18184            .map(|(i, _)| i)
18185            .chain(std::iter::once(src.len()))
18186            .collect();
18187        for off in walk_right(&mut d) {
18188            assert!(
18189                boundaries.contains(&off),
18190                "Right stopped at {off}, inside a grapheme cluster"
18191            );
18192        }
18193    }
18194
18195    #[test]
18196    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
18197        // The reproduction: ⌥→ from inside the opening `**` computed its
18198        // boundary over the raw source and landed on byte 8 — inside the
18199        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
18200        // "bold". The caret drew past the bold word and sat inside it.
18201        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
18202        d.caret = 2;
18203        d.move_word_right(false);
18204        assert!(
18205            d.vmap.is_stop(d.caret),
18206            "landed at {}, not a caret stop",
18207            d.caret
18208        );
18209        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
18210        // The rendered row is "a bold c": column 6 is the space just past "bold",
18211        // and now the caret is really there rather than only drawn there.
18212        assert_eq!(d.caret_pos(), (0, 6));
18213
18214        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
18215        d.move_word_left(false);
18216        assert_eq!(d.caret, 4);
18217        assert_eq!(d.caret_pos(), (0, 2));
18218    }
18219
18220    #[test]
18221    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
18222        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
18223        // inside the closing `**`, and left "a ** c\n" — delimiters with no
18224        // opener. Glyph space covers the word alone, which would leave
18225        // "a **** c": markup wrapped around nothing. The word and the styling
18226        // that was only ever the word's go together.
18227        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
18228        d.caret = 10;
18229        d.delete_word_back();
18230        assert_eq!(d.source, "a  c\n");
18231        assert_eq!(d.caret, 2);
18232
18233        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
18234        d.caret = 4; // the "b"
18235        d.delete_word_forward();
18236        assert_eq!(d.source, "a  c\n");
18237    }
18238
18239    #[test]
18240    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
18241        let src = "a ***bold*** c\n";
18242        let mut d = wysiwyg_doc("wys_word_del_nest", src);
18243        d.caret = src.find(" c").unwrap();
18244        d.delete_word_back();
18245        assert_eq!(
18246            d.source, "a  c\n",
18247            "the emph inside the strong empties it too"
18248        );
18249
18250        let src = "a `code` c\n";
18251        let mut d = wysiwyg_doc("wys_word_del_code", src);
18252        d.caret = src.find(" c").unwrap();
18253        d.delete_word_back();
18254        assert_eq!(d.source, "a  c\n");
18255    }
18256
18257    #[test]
18258    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
18259        // Only an *emptied* node goes. Take one word of two and the `**` still
18260        // has a job to do — over the word that's left, with the space the delete
18261        // pushed against the opening delimiter moved out in front of it, or the
18262        // run would be no run at all (`** words**` is literal asterisks — see
18263        // the mark-edge rule on `splice`).
18264        let src = "a **two words** c\n";
18265        let mut d = wysiwyg_doc("wys_word_del_partial", src);
18266        d.caret = src.find(" words").unwrap();
18267        d.delete_word_back();
18268        assert_eq!(d.source, "a  **words** c\n");
18269    }
18270
18271    #[test]
18272    fn source_view_word_motion_still_walks_the_markup() {
18273        // The other half of the decision: in the source view the `**` are
18274        // characters like any other — they're on the screen, so word motion has
18275        // to stop at them and a word-delete has to leave them behind. Only
18276        // WYSIWYG hides them, so only WYSIWYG steps over them.
18277        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
18278        assert_eq!(
18279            g("src_word_motion", "a |**bold** c\n", |d| d
18280                .move_word_right(false)),
18281            "a **bold|** c\n"
18282        );
18283        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
18284        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
18285        assert_eq!(
18286            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
18287            "a **| c\n"
18288        );
18289    }
18290
18291    #[test]
18292    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
18293        // The single invariant both bugs violated: the caret draws and edits at
18294        // the same place only when it's on a stop. `debug_assert_on_a_stop`
18295        // makes the same claim in-place; this pins it from the outside, over a
18296        // document with every kind of thing the map has to be careful about.
18297        // At two widths: the wide one every other test builds at, where no
18298        // fixture folds, and one narrow enough that they all do. A soft wrap is
18299        // where an offset stops being on exactly one row, and testing only the
18300        // width that never wraps is how the caret came to be pinned at the first
18301        // one Down reached.
18302        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
18303                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
18304        // A table of named operations, which is what it looks like.
18305        #[allow(clippy::type_complexity)]
18306        let motions: [(&str, fn(&mut Doc)); 8] = [
18307            ("right", |d| d.move_right(false)),
18308            ("left", |d| d.move_left(false)),
18309            ("word_right", |d| d.move_word_right(false)),
18310            ("word_left", |d| d.move_word_left(false)),
18311            ("down", |d| d.move_down(false)),
18312            ("up", |d| d.move_up(false)),
18313            ("home", |d| d.move_home(false)),
18314            ("end", |d| d.move_end(false)),
18315        ];
18316        for width in [80, 12] {
18317            let mut d = wysiwyg_doc("stop_invariant", src);
18318            d.build_visual(width);
18319            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18320            assert!(stops.len() > 20, "fixture should have plenty of stops");
18321            for start in stops {
18322                for (name, motion) in &motions {
18323                    d.caret = start;
18324                    d.anchor = None;
18325                    motion(&mut d);
18326                    assert!(
18327                        d.vmap.is_stop(d.caret),
18328                        "{name} from {start} at width {width} landed at {} — not a caret stop",
18329                        d.caret
18330                    );
18331                }
18332            }
18333        }
18334    }
18335
18336    #[test]
18337    fn no_wysiwyg_motion_is_a_dead_end() {
18338        // Down held to the bottom of a document reaches the bottom, and Up held
18339        // to the top reaches the top — from anywhere, at a width that wraps. The
18340        // invariant above says a motion lands somewhere legal; this one says it
18341        // gets somewhere at all, which is what a caret pinned at a wrap boundary
18342        // was quietly failing to do while every assertion around it held.
18343        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
18344                   - item one two three four five\n\nlast\n";
18345        for width in [80, 12] {
18346            let mut d = wysiwyg_doc("no_dead_end", src);
18347            d.build_visual(width);
18348            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18349            let (first, last) = (stops[0], stops[stops.len() - 1]);
18350            for &start in &stops {
18351                for (name, motion, want) in [
18352                    (
18353                        "down",
18354                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
18355                        last,
18356                    ),
18357                    ("up", |d: &mut Doc| d.move_up(false), first),
18358                ] {
18359                    d.caret = start;
18360                    d.anchor = None;
18361                    d.goal_col = None;
18362                    // Every row, plus the presses the edges take, plus slack.
18363                    for _ in 0..d.vmap.num_rows() + 4 {
18364                        motion(&mut d);
18365                    }
18366                    assert_eq!(
18367                        d.caret, want,
18368                        "{name} held from {start} at width {width} never arrived"
18369                    );
18370                }
18371            }
18372        }
18373    }
18374    // ── display columns ──────────────────────────────────────────────────────
18375    // A `col` is a terminal cell, not a character. The two are the same number
18376    // for the ASCII the fixtures above are written in, which is how they came
18377    // apart in the first place: `你` is one character drawn in two cells, so a
18378    // column counted in characters names a cell the text isn't in — one earlier
18379    // for every wide character to its left.
18380
18381    #[test]
18382    fn a_wide_character_is_two_columns_wide() {
18383        // The reproduction: `你` is one char and two cells, so the caret just
18384        // past it drew at column 1 — inside the character it had already left.
18385        for (view, tag) in VIEWS {
18386            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
18387            d.caret = "你".len();
18388            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
18389            d.caret = "你好".len();
18390            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
18391        }
18392    }
18393
18394    #[test]
18395    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
18396        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
18397        // two-cell — measuring six cells one at a time, but the character they
18398        // spell is drawn in two. Width belongs to the cluster, not the glyph,
18399        // and the frontends measure it the same way.
18400        let family = "👨‍👩‍👧";
18401        for (view, tag) in VIEWS {
18402            let src = format!("a{family}b\n");
18403            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
18404            d.caret = 1 + family.len();
18405            assert_eq!(
18406                d.caret_pos(),
18407                (0, 3),
18408                "{tag}: 'a' is one cell, the family two"
18409            );
18410        }
18411    }
18412
18413    #[test]
18414    fn both_cells_of_a_wide_character_mean_the_character() {
18415        // Clicking the far half of `好` is still clicking `好`: half a character
18416        // is not a place the caret can be, so it comes to rest at the
18417        // character's start — the column it would have been drawn at anyway.
18418        for (view, tag) in VIEWS {
18419            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
18420            for col in [2, 3] {
18421                d.caret = 0;
18422                d.click(0, col, false);
18423                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
18424                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
18425            }
18426            // Past the last cell is the line's end, as it is for ASCII.
18427            d.click(0, 9, false);
18428            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
18429        }
18430    }
18431
18432    #[test]
18433    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
18434        // The mapping is only a mapping if it inverts: the cell the caret is
18435        // drawn in has to be the cell that brings it back to the same offset.
18436        // Over a fixture where a character may be one cell or two, and one
18437        // codepoint or five.
18438        use unicode_segmentation::UnicodeSegmentation;
18439
18440        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
18441
18442        let mut d = doc_in(View::Source, "roundtrip_source", src);
18443        // Every offset the source view's caret can occupy: it steps by grapheme
18444        // cluster, so those are its boundaries.
18445        for (off, _) in src
18446            .grapheme_indices(true)
18447            .chain(std::iter::once((src.len(), "")))
18448        {
18449            d.caret = off;
18450            let (row, col) = d.caret_pos();
18451            d.click(row, col, false);
18452            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
18453        }
18454
18455        // And in WYSIWYG, where the offsets the caret can occupy are the map's
18456        // stops rather than every boundary.
18457        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
18458        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18459        assert!(stops.len() > 20, "fixture should have plenty of stops");
18460        for off in stops {
18461            d.caret = off;
18462            let (row, col) = d.caret_pos();
18463            d.click(row, col, false);
18464            assert_eq!(
18465                d.caret, off,
18466                "wysiwyg: {off} → ({row}, {col}) → {}",
18467                d.caret
18468            );
18469        }
18470    }
18471
18472    #[test]
18473    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
18474        // Down from under `世` lands under the glyph in that cell, not two
18475        // characters further along the line. The goal is a column, so a line of
18476        // wide characters and a line of ASCII line up the way they're drawn.
18477        //
18478        // The gap differs by view: a bare newline inside a paragraph is a soft
18479        // break, which WYSIWYG draws as a space on a single row. The views share
18480        // a grid only where the source's lines are the renderer's rows too.
18481        for (view, tag) in VIEWS {
18482            let gap = if view == View::Source { "\n" } else { "\n\n" };
18483            let src = format!("你好世{gap}abcdef\n");
18484            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
18485            d.caret = "你好".len();
18486            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
18487            d.move_down(false);
18488            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
18489            assert!(
18490                d.source[d.caret..].starts_with('e'),
18491                "{tag}: landed on the wrong glyph"
18492            );
18493        }
18494    }
18495
18496    #[test]
18497    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
18498        // Down from column 3 onto `你好`, whose characters start at columns 0
18499        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
18500        // between the cells of one character, so the caret rests on it — and on
18501        // its start, which is the only offset there that is a caret stop.
18502        for (view, tag) in VIEWS {
18503            let gap = if view == View::Source { "\n" } else { "\n\n" };
18504            let src = format!("abcdef{gap}你好\n");
18505            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
18506            let line = src.find('你').unwrap();
18507            d.caret = 3;
18508            d.move_down(false);
18509            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
18510            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
18511        }
18512    }
18513
18514    #[test]
18515    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
18516        // The column the cell's text is laid out in is measured in cells, so the
18517        // caret walking that text has to be too — the two agreeing is the whole
18518        // point of the grid staying square.
18519        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
18520        let at = d.source.find("你").unwrap();
18521        d.caret = at;
18522        let (row, col) = d.caret_pos();
18523        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
18524        // cells further along.
18525        assert_eq!(col, 2, "the cell's first character");
18526        d.move_right(false);
18527        assert_eq!(
18528            d.caret_pos(),
18529            (row, 4),
18530            "`好` is drawn past `你`'s two cells"
18531        );
18532        assert_eq!(d.caret, at + "你".len());
18533    }
18534
18535    // ── active inline marks ───────────────────────────────────────────────────
18536
18537    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
18538    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
18539        let (src, caret) = parse_caret(marked);
18540        let mut d = doc_in(view, name, &src);
18541        d.caret = caret;
18542        d.active_inline_marks().iter().collect()
18543    }
18544
18545    /// The marks over the selection `[start, end)`.
18546    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
18547        let mut d = doc_in(view, name, src);
18548        d.anchor = Some(start);
18549        d.caret = end;
18550        d.active_inline_marks().iter().collect()
18551    }
18552
18553    #[test]
18554    fn a_caret_in_a_mark_reports_it() {
18555        for (view, tag) in VIEWS {
18556            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
18557            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
18558            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
18559            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
18560            // Plain text under no mark lights nothing — the toolbar's resting state.
18561            assert_eq!(m("a| **bold** b"), [], "{tag}");
18562            assert!(m("plain t|ext").is_empty(), "{tag}");
18563        }
18564    }
18565
18566    #[test]
18567    fn nested_marks_all_report() {
18568        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
18569        // the ancestor chain is a chain, and every mark on it is in force.
18570        for (view, tag) in VIEWS {
18571            assert_eq!(
18572                marks(
18573                    view,
18574                    &format!("marks_nested_{tag}"),
18575                    "**bold and *bo|th*** end"
18576                ),
18577                [InlineKind::Strong, InlineKind::Emph],
18578                "{tag}"
18579            );
18580        }
18581    }
18582
18583    #[test]
18584    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
18585        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
18586        // the first byte of its text and the byte after its last — both inside
18587        // the mark's span, both places typing lands inside the bold. The offset
18588        // past the closing delimiter is the next text, and reports nothing.
18589        let src = "a **bold** b";
18590        let inner_start = src.find("bold").unwrap(); // 4
18591        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
18592        for (view, tag) in VIEWS {
18593            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
18594            for off in [2, 3, inner_start, inner_end, 9] {
18595                d.caret = off;
18596                assert!(
18597                    d.active_inline_marks().contains(InlineKind::Strong),
18598                    "{tag}: offset {off} is inside the strong span"
18599                );
18600            }
18601            for off in [0, 1, 10, 11, 12] {
18602                d.caret = off;
18603                assert!(
18604                    !d.active_inline_marks().contains(InlineKind::Strong),
18605                    "{tag}: offset {off} is outside the strong run"
18606                );
18607            }
18608        }
18609    }
18610
18611    #[test]
18612    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
18613        // Regression: twig resolves an offset that is one node's end and the
18614        // next one's start to the node that *starts* there, so `**bold**|\n`
18615        // isn't bold. With nothing following there's no tie to break and the
18616        // chain still ended at the mark, which made a trailing `\n` — not the
18617        // text — decide whether the caret after a bold word reported bold. It's
18618        // the offset past the mark either way, and typing there is plain either
18619        // way. A blank document typed into is exactly this shape.
18620        for (view, tag) in VIEWS {
18621            let m = |name: String, marked| marks(view, &name, marked);
18622            assert_eq!(
18623                m(format!("marks_eob_{tag}"), "**bold**|"),
18624                [],
18625                "{tag}: no trailing newline"
18626            );
18627            assert_eq!(
18628                m(format!("marks_eol_{tag}"), "**bold**|\n"),
18629                [],
18630                "{tag}: with one"
18631            );
18632            // And the last offset that *is* in the mark still is.
18633            assert_eq!(
18634                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
18635                [InlineKind::Strong],
18636                "{tag}"
18637            );
18638        }
18639    }
18640
18641    #[test]
18642    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
18643        let src = "a **bold** b";
18644        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
18645        for (view, tag) in VIEWS {
18646            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
18647            // The whole bold word, and a slice of it.
18648            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
18649            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
18650            // Ending exactly at the closing delimiter's start is still all-bold:
18651            // an exclusive end sits *past* the last selected character, so the
18652            // question is asked of the character, not the boundary.
18653            assert_eq!(
18654                m(b, d_ + 2),
18655                [InlineKind::Strong],
18656                "{tag}: through the close"
18657            );
18658            // Half in, half out: Bold lit here would claim a press turns it off.
18659            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
18660            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
18661        }
18662    }
18663
18664    #[test]
18665    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
18666        // Both ends are bold, but the space between them isn't — two runs are two
18667        // nodes, which is exactly what the node id catches and a kind-only
18668        // comparison would not.
18669        let src = "**one** **two**";
18670        for (view, tag) in VIEWS {
18671            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
18672            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
18673        }
18674    }
18675
18676    #[test]
18677    fn marks_read_the_document_as_it_is_edited() {
18678        // The point of asking twig every frame instead of caching: the answer has
18679        // to follow the toggle that changed it.
18680        let mut d = wysiwyg_doc("marks_live", "one two\n");
18681        d.anchor = Some(0);
18682        d.caret = 3;
18683        assert!(d.active_inline_marks().is_empty(), "plain to start");
18684        d.toggle(InlineKind::Strong);
18685        assert_eq!(d.source, "**one** two\n");
18686        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
18687        assert!(d.active_inline_marks().contains(InlineKind::Strong));
18688        d.toggle(InlineKind::Strong);
18689        assert!(d.active_inline_marks().is_empty(), "and off again");
18690    }
18691
18692    #[test]
18693    fn a_link_is_not_an_inline_mark() {
18694        // `link`/`str` are inline nodes, but nothing on the inline toolbar
18695        // toggles them — a set with a "link mark" in it would have no button.
18696        for (view, tag) in VIEWS {
18697            assert_eq!(
18698                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
18699                [],
18700                "{tag}"
18701            );
18702        }
18703    }
18704
18705    // ── blank documents ───────────────────────────────────────────────────────
18706
18707    #[test]
18708    fn a_blank_document_is_untitled_empty_and_markdown() {
18709        let mut d = Doc::blank().unwrap();
18710        assert!(d.is_untitled());
18711        assert_eq!(d.path, PathBuf::new());
18712        assert_eq!(
18713            d.file_name(),
18714            "untitled",
18715            "the header has to show something"
18716        );
18717        assert_eq!(d.format_name(), "markdown");
18718        assert_eq!(d.source, "");
18719        assert!(!d.dirty, "nothing typed yet is nothing to lose");
18720        assert_eq!(d.disk_state(), DiskState::Untitled);
18721        // And it's a document you can be in: the default view renders it.
18722        d.build_visual(80);
18723        assert_eq!(d.caret, 0);
18724    }
18725
18726    #[test]
18727    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
18728        let mut d = Doc::blank().unwrap();
18729        d.insert("hello");
18730        assert!(d.dirty);
18731        d.save();
18732        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
18733        assert!(d.dirty, "it must not come away believing it saved");
18734        assert!(d.is_untitled(), "and it still has no file");
18735    }
18736
18737    #[test]
18738    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
18739        let p = temp_path("blank_save_as");
18740        let mut d = Doc::blank().unwrap();
18741        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
18742        // be kept literal (`\#`); this test is about save-as, not escaping (which
18743        // has its own test), so it types nothing that escaping would touch.
18744        d.insert("hi");
18745        d.save_as(p.clone());
18746        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
18747        assert!(!d.is_untitled());
18748        assert!(!d.dirty);
18749        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
18750        assert_eq!(
18751            d.disk_state(),
18752            DiskState::Unchanged,
18753            "the watermark is stamped"
18754        );
18755        // And ⌘S is a plain save from here on.
18756        d.insert("!");
18757        d.save();
18758        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
18759        let _ = std::fs::remove_file(&p);
18760    }
18761
18762    // ── a file that isn't there yet ───────────────────────────────────────────
18763
18764    /// A unique path in the temp dir with the given extension, guaranteed not to
18765    /// exist — what `leaf notes.md` is handed when the file has never been made.
18766    fn missing_path(name: &str, ext: &str) -> PathBuf {
18767        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18768        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18769        let mut p = std::env::temp_dir();
18770        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
18771        let _ = std::fs::remove_file(&p);
18772        p
18773    }
18774
18775    #[test]
18776    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
18777        let p = missing_path("named", "md");
18778        let mut d = Doc::open_or_create(p.clone()).unwrap();
18779
18780        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
18781        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
18782        assert!(
18783            !d.is_untitled(),
18784            "it has the name the user asked for — ^S must not detour to Save As"
18785        );
18786        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
18787        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
18788        assert!(!p.exists(), "and opening it wrote nothing");
18789        // And it's a document you can be in.
18790        d.build_visual(80);
18791        assert_eq!(d.caret, 0);
18792    }
18793
18794    #[test]
18795    fn a_new_file_is_created_by_its_first_save() {
18796        let p = missing_path("first_save", "md");
18797        let mut d = Doc::open_or_create(p.clone()).unwrap();
18798        d.insert("hello\n");
18799        assert!(d.dirty);
18800        d.save();
18801
18802        assert_eq!(
18803            std::fs::read_to_string(&p).unwrap(),
18804            "hello\n",
18805            "a plain ^S wrote it — no Save As, no name to invent"
18806        );
18807        assert!(!d.dirty);
18808        assert_eq!(d.disk_state(), DiskState::Unchanged);
18809        let _ = std::fs::remove_file(&p);
18810    }
18811
18812    #[test]
18813    fn a_new_file_takes_its_format_from_the_extension() {
18814        // The one thing `blank` can't do: with no name it has to assume Markdown,
18815        // and typing djot into a Markdown parse is the wrong buffer.
18816        let dj = missing_path("format", "dj");
18817        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
18818        let md = missing_path("format", "md");
18819        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
18820    }
18821
18822    #[test]
18823    fn a_new_file_reports_itself_missing_until_it_is_saved() {
18824        // Not `Untitled` — that's the answer for a document with no path, and it
18825        // would tell a frontend there is nothing a save could collide with. Here
18826        // there is a path, and the file simply isn't at it yet.
18827        let p = missing_path("disk_state", "md");
18828        let mut d = Doc::open_or_create(p.clone()).unwrap();
18829        assert_eq!(d.disk_state(), DiskState::Missing);
18830
18831        // Somebody else creates it while the buffer is open: that's an overwrite
18832        // the frontend has to be able to prompt about, exactly as for an opened
18833        // file. Their bytes, not ours, so `Changed`.
18834        std::fs::write(&p, "theirs\n").unwrap();
18835        assert_eq!(d.disk_state(), DiskState::Changed);
18836
18837        // Saving makes the file ours and re-stamps the watermark.
18838        d.insert("ours\n");
18839        d.save();
18840        assert_eq!(d.disk_state(), DiskState::Unchanged);
18841        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
18842        let _ = std::fs::remove_file(&p);
18843    }
18844
18845    #[test]
18846    fn open_or_create_still_opens_a_file_that_is_there() {
18847        let d = doc_with("open_or_create_existing", "body\n");
18848        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
18849        assert_eq!(reopened.source, "body\n");
18850        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
18851    }
18852
18853    #[test]
18854    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
18855        // A mistyped flag or a stray argument must not become a buffer promising
18856        // to save somewhere — the same refusal `open` gives a real file.
18857        let mut p = std::env::temp_dir();
18858        p.push("leaf_test_new_bad_ext.wat");
18859        assert!(Doc::open_or_create(p).is_err());
18860        let mut none = std::env::temp_dir();
18861        none.push("leaf_test_new_no_ext");
18862        assert!(Doc::open_or_create(none).is_err());
18863    }
18864
18865    #[test]
18866    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
18867        // Opening reads nothing, so there is nothing to fail on yet; the write is
18868        // where it fails, and it says so rather than claiming a save.
18869        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
18870        let mut d = Doc::open_or_create(p).unwrap();
18871        d.insert("x");
18872        d.save();
18873        assert!(
18874            d.status.as_deref().unwrap().starts_with("save failed:"),
18875            "got {:?}",
18876            d.status
18877        );
18878        assert!(d.dirty, "it must not come away believing it saved");
18879    }
18880
18881    // ── save as ───────────────────────────────────────────────────────────────
18882
18883    /// A unique path in the temp dir that no fixture wrote — a Save As target.
18884    fn temp_path(name: &str) -> PathBuf {
18885        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18886        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18887        let mut p = std::env::temp_dir();
18888        p.push(format!("leaf_test_target_{name}_{seq}.md"));
18889        let _ = std::fs::remove_file(&p);
18890        p
18891    }
18892
18893    #[test]
18894    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
18895        let mut d = doc_with("save_as_move", "original\n");
18896        let old = d.path.clone();
18897        let new = temp_path("save_as_move");
18898        d.insert("edited: ");
18899        d.save_as(new.clone());
18900
18901        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
18902        assert_eq!(
18903            std::fs::read_to_string(&old).unwrap(),
18904            "original\n",
18905            "Save As doesn't touch the file it came from"
18906        );
18907        assert_eq!(d.path, new, "the document moved");
18908        assert!(!d.dirty);
18909        assert_eq!(
18910            d.status.as_deref(),
18911            Some(&*format!("saved {}", d.file_name()))
18912        );
18913
18914        // Every later save follows it, which is the whole difference from a copy.
18915        d.caret = 0;
18916        d.insert("re-");
18917        d.save();
18918        assert_eq!(
18919            std::fs::read_to_string(&new).unwrap(),
18920            "re-edited: original\n"
18921        );
18922        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
18923        let _ = std::fs::remove_file(&new);
18924    }
18925
18926    #[test]
18927    fn save_as_overwrites_an_existing_target() {
18928        // The picker already asked; asking again down here is the same question
18929        // twice, and the second one has no way to be answered.
18930        let new = temp_path("save_as_over");
18931        std::fs::write(&new, "theirs\n").unwrap();
18932        let mut d = doc_with("save_as_over", "ours\n");
18933        d.save_as(new.clone());
18934        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
18935        let _ = std::fs::remove_file(&new);
18936    }
18937
18938    #[test]
18939    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
18940        let mut d = doc_with("save_as_fail", "body\n");
18941        let old = d.path.clone();
18942        d.insert("x");
18943        // A directory that doesn't exist: the write can't land.
18944        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
18945        d.save_as(bad);
18946
18947        assert_eq!(
18948            d.path, old,
18949            "the document must not move to a file that isn't there"
18950        );
18951        assert!(d.dirty, "and must not believe it saved");
18952        assert!(
18953            d.status.as_deref().unwrap().starts_with("save failed:"),
18954            "the same failure a plain save reports, got {:?}",
18955            d.status
18956        );
18957        // The original is still the document's file, and still saveable.
18958        d.save();
18959        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
18960        assert!(!d.dirty);
18961    }
18962
18963    #[test]
18964    fn save_as_renames_without_reparsing_the_format() {
18965        // `.dj` on the name doesn't make the buffer djot: it was parsed as
18966        // Markdown and still is, and saying otherwise would be a conversion the
18967        // user never asked for (and an undo history thrown away to do it).
18968        let mut d = doc_with("save_as_format", "**b**\n");
18969        let mut new = temp_path("save_as_format");
18970        new.set_extension("dj");
18971        d.save_as(new.clone());
18972        assert_eq!(d.format_name(), "markdown");
18973        let _ = std::fs::remove_file(&new);
18974    }
18975
18976    // ── external change / reload ──────────────────────────────────────────────
18977
18978    #[test]
18979    fn an_untouched_file_reports_unchanged() {
18980        let mut d = doc_with("disk_clean", "body\n");
18981        assert_eq!(d.disk_state(), DiskState::Unchanged);
18982        // Editing the buffer is not editing the file.
18983        d.insert("x");
18984        assert_eq!(d.disk_state(), DiskState::Unchanged);
18985        assert!(d.dirty);
18986        // Saving re-stamps the watermark rather than reporting our own bytes back.
18987        d.save();
18988        assert_eq!(d.disk_state(), DiskState::Unchanged);
18989    }
18990
18991    #[test]
18992    fn a_file_written_underneath_reports_changed() {
18993        let mut d = doc_with("disk_changed", "body\n");
18994        std::fs::write(&d.path, "someone else\n").unwrap();
18995        assert_eq!(d.disk_state(), DiskState::Changed);
18996        // Dirty *and* changed is the clobber: both halves are readable, and
18997        // leaf-core takes neither side.
18998        d.insert("x");
18999        assert!(d.dirty && d.disk_state() == DiskState::Changed);
19000        // Saving anyway is allowed — the frontend asked, or chose not to.
19001        d.save();
19002        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
19003        assert_eq!(d.disk_state(), DiskState::Unchanged);
19004    }
19005
19006    #[test]
19007    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
19008        // The hash is what makes this honest: the file was written (a fresh
19009        // mtime), and nothing about the document is stale.
19010        let d = doc_with("disk_same_bytes", "body\n");
19011        std::fs::write(&d.path, "body\n").unwrap();
19012        assert_eq!(d.disk_state(), DiskState::Unchanged);
19013    }
19014
19015    #[test]
19016    fn a_deleted_file_reports_missing() {
19017        let mut d = doc_with("disk_missing", "body\n");
19018        std::fs::remove_file(&d.path).unwrap();
19019        assert_eq!(d.disk_state(), DiskState::Missing);
19020        // A save recreates it, and the document is whole again.
19021        d.save();
19022        assert_eq!(d.disk_state(), DiskState::Unchanged);
19023        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
19024    }
19025
19026    #[test]
19027    fn reload_replaces_the_document_with_the_file() {
19028        for (view, tag) in VIEWS {
19029            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
19030            d.insert("edited ");
19031            assert!(d.dirty);
19032            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
19033            d.reload();
19034
19035            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
19036            assert!(!d.dirty, "{tag}: the file is what we have");
19037            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
19038            assert_eq!(
19039                d.status.as_deref(),
19040                Some(&*format!("reloaded {}", d.file_name()))
19041            );
19042            // The reloaded tree is live, not the old parse.
19043            d.caret = d.source.find("three").unwrap();
19044            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
19045        }
19046    }
19047
19048    #[test]
19049    fn reload_clamps_the_caret_and_drops_the_selection() {
19050        let mut d = doc_with("reload_caret", "a long first line\n");
19051        d.caret = 12;
19052        d.anchor = Some(4);
19053        std::fs::write(&d.path, "short\n").unwrap();
19054        d.reload();
19055        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
19056        assert_eq!(
19057            d.anchor, None,
19058            "a selection over bytes that changed is a lie"
19059        );
19060        assert!(d.selection().is_none());
19061
19062        // A caret the file still has room for stays put.
19063        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
19064        d.caret = 2;
19065        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
19066        d.reload();
19067        assert_eq!(d.caret, 2);
19068    }
19069
19070    /// A silent reload is something that happened *to* a reader — a formatter,
19071    /// a `git checkout` — so it has to be undoable like anything else that
19072    /// changes the document, and undoable as one step rather than as however
19073    /// many the file happens to differ by.
19074    #[test]
19075    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
19076        let mut d = doc_with("reload_undo", "body\n");
19077        d.insert("x");
19078        assert_eq!(d.source, "xbody\n");
19079        std::fs::write(&d.path, "replaced\n").unwrap();
19080        d.reload();
19081        assert_eq!(d.source, "replaced\n");
19082        assert!(!d.dirty, "a reload lands clean");
19083
19084        // One ^Z takes the whole swap off, and hands back the unsaved work it
19085        // replaced — which is unsaved again, because the file no longer says it.
19086        d.undo();
19087        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
19088        assert!(d.dirty, "and what it comes back to is unsaved");
19089        // …and the history under it is still there.
19090        d.undo();
19091        assert_eq!(
19092            d.source, "body\n",
19093            "the typing before the reload undoes too"
19094        );
19095        // Redo walks back up through the reload.
19096        d.redo();
19097        d.redo();
19098        assert_eq!(d.source, "replaced\n");
19099    }
19100
19101    /// A file rewritten with the bytes it already had is not an edit, so it
19102    /// must not leave an undo step behind for something nobody did.
19103    #[test]
19104    fn reloading_identical_bytes_pushes_no_undo_step() {
19105        let mut d = doc_with("reload_same", "body\n");
19106        d.insert("x");
19107        std::fs::write(&d.path, "xbody\n").unwrap();
19108        d.reload();
19109        assert_eq!(d.source, "xbody\n");
19110        assert!(!d.dirty, "the file now says what the buffer does");
19111        d.undo();
19112        assert_eq!(
19113            d.source, "body\n",
19114            "one step back is the typing, not a no-op"
19115        );
19116    }
19117
19118    #[test]
19119    fn a_reload_that_cant_read_leaves_the_document_alone() {
19120        let mut d = doc_with("reload_gone", "body\n");
19121        d.insert("x");
19122        std::fs::remove_file(&d.path).unwrap();
19123        d.reload();
19124        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
19125        assert!(d.dirty);
19126        assert!(
19127            d.status.as_deref().unwrap().starts_with("reload failed:"),
19128            "{:?}",
19129            d.status
19130        );
19131
19132        // And an untitled document has nothing to reload from.
19133        let mut d = Doc::blank().unwrap();
19134        d.insert("typed");
19135        d.reload();
19136        assert_eq!(d.source, "typed");
19137        assert_eq!(d.status.as_deref(), Some("no file to reload"));
19138    }
19139
19140    #[test]
19141    fn a_read_only_document_refuses_every_door() {
19142        let mut d = doc_with("readonly", "one two three\n");
19143        d.insert("x");
19144        assert!(d.dirty, "writable first, so the undo step exists");
19145        d.set_read_only(true);
19146        let before = d.source.clone();
19147        d.insert("y");
19148        d.backspace();
19149        d.undo();
19150        d.redo();
19151        assert_eq!(d.source, before, "no door moved a byte");
19152        d.set_read_only(false);
19153        d.undo();
19154        assert_ne!(d.source, before, "off again, the same doors work");
19155    }
19156
19157    /// The doors that go to twig's own verbs rather than through the splice.
19158    /// Typed text in the rendered view under the default markup mode is the
19159    /// everyday one — it is what a keystroke in leaf-web or the Apple views
19160    /// becomes — and it walked straight past the gate.
19161    #[test]
19162    fn a_read_only_document_refuses_the_doors_around_the_splice() {
19163        let mut d = wysiwyg_doc(
19164            "readonly-doors",
19165            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
19166        );
19167        d.set_markup_mode(MarkupMode::None);
19168        d.set_read_only(true);
19169        let before = d.source.clone();
19170        d.place_caret(3, false);
19171        d.insert("y");
19172        d.insert_link("https://example.com");
19173        d.insert_image("a.png", "alt");
19174        d.insert_thematic_break();
19175        d.insert_footnote();
19176        d.place_caret(0, false);
19177        d.place_caret(3, true);
19178        d.toggle(InlineKind::Strong);
19179        d.toggle_heading(2);
19180        d.set_block(BlockKind::Paragraph);
19181        d.toggle_list(false);
19182        d.toggle_blockquote();
19183        d.toggle_task_item();
19184        d.newline();
19185        d.indent();
19186        d.set_code_language("rust");
19187        let in_cell = d.source.find("| c").unwrap() + 2;
19188        d.place_caret(in_cell, false);
19189        assert!(d.caret_in_table(), "the caret is in the grid");
19190        assert!(!d.cell_line_break(), "the cell break reports the refusal");
19191        assert_eq!(d.source, before, "no door moved a byte");
19192        assert!(!d.dirty, "nothing to save");
19193        d.set_read_only(false);
19194        d.place_caret(3, false);
19195        d.insert("y");
19196        assert_ne!(d.source, before, "off again, the same doors work");
19197    }
19198
19199    #[test]
19200    fn a_selection_quote_carries_its_context_on_char_boundaries() {
19201        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
19202        let start = d.source.find("exact").unwrap();
19203        d.place_caret(start, false);
19204        d.place_caret(start + "exact".len(), true);
19205        let q = d.selection_quote(3).unwrap();
19206        assert_eq!(q.exact, "exact");
19207        assert_eq!(
19208            q.prefix, "你好 ",
19209            "chars, not bytes — the multibyte pair counts as two"
19210        );
19211        assert_eq!(q.suffix, " 世界");
19212        assert_eq!(&d.source[q.start..q.end], "exact");
19213        // At the edges the context clips rather than erring.
19214        d.place_caret(0, false);
19215        d.place_caret(6, true);
19216        let q = d.selection_quote(40).unwrap();
19217        assert_eq!(q.prefix, "");
19218        assert_eq!(q.exact, "before");
19219        // No selection is no quote.
19220        d.place_caret(0, false);
19221        assert!(d.selection_quote(3).is_none());
19222    }
19223
19224    #[test]
19225    fn highlights_are_kept_sorted_and_answer_point_queries() {
19226        let mut d = doc_with("hl", "one two three\n");
19227        d.set_highlights(vec![
19228            Highlight {
19229                start: 8,
19230                end: 13,
19231                id: "b".into(),
19232                color: None,
19233                marker: None,
19234            },
19235            Highlight {
19236                start: 0,
19237                end: 3,
19238                id: "a".into(),
19239                color: Some("#ffe066".into()),
19240                marker: None,
19241            },
19242            Highlight {
19243                start: 5,
19244                end: 5,
19245                id: "empty".into(),
19246                color: None,
19247                marker: None,
19248            },
19249        ]);
19250        assert_eq!(
19251            d.highlights()
19252                .iter()
19253                .map(|h| h.id.as_str())
19254                .collect::<Vec<_>>(),
19255            ["a", "b"],
19256            "sorted by start, the empty range dropped"
19257        );
19258        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
19259        assert_eq!(d.highlight_at(3), None, "end is exclusive");
19260        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
19261        d.set_highlights(Vec::new());
19262        assert!(d.highlights().is_empty(), "a replace is a replace");
19263    }
19264
19265    /// `Highlight::covering` and the cursor over it are what both painters ask
19266    /// per glyph, so they have to answer the same as the scan they replaced —
19267    /// including in the gaps, which is where most glyphs are.
19268    #[test]
19269    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
19270        let hl = |start: usize, end: usize, id: &str| Highlight {
19271            start,
19272            end,
19273            id: id.into(),
19274            color: None,
19275            marker: None,
19276        };
19277        // Disjoint, as search hits are: in a range, in a gap, and past the end.
19278        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
19279        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
19280        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
19281        assert_eq!(
19282            Highlight::covering(&hits, 105),
19283            None,
19284            "a gap covers nothing"
19285        );
19286        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
19287        assert_eq!(Highlight::covering(&hits, 9_999), None);
19288        assert_eq!(Highlight::covering(&[], 0), None);
19289
19290        // Nested: first by start, so a hit inside an annotation still resolves
19291        // to the annotation — and the range that stops short doesn't mask it.
19292        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
19293        assert_eq!(
19294            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
19295            Some("outer")
19296        );
19297        assert_eq!(
19298            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
19299            Some("outer")
19300        );
19301    }
19302
19303    /// The cursor is an optimisation, so the only thing worth asserting is that
19304    /// it is not also a change of answer — at every offset, over a list with a
19305    /// nest in it, walked forwards and then backwards.
19306    #[test]
19307    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
19308        let hl = |start: usize, end: usize, id: &str| Highlight {
19309            start,
19310            end,
19311            id: id.into(),
19312            color: None,
19313            marker: None,
19314        };
19315        let mut list = vec![
19316            hl(0, 20, "outer"),
19317            hl(5, 10, "inner"),
19318            hl(30, 33, "hit"),
19319            hl(40, 43, "hit"),
19320        ];
19321        list.sort_by_key(|h| (h.start, h.end));
19322
19323        let mut cursor = HighlightCursor::new(&list);
19324        for offset in 0..50 {
19325            assert_eq!(
19326                cursor.at(offset).map(|h| h.id.as_str()),
19327                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19328                "cursor disagrees at {offset}"
19329            );
19330        }
19331        // Backwards: the cursor re-seats rather than answering from where it
19332        // had got to, so a painter that revisits a row is still told the truth.
19333        for offset in (0..50).rev() {
19334            assert_eq!(
19335                cursor.at(offset).map(|h| h.id.as_str()),
19336                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19337                "cursor disagrees walking back at {offset}"
19338            );
19339        }
19340    }
19341
19342    // ── the presentation vocabulary ─────────────────────────────────────────
19343
19344    /// A document in `format`, for the gesture tests that want more than the
19345    /// Markdown `doc_with` writes.
19346    fn fmt_doc(body: &str, format: Format) -> Doc {
19347        Doc::from_source(body.to_string(), format).unwrap()
19348    }
19349
19350    /// Alignment is a block property, so the gesture is `set_block_attrs` on
19351    /// the caret's block whatever is selected — and each format spells it its
19352    /// own way: djot's `{…}` line above the block, a `<div>` around it in
19353    /// Markdown (the format has nowhere else to put it), the tag in HTML.
19354    #[test]
19355    fn set_alignment_spells_the_class_the_format_s_own_way() {
19356        let mut dj = fmt_doc("hello\n", Format::Djot);
19357        dj.caret = 1;
19358        dj.set_alignment(Some(Align::Center));
19359        assert_eq!(dj.source, "{.center}\nhello\n");
19360        assert!(dj.dirty);
19361        assert_eq!(dj.status, None);
19362
19363        let mut md = fmt_doc("hello\n", Format::Markdown);
19364        md.caret = 1;
19365        md.set_alignment(Some(Align::Right));
19366        assert_eq!(md.source, "<div class=\"right\">\n\nhello\n\n</div>\n");
19367
19368        let mut html = fmt_doc("<p>hello</p>\n", Format::Html);
19369        html.caret = html.source.find("hello").unwrap();
19370        html.set_alignment(Some(Align::Justify));
19371        assert_eq!(html.source, "<p class=\"justify\">hello</p>\n");
19372    }
19373
19374    /// Each gesture edits **one key and keeps the rest** — twig's contract is
19375    /// replace-not-merge, so leaf reads the node's attributes, edits its own
19376    /// key out of them, and passes the list back whole. A document from
19377    /// elsewhere passes through the editor unharmed.
19378    #[test]
19379    fn a_presentation_gesture_keeps_every_attribute_it_did_not_write() {
19380        let mut d = fmt_doc(
19381            "{.lead .center #intro data-line-height=\"1.5\"}\nhello\n",
19382            Format::Djot,
19383        );
19384        d.caret = d.source.find("hello").unwrap();
19385        d.set_alignment(Some(Align::Right));
19386        // `center` goes, `lead` stays, and neither the id nor the spacing is
19387        // touched.
19388        // The serializer picks the order; what matters is which keys survive.
19389        assert!(d.source.contains(".lead"), "{:?}", d.source);
19390        assert!(d.source.contains(".right"), "{:?}", d.source);
19391        assert!(!d.source.contains(".center"), "{:?}", d.source);
19392        assert!(d.source.contains("#intro"), "{:?}", d.source);
19393        assert!(
19394            d.source.contains("data-line-height=\"1.5\""),
19395            "{:?}",
19396            d.source
19397        );
19398        assert_eq!(d.alignment_at_caret(), Some(Align::Right));
19399        assert_eq!(
19400            d.line_spacing_at_caret(),
19401            Some(LineHeight::Step(LineSpacing::OneHalf))
19402        );
19403
19404        // And the other way round: the spacing gesture leaves the classes be.
19405        d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19406        assert!(d.source.contains(".lead"), "{:?}", d.source);
19407        assert!(d.source.contains(".right"), "{:?}", d.source);
19408        assert_eq!(
19409            d.line_spacing_at_caret(),
19410            Some(LineHeight::Step(LineSpacing::Double))
19411        );
19412    }
19413
19414    /// Clearing is the same gesture with `None`: the key goes, the tokens leaf
19415    /// owns go out of `class`, and a block left with nothing at all is spelled
19416    /// bare again — in Markdown by unwrapping the div twig wrapped it in.
19417    #[test]
19418    fn none_clears_a_key_and_an_empty_set_unwraps_the_block() {
19419        let mut dj = fmt_doc("{.lead .center}\nhello\n", Format::Djot);
19420        dj.caret = dj.source.find("hello").unwrap();
19421        dj.set_alignment(None);
19422        assert_eq!(dj.source, "{.lead}\nhello\n", "the foreign class stays");
19423        assert_eq!(dj.alignment_at_caret(), None);
19424
19425        let mut bare = fmt_doc("{.center}\nhello\n", Format::Djot);
19426        bare.caret = bare.source.find("hello").unwrap();
19427        bare.set_alignment(None);
19428        assert_eq!(
19429            bare.source, "hello\n",
19430            "the last key takes the line with it"
19431        );
19432
19433        let mut md = fmt_doc("hello\n", Format::Markdown);
19434        md.caret = 1;
19435        md.set_alignment(Some(Align::Center));
19436        assert_eq!(md.source, "<div class=\"center\">\n\nhello\n\n</div>\n");
19437        md.caret = md.source.find("hello").unwrap();
19438        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::OneFifteen)));
19439        assert_eq!(
19440            md.source, "<div class=\"center\" data-line-height=\"1.15\">\n\nhello\n\n</div>\n",
19441            "the second key rewrites the div rather than nesting a second"
19442        );
19443        md.caret = md.source.find("hello").unwrap();
19444        md.set_alignment(None);
19445        md.caret = md.source.find("hello").unwrap();
19446        md.set_line_spacing(None);
19447        assert_eq!(md.source, "hello\n", "an empty set unwraps the div");
19448    }
19449
19450    /// Size, face and colour are the run's over a selection and the block's
19451    /// with none — so "make this paragraph larger" is a click with the caret in
19452    /// it rather than a select-all first.
19453    #[test]
19454    fn a_run_gesture_wraps_a_selection_and_sets_the_block_without_one() {
19455        // With a selection: a span, in each format's own spelling.
19456        let mut dj = fmt_doc("a big b\n", Format::Djot);
19457        dj.anchor = Some(2);
19458        dj.caret = 5;
19459        dj.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19460        assert_eq!(dj.source, "a [big]{data-size=\"large\"} b\n");
19461        assert_eq!(
19462            dj.font_size_at_caret(),
19463            Some(FontSize::Step(SizeStep::Large))
19464        );
19465
19466        let mut md = fmt_doc("a big b\n", Format::Markdown);
19467        md.anchor = Some(2);
19468        md.caret = 5;
19469        md.set_text_color(Some(TextColor::Named(MarkColor::Blue)));
19470        assert_eq!(md.source, "a <span data-color=\"blue\">big</span> b\n");
19471        assert_eq!(
19472            md.text_color_at_caret(),
19473            Some(TextColor::Named(MarkColor::Blue))
19474        );
19475
19476        // Without one: the caret's block, through the block gesture.
19477        let mut block = fmt_doc("a big b\n", Format::Djot);
19478        block.caret = 3;
19479        block.set_font_family(Some(FontFace::Generic(FontFamily::Monospace)));
19480        assert_eq!(block.source, "{data-font=\"monospace\"}\na big b\n");
19481        assert_eq!(
19482            block.font_family_at_caret(),
19483            Some(FontFace::Generic(FontFamily::Monospace))
19484        );
19485    }
19486
19487    /// The *Other…* row of each of the four menus: a value goes into the
19488    /// document in its canonical spelling and comes back out of the query as
19489    /// the same value. One round trip per property, because the four go out
19490    /// through different doors — two block gestures, and the run three through
19491    /// the span that `wrap_range_attrs` mints.
19492    #[test]
19493    fn an_exact_value_round_trips_through_the_gesture_and_the_query() {
19494        // Size: the run three, over a selection.
19495        let mut d = fmt_doc("a big b\n", Format::Djot);
19496        d.anchor = Some(2);
19497        d.caret = 5;
19498        d.set_font_size(FontSize::points(14.0));
19499        assert_eq!(d.source, "a [big]{data-size=\"14pt\"} b\n");
19500        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19501
19502        // Colour, onto the same span — the gesture keeps the size it finds.
19503        d.set_text_color(Some(TextColor::Rgb {
19504            r: 0xc0,
19505            g: 0x30,
19506            b: 0x30,
19507        }));
19508        assert_eq!(
19509            d.source,
19510            "a [big]{data-size=\"14pt\" data-color=\"#c03030\"} b\n"
19511        );
19512        assert_eq!(
19513            d.text_color_at_caret(),
19514            Some(TextColor::Rgb {
19515                r: 0xc0,
19516                g: 0x30,
19517                b: 0x30
19518            })
19519        );
19520
19521        // Face: a family name, as given.
19522        d.set_font_family(Some(FontFace::Named("Garamond".into())));
19523        assert!(
19524            d.source.contains("data-font=\"Garamond\""),
19525            "{:?}",
19526            d.source
19527        );
19528        assert_eq!(
19529            d.font_family_at_caret(),
19530            Some(FontFace::Named("Garamond".into()))
19531        );
19532
19533        // Line spacing: a block gesture, and an exact ratio.
19534        let mut block = fmt_doc("hello\n", Format::Djot);
19535        block.caret = 1;
19536        block.set_line_spacing(LineHeight::ratio(1.3));
19537        assert_eq!(block.source, "{data-line-height=\"1.3\"}\nhello\n");
19538        assert_eq!(block.line_spacing_at_caret(), LineHeight::ratio(1.3));
19539
19540        // And a value spelled long is written back short, so the same press
19541        // twice writes the same bytes: `14.0pt` in, `14pt` out.
19542        let mut long = fmt_doc("{data-size=\"14.0pt\"}\nhello\n", Format::Djot);
19543        long.caret = long.source.find("hello").unwrap();
19544        assert_eq!(long.font_size_at_caret(), FontSize::points(14.0));
19545        let in_force = long.font_size_at_caret();
19546        long.set_font_size(in_force);
19547        assert_eq!(long.source, "{data-size=\"14pt\"}\nhello\n");
19548    }
19549
19550    /// A value the grammar does not cover is what it was before the vocabulary
19551    /// opened: carried untouched by the document, answered `None` by the query
19552    /// so the menu ticks *Default*, and rewritten only by a gesture on its own
19553    /// key. leaf is not going to grow a CSS parser to guess at `1.3em`.
19554    #[test]
19555    fn a_value_outside_the_grammar_is_carried_and_the_menu_ticks_the_default() {
19556        let src =
19557            "{data-size=\"huge\" data-color=\"rgb(1,2,3)\" data-line-height=\"1.3em\"}\nhello\n";
19558        let mut d = fmt_doc(src, Format::Djot);
19559        d.caret = d.source.find("hello").unwrap();
19560        assert_eq!(d.font_size_at_caret(), None);
19561        assert_eq!(d.text_color_at_caret(), None);
19562        assert_eq!(d.line_spacing_at_caret(), None);
19563
19564        // The keys are still there, untouched, after a gesture on a *different*
19565        // key — "edit one key and keep the rest" holds for a value it cannot
19566        // read as readily as for one it can.
19567        d.set_alignment(Some(Align::Center));
19568        assert!(d.source.contains("data-size=\"huge\""), "{:?}", d.source);
19569        assert!(
19570            d.source.contains("data-color=\"rgb(1,2,3)\""),
19571            "{:?}",
19572            d.source
19573        );
19574        assert!(
19575            d.source.contains("data-line-height=\"1.3em\""),
19576            "{:?}",
19577            d.source
19578        );
19579        // And the gesture on its *own* key replaces it, which is the one way a
19580        // carried value ever changes.
19581        d.caret = d.source.find("hello").unwrap();
19582        d.set_font_size(FontSize::points(12.0));
19583        assert!(d.source.contains("data-size=\"12pt\""), "{:?}", d.source);
19584        assert!(!d.source.contains("huge"), "{:?}", d.source);
19585    }
19586
19587    /// The nearest node wins whichever *form* either node wrote: a value inside
19588    /// a name, a name inside a value. The fold has one rule and does not learn
19589    /// a second one for exact values.
19590    #[test]
19591    fn the_nearest_node_wins_whether_it_named_a_size_or_measured_one() {
19592        // A value inside a name: the block says `small`, the span says `14pt`.
19593        let mut d = fmt_doc(
19594            "{data-size=\"small\"}\nx [y]{data-size=\"14pt\"} z\n",
19595            Format::Djot,
19596        );
19597        d.caret = d.source.find('y').unwrap();
19598        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19599        d.caret = d.source.find('x').unwrap();
19600        assert_eq!(
19601            d.font_size_at_caret(),
19602            Some(FontSize::Step(SizeStep::Small))
19603        );
19604
19605        // And a name inside a value, which is the same rule read the other way.
19606        let mut e = fmt_doc(
19607            "{data-size=\"14pt\" data-color=\"#c03030\"}\nx [y]{data-size=\"small\"} z\n",
19608            Format::Djot,
19609        );
19610        e.caret = e.source.find('y').unwrap();
19611        assert_eq!(
19612            e.font_size_at_caret(),
19613            Some(FontSize::Step(SizeStep::Small))
19614        );
19615        assert_eq!(
19616            e.text_color_at_caret(),
19617            Some(TextColor::Rgb {
19618                r: 0xc0,
19619                g: 0x30,
19620                b: 0x30
19621            }),
19622            "the block's colour still reaches the span"
19623        );
19624        e.caret = e.source.find('x').unwrap();
19625        assert_eq!(e.font_size_at_caret(), FontSize::points(14.0));
19626    }
19627
19628    /// twig re-styles the span a range already lies in rather than nesting a
19629    /// second, and an empty set unwraps it — so a second press of the menu
19630    /// fixes the size instead of building `[[big]{.a}]{.b}`, and the entry that
19631    /// means "the theme's own" takes the span away.
19632    #[test]
19633    fn a_second_run_gesture_re_styles_the_span_and_none_unwraps_it() {
19634        let mut d = fmt_doc("a big b\n", Format::Djot);
19635        d.anchor = Some(2);
19636        d.caret = 5;
19637        d.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19638        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19639
19640        // The selection `wrap_range_attrs` left behind covers the whole span;
19641        // colouring it now keeps the size, because the gesture reads the span's
19642        // attributes before it edits its own key.
19643        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19644        assert_eq!(
19645            d.source, "a [big]{data-size=\"large\" data-color=\"red\"} b\n",
19646            "one span, both keys"
19647        );
19648        assert_eq!(
19649            d.font_size_at_caret(),
19650            Some(FontSize::Step(SizeStep::Large))
19651        );
19652        assert_eq!(
19653            d.text_color_at_caret(),
19654            Some(TextColor::Named(MarkColor::Red))
19655        );
19656
19657        d.set_text_color(None);
19658        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19659        d.set_font_size(None);
19660        assert_eq!(d.source, "a big b\n", "the last key unwraps the span");
19661        assert_eq!(d.font_size_at_caret(), None);
19662    }
19663
19664    /// The queries read the nearest node that names the property: the span the
19665    /// caret is in, then its block, then the `div`s around it.
19666    #[test]
19667    fn a_presentation_query_reads_the_nearest_node_that_names_it() {
19668        let mut d = fmt_doc(
19669            "{.center data-size=\"small\" data-font=\"serif\"}\nx [y]{data-size=\"xx-large\"} z\n",
19670            Format::Djot,
19671        );
19672        // In the span: its own size, the block's face and alignment.
19673        d.caret = d.source.find('y').unwrap();
19674        assert_eq!(
19675            d.font_size_at_caret(),
19676            Some(FontSize::Step(SizeStep::XxLarge))
19677        );
19678        assert_eq!(
19679            d.font_family_at_caret(),
19680            Some(FontFace::Generic(FontFamily::Serif))
19681        );
19682        assert_eq!(d.alignment_at_caret(), Some(Align::Center));
19683        assert_eq!(d.line_spacing_at_caret(), None);
19684        assert_eq!(d.text_color_at_caret(), None);
19685
19686        // Outside it: the block's size.
19687        d.caret = d.source.find('x').unwrap();
19688        assert_eq!(
19689            d.font_size_at_caret(),
19690            Some(FontSize::Step(SizeStep::Small))
19691        );
19692
19693        // And through a Markdown div, which is where a Markdown block's
19694        // attributes live.
19695        let mut md = fmt_doc(
19696            "<div class=\"center\" data-size=\"large\">\n\nhello\n\n</div>\n",
19697            Format::Markdown,
19698        );
19699        md.caret = md.source.find("hello").unwrap();
19700        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19701        assert_eq!(
19702            md.font_size_at_caret(),
19703            Some(FontSize::Step(SizeStep::Large))
19704        );
19705
19706        // A document that names none of it answers `None` everywhere, which is
19707        // "the theme's own" and what every toolbar draws unlit.
19708        let mut plain = doc_with("plain_presentation", "hello\n");
19709        plain.caret = 1;
19710        assert_eq!(plain.alignment_at_caret(), None);
19711        assert_eq!(plain.line_spacing_at_caret(), None);
19712        assert_eq!(plain.font_size_at_caret(), None);
19713        assert_eq!(plain.font_family_at_caret(), None);
19714        assert_eq!(plain.text_color_at_caret(), None);
19715    }
19716
19717    /// A djot fenced div is anonymous the way an attributed span is, and is a
19718    /// block all the same — the *form* is the whole of what tells them apart.
19719    /// Read as a span it poisoned both halves: the run gesture copied the div's
19720    /// entire attribute set onto the span it minted, duplicating the `id`, and
19721    /// the run and block queries answered off a node the walker draws nothing
19722    /// for.
19723    #[test]
19724    fn a_djot_fenced_div_is_not_an_attributed_span() {
19725        let src = "{.center data-size=\"small\" #box}\n:::\nhello world\n:::\n";
19726        let mut d = fmt_doc(src, Format::Djot);
19727        let at = d.source.find("world").unwrap();
19728        d.anchor = Some(at);
19729        d.caret = at + "world".len();
19730        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19731        assert_eq!(
19732            d.source,
19733            "{.center data-size=\"small\" #box}\n:::\nhello [world]{data-color=\"red\"}\n:::\n",
19734            "the span carries its own key and nothing of the div's"
19735        );
19736
19737        // And the queries stop at the block: a djot div is not a `<div>`, the
19738        // walker lends its keys to nothing inside it, and a query that said
19739        // otherwise would tick a menu entry no glyph on screen obeys.
19740        assert_eq!(
19741            d.text_color_at_caret(),
19742            Some(TextColor::Named(MarkColor::Red))
19743        );
19744        assert_eq!(d.font_size_at_caret(), None);
19745        assert_eq!(d.alignment_at_caret(), None);
19746    }
19747
19748    /// Clearing a property the block does not name and a `div` around it does
19749    /// would write nothing and change nothing — twig's `set_block_attrs`
19750    /// reaches one node, and the div is not it. The gesture says so instead of
19751    /// leaving the author pressing an entry that never ticks.
19752    #[test]
19753    fn clearing_a_property_an_enclosing_div_names_says_so_and_writes_nothing() {
19754        // Markdown, two paragraphs in one div: not the sole-child shape twig
19755        // writes, so `block_attrs_at_caret` reads the paragraph and the
19756        // paragraph names none of it.
19757        let src = "<div class=\"center\" data-line-height=\"1.5\" data-size=\"large\">\n\nhello\n\nworld\n\n</div>\n";
19758        let mut md = fmt_doc(src, Format::Markdown);
19759        md.caret = md.source.find("hello").unwrap();
19760        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19761
19762        md.set_alignment(None);
19763        assert_eq!(md.source, src, "nothing written");
19764        assert!(!md.dirty);
19765        assert_eq!(
19766            md.status.as_deref(),
19767            Some("alignment: set on the div around the block")
19768        );
19769        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19770
19771        // The same for a `data-` key, at both levels — the block pair and the
19772        // run three, the run three at a bare caret being the block gesture.
19773        md.set_line_spacing(None);
19774        assert_eq!(md.source, src);
19775        assert_eq!(
19776            md.status.as_deref(),
19777            Some("line spacing: set on the div around the block")
19778        );
19779        md.set_font_size(None);
19780        assert_eq!(md.source, src);
19781        assert_eq!(
19782            md.status.as_deref(),
19783            Some("size: set on the div around the block")
19784        );
19785
19786        // HTML has no sole-child fold at all: a block's attributes go on the
19787        // block, so the div around one is always out of reach.
19788        let html_src = "<div class=\"center\"><p>hi</p></div>\n";
19789        let mut html = fmt_doc(html_src, Format::Html);
19790        html.caret = html.source.find("hi").unwrap();
19791        assert_eq!(html.alignment_at_caret(), Some(Align::Center));
19792        html.set_alignment(None);
19793        assert_eq!(html.source, html_src);
19794        assert!(!html.dirty);
19795        assert_eq!(
19796            html.status.as_deref(),
19797            Some("alignment: set on the div around the block")
19798        );
19799
19800        // And it is a refusal, not a rule against clearing: a block that names
19801        // the property itself still loses it, div or no div.
19802        let mut own = fmt_doc(
19803            "<div class=\"center\"><p class=\"right\">hi</p></div>\n",
19804            Format::Html,
19805        );
19806        own.caret = own.source.find("hi").unwrap();
19807        own.set_alignment(None);
19808        assert_eq!(own.source, "<div class=\"center\"><p>hi</p></div>\n");
19809        assert_eq!(own.status, None);
19810    }
19811
19812    /// An edited key is rewritten **where it stands**. The proposal's worked
19813    /// example is the test: a paragraph that came in as `id="intro"
19814    /// class="lead center" data-line-height="1.5"` and is right-aligned goes
19815    /// out as the same list with one token changed. Removing the key and
19816    /// pushing it back shuffled a document's attributes on every press.
19817    #[test]
19818    fn an_edited_key_keeps_its_place_among_the_attributes() {
19819        let mut html = fmt_doc(
19820            "<p id=\"intro\" class=\"lead center\" data-line-height=\"1.5\">hello</p>\n",
19821            Format::Html,
19822        );
19823        html.caret = html.source.find("hello").unwrap();
19824        html.set_alignment(Some(Align::Right));
19825        assert_eq!(
19826            html.source,
19827            "<p id=\"intro\" class=\"lead right\" data-line-height=\"1.5\">hello</p>\n"
19828        );
19829
19830        // A `data-` key the same way, and a key the block did not have still
19831        // goes on the end.
19832        html.caret = html.source.find("hello").unwrap();
19833        html.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19834        assert_eq!(
19835            html.source,
19836            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\">hello</p>\n"
19837        );
19838        html.caret = html.source.find("hello").unwrap();
19839        html.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19840        assert_eq!(
19841            html.source,
19842            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\" data-size=\"large\">hello</p>\n"
19843        );
19844
19845        // Djot writes the same list in its own spelling, and the order is the
19846        // author's there too.
19847        let mut dj = fmt_doc(
19848            "{#intro .lead .center data-line-height=\"1.5\"}\nhello\n",
19849            Format::Djot,
19850        );
19851        dj.caret = dj.source.find("hello").unwrap();
19852        dj.set_alignment(Some(Align::Right));
19853        assert_eq!(
19854            dj.source,
19855            "{#intro .lead .right data-line-height=\"1.5\"}\nhello\n"
19856        );
19857    }
19858
19859    /// A page break is a block, so twig alone lands one after the caret's whole
19860    /// block; the paragraph is parted at the caret first, exactly as
19861    /// `insert_thematic_break` parts it, and each format spells the directive
19862    /// its own way.
19863    #[test]
19864    fn insert_page_break_parts_the_paragraph_and_spells_the_directive() {
19865        let mut md = doc_with("page_break_md", "hello world\n");
19866        md.caret = 5;
19867        md.insert_page_break();
19868        assert_eq!(md.source, "hello\n\n::page-break\n\nworld\n");
19869        assert!(md.dirty);
19870        assert_eq!(md.status, None);
19871
19872        let mut dj = fmt_doc("hello world\n", Format::Djot);
19873        dj.caret = 5;
19874        dj.insert_page_break();
19875        assert_eq!(dj.source, "hello\n\n::: page-break\n:::\n\nworld\n");
19876
19877        // At a block's end there is no second half to mint, so the break simply
19878        // follows the block — the rule the rule button already has.
19879        let mut end = doc_with("page_break_end", "hello\n");
19880        end.caret = 5;
19881        end.insert_page_break();
19882        assert_eq!(end.source, "hello\n\n::page-break\n\n");
19883        assert_eq!(end.caret, end.source.len(), "on the line under the break");
19884
19885        // And it reaches the map as the placeholder row a frontend paginates on.
19886        end.view = View::Wysiwyg;
19887        end.build_visual(80);
19888        assert_eq!(
19889            end.vmap
19890                .rows
19891                .iter()
19892                .find_map(|r| r.leaf_directive.as_ref())
19893                .map(|m| m.name.as_str()),
19894            Some(PAGE_BREAK)
19895        );
19896
19897        // HTML and AsciiDoc spell it their own way, and draw it the same.
19898        for (fmt, src, spelled) in [
19899            (Format::Html, "<p>hello</p>\n", "<page-break></page-break>"),
19900            (Format::Asciidoc, "hello\n", "<<<"),
19901        ] {
19902            let mut d = fmt_doc(src, fmt);
19903            d.caret = d.source.find("hello").unwrap() + 5;
19904            d.insert_page_break();
19905            assert!(d.source.contains(spelled), "{fmt:?}: {:?}", d.source);
19906            d.view = View::Wysiwyg;
19907            d.build_visual(80);
19908            let marks = d
19909                .vmap
19910                .rows
19911                .iter()
19912                .filter_map(|r| r.leaf_directive.as_ref())
19913                .map(|m| m.name.as_str())
19914                .collect::<Vec<_>>();
19915            assert_eq!(marks, [PAGE_BREAK], "{fmt:?}");
19916        }
19917    }
19918
19919    /// The vocabulary's capabilities, per format. The two block properties are
19920    /// `SetBlockAttrs` and the three run ones `WrapRangeAttrs`, which is why
19921    /// AsciiDoc can align a paragraph and not size a run: its `[#id.role]#text#`
19922    /// keeps an id and a role and has no slot for a `data-` key.
19923    #[test]
19924    fn the_presentation_capabilities_are_ragged_per_format() {
19925        for fmt in [Format::Markdown, Format::Djot, Format::Html] {
19926            let c = Capabilities::of(fmt);
19927            assert!(c.alignment, "{fmt:?} alignment");
19928            assert!(c.line_spacing, "{fmt:?} line spacing");
19929            assert!(c.font_size, "{fmt:?} size");
19930            assert!(c.font_family, "{fmt:?} face");
19931            assert!(c.text_color, "{fmt:?} colour");
19932        }
19933        // Markdown spells both only under the extensions leaf parses with — a
19934        // `<div>` and a `<span>` read back as containers under `html_elements`,
19935        // and `::page-break` as a directive under `directives`. Ask twig's own
19936        // defaults and the answer is no, which is why `Capabilities` is built
19937        // with `supports_with`.
19938        assert!(!Format::Markdown.supports(Gesture::SetBlockAttrs));
19939        assert!(!Format::Markdown.supports(Gesture::WrapRangeAttrs));
19940        assert!(!Format::Markdown.supports(Gesture::InsertDirective));
19941
19942        let adoc = Capabilities::of(Format::Asciidoc);
19943        assert!(adoc.alignment && adoc.line_spacing, "AsciiDoc's `[…]` line");
19944        assert!(
19945            !adoc.font_size && !adoc.font_family && !adoc.text_color,
19946            "AsciiDoc has no inline spelling that keeps a data- key"
19947        );
19948
19949        // XML spells none of it, and neither page break — nor has it blocks a
19950        // caret could name for a move.
19951        let xml = Capabilities::of(Format::Xml);
19952        assert!(!xml.alignment && !xml.font_size && !xml.page_break && !xml.move_block);
19953        for f in [Format::Markdown, Format::Djot, Format::Html] {
19954            assert!(Capabilities::of(f).move_block, "{f:?} moves blocks");
19955        }
19956        for f in [
19957            Format::Markdown,
19958            Format::Djot,
19959            Format::Html,
19960            Format::Asciidoc,
19961        ] {
19962            assert!(Capabilities::of(f).page_break, "{f:?} breaks pages");
19963        }
19964    }
19965
19966    /// A format that cannot spell a property refuses in its own words and
19967    /// writes nothing — the guard every other gesture has.
19968    #[test]
19969    fn a_presentation_gesture_a_format_cannot_spell_is_refused_with_a_reason() {
19970        let src = "<doc><p>hello</p></doc>\n";
19971        #[allow(clippy::type_complexity)]
19972        let ops: [(&str, &dyn Fn(&mut Doc)); 6] = [
19973            ("alignment", &|d: &mut Doc| {
19974                d.set_alignment(Some(Align::Center))
19975            }),
19976            ("line spacing", &|d: &mut Doc| {
19977                d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)))
19978            }),
19979            ("size", &|d: &mut Doc| {
19980                d.set_font_size(Some(FontSize::Step(SizeStep::Large)))
19981            }),
19982            ("face", &|d: &mut Doc| {
19983                d.set_font_family(Some(FontFace::Generic(FontFamily::Serif)))
19984            }),
19985            ("colour", &|d: &mut Doc| {
19986                d.set_text_color(Some(TextColor::Named(MarkColor::Red)))
19987            }),
19988            ("page break", &|d: &mut Doc| d.insert_page_break()),
19989        ];
19990        for (name, op) in ops {
19991            let mut d = fmt_doc(src, Format::Xml);
19992            let at = d.source.find("hello").unwrap();
19993            d.caret = at;
19994            d.anchor = Some(at + 5);
19995            op(&mut d);
19996            assert_eq!(d.source, src, "{name} edited an XML document");
19997            assert!(!d.dirty, "{name} marked the document dirty");
19998            let status = d.status.as_deref().unwrap_or("");
19999            assert!(
20000                status.contains("xml"),
20001                "{name}: the refusal should name the format, got {status:?}"
20002            );
20003        }
20004
20005        // AsciiDoc is the ragged one: the block gesture works where the run
20006        // gesture does not, and a *selection* is what tells the two apart.
20007        let mut adoc = fmt_doc("hello world\n", Format::Asciidoc);
20008        adoc.anchor = Some(0);
20009        adoc.caret = 5;
20010        adoc.set_font_size(Some(FontSize::Step(SizeStep::Large)));
20011        assert_eq!(adoc.source, "hello world\n", "no inline spelling");
20012        assert!(adoc.status.is_some());
20013    }
20014
20015    /// A read-only document takes none of it, and a caret on a blank line has
20016    /// no block to carry an attribute — both say so rather than writing.
20017    #[test]
20018    fn a_presentation_gesture_respects_read_only_and_a_blank_line() {
20019        let mut ro = fmt_doc("hello\n", Format::Djot);
20020        ro.read_only = true;
20021        ro.caret = 1;
20022        ro.set_alignment(Some(Align::Center));
20023        assert_eq!(ro.source, "hello\n");
20024
20025        let mut blank = fmt_doc("a\n\n\nb\n", Format::Djot);
20026        blank.caret = 2; // the empty line between the two paragraphs
20027        blank.set_alignment(Some(Align::Center));
20028        assert_eq!(blank.source, "a\n\n\nb\n");
20029        assert!(
20030            blank.status.as_deref().unwrap_or("").contains("no block"),
20031            "got {:?}",
20032            blank.status
20033        );
20034    }
20035
20036    /// A block attribute gesture keeps the caret on the **text** it was on, not
20037    /// on the byte offset it had. Markdown has nowhere to put a paragraph's
20038    /// attributes but a `<div>` around it, and twig splices the div and the
20039    /// block it wraps as one region — so a caret that kept its offset landed in
20040    /// the markup, and every press after the first answered "no block at the
20041    /// caret" with the toolbar's queries reading nothing.
20042    #[test]
20043    fn a_markdown_block_gesture_keeps_the_caret_on_its_text() {
20044        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
20045        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
20046        md.caret = md.source.find("brown").unwrap() + 2; // "br|own"
20047
20048        // Wrapping: the div and two blank lines open above the block.
20049        md.set_alignment(Some(Align::Center));
20050        assert_eq!(
20051            md.source,
20052            "<div class=\"center\">\n\nthe quick brown fox\n\n</div>\n"
20053        );
20054        assert_eq!(word(&md), 2, "the caret left its word: {}", md.caret);
20055        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
20056
20057        // Re-styling: the attribute line changes length under the same caret,
20058        // and the second press reaches the same block rather than nothing.
20059        md.set_alignment(Some(Align::Right));
20060        assert_eq!(
20061            md.source, "<div class=\"right\">\n\nthe quick brown fox\n\n</div>\n",
20062            "a second press re-styles the div"
20063        );
20064        assert_eq!(md.status, None);
20065        assert_eq!(word(&md), 2);
20066
20067        // A second key on the same div — the line grows, the caret rides it.
20068        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
20069        assert_eq!(
20070            md.source,
20071            "<div class=\"right\" data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
20072        );
20073        assert_eq!(word(&md), 2);
20074        assert_eq!(
20075            md.line_spacing_at_caret(),
20076            Some(LineHeight::Step(LineSpacing::Double))
20077        );
20078
20079        // Unwrapping: the line shrinks, and then the div goes altogether.
20080        md.set_alignment(None);
20081        assert_eq!(
20082            md.source,
20083            "<div data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
20084        );
20085        assert_eq!(word(&md), 2);
20086        md.set_line_spacing(None);
20087        assert_eq!(md.source, "the quick brown fox\n", "the last key unwraps");
20088        assert_eq!(word(&md), 2, "the caret came back down with the block");
20089        assert_eq!(md.alignment_at_caret(), None);
20090        assert_eq!(md.status, None);
20091    }
20092
20093    /// The same rule in djot, where the spelling is a `{…}` line *above* the
20094    /// block rather than a wrapper around it: inserting it pushes the block
20095    /// down, re-styling it changes the line's length, and clearing the last key
20096    /// takes the line away again. The caret rides all three.
20097    #[test]
20098    fn a_djot_attribute_line_keeps_the_caret_on_its_text() {
20099        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
20100        let mut dj = fmt_doc("the quick brown fox\n", Format::Djot);
20101        dj.caret = dj.source.find("brown").unwrap() + 2;
20102
20103        dj.set_alignment(Some(Align::Center));
20104        assert_eq!(dj.source, "{.center}\nthe quick brown fox\n");
20105        assert_eq!(word(&dj), 2);
20106        assert_eq!(dj.alignment_at_caret(), Some(Align::Center));
20107
20108        dj.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
20109        assert_eq!(
20110            dj.source, "{.center data-line-height=\"2\"}\nthe quick brown fox\n",
20111            "a second press edits the line the first wrote"
20112        );
20113        assert_eq!(word(&dj), 2);
20114
20115        dj.set_alignment(None);
20116        assert_eq!(dj.source, "{data-line-height=\"2\"}\nthe quick brown fox\n");
20117        assert_eq!(word(&dj), 2);
20118
20119        dj.set_line_spacing(None);
20120        assert_eq!(dj.source, "the quick brown fox\n");
20121        assert_eq!(word(&dj), 2);
20122        assert_eq!(dj.status, None);
20123    }
20124
20125    /// The run gestures with no selection are the block gesture, so they keep
20126    /// the caret the same way — and a heading keeps it inside the heading's own
20127    /// text, past the `# ` its content span starts after. A selection rides
20128    /// along whole: a block gesture is not a run gesture, and what was selected
20129    /// before the press is still selected after it.
20130    #[test]
20131    fn a_block_gesture_carries_a_selection_and_a_heading_caret_too() {
20132        // No selection: the run gesture goes through the block door.
20133        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
20134        md.caret = md.source.find("brown").unwrap() + 2;
20135        md.set_font_size(Some(FontSize::Step(SizeStep::Large)));
20136        assert_eq!(
20137            md.source,
20138            "<div data-size=\"large\">\n\nthe quick brown fox\n\n</div>\n"
20139        );
20140        assert_eq!(md.caret - md.source.find("brown").unwrap(), 2);
20141        assert_eq!(
20142            md.font_size_at_caret(),
20143            Some(FontSize::Step(SizeStep::Large))
20144        );
20145        md.set_font_size(Some(FontSize::Step(SizeStep::Small)));
20146        assert_eq!(
20147            md.font_size_at_caret(),
20148            Some(FontSize::Step(SizeStep::Small)),
20149            "the second press reached the same block"
20150        );
20151
20152        // A selection: alignment is the block's whatever is selected, and the
20153        // words stay selected.
20154        let mut sel = fmt_doc("the quick brown fox\n", Format::Markdown);
20155        let at = sel.source.find("brown").unwrap();
20156        sel.anchor = Some(at);
20157        sel.caret = at + 5;
20158        sel.set_alignment(Some(Align::Center));
20159        let now = sel.source.find("brown").unwrap();
20160        assert_eq!(sel.selection(), Some((now, now + 5)), "the words moved out");
20161
20162        // A heading: the content span starts past the `# `.
20163        let mut h = fmt_doc("# hi there\n\nbody\n", Format::Markdown);
20164        h.caret = h.source.find("there").unwrap() + 1;
20165        h.set_alignment(Some(Align::Right));
20166        assert_eq!(
20167            h.source,
20168            "<div class=\"right\">\n\n# hi there\n\n</div>\n\nbody\n"
20169        );
20170        assert_eq!(h.caret, h.source.find("there").unwrap() + 1);
20171        assert_eq!(h.alignment_at_caret(), Some(Align::Right));
20172    }
20173
20174    /// A djot document open in the rich view, with its map built as
20175    /// [`wysiwyg_doc`] builds a Markdown one's.
20176    fn wysiwyg_djot(body: &str) -> Doc {
20177        let mut d = fmt_doc(body, Format::Djot);
20178        d.view = View::Wysiwyg;
20179        d.build_visual(80);
20180        d
20181    }
20182
20183    /// Backspace at the start of a block whose presentation is spelled as
20184    /// hidden markup before it strips that presentation, the way Backspace at
20185    /// a heading's start strips its `#`. The ordinary delete fused djot's
20186    /// `{.center}` line onto the text and took the blank line a Markdown div
20187    /// needs between its tag and its paragraph.
20188    #[test]
20189    fn backspace_at_the_start_of_a_centred_paragraph_strips_its_attributes() {
20190        let mut md = wysiwyg_doc(
20191            "wys_attr_bksp",
20192            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
20193        );
20194        md.caret = md.source.find("hello").unwrap();
20195        md.backspace();
20196        assert_eq!(
20197            md.source, "above\n\nhello\n\nbelow\n",
20198            "the div is unwrapped"
20199        );
20200        assert_eq!(md.caret, 7, "the caret stays at the start of its text");
20201        md.backspace();
20202        assert_eq!(
20203            md.source, "above\nhello\n\nbelow\n",
20204            "the next press joins the paragraphs, as it always did"
20205        );
20206
20207        let mut dj = wysiwyg_djot("above\n\n{.center}\nhello\n\nbelow\n");
20208        dj.caret = dj.source.find("hello").unwrap();
20209        dj.backspace();
20210        assert_eq!(
20211            dj.source, "above\n\nhello\n\nbelow\n",
20212            "the attribute line goes"
20213        );
20214        assert_eq!(dj.caret, 7);
20215
20216        // A heading's own marker is the nearer hidden markup, and goes first;
20217        // the attributes are the next press's.
20218        let mut dj = wysiwyg_djot("{.center}\n# Title\n");
20219        dj.caret = dj.source.find("Title").unwrap();
20220        dj.backspace();
20221        assert_eq!(dj.source, "{.center}\nTitle\n", "the `#` first");
20222        dj.build_visual(80);
20223        dj.backspace();
20224        assert_eq!(dj.source, "Title\n", "then the attributes");
20225        assert_eq!(dj.caret, 0);
20226    }
20227
20228    /// A div around several blocks has no sole child for twig to unwrap, so
20229    /// at its first block the caret steps back to the stop before rather than
20230    /// taking the div apart; a later block has an ordinary paragraph above it
20231    /// and joins as any paragraph does.
20232    #[test]
20233    fn backspace_at_the_first_of_a_div_s_blocks_steps_back_and_a_later_one_joins() {
20234        let src = "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n";
20235        let mut d = wysiwyg_doc("wys_div_first", src);
20236        d.caret = d.source.find("hello").unwrap();
20237        d.backspace();
20238        assert_eq!(d.source, src, "nothing is deleted");
20239        assert_eq!(d.caret, 5, "the caret steps back to the end of `above`");
20240
20241        let mut d = wysiwyg_doc("wys_div_later", src);
20242        d.caret = d.source.find("world").unwrap();
20243        d.backspace();
20244        assert_eq!(
20245            d.source, "above\n\n<div class=\"center\">\n\nhello\nworld\n\n</div>\n",
20246            "a later block joins the one above it"
20247        );
20248    }
20249
20250    /// Backspace at the start of the paragraph after a Markdown div joins it
20251    /// into the div's last paragraph — the join any two paragraphs make, with
20252    /// the hidden `</div>` carried past the joined text. The ordinary delete
20253    /// took the newline under the tag, which drew nothing different, and the
20254    /// next press took the `>` and left the div unclosed.
20255    #[test]
20256    fn backspace_after_a_div_joins_the_paragraph_into_it() {
20257        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20258        let mut d = wysiwyg_doc("wys_div_join", src);
20259        d.caret = d.source.find("below").unwrap();
20260        d.backspace();
20261        assert_eq!(
20262            d.source,
20263            "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n"
20264        );
20265        assert_eq!(
20266            d.caret,
20267            d.source.find("below").unwrap(),
20268            "the caret stays at the start of the joined text"
20269        );
20270        d.build_visual(80);
20271        assert_eq!(
20272            d.alignment_at_caret(),
20273            Some(Align::Center),
20274            "and is centred now"
20275        );
20276        d.undo();
20277        assert_eq!(d.source, src, "one undo step");
20278
20279        // A list closes the div: the paragraph joins the last item's text,
20280        // under the item's continuation indent, inside the div.
20281        let src = "<div class=\"center\">\n\n- item\n\n</div>\n\nbelow\n";
20282        let mut d = wysiwyg_doc("wys_div_list", src);
20283        d.caret = d.source.find("below").unwrap();
20284        d.backspace();
20285        assert_eq!(
20286            d.source, "<div class=\"center\">\n\n- item\n  below\n\n</div>\n",
20287            "the paragraph joins the item"
20288        );
20289        assert_eq!(d.caret, d.source.find("below").unwrap());
20290
20291        // And where twig has nothing to join into — a code block above — the
20292        // caret steps back to the stop before, and nothing is deleted.
20293        let src = "```\ncode\n```\n\nbelow\n";
20294        let mut d = wysiwyg_doc("wys_code_then_para", src);
20295        d.caret = d.source.find("below").unwrap();
20296        d.backspace();
20297        assert_eq!(d.source, src, "nothing is deleted");
20298        assert!(
20299            d.caret < d.source.find("below").unwrap(),
20300            "the caret stepped back"
20301        );
20302    }
20303
20304    /// Backspace on a blank line collapses to the stop before it — but not
20305    /// across hidden markup, which that collapse deleted whole: a `</div>`,
20306    /// or a comment between two blocks. There the blank line goes alone, and
20307    /// the caret lands where the collapse would have put it.
20308    #[test]
20309    fn backspace_on_a_blank_line_after_hidden_markup_keeps_the_markup() {
20310        let mut d = wysiwyg_doc(
20311            "wys_div_blank",
20312            "<div class=\"center\">\n\nhello\n\n</div>\n\n\n\nbelow\n",
20313        );
20314        d.caret = d.source.find("below").unwrap() - 2; // the empty paragraph
20315        assert!(
20316            d.vmap.is_stop(d.caret),
20317            "the empty paragraph is a caret home"
20318        );
20319        d.backspace();
20320        assert_eq!(
20321            d.source, "<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
20322            "the blank line goes and the div stays closed"
20323        );
20324        assert_eq!(
20325            d.caret,
20326            d.source.find("hello").unwrap() + 5,
20327            "onto the end of `hello`"
20328        );
20329
20330        let mut d = wysiwyg_doc("wys_comment_blank", "above\n\n<!-- note -->\n\n\n\nbelow\n");
20331        d.caret = d.source.find("below").unwrap() - 2;
20332        assert!(d.vmap.is_stop(d.caret));
20333        d.backspace();
20334        assert_eq!(
20335            d.source, "above\n\n<!-- note -->\n\nbelow\n",
20336            "the comment stays"
20337        );
20338        assert_eq!(d.caret, 5);
20339    }
20340
20341    /// Backspace at the end of an attributed span steps inside its hidden
20342    /// closing tag the way it steps inside a `**`, and takes the span with
20343    /// its last letter. Before, the byte-step took the `>` of `</span>`,
20344    /// which left the paragraph unparseable: it vanished from the rich view,
20345    /// and the Backspace after that joined the next block into the wreck.
20346    #[test]
20347    fn backspace_walks_into_a_sized_span_and_takes_the_emptied_span_with_its_space() {
20348        let src = "above\n\nThis <span data-size=\"x-large\">is</span> a test\n\nTest 2\n";
20349        let mut d = wysiwyg_doc("wys_span_bs", src);
20350        d.caret = d.source.find("a test").unwrap() + 6;
20351        for _ in 0..7 {
20352            d.backspace();
20353        }
20354        assert_eq!(
20355            d.source,
20356            "above\n\nThis <span data-size=\"x-large\">is</span>\n\nTest 2\n"
20357        );
20358        d.backspace();
20359        assert_eq!(
20360            d.source, "above\n\nThis <span data-size=\"x-large\">i</span>\n\nTest 2\n",
20361            "the first Backspace after the tag takes the letter, not the `>`"
20362        );
20363        d.backspace();
20364        assert_eq!(
20365            d.source, "above\n\nThis \n\nTest 2\n",
20366            "the last letter takes the span with it"
20367        );
20368        assert_eq!(d.caret, 12, "the caret is where the letter was");
20369        d.backspace();
20370        assert_eq!(d.source, "above\n\nThis\n\nTest 2\n");
20371        assert_eq!(d.caret, 11);
20372        d.build_visual(80);
20373        assert!(
20374            d.vmap
20375                .rows
20376                .iter()
20377                .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "This"),
20378            "the paragraph is still drawn"
20379        );
20380    }
20381
20382    #[test]
20383    fn backspace_walks_into_a_djot_sized_span_too() {
20384        let mut d = wysiwyg_djot("This [is]{data-size=\"x-large\"}\n\nTest 2\n");
20385        d.caret = d.source.find("\n\nTest 2").unwrap();
20386        // The caret home at the paragraph's end is inside the span, before
20387        // its `]`: the map offers no stop after `]{…}`.
20388        d.build_visual(80);
20389        assert_eq!(d.vmap.stop_before(31), Some(8));
20390        d.caret = 8;
20391        d.backspace();
20392        assert_eq!(d.source, "This [i]{data-size=\"x-large\"}\n\nTest 2\n");
20393        d.backspace();
20394        assert_eq!(
20395            d.source, "This \n\nTest 2\n",
20396            "the attribute block outside the span goes with it"
20397        );
20398        d.backspace();
20399        assert_eq!(d.source, "This\n\nTest 2\n");
20400        assert_eq!(d.caret, 4);
20401    }
20402
20403    /// A span that is empty as the file was written has no stop of its own;
20404    /// Backspace reaching it from behind takes it with the character before
20405    /// it, the character the key looked aimed at.
20406    #[test]
20407    fn backspace_over_an_already_empty_span_takes_it_with_the_character_before() {
20408        let src = "This <span data-size=\"x-large\"></span> a test\n";
20409        let mut d = wysiwyg_doc("wys_span_empty", src);
20410        d.caret = d.source.find(" a test").unwrap();
20411        d.backspace();
20412        assert_eq!(d.source, "This a test\n");
20413        assert_eq!(d.caret, 4);
20414    }
20415
20416    /// The mirror: Delete in front of a span's opening tag takes its first
20417    /// letter, and the span with its last.
20418    #[test]
20419    fn delete_walks_into_a_sized_span_and_takes_the_span_with_its_last_letter() {
20420        let src = "This <span data-size=\"x-large\">is</span> a test\n";
20421        let mut d = wysiwyg_doc("wys_span_del", src);
20422        d.caret = 5;
20423        d.delete_forward();
20424        assert_eq!(
20425            d.source,
20426            "This <span data-size=\"x-large\">s</span> a test\n"
20427        );
20428        d.delete_forward();
20429        assert_eq!(d.source, "This  a test\n");
20430        assert_eq!(d.caret, 5);
20431        d.delete_forward();
20432        assert_eq!(d.source, "This a test\n");
20433        assert_eq!(d.caret, 5);
20434    }
20435
20436    /// The block version of the span's emptying rule. Centre a one-letter
20437    /// paragraph — Markdown spells that as a `<div>` around it — and
20438    /// Backspace the letter: the div goes with it, leaving a plain blank line
20439    /// the caret is at home on, in the incremental map and the from-scratch
20440    /// one alike. Before, the letter went alone; the emptied div drew a
20441    /// caret home only the stale map had, and the next Backspace collapsed
20442    /// the line and left `<div class="center">\n\n</div>` standing invisibly
20443    /// in the file.
20444    #[test]
20445    fn backspace_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20446        let mut d = wysiwyg_doc("wys_div_empty", "Try the toolbar.\n\nT\n");
20447        d.caret = d.source.len() - 1;
20448        d.set_alignment(Some(Align::Center));
20449        assert_eq!(
20450            d.source,
20451            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n"
20452        );
20453        d.backspace();
20454        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20455        assert_eq!(d.caret, 18, "on the blank line where the letter was");
20456        // The host rebuilds the map after every key; the spliced map and a
20457        // fresh one both give the line a caret home.
20458        d.build_visual_unwrapped();
20459        assert!(d.vmap.is_stop(18));
20460        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20461        d.backspace();
20462        assert_eq!(
20463            d.source, "Try the toolbar.\n",
20464            "then the blank line collapses"
20465        );
20466        assert_eq!(d.caret, 16);
20467
20468        // With a block after the div the blank line keeps a gap each side.
20469        let mut d = wysiwyg_doc(
20470            "wys_div_empty_mid",
20471            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n\nbelow\n",
20472        );
20473        d.caret = d.source.find("T\n").unwrap() + 1;
20474        d.backspace();
20475        assert_eq!(d.source, "Try the toolbar.\n\n\n\nbelow\n");
20476        assert_eq!(d.caret, 18);
20477        d.build_visual_unwrapped();
20478        assert!(d.vmap.is_stop(18));
20479        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20480    }
20481
20482    /// djot spells the same paragraph as a `{.center}` line above it, and
20483    /// twig has no node at all for that line once the paragraph is gone —
20484    /// so the line goes with the letter too.
20485    #[test]
20486    fn backspace_that_empties_a_centred_paragraph_takes_its_djot_attrs_line_too() {
20487        let mut d = fmt_doc("Try the toolbar.\n\nT\n", Format::Djot);
20488        d.build_visual(80);
20489        d.caret = d.source.len() - 1;
20490        d.set_alignment(Some(Align::Center));
20491        assert_eq!(d.source, "Try the toolbar.\n\n{.center}\nT\n");
20492        d.backspace();
20493        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20494        assert_eq!(d.caret, 18);
20495        d.build_visual(80);
20496        assert!(d.vmap.is_stop(18));
20497    }
20498
20499    /// The rule is for a block that would be no block: a div holding more
20500    /// keeps its tags, and an emptied heading is still a heading.
20501    #[test]
20502    fn emptying_a_paragraph_keeps_a_div_that_holds_more_and_a_heading_its_marker() {
20503        let mut d = wysiwyg_doc(
20504            "wys_div_more",
20505            "<div class=\"center\">\n\nText\n\nT\n\n</div>\n",
20506        );
20507        d.caret = d.source.find("T\n").unwrap() + 1;
20508        d.backspace();
20509        assert_eq!(d.source, "<div class=\"center\">\n\nText\n\n\n\n</div>\n");
20510        assert_eq!(d.caret, 28, "the blank line inside the div, as after Enter");
20511
20512        let mut d = wysiwyg_doc(
20513            "wys_div_heading",
20514            "<div class=\"center\">\n\n# T\n\n</div>\n",
20515        );
20516        d.caret = d.source.find("T\n").unwrap() + 1;
20517        d.backspace();
20518        assert_eq!(d.source, "<div class=\"center\">\n\n# \n\n</div>\n");
20519        assert_eq!(d.caret, 24);
20520        d.build_visual(80);
20521        assert!(
20522            d.vmap.is_stop(24),
20523            "the empty heading is still a caret home"
20524        );
20525    }
20526
20527    /// The mirror: Delete in front of the letter takes the div with it.
20528    #[test]
20529    fn delete_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20530        let mut d = wysiwyg_doc(
20531            "wys_div_empty_del",
20532            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n",
20533        );
20534        d.caret = d.source.find("T\n").unwrap();
20535        d.delete_forward();
20536        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20537        assert_eq!(d.caret, 18);
20538        d.build_visual(80);
20539        assert!(d.vmap.is_stop(18));
20540
20541        let mut d = fmt_doc("Try the toolbar.\n\n{.center}\nT\n", Format::Djot);
20542        d.build_visual(80);
20543        d.caret = d.source.find("T\n").unwrap();
20544        d.delete_forward();
20545        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20546        assert_eq!(d.caret, 18);
20547    }
20548
20549    /// Backspace at a block's start is twig's join, spelled per format — so
20550    /// the cases the one-newline delete got wrong come out right: a
20551    /// paragraph joins onto a heading's line, HTML's `</p><p>` goes as one,
20552    /// and a quote's prefix is written on the joined line.
20553    #[test]
20554    fn backspace_at_a_block_start_joins_it_the_format_s_way() {
20555        let mut d = wysiwyg_doc("wys_join_heading", "# Title\n\nbelow\n");
20556        d.caret = d.source.find("below").unwrap();
20557        d.backspace();
20558        assert_eq!(d.source, "# Title below\n", "onto the heading's line");
20559        assert_eq!(d.caret, d.source.find("below").unwrap());
20560        d.undo();
20561        assert_eq!(d.source, "# Title\n\nbelow\n", "one undo step");
20562
20563        let mut d = wysiwyg_doc("wys_join_quote", "> a\n\nb\n");
20564        d.caret = d.source.find('b').unwrap();
20565        d.backspace();
20566        assert_eq!(d.source, "> a\n> b\n", "into the quote, with its prefix");
20567        assert_eq!(d.caret, d.source.find('b').unwrap());
20568
20569        let mut h = fmt_doc("<p>above</p>\n<p class=\"x\">below</p>\n", Format::Html);
20570        h.view = View::Wysiwyg;
20571        h.build_visual(80);
20572        h.caret = h.source.find("below").unwrap();
20573        h.backspace();
20574        assert_eq!(
20575            h.source, "<p>above\nbelow</p>\n",
20576            "one paragraph, the tag gone whole"
20577        );
20578        assert_eq!(h.caret, h.source.find("below").unwrap());
20579    }
20580
20581    /// Delete at the end of a block's content is the same join aimed at the
20582    /// block after it, and the caret stays where the joined text now begins.
20583    #[test]
20584    fn delete_at_a_block_end_joins_the_next_block_into_it() {
20585        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20586        let mut d = wysiwyg_doc("wys_del_join", src);
20587        d.caret = d.source.find("hello").unwrap() + 5;
20588        d.delete_forward();
20589        assert_eq!(
20590            d.source, "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n",
20591            "below joins hello inside the div"
20592        );
20593        assert_eq!(
20594            d.caret,
20595            d.source.find("hello").unwrap() + 5,
20596            "the caret stays"
20597        );
20598
20599        let mut d = wysiwyg_doc("wys_del_join_head", "above\n\n# Title\n");
20600        d.caret = 5;
20601        d.delete_forward();
20602        assert_eq!(
20603            d.source, "above\nTitle\n",
20604            "the heading's marker goes with the join"
20605        );
20606        assert_eq!(d.caret, 5);
20607
20608        // A code block after the paragraph: nothing to join, the caret steps
20609        // forward onto the next stop and nothing is deleted.
20610        let src = "above\n\n```\ncode\n```\n";
20611        let mut d = wysiwyg_doc("wys_del_code", src);
20612        d.caret = 5;
20613        d.delete_forward();
20614        assert_eq!(d.source, src);
20615        assert!(d.caret > 5, "the caret stepped forward");
20616    }
20617
20618    // ── Text statistics ──────────────────────────────────────────────────────
20619
20620    /// The counts of `body`, from a document open in the WYSIWYG view — the
20621    /// shape every case below starts from.
20622    fn counts_of(name: &str, body: &str) -> TextCounts {
20623        doc_in(View::Wysiwyg, name, body).counts()
20624    }
20625
20626    #[test]
20627    fn counts_tally_plain_prose() {
20628        let c = counts_of(
20629            "counts_prose",
20630            "The quick brown fox jumps over the lazy dog.\n",
20631        );
20632        assert_eq!(
20633            c,
20634            TextCounts {
20635                words: 9,
20636                characters: 44,
20637                characters_without_spaces: 36,
20638                paragraphs: 1,
20639            }
20640        );
20641    }
20642
20643    #[test]
20644    fn counts_read_the_text_and_not_the_markup() {
20645        // The `**` are four bytes of source and no part of the word.
20646        assert_eq!(
20647            counts_of("counts_marks", "a **bold** word\n"),
20648            TextCounts {
20649                words: 3,
20650                characters: 11,
20651                characters_without_spaces: 9,
20652                paragraphs: 1,
20653            }
20654        );
20655        // A link is its label; the destination is plumbing, however long.
20656        assert_eq!(
20657            counts_of(
20658                "counts_link",
20659                "see [the label](https://example.com/a/b/c) here\n"
20660            ),
20661            TextCounts {
20662                words: 4,
20663                characters: 18,
20664                characters_without_spaces: 15,
20665                paragraphs: 1,
20666            }
20667        );
20668    }
20669
20670    #[test]
20671    fn counts_spend_nothing_on_a_picture() {
20672        // A block image renders as a `🖼 alt` placeholder — a picture, not a
20673        // sentence, and not a paragraph either.
20674        assert_eq!(
20675            counts_of("counts_image", "![a long caption](pic.png)\n"),
20676            TextCounts::default()
20677        );
20678        // And it adds nothing to the prose around it.
20679        assert_eq!(
20680            counts_of("counts_image_prose", "text\n\n![a long caption](pic.png)\n"),
20681            TextCounts {
20682                words: 1,
20683                characters: 4,
20684                characters_without_spaces: 4,
20685                paragraphs: 1,
20686            }
20687        );
20688    }
20689
20690    #[test]
20691    fn counts_spend_nothing_on_drawn_furniture() {
20692        // A thematic break is drawn, not written, and an empty paragraph has
20693        // nothing in it — neither is a paragraph of the document.
20694        assert_eq!(
20695            counts_of("counts_rule", "one\n\n---\n\ntwo\n"),
20696            TextCounts {
20697                words: 2,
20698                characters: 6,
20699                characters_without_spaces: 6,
20700                paragraphs: 2,
20701            }
20702        );
20703    }
20704
20705    #[test]
20706    fn counts_measure_characters_as_a_reader_does() {
20707        // Four Han characters (each its own word under UAX#29), one ZWJ emoji
20708        // family that is a single grapheme cluster, and two letters.
20709        let c = counts_of(
20710            "counts_graphemes",
20711            "你好世界 👩\u{200d}👩\u{200d}👧\u{200d}👦 ok\n",
20712        );
20713        assert_eq!(
20714            c,
20715            TextCounts {
20716                words: 5,
20717                characters: 9,
20718                characters_without_spaces: 7,
20719                paragraphs: 1,
20720            }
20721        );
20722    }
20723
20724    #[test]
20725    fn counts_take_a_code_block_as_one_paragraph() {
20726        let c = counts_of("counts_code", "```rust\nlet x = 1;\n\nlet y = 2;\n```\n");
20727        assert_eq!(
20728            c,
20729            TextCounts {
20730                words: 6,
20731                characters: 20,
20732                characters_without_spaces: 14,
20733                paragraphs: 1,
20734            }
20735        );
20736    }
20737
20738    #[test]
20739    fn counts_take_a_table_as_one_paragraph() {
20740        // The box-drawn borders and the column padding are the renderer's, not
20741        // the author's; the cells are what was written.
20742        let c = counts_of("counts_table", "| a b | c |\n| - | - |\n| d | e |\n");
20743        assert_eq!(
20744            c,
20745            TextCounts {
20746                words: 5,
20747                characters: 6,
20748                characters_without_spaces: 5,
20749                paragraphs: 1,
20750            }
20751        );
20752    }
20753
20754    #[test]
20755    fn counts_give_every_item_and_every_quoted_paragraph_its_own_paragraph() {
20756        let c = counts_of(
20757            "counts_blocks",
20758            "- one\n- two\n- three\n\n> first quoted\n>\n> second quoted\n",
20759        );
20760        assert_eq!(
20761            c,
20762            TextCounts {
20763                words: 7,
20764                characters: 36,
20765                characters_without_spaces: 34,
20766                paragraphs: 5,
20767            }
20768        );
20769    }
20770
20771    #[test]
20772    fn counts_leave_the_frontmatter_out() {
20773        // The WYSIWYG view doesn't render it and a writer didn't write it.
20774        let c = counts_of(
20775            "counts_frontmatter",
20776            "---\ntitle: Hidden\n---\n\nvisible words here\n",
20777        );
20778        assert_eq!(
20779            c,
20780            TextCounts {
20781                words: 3,
20782                characters: 18,
20783                characters_without_spaces: 16,
20784                paragraphs: 1,
20785            }
20786        );
20787    }
20788
20789    #[test]
20790    fn counts_of_an_empty_document_are_all_zero() {
20791        assert_eq!(counts_of("counts_empty", ""), TextCounts::default());
20792    }
20793
20794    /// UAX#29 puts a boundary at the hyphen, so a hyphenated compound is two
20795    /// words. Recorded rather than corrected: it is what the algorithm says,
20796    /// and what every other UAX#29 counter reports.
20797    #[test]
20798    fn counts_split_a_hyphenated_compound_in_two() {
20799        let c = counts_of("counts_hyphen", "well-known example\n");
20800        assert_eq!(c.words, 3);
20801        assert_eq!(c.characters, 18);
20802        // Punctuation on its own is no word, and an apostrophe doesn't split one.
20803        assert_eq!(counts_of("counts_punct", "don't ... stop\n").words, 2);
20804    }
20805
20806    #[test]
20807    fn selection_counts_measure_the_selection_and_nothing_without_one() {
20808        let src = "alpha beta\n\ngamma delta\n";
20809        let mut d = doc_in(View::Wysiwyg, "counts_sel", src);
20810        assert_eq!(d.selection_counts(), None, "no selection, no counts");
20811
20812        // From the `b` of `beta` to the end of `gamma`: two blocks clipped.
20813        d.select_range(6, 17);
20814        assert_eq!(
20815            d.selection_counts(),
20816            Some(TextCounts {
20817                words: 2,
20818                characters: 9,
20819                characters_without_spaces: 9,
20820                paragraphs: 2,
20821            })
20822        );
20823    }
20824
20825    /// The count is of the document, not of the window it is shown in — so
20826    /// ⌘E must not move it, and neither must a resize or an edit made with no
20827    /// map built at all.
20828    #[test]
20829    fn counts_agree_across_the_views() {
20830        let src =
20831            "# Head\n\nA **bold** word, a [label](http://x), and more.\n\n- item one\n- item two\n";
20832        let mut d = doc_in(View::Wysiwyg, "counts_views", src);
20833        let wysiwyg = d.counts();
20834        assert!(wysiwyg.words > 0 && wysiwyg.paragraphs == 4);
20835
20836        d.toggle_view();
20837        assert_eq!(d.view, View::Source);
20838        d.build_source();
20839        assert_eq!(d.counts(), wysiwyg, "the source view counts the same text");
20840
20841        // A narrower measure is a narrower window, not a shorter document.
20842        d.toggle_view();
20843        d.build_visual(24);
20844        assert_eq!(d.counts(), wysiwyg, "wrapping is not an input");
20845
20846        // And an edit made in the source view, with the visual map left stale,
20847        // still counts the document as it now stands.
20848        d.toggle_view();
20849        d.caret = d.source.len();
20850        d.insert("\n\ntail words\n");
20851        let after = d.counts();
20852        assert_eq!(after.paragraphs, wysiwyg.paragraphs + 1);
20853        assert_eq!(after.words, wysiwyg.words + 2);
20854    }
20855
20856    // ── math ─────────────────────────────────────────────────────────────────
20857
20858    #[test]
20859    fn a_formula_reveals_on_the_caret_line_in_the_hidden_modes() {
20860        // The rule the proposal states: a formula's content is its TeX, not
20861        // its picture, so it reveals on the caret's line in *every* mode —
20862        // and nothing else on that line does outside `Full`.
20863        let mut d = doc_in(
20864            View::Wysiwyg,
20865            "math_reveal",
20866            "*one* $x+y$ here\n\ntwo there\n",
20867        );
20868        d.set_inline_pictures(true);
20869        assert_eq!(d.markup_mode(), MarkupMode::None);
20870
20871        // Away from the formula's line: the atom, and no reveal at all.
20872        caret_at(&mut d, "two");
20873        assert!(
20874            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20875            "{:?}",
20876            drawn_rows(&d)
20877        );
20878        assert_eq!(d.vmap.math.len(), 1);
20879        assert_eq!(d.reveal_line(), None, "a line with no math keys nothing");
20880
20881        // On it: the formula is its source, the emphasis is still resolved.
20882        caret_at(&mut d, "here");
20883        assert!(
20884            drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"),
20885            "{:?}",
20886            drawn_rows(&d)
20887        );
20888        assert!(d.vmap.math.is_empty());
20889        assert_eq!(d.reveal_line(), Some(Reveal::math(0..16)));
20890
20891        // Off again, and the picture is back.
20892        caret_at(&mut d, "two");
20893        assert!(drawn_rows(&d).iter().any(|r| r == "one ∑ here"));
20894
20895        // The same in Shortcuts; and Full reveals the emphasis too.
20896        d.set_markup_mode(MarkupMode::Shortcuts);
20897        caret_at(&mut d, "here");
20898        assert!(drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"));
20899        d.set_markup_mode(MarkupMode::Full);
20900        caret_at(&mut d, "here");
20901        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20902    }
20903
20904    #[test]
20905    fn an_unrevealed_map_shows_the_carets_line_as_a_page_does() {
20906        let mut d = doc_in(
20907            View::Wysiwyg,
20908            "math_unrevealed",
20909            "*one* $x+y$ here\n\ntwo there\n",
20910        );
20911        d.set_inline_pictures(true);
20912        d.set_markup_mode(MarkupMode::Full);
20913        caret_at(&mut d, "here");
20914        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20915        let (screen, caret) = (d.visual_key(), d.caret);
20916
20917        // On paper: the delimiters hidden and the formula a picture, though
20918        // the caret has not moved off the line.
20919        d.set_unrevealed(true);
20920        d.build_visual(80);
20921        assert!(
20922            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20923            "{:?}",
20924            drawn_rows(&d)
20925        );
20926        assert_eq!(d.vmap.math.len(), 1);
20927        assert_eq!(d.caret, caret);
20928
20929        // Off again: the screen's map is back as it was, and the next build
20930        // reuses it rather than building it over.
20931        d.set_unrevealed(false);
20932        assert_eq!(d.visual_key(), screen);
20933        d.build_visual(80);
20934        assert_eq!(d.visual_key(), screen);
20935        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20936        assert_eq!(d.caret, caret);
20937    }
20938
20939    #[test]
20940    fn a_formula_closed_by_typing_reveals_at_once() {
20941        // The reveal line is decided from the last build's layout, which
20942        // across an edit is stale: the keystroke that closes a `$…$` asks a
20943        // layout that knew no math. `build_map` asks again once the new
20944        // layout is in, so the formula does not snap to its picture under
20945        // the caret.
20946        let mut d = doc_in(View::Wysiwyg, "math_typed", "say \n");
20947        d.set_inline_pictures(true);
20948        d.set_markup_mode(MarkupMode::Shortcuts);
20949        d.caret = 4;
20950        for ch in ["$", "x", "$"] {
20951            d.insert(ch);
20952            d.build_visual(80);
20953        }
20954        assert_eq!(d.source, "say $x$\n");
20955        assert_eq!(
20956            drawn_rows(&d)[0],
20957            "say $x$",
20958            "source, not a picture, under the caret"
20959        );
20960        assert!(d.vmap.math.is_empty());
20961        // Leaving the line folds it — there is only one line, so add one.
20962        d.newline();
20963        d.insert("more");
20964        d.build_visual(80);
20965        assert_eq!(drawn_rows(&d)[0], "say ∑");
20966        assert_eq!(d.vmap.math.len(), 1);
20967        // And deleting the formula while revealed drops the reveal with it.
20968        d.caret = 7;
20969        d.build_visual(80);
20970        assert_eq!(drawn_rows(&d)[0], "say $x$");
20971        for _ in 0..3 {
20972            d.backspace();
20973        }
20974        d.build_visual(80);
20975        assert_eq!(d.source, "say \n\nmore\n");
20976        assert_eq!(d.reveal_line(), None);
20977    }
20978
20979    #[test]
20980    fn a_display_block_is_edited_where_it_stands() {
20981        let mut d = doc_in(
20982            View::Wysiwyg,
20983            "math_block",
20984            "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n",
20985        );
20986        caret_at(&mut d, "end");
20987        assert_eq!(
20988            drawn_rows(&d),
20989            vec!["intro", "", "∑ \\int_0^1 x", "", "end"]
20990        );
20991        // Up from `end` lands on the placeholder, whose glyphs all carry the
20992        // block's start — which is on its `$$` line, so the block reveals.
20993        d.move_up(false);
20994        d.build_visual(80);
20995        assert_eq!(d.caret, 7);
20996        assert_eq!(
20997            drawn_rows(&d),
20998            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
20999        );
21000        // Down walks the source lines, still revealed; typing edits the TeX.
21001        d.move_down(false);
21002        d.build_visual(80);
21003        assert_eq!(d.caret, 10);
21004        d.move_end(false);
21005        d.insert("^2");
21006        d.build_visual(80);
21007        assert_eq!(d.source, "intro\n\n$$\n\\int_0^1 x^2\n$$\n\nend\n");
21008        assert_eq!(drawn_rows(&d)[3], "\\int_0^1 x^2");
21009        // Out below, and it folds to the placeholder with the new TeX.
21010        d.move_down(false);
21011        d.move_down(false);
21012        d.move_down(false);
21013        d.build_visual(80);
21014        assert_eq!(drawn_rows(&d)[2], "∑ \\int_0^1 x^2");
21015        assert_eq!(d.vmap.math[0].tex, "\n\\int_0^1 x^2\n");
21016    }
21017
21018    #[test]
21019    fn set_math_rows_reserves_filler_rows_by_tex() {
21020        let mut d = doc_in(View::Wysiwyg, "math_rows", "$$\nx\n$$\n\nend\n");
21021        caret_at(&mut d, "end");
21022        assert_eq!(d.vmap.math[0].rows_span, 0..1);
21023        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
21024        d.build_visual(80);
21025        assert_eq!(d.vmap.math[0].rows_span, 0..3);
21026        assert_eq!(drawn_rows(&d)[..3], ["∑ x", "", ""]);
21027        // Cheap when nothing changed.
21028        let key = d.visual_key();
21029        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
21030        d.build_visual(80);
21031        assert_eq!(d.visual_key(), key);
21032    }
21033
21034    #[test]
21035    fn a_dollar_typed_in_shortcuts_authors_math() {
21036        let mut d = doc_in(View::Wysiwyg, "math_dollar_sc", "\n");
21037        d.set_markup_mode(MarkupMode::Shortcuts);
21038        d.caret = 0;
21039        d.insert("$x$");
21040        assert_eq!(d.source, "$x$\n");
21041        d.caret = 1;
21042        assert_eq!(d.breadcrumb(), "doc › para › inline_math");
21043
21044        // `None` keeps typed syntax literal, and under the math extension a
21045        // `$` is syntax: twig escapes it, and the paragraph stays text.
21046        let mut d = doc_in(View::Wysiwyg, "math_dollar_none", "\n");
21047        assert_eq!(d.markup_mode(), MarkupMode::None);
21048        d.caret = 0;
21049        d.insert("$x$");
21050        assert_eq!(d.source, "\\$x\\$\n");
21051        d.caret = 2;
21052        assert_eq!(d.breadcrumb(), "doc › para › str");
21053    }
21054
21055    #[test]
21056    fn counts_see_a_formula_as_a_picture_however_it_is_written() {
21057        let c = counts_of(
21058            "counts_math",
21059            "the sum $\\sum_i x_i$ and\n\n$$\ny = mx + c\n$$\n",
21060        );
21061        // `the sum … and` is three words; neither formula counts, and the
21062        // display block is not a paragraph of text.
21063        assert_eq!(c.words, 3);
21064        assert_eq!(c.paragraphs, 1);
21065    }
21066}