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        let delta = self.source.len() as isize - before as isize;
1957        let new_end = (end as isize + delta).max(start as isize) as usize;
1958        // A place after the range moves with it, one inside it goes to the end
1959        // of what replaced it, and one before it stays.
1960        fn shift(p: usize, start: usize, end: usize, new_end: usize, delta: isize) -> usize {
1961            if p >= end {
1962                (p as isize + delta).max(0) as usize
1963            } else if p > start {
1964                new_end
1965            } else {
1966                p
1967            }
1968        }
1969        self.caret = shift(caret, start, end, new_end, delta);
1970        self.anchor = anchor
1971            .map(|a| shift(a, start, end, new_end, delta))
1972            .filter(|&a| a != self.caret);
1973        if pending_at == Some(caret) {
1974            self.pending_marks = pending_marks;
1975            self.pending_at = Some(self.caret);
1976        }
1977        self.goal_col = None;
1978        self.last_edit_kind = None;
1979        self.clamp_caret();
1980        // The caret the step leaves, so a redo puts it back here too.
1981        self.record_caret();
1982        true
1983    }
1984
1985    /// Put back `deleted`, the bytes a half-made [`substitute`](Self::substitute)
1986    /// took out at `at`, and leave nothing of the pair on the history.
1987    ///
1988    /// Not [`undo`](Self::undo): that closes an open group and takes the whole
1989    /// of it back — every substitution of the keystroke made before this one
1990    /// — and leaves a redo step that would delete the bytes again. Instead the
1991    /// bytes go back as an edit of their own, and the two edits, which change
1992    /// nothing together, are folded away: inside a group that already had a
1993    /// step they fold into it as they land; as a group's first step, or
1994    /// outside a group, into the step before. With no step before it there is
1995    /// nothing to fold into, and one step that changes nothing is left.
1996    /// `group_had_step` is what the group said before the deletion — `None`
1997    /// outside one.
1998    fn restore_deleted(&mut self, at: usize, deleted: &str, group_had_step: Option<bool>) {
1999        if !self.splice_exact(at, at, deleted, EditKind::Other) {
2000            // twig will not take its own bytes back: the history's way, which
2001            // at least leaves the document as it was.
2002            self.undo();
2003            return;
2004        }
2005        match group_had_step {
2006            Some(true) => {}
2007            Some(false) => {
2008                let steps = self.undo_steps;
2009                self.fold_last_undo();
2010                if self.undo_steps < steps
2011                    && let Some(g) = &mut self.undo_group
2012                {
2013                    g.has_step = false;
2014                }
2015            }
2016            None => {
2017                self.fold_last_undo();
2018                self.fold_last_undo();
2019            }
2020        }
2021        self.last_edit_kind = None;
2022    }
2023
2024    /// Insert typed `text` at the caret, replacing the selection if there is one.
2025    /// A single typed character coalesces with the run of typing before it; a
2026    /// newline or a multi-character insert is its own undo step.
2027    ///
2028    /// Typed input only — clipboard text goes through [`paste`](Self::paste).
2029    pub fn insert(&mut self, text: &str) {
2030        // The read-only gate, up front: the paths below reach twig by several
2031        // verbs, not all of them through the splice — see the field.
2032        if self.read_only {
2033            return;
2034        }
2035        // Typing against a block picture would dissolve it, and typing past a
2036        // table would grow it a row — see `open_paragraph_at_block_edge`. Give
2037        // the text a paragraph first, so what the caret was standing beside
2038        // stays what it was.
2039        self.open_paragraph_at_block_edge(text);
2040        // Armed sticky marks (⌘b with no selection) turn the next typed text
2041        // bold/italic/… and then retire — see `insert_with_marks`. Whitespace is
2042        // the exception: it takes no mark of its own and keeps the delta armed
2043        // for the character behind it — see `insert_space_with_marks`.
2044        let pending = self.pending_here();
2045        if !pending.is_empty() && self.selection().is_none() && !text.is_empty() {
2046            if text.trim().is_empty() {
2047                self.insert_space_with_marks(self.caret, text, pending);
2048            } else {
2049                self.insert_with_marks(self.caret, text, pending);
2050            }
2051            return;
2052        }
2053        // `MarkupMode::None`: typed syntax stays literal — twig escapes
2054        // anything that would open markup, so a Diaryx user never mints
2055        // formatting by keyboard (it comes from commands instead). The other two
2056        // rungs of the ladder author markup from what you type, which is the
2057        // whole difference between them and this one. Only in the rendered view
2058        // (source view is for typing raw markup) and only where the format has a
2059        // literal spelling at all: escaping is a backslash before a byte from the
2060        // format's own alphabet, and a format with no such alphabet (HTML escapes
2061        // with entities, XML spells nothing) would have `\&` written into it,
2062        // which is two literal characters and not an escape. Marks (⌘b) still
2063        // format — that path returned above; and leaf's own structural inserts go
2064        // through `insert_raw`, never here, so a list marker or quote gutter is
2065        // written as the markup it is.
2066        if !self.markup_mode.authors()
2067            && self.view == View::Wysiwyg
2068            && !text.is_empty()
2069            && self.supports(Gesture::InsertLiteral)
2070        {
2071            self.insert_literal_typed(text);
2072            return;
2073        }
2074        self.insert_raw(text);
2075    }
2076
2077    /// Insert `text` verbatim at the caret (replacing any selection) — the plain
2078    /// path with no Hidden-mode literal escaping. leaf's own structural inserts
2079    /// (a list marker, a quote gutter, an in-cell `<br>`) call this: they ARE
2080    /// markup by design and must not be escaped.
2081    fn insert_raw(&mut self, text: &str) {
2082        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2083        self.splice(s, e, text, typed_edit_kind(text));
2084    }
2085
2086    /// Open a paragraph for text about to be inserted at one of a block media's
2087    /// two caret stops, or at a table's trailing stop, and leave the caret
2088    /// standing in it.
2089    ///
2090    /// A block image is a paragraph whose entire content is the picture, and the
2091    /// caret's only homes on it are in front of it and just past it (see
2092    /// [`VisualMap::block_media_stop`]). Text inserted at either offset joins
2093    /// *that* paragraph — and a paragraph holding anything besides the image is
2094    /// no longer a block image but a line of text with an inline one in it. The
2095    /// frontend that was painting a photo there paints a text run instead; the
2096    /// picture is still in the file, and nothing said a word. Those two offsets
2097    /// are also exactly where a click on the picture lands, so the whole accident
2098    /// is one tap and one keystroke.
2099    ///
2100    /// So the break goes in first and the text lands in the new empty paragraph —
2101    /// what pressing Return before typing would have done, which is a habit no
2102    /// one should have to learn from losing a photo. A no-op everywhere else, and
2103    /// over a selection (which is replaced, not joined into).
2104    ///
2105    /// A picture inside a quote or a list leaves its container, because `\n\n`
2106    /// ends the block. The alternative is worse: the `\n> ` / next-item
2107    /// continuation [`newline`](Self::newline) writes stays in the same
2108    /// *paragraph*, which is the thing being prevented.
2109    ///
2110    /// A table's trailing stop ([`VisualMap::table_end_stop`]) is the same
2111    /// accident from the other side of a different block: the stop sits at the
2112    /// end of the table's last source line, and a line glued under a table is
2113    /// a row of it — `| 1 | 2 |x` is a three-cell row, not a paragraph. So the
2114    /// break goes in there too, and the text lands under the table.
2115    ///
2116    /// Only in the rendered view. Source view is for typing raw markup, where
2117    /// putting a character against an image is exactly what it looks like.
2118    fn open_paragraph_at_block_edge(&mut self, text: &str) {
2119        if self.view != View::Wysiwyg || text.is_empty() || text == "\n" {
2120            return;
2121        }
2122        if self.selection().is_some() {
2123            return;
2124        }
2125        // The map may be a revision behind (nothing has drawn since the last
2126        // edit), and this asks it about offsets — a stale answer would splice a
2127        // break into the wrong place. Free when it is already current, which it
2128        // is whenever a frontend drew a frame between keystrokes.
2129        self.rebuild_map();
2130        let at = self.caret;
2131        let side = match self.vmap.block_media_stop(at) {
2132            Some((side, _)) => side,
2133            None if self.vmap.table_end_stop(at) => MediaStop::After,
2134            None => return,
2135        };
2136        if !self.splice(at, at, "\n\n", EditKind::Other) {
2137            return;
2138        }
2139        // The break is part of the keystroke, not an edit of its own: leave the
2140        // run marked as typing so the character about to arrive folds into it and
2141        // one undo puts the document back the way it was found. (A paste, or a
2142        // multi-character insert, is `EditKind::Other` and stays its own step —
2143        // as it would have been anywhere else in the document.)
2144        self.last_edit_kind = Some(EditKind::Insert);
2145        if side == MediaStop::Before {
2146            // The break went in above the picture and the caret rode to the end
2147            // of it — which is still hard against the picture. Step back onto the
2148            // blank line it opened, so the text lands above rather than in front.
2149            self.caret = at;
2150        }
2151    }
2152
2153    /// A delete key pressed at one of a block picture's two caret stops, handled
2154    /// as the picture being an *atom* rather than a run of bytes. Returns whether
2155    /// the key was consumed.
2156    ///
2157    /// The caret rests in front of a block image and just past it, never inside
2158    /// its markup — which the rendered view doesn't show. So the byte a delete
2159    /// key nominally takes there is one the writer cannot see, and taking it
2160    /// leaves the picture as broken markup rather than as anything anyone asked
2161    /// for: Backspace at the stop past `![](p.png)` removes the closing paren, and
2162    /// a photo becomes the literal text `![](p.png`. That is how a picture goes
2163    /// missing from a document with nobody having touched it — the same
2164    /// dissolution [`open_paragraph_at_block_edge`](Self::open_paragraph_at_block_edge)
2165    /// prevents from the typing side, and it cost this repository's own test vault
2166    /// a photo before it was found.
2167    ///
2168    /// So the key aimed *at* the picture deletes the picture, whole — Backspace
2169    /// when it is behind the caret, Delete when it is in front — which is what
2170    /// every editor does with an embed, and one undo away. The key aimed *away*
2171    /// from it would otherwise delete the paragraph break and merge a neighbour
2172    /// into the picture's own paragraph, which dissolves it just as surely; it
2173    /// steps the caret over the boundary instead and leaves the
2174    /// next press to delete in the block it has reached — the same "first press
2175    /// steps out of the atom, second press deletes" every delete key here gets,
2176    /// word-deletes included (⌥⌫ in front of a picture is aimed at the prose
2177    /// above, and reaches it on the second press rather than taking the break and
2178    /// the picture with it on the first).
2179    fn delete_around_block_media(&mut self, forward: bool) -> bool {
2180        // The map answers about offsets, so it has to be this revision's — see
2181        // the same call in `open_paragraph_at_block_edge`.
2182        self.rebuild_map();
2183        let Some((side, span)) = self.vmap.block_media_stop(self.caret) else {
2184            return false;
2185        };
2186        let aimed_at_it = side
2187            == if forward {
2188                MediaStop::Before
2189            } else {
2190                MediaStop::After
2191            };
2192        if !aimed_at_it {
2193            let over = if forward {
2194                self.vmap.stop_after(self.caret)
2195            } else {
2196                self.vmap.stop_before(self.caret)
2197            };
2198            if let Some(off) = over.filter(|&o| o >= self.caret_floor()) {
2199                self.caret = off;
2200                self.anchor = None;
2201                self.goal_col = None;
2202            }
2203            return true;
2204        }
2205        // Take the break that held the picture apart from its neighbour with it,
2206        // so the delete doesn't leave a blank paragraph standing where the
2207        // picture was. The last arm is a picture that is the whole document.
2208        let (from, to) = if self.source[..span.start].ends_with("\n\n") {
2209            (span.start - 2, span.end)
2210        } else if self.source[span.end..].starts_with("\n\n") {
2211            (span.start, span.end + 2)
2212        } else {
2213            (span.start, span.end)
2214        };
2215        self.splice(from.max(self.caret_floor()), to, "", EditKind::Other);
2216        true
2217    }
2218
2219    /// The Hidden-mode typing path: replace any selection, then insert `text`
2220    /// escaped so it stays literal. When it replaces a selection the two edits
2221    /// fold into one undo step, so an overwrite undoes atomically (and restores
2222    /// the selection) exactly as a plain one does.
2223    fn insert_literal_typed(&mut self, text: &str) {
2224        let kind = typed_edit_kind(text);
2225        match self.selection() {
2226            Some((s, e)) => {
2227                if !self.splice(s, e, "", EditKind::Other) {
2228                    return;
2229                }
2230                // Typing over a whole marked run takes its delimiters with it
2231                // (the empty content couldn't hold them — see
2232                // `repair_mark_edges`) and leaves its marks armed at the caret.
2233                // The text taking the run's place inherits them, exactly as it
2234                // would have by landing inside a run that survived.
2235                let pending = self.pending_here();
2236                if !pending.is_empty() && !text.trim().is_empty() {
2237                    self.insert_with_marks(self.caret, text, pending);
2238                    return;
2239                }
2240                self.insert_literal_at(self.caret, text, kind, true);
2241            }
2242            None => {
2243                self.insert_literal_at(self.caret, text, kind, false);
2244            }
2245        }
2246    }
2247
2248    /// The sticky-mark delta that is live right now: the marks armed by [`toggle`]
2249    /// at a collapsed caret, but only while the caret still stands where they
2250    /// were armed and nothing is selected. Empty otherwise, so a stale delta
2251    /// never styles text it wasn't meant for.
2252    fn pending_here(&self) -> InlineMarks {
2253        if self.anchor.is_none() && self.pending_at == Some(self.caret) {
2254            self.pending_marks
2255        } else {
2256            InlineMarks::empty()
2257        }
2258    }
2259
2260    /// Drop the armed sticky marks — any caret motion, selection, or edit does
2261    /// this, so "start bold here" only ever applies at the exact spot it was
2262    /// asked for.
2263    fn clear_pending(&mut self) {
2264        self.pending_marks = InlineMarks::empty();
2265        self.pending_at = None;
2266    }
2267
2268    /// Insert `text` at `at` carrying the armed sticky `marks`: a mark not yet in
2269    /// force is wrapped around the freshly typed text; a mark the caret already
2270    /// stands inside is *shed* — the text is inserted past the run's end so it
2271    /// lands unmarked ("type normally again"). The caret comes to rest inside any
2272    /// added runs, so continued typing inherits the marks with no re-wrapping,
2273    /// and the delta is cleared: the marks now live in the document, not here.
2274    fn insert_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
2275        let base = self.mark_spans_at(at);
2276        let base_set: InlineMarks = base.iter().map(|(k, _)| *k).collect();
2277        // Nothing to shed, and a run of exactly these marks standing just behind
2278        // the caret: carry on writing *that* run rather than opening a second
2279        // one beside it.
2280        if base_set.is_empty() && self.rejoin_run(at, text, marks) {
2281            return;
2282        }
2283        // Shed the marks we're turning off: step the insertion point past the
2284        // end of each run the caret sits in, so the new text falls outside it.
2285        let mut ins_at = at;
2286        for (kind, span) in &base {
2287            if marks.contains(*kind) {
2288                ins_at = ins_at.max(span.end);
2289            }
2290        }
2291        if !self.splice_exact(ins_at, ins_at, text, EditKind::Other) {
2292            return;
2293        }
2294        // The plain splice inserted exactly `text` at `ins_at`; that byte range
2295        // is the content every added mark wraps.
2296        let (mut cs, mut ce) = (ins_at, ins_at + text.len());
2297        for kind in marks.iter() {
2298            if !base_set.contains(kind) {
2299                let (ncs, nce) = self.wrap_span(cs, ce, kind);
2300                cs = ncs;
2301                ce = nce;
2302            }
2303        }
2304        self.caret = ce.min(self.source.len());
2305        self.anchor = None;
2306        self.last_edit_kind = None;
2307        // Realised: the marks are in the document now, and the caret sits inside
2308        // them, so there is no delta left to carry. Arm nothing, but remember the
2309        // spot so a *further* toggle before typing starts a clean delta here.
2310        self.pending_marks = InlineMarks::empty();
2311        self.pending_at = Some(self.caret);
2312        self.clamp_caret();
2313        self.record_caret();
2314    }
2315
2316    /// Carry on the marked run just behind `at` — moving its closing delimiters
2317    /// out past the new text — instead of opening a second run of the same marks
2318    /// beside it. Returns whether it did.
2319    ///
2320    /// This is the far half of the mark-edge rule (see [`splice`](Self::splice)).
2321    /// A space typed after a bold word steps the caret out of the run, because
2322    /// `**bold **` is not bold; the next character has to step back *in*, or the
2323    /// writer who typed one bold phrase is left with `**bold** **and**` — two
2324    /// runs that read the same to a reader but spell the file in a way nobody
2325    /// wrote. Only whitespace may stand in the gap (a run doesn't reach across
2326    /// words it isn't marking), and the marks behind it must be exactly the ones
2327    /// armed — a run of *some* other kind is a neighbour, not this phrase.
2328    fn rejoin_run(&mut self, at: usize, text: &str, marks: InlineMarks) -> bool {
2329        if text.is_empty() || text.trim() != text {
2330            return false;
2331        }
2332        let gap_at = self.source[..at].trim_end_matches([' ', '\t']).len();
2333        // Walk in through the delimiters stacked at that point, innermost last:
2334        // `***both*** ` closes two runs with one `***`, and rejoining means
2335        // getting behind all of them.
2336        let (mut cut, mut kinds) = (gap_at, InlineMarks::empty());
2337        while let Some((kind, content_end)) = self
2338            .editor
2339            .ancestors_at(prev_boundary(&self.source, cut))
2340            .unwrap_or_default()
2341            .into_iter()
2342            .filter(|m| m.span.end == cut)
2343            .find_map(|m| Some((inline_kind(&m.kind)?, m.content_span.clone()?.end)))
2344        {
2345            if content_end >= cut {
2346                break; // a mark with no closing delimiter to step behind
2347            }
2348            kinds.insert(kind);
2349            cut = content_end;
2350        }
2351        if cut == gap_at || kinds != marks {
2352            return false;
2353        }
2354        // Re-spell the tail: the gap, then the new text, then the delimiters that
2355        // used to close in front of them — read out of the document rather than
2356        // written from a table, so whatever twig spells them with is what moves.
2357        let tail = format!(
2358            "{}{text}{}",
2359            &self.source[gap_at..at],
2360            &self.source[cut..gap_at]
2361        );
2362        if !self.splice_exact(cut, at, &tail, EditKind::Other) {
2363            return false;
2364        }
2365        self.caret = (cut + (at - gap_at) + text.len()).min(self.source.len());
2366        self.anchor = None;
2367        self.last_edit_kind = None;
2368        self.pending_marks = InlineMarks::empty();
2369        self.pending_at = Some(self.caret);
2370        self.clamp_caret();
2371        self.record_caret();
2372        true
2373    }
2374
2375    /// Insert typed whitespace at a caret with sticky marks armed. Whitespace is
2376    /// never itself wrapped: a mark around a space draws nothing a reader can
2377    /// see, and in Markdown and Djot it draws its own delimiters instead
2378    /// (`** **`). So the space goes in unmarked — outside any run the armed
2379    /// marks are shedding — and the marks stay armed for the character after it,
2380    /// which rejoins the run (see [`rejoin_run`](Self::rejoin_run)).
2381    fn insert_space_with_marks(&mut self, at: usize, text: &str, marks: InlineMarks) {
2382        let base = self.mark_spans_at(at);
2383        // What the *next* character carries: the armed delta resolved against the
2384        // marks in force here, which the space must not quietly drop.
2385        let want = base
2386            .iter()
2387            .map(|(k, _)| *k)
2388            .collect::<InlineMarks>()
2389            .xor(marks);
2390        let mut ins_at = at;
2391        for (kind, span) in &base {
2392            if marks.contains(*kind) {
2393                ins_at = ins_at.max(span.end);
2394            }
2395        }
2396        if !self.splice(ins_at, ins_at, text, typed_edit_kind(text)) {
2397            return;
2398        }
2399        self.rearm(want);
2400        self.record_caret();
2401    }
2402
2403    /// Wrap `[s, e)` in `kind` via twig and return the byte span the *content*
2404    /// (not the delimiters) occupies afterwards. Markdown/Djot inline delimiters
2405    /// are symmetric (`**`…`**`, `_`…`_`, `` ` ``…`` ` ``), so the bytes twig
2406    /// added split evenly around the content — half the growth on each side.
2407    fn wrap_span(&mut self, s: usize, e: usize, kind: InlineKind) -> (usize, usize) {
2408        // The read-only gate — this door reaches twig without the splice.
2409        if self.read_only {
2410            return (s, e);
2411        }
2412        match self.editor.toggle_inline(s, e, kind) {
2413            Ok(change) => {
2414                self.last_edit_kind = None;
2415                self.refresh();
2416                self.dirty = self.source != self.clean_source;
2417                let added = (change.new.end - change.new.start).saturating_sub(e - s);
2418                let half = added / 2;
2419                (change.new.start + half, change.new.end - half)
2420            }
2421            // Unsupported here (e.g. mark on Markdown): leave the text unwrapped
2422            // rather than lose the keystroke.
2423            Err(e2) => {
2424                self.status = Some(format!("{kind:?}: {e2}"));
2425                (s, e)
2426            }
2427        }
2428    }
2429
2430    /// The safe offset to splice a block-level break at, given a caret that may
2431    /// sit exactly between an inline mark's content and its own closing
2432    /// delimiter (`content_span.end == off < span.end` for some enclosing mark
2433    /// — the WYSIWYG caret's natural resting place at the end of `**bold**`
2434    /// with nothing following it on the line: the closing `**` renders no
2435    /// glyph of its own, so the caret's "end of line" offset lands right
2436    /// before it). Splicing a paragraph/list/quote break at `off` itself would
2437    /// sever the delimiter from its content, stranding it alone on the new
2438    /// line. Walks out to the *outermost* such mark's `span.end` instead, so
2439    /// nested marks closing at the same point (`**_x_**`) all clear together.
2440    /// A no-op everywhere else — mid-run, or past real trailing content, no
2441    /// mark's `content_span` ends exactly at `off`.
2442    fn skip_trailing_close_delims(&mut self, off: usize) -> usize {
2443        let off = off.min(self.source.len());
2444        let runs = self.run_span_ids();
2445        self.editor
2446            .ancestors_at(off)
2447            .unwrap_or_default()
2448            .into_iter()
2449            .filter(|m| hides_delims(m, &runs))
2450            .filter(|m| off < m.span.end && m.content_span.as_ref().is_some_and(|c| c.end == off))
2451            .map(|m| m.span.end)
2452            .max()
2453            .unwrap_or(off)
2454    }
2455
2456    /// The offset a *delete* aimed at the character before `off` should stop at,
2457    /// when `off` is the start of a run's text and the bytes behind it are that
2458    /// run's opening delimiter. The rich view draws no glyph for a `**`, so the
2459    /// byte behind the caret at the start of a bold word is not a character the
2460    /// writer can see, let alone one they aimed Backspace at: taking it leaves
2461    /// `a *bold** c` — the styling gone and a literal asterisk in its place. The
2462    /// delete steps over the whole delimiter to the visible character in front of
2463    /// it instead. Walks out to the *outermost* mark opening there, so
2464    /// `**_x_**` clears every delimiter at once, and is a no-op anywhere else.
2465    fn skip_leading_open_delims(&mut self, off: usize) -> usize {
2466        let off = off.min(self.source.len());
2467        let runs = self.run_span_ids();
2468        self.editor
2469            .ancestors_at(off)
2470            .unwrap_or_default()
2471            .into_iter()
2472            .filter(|m| hides_delims(m, &runs))
2473            .filter(|m| {
2474                m.span.start < off && m.content_span.as_ref().is_some_and(|c| c.start == off)
2475            })
2476            .map(|m| m.span.start)
2477            .min()
2478            .unwrap_or(off)
2479    }
2480
2481    /// `off` moved *inside* the run whose closing delimiters end there — the
2482    /// other offset the rich view draws in the same place, since a `**` renders
2483    /// no glyph of its own. `**bold**` has a caret home on each side of its
2484    /// closing delimiter, one column apart on screen and eight bytes and a whole
2485    /// run apart in the file, and a plain ← lands on the outer one whenever a
2486    /// space follows the phrase. The inner one is what the writer is pointing at
2487    /// there: the end of their bold word. Walks in through every mark closing at
2488    /// that point, innermost last, so `***both***` lands inside both. A no-op
2489    /// anywhere else — mid-run, or in prose, no mark's span ends at `off`.
2490    fn step_inside_close_delims(&mut self, off: usize) -> usize {
2491        let mut off = off.min(self.source.len());
2492        let runs = self.run_span_ids();
2493        loop {
2494            let inner = self
2495                .editor
2496                .ancestors_at(prev_boundary(&self.source, off))
2497                .unwrap_or_default()
2498                .into_iter()
2499                .filter(|m| hides_delims(m, &runs) && m.span.end == off)
2500                .filter_map(|m| m.content_span.clone().map(|c| c.end))
2501                .filter(|&end| end < off)
2502                .max();
2503            match inner {
2504                Some(end) => off = end,
2505                None => return off,
2506            }
2507        }
2508    }
2509
2510    /// The mirror at the opening edge: `off` moved inside the run whose
2511    /// delimiters *start* there, onto the first character of its text. See
2512    /// [`step_inside_close_delims`](Self::step_inside_close_delims).
2513    fn step_inside_open_delims(&mut self, off: usize) -> usize {
2514        let mut off = off.min(self.source.len());
2515        let runs = self.run_span_ids();
2516        loop {
2517            let inner = self
2518                .editor
2519                .ancestors_at(off)
2520                .unwrap_or_default()
2521                .into_iter()
2522                .filter(|m| hides_delims(m, &runs) && m.span.start == off)
2523                .filter_map(|m| m.content_span.clone().map(|c| c.start))
2524                .filter(|&start| start > off)
2525                .min();
2526            match inner {
2527                Some(start) => off = start,
2528                None => return off,
2529            }
2530        }
2531    }
2532
2533    /// The ids of the document's attributed run spans — the inline
2534    /// `Container`s [`wysiwyg::is_run_span`] picks out — for [`hides_delims`],
2535    /// which sees an ancestor chain and so only a kind. Read once per gesture,
2536    /// not once per step of a walk.
2537    fn run_span_ids(&mut self) -> Vec<NodeId> {
2538        self.nodes()
2539            .iter()
2540            .filter(|n| wysiwyg::is_run_span(n))
2541            .map(|n| n.id)
2542            .collect()
2543    }
2544
2545    /// The attributed span whose text is exactly `content` — the whole of
2546    /// `<span …>i</span>`'s `i`, or nothing at all when `content` is empty
2547    /// and sits between the tags of `<span …></span>` — as the whole range
2548    /// spelling the span: the node's span, widened to its attribute block
2549    /// where the format writes that outside the node, as djot's
2550    /// `[i]{data-size="large"}` does. `None` for any other range, including
2551    /// part of a span's text.
2552    ///
2553    /// An empty span has an interior of no bytes, or no known interior at
2554    /// all: twig gives Markdown's `<span …></span>` the first and djot's
2555    /// `[]{…}` the second, and the chain already says the offset is inside.
2556    fn run_span_of_content(&mut self, content: Range<usize>) -> Option<Range<usize>> {
2557        let runs = self.run_span_ids();
2558        let m = self
2559            .editor
2560            .ancestors_at(content.start)
2561            .unwrap_or_default()
2562            .into_iter()
2563            .filter(|m| runs.contains(&NodeId(m.node_id)))
2564            .find(|m| match &m.content_span {
2565                Some(c) => *c == content,
2566                None => content.is_empty(),
2567            })?;
2568        let mut range = m.span;
2569        if let Some(attrs) = self
2570            .editor
2571            .document()
2572            .ok()
2573            .and_then(|mut d| d.attrs_span(NodeId(m.node_id)).ok().flatten())
2574        {
2575            range.start = range.start.min(attrs.start);
2576            range.end = range.end.max(attrs.end);
2577        }
2578        Some(range)
2579    }
2580
2581    /// The attributed block whose whole text is exactly `content` — the `T`
2582    /// of Markdown's `<div class="center">\n\nT\n\n</div>` or djot's
2583    /// `{.center}\nT` — as the range a delete that takes that text takes with
2584    /// it: the whole `<div>` when the block is all the div holds, or the
2585    /// `{…}` line down to the end of the text. The block version of
2586    /// [`run_span_of_content`](Self::run_span_of_content), for the same
2587    /// reason: a paragraph with no text is no block, so the div would stand
2588    /// around nothing and the `{…}` line above nothing, and a from-scratch
2589    /// map gives neither a caret home — the `T`'s row is gone with the `T`.
2590    /// `None` for a block with more text, a div holding more, a heading (an
2591    /// empty `# ` is still a heading), and a format whose attributes are the
2592    /// block's own tag (HTML's `<p class="center"></p>` is still a
2593    /// paragraph).
2594    fn attributed_block_of_content(&mut self, content: Range<usize>) -> Option<Range<usize>> {
2595        if content.is_empty() || !matches!(self.format, Format::Markdown | Format::Djot) {
2596            return None;
2597        }
2598        let nodes = self.nodes();
2599        let block = nodes
2600            .iter()
2601            .filter(|n| n.kind == Kind::Para)
2602            .find(|n| n.content_span.as_ref() == Some(&content))?;
2603        match self.format {
2604            Format::Djot => {
2605                let attrs = self
2606                    .editor
2607                    .document()
2608                    .ok()
2609                    .and_then(|mut d| d.attrs_span(block.id).ok().flatten())?;
2610                (attrs.end <= block.span.start).then_some(attrs.start..content.end)
2611            }
2612            _ => {
2613                let div = block
2614                    .parent
2615                    .and_then(|p| nodes.iter().find(|n| n.id == p))
2616                    .filter(|p| wysiwyg::element_tag(p) == Some("div"))?;
2617                let alone = nodes.iter().filter(|n| n.parent == Some(div.id)).count() == 1;
2618                alone.then(|| div.span.clone())
2619            }
2620        }
2621    }
2622
2623    /// The inline mark kinds whose span covers `off`, each with that span — the
2624    /// span-carrying sibling of [`marks_at`](Self::marks_at), which reports node
2625    /// ids instead. Used to shed a mark by stepping past the end of its run.
2626    fn mark_spans_at(&mut self, off: usize) -> Vec<(InlineKind, std::ops::Range<usize>)> {
2627        let off = off.min(self.source.len());
2628        self.editor
2629            .ancestors_at(off)
2630            .unwrap_or_default()
2631            .into_iter()
2632            .filter(|m| off < m.span.end)
2633            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.span.clone())))
2634            .collect()
2635    }
2636
2637    /// Insert clipboard `text` at the caret, replacing the selection if there is
2638    /// one — always its own undo step, whatever its length.
2639    ///
2640    /// Provenance is the whole point, and only the caller has it. `insert` reads
2641    /// a lone character as a keystroke and folds it into the run around it,
2642    /// which is right for typing and wrong for a one-character paste: that paste
2643    /// would vanish mid-run on an undo it was never part of, and the characters
2644    /// the user actually typed would go with it. Length can't tell the two
2645    /// apart — `⌘V` of `x` and typing `x` are the same string — so the door the
2646    /// caller comes through is what says which happened.
2647    pub fn paste(&mut self, text: &str) {
2648        // Pasting against a block picture or a table's end joins the block
2649        // exactly as typing does, and for the same reason — see
2650        // `open_paragraph_at_block_edge`.
2651        self.open_paragraph_at_block_edge(text);
2652        let (s, e) = self.selection().unwrap_or((self.caret, self.caret));
2653        self.splice(s, e, text, EditKind::Other);
2654    }
2655
2656    /// Replace `[start, end)` with `text` as one step of an IME composition —
2657    /// the same splice as [`edit`](Self::edit), but marked so the run of steps
2658    /// folds into a single undo.
2659    ///
2660    /// A composition is *one* act of writing. Typing `かんじ` and picking 感じ is a
2661    /// dozen calls here, each replacing the last one's provisional bytes, and an
2662    /// undo step per call means undoing a word means pressing ⌘Z until the reading
2663    /// unspools backwards through kana — the intermediate states were never text
2664    /// the user wrote. Only the frontend knows a call is provisional (the bytes
2665    /// look like any other edit), so the door the caller comes through is what
2666    /// says so, exactly as it is for [`paste`](Self::paste) versus
2667    /// [`insert`](Self::insert).
2668    ///
2669    /// Pair with [`end_composition`](Self::end_composition), or the *next*
2670    /// composition folds into this one.
2671    pub fn edit_composing(&mut self, start: usize, end: usize, text: &str) {
2672        self.splice(start, end, text, EditKind::Compose);
2673    }
2674
2675    /// Close the open composition run, so the next one is its own undo step.
2676    /// Call when the IME commits or withdraws a composition.
2677    ///
2678    /// Only clears a *composition* run: a frontend that reports an end it never
2679    /// began (some IMEs unmark unprompted) would otherwise split the run of
2680    /// typing around it into two undo steps for no reason the user can see.
2681    pub fn end_composition(&mut self) {
2682        if self.last_edit_kind == Some(EditKind::Compose) {
2683            self.last_edit_kind = None;
2684        }
2685    }
2686
2687    // ── the clipboard's rich flavor ──────────────────────────────────────────
2688
2689    /// The selection rendered as HTML, for the clipboard's `text/html` flavor —
2690    /// what lets a paste into Docs/Mail/Slack keep its formatting. `None` when
2691    /// nothing is selected, or when the selection doesn't render (the caller
2692    /// still has [`selected_text`](Self::selected_text), which is what to publish
2693    /// as `text/plain` either way).
2694    ///
2695    /// **The fragment is a source substring, and that is the honest limit here.**
2696    /// It's parsed standalone, so a selection whose meaning depends on its
2697    /// surroundings converts as what it literally says rather than what it looks
2698    /// like on screen: half a list item is a paragraph, a row torn out of a table
2699    /// is the text of a row, the `**` of a bold run selected without its closing
2700    /// `**` is two asterisks. Every one of those still *renders* — there's no
2701    /// error to report — it just renders as the fragment and not as the document.
2702    /// Widening the range to whole blocks would publish text the user didn't
2703    /// select, which is a worse lie than a fragment being a fragment; the plain
2704    /// flavor has the same substring, so the two flavors at least agree.
2705    pub fn selection_html(&mut self) -> Option<String> {
2706        let (start, end) = self.selection()?;
2707        let inline = self.selection_is_inline(start, end);
2708        let html = html::render_fragment(&self.source[start..end], self.format)?;
2709        Some(match inline {
2710            true => html::strip_sole_paragraph(html),
2711            false => html,
2712        })
2713    }
2714
2715    /// Paste the clipboard's `text/html` flavor, converting it to this document's
2716    /// format first. Its own undo step, like any [`paste`](Self::paste).
2717    ///
2718    /// Returns whether it landed. `false` means the HTML didn't convert to
2719    /// anything worth pasting — the caller should fall back to the plain flavor
2720    /// rather than treat it as an error. The `html` module has the full list of
2721    /// what that covers: a table twig won't build, markup it doesn't recognise,
2722    /// an empty result.
2723    pub fn paste_html(&mut self, html: &str) -> bool {
2724        match html::parse_fragment(html, self.format) {
2725            Some(source) => {
2726                self.paste(&source);
2727                true
2728            }
2729            None => false,
2730        }
2731    }
2732
2733    /// Does the selection live *inside* a single top-level block?
2734    ///
2735    /// The question [`selection_html`](Self::selection_html) needs and the
2736    /// fragment can't answer: `**bold**` renders as `<p><strong>bold</strong></p>`
2737    /// whether the user selected one word of a sentence or a whole paragraph, and
2738    /// only the document knows which. Selecting a word and pasting into Docs
2739    /// should extend the line you paste into; selecting the paragraph should make
2740    /// a paragraph. So a selection strictly within one block is inline (its `<p>`
2741    /// is an artifact of standalone parsing), and one that covers a whole block —
2742    /// or spans two — keeps its structure.
2743    ///
2744    /// Reads the block from twig rather than guessing from the bytes:
2745    /// `ancestors_at` is `[doc, block, …inline]`, so index 1 is the top-level
2746    /// block containing an offset, and two ends inside the same one cannot have
2747    /// crossed a block boundary.
2748    fn selection_is_inline(&mut self, start: usize, end: usize) -> bool {
2749        // The last *character*, not `end - 1`: the selection's end is exclusive
2750        // and may sit mid-codepoint's-worth of bytes past the last char.
2751        let Some((off, _)) = self.source[start..end].char_indices().next_back() else {
2752            return false;
2753        };
2754        let (Some(head), Some(tail)) =
2755            (self.top_block_span(start), self.top_block_span(start + off))
2756        else {
2757            return false;
2758        };
2759        head == tail && !(start <= head.start && end >= head.end)
2760    }
2761
2762    /// The byte span of the top-level block containing `offset`, or `None` at an
2763    /// offset that belongs to no block (the blank line between two of them).
2764    fn top_block_span(&mut self, offset: usize) -> Option<std::ops::Range<usize>> {
2765        self.editor
2766            .ancestors_at(offset)
2767            .ok()?
2768            .get(1)
2769            .map(|m| m.span.clone())
2770    }
2771
2772    // ── indentation ──────────────────────────────────────────────────────────
2773
2774    /// One indent level.
2775    ///
2776    /// Two spaces, not the four both frontends type for Tab today, because in a
2777    /// markdown document four columns isn't a width — it's a *meaning*. Four
2778    /// spaces at the head of a line is markdown's indented-code-block marker, so
2779    /// one Tab on a paragraph would reparse it into code and style it as such;
2780    /// two cannot, and the line stays the prose it was. Two is also exactly
2781    /// where a `- ` bullet's content starts, so an indented line lands under its
2782    /// parent item's text instead of beside it — the column a list-aware indent
2783    /// has to hit anyway, which keeps this width from being relitigated later.
2784    const INDENT: &'static str = "  ";
2785
2786    /// Indent the selected lines — or the caret's line, with no selection — by
2787    /// one level (Tab).
2788    pub fn indent(&mut self) {
2789        self.reindent(true);
2790        // Nesting changes an ordered list's numbering (the nested item restarts,
2791        // its old siblings resume) — keep the source markers in step.
2792        self.renumber_here();
2793        // Nesting an empty `-` item under a text line reparses that text as a
2794        // setext heading; swap the dash for a `*` before it can (a no-op unless
2795        // the collapse actually happened).
2796        self.avoid_setext_collapse();
2797    }
2798
2799    /// Take one indent level back off the selected lines, or the caret's line
2800    /// (Shift+Tab). A line with no indentation is left exactly as it is.
2801    ///
2802    /// A line with *less* than a full level gives back what it has rather than
2803    /// refusing: outdent's job is to walk a line left, and real documents — hand
2804    /// written, or reflowed by some other editor — are full of indentation that
2805    /// was never a clean multiple of anything. Refusing there would strand the
2806    /// line at a depth Shift+Tab couldn't undo.
2807    pub fn outdent(&mut self) {
2808        self.reindent(false);
2809        self.renumber_here();
2810    }
2811
2812    /// The body of [`indent`](Self::indent) / [`outdent`](Self::outdent).
2813    ///
2814    /// One splice across the whole line range, never one per line: a Tab is one
2815    /// thing the user did, so it has to be one undo step and one reparse. Per
2816    /// line, twig would reparse the document once per line and leave a stack of
2817    /// steps that Shift+⌘Z walks back one line at a time.
2818    fn reindent(&mut self, add: bool) {
2819        let (sel_start, sel_end) = self.selection().unwrap_or((self.caret, self.caret));
2820        let start = source_line_range(&self.source, sel_start).start;
2821        let end = source_line_range(&self.source, sel_end).end;
2822        let region = self.source[start..end].to_string();
2823        let lines: Vec<&str> = region.split('\n').collect();
2824        // A blank line has no text to move, and padding it would leave nothing
2825        // but trailing whitespace — but Tab on a blank line *is* a request for
2826        // indentation to type into, so the skip only applies where the op has
2827        // other lines to do real work on.
2828        let skip_blank = add && lines.len() > 1;
2829
2830        let mut out = String::with_capacity(region.len() + lines.len() * Self::INDENT.len());
2831        let mut deltas: Vec<isize> = Vec::with_capacity(lines.len());
2832        let mut line_off = start;
2833        for (i, full) in lines.iter().enumerate() {
2834            if i > 0 {
2835                out.push('\n');
2836            }
2837            // A list item moves by having its whole leading prefix *replaced*,
2838            // never by having spaces pushed in front of the line. twig spells
2839            // both prefixes, so the quote markers, the parent's indent and an
2840            // ordered marker's extra column all come out right without leaf
2841            // measuring any of them — and a line that only looks like an item
2842            // (a Djot continuation) reports no marker and is left to the plain
2843            // path, where a Tab is just a Tab.
2844            let marker = self.list_marker_on_line(line_off);
2845            let own = marker
2846                .as_ref()
2847                .map(|m| m.marker_start - m.line_start)
2848                .unwrap_or(0);
2849            let delta = if add {
2850                if skip_blank && full.trim().is_empty() {
2851                    out.push_str(full);
2852                    0
2853                } else if marker.is_some() && self.first_item_of_list(line_off) {
2854                    // The first item of a list has no preceding sibling to nest
2855                    // under, so a Tab here can't spell a sub-list — twig would
2856                    // reparse the shoved-over marker as the same list, only
2857                    // indented, which Shift+Tab then can't cleanly undo. Leave the
2858                    // item where it is, the way every list editor refuses to
2859                    // over-indent a list's first line.
2860                    out.push_str(full);
2861                    0
2862                } else if marker.is_some() {
2863                    // Nesting means standing where a *continuation* of this line
2864                    // would stand: past the parent's marker, inside its content
2865                    // column. That is `continuation_prefix`, less a checkbox.
2866                    let new = self.nesting_prefix_at(line_off);
2867                    let delta = new.len() as isize - own as isize;
2868                    out.push_str(&new);
2869                    out.push_str(&full[own..]);
2870                    delta
2871                } else {
2872                    out.push_str(Self::INDENT);
2873                    out.push_str(full);
2874                    Self::INDENT.len() as isize
2875                }
2876            } else if marker.is_some() {
2877                // Unnesting is the mirror: stand where the parent item's own
2878                // line starts, which drops exactly the level it contributed.
2879                let new = self.outdent_prefix_at(line_off);
2880                let delta = new.len() as isize - own as isize;
2881                out.push_str(&new);
2882                out.push_str(&full[own..]);
2883                delta
2884            } else {
2885                // A plain line gives back the ordinary step.
2886                let strip = outdent_width(full, Self::INDENT.len());
2887                out.push_str(&full[strip..]);
2888                -(strip as isize)
2889            };
2890            deltas.push(delta);
2891            line_off += full.len() + 1;
2892        }
2893        // Nothing to give back. Returning before the splice keeps an outdent at
2894        // column zero from spending an undo step on a document it never changed.
2895        if deltas.iter().all(|d| *d == 0) {
2896            return;
2897        }
2898
2899        // Every line's text keeps its offset *within the line*, so the caret is
2900        // remapped by its column, not by its byte offset — which the prefixes on
2901        // the lines above it have already invalidated.
2902        let remap = |off: usize| -> usize {
2903            let (mut old_ls, mut new_ls) = (start, start);
2904            for (line, delta) in lines.iter().zip(&deltas) {
2905                let old_le = old_ls + line.len();
2906                let new_len = (line.len() as isize + delta) as usize;
2907                if off <= old_le {
2908                    let col = (off - old_ls) as isize;
2909                    return new_ls + ((col + delta).max(0) as usize).min(new_len);
2910                }
2911                old_ls = old_le + 1;
2912                new_ls += new_len + 1;
2913            }
2914            start + out.len()
2915        };
2916        let placed = match self.selection() {
2917            // Keep the rewritten region selected, the way a container toggle
2918            // keeps its own: it leaves a second Tab aimed at the same lines
2919            // rather than at whatever the shifted offsets now happen to cover.
2920            Some(_) => (start + out.len(), Some(start)),
2921            None => (remap(self.caret), None),
2922        };
2923
2924        // A rolled-back splice leaves the old source in place, where every offset
2925        // computed above addresses text that was never written.
2926        if !self.splice(start, end, &out, EditKind::Other) {
2927            return;
2928        }
2929        // `splice` re-anchors to the end of the `Change`, which for a whole-region
2930        // rewrite is the last line's end — nowhere the caret was. Place it, then
2931        // re-record the caret so this is the state redo restores, not the one
2932        // `splice` left behind from the `Change`.
2933        self.caret = placed.0.min(self.source.len());
2934        self.anchor = placed.1;
2935        self.clamp_caret();
2936        self.record_caret();
2937    }
2938
2939    /// The Enter key.
2940    ///
2941    /// In source view it's a literal newline. In WYSIWYG it's **AST-aware**: a
2942    /// bare `\n` is only a markdown soft break (same paragraph), so the block the
2943    /// caret is in decides what actually gets written.
2944    ///
2945    ///   - paragraph            → twig's [`Editor::split_block`], which parts the
2946    ///                            block at the caret and reopens its container
2947    ///   - list item            → likewise: the next item, its indent, quote
2948    ///                            prefix and `[ ]` box all reproduced by twig —
2949    ///                            except an *empty* item, which exits the list
2950    ///   - block quote          → likewise: a new paragraph inside the quote
2951    ///   - heading              → a new *paragraph*, not another heading
2952    ///   - code block           → a literal newline (stay in the block)
2953    ///   - thematic break       → the line under the rule, opened if it has
2954    ///                            none ([`stand_under_block`](Self::stand_under_block))
2955    ///   - blank line           → a literal newline (one Backspace undoes it)
2956    ///   - [`LineFlow::Preserve`] → a single soft break, which renders as a
2957    ///                            visible line
2958    ///
2959    /// Where `split_block` is used it replaces markup leaf used to spell by hand,
2960    /// and it is better at it: it drops the whitespace the caret was sitting in
2961    /// front of instead of stranding it at the head of the second half, and it
2962    /// knows continuations leaf's marker scan never covered — a checklist item
2963    /// continues as an *unchecked* checklist item rather than a plain bullet.
2964    ///
2965    /// The exceptions above are exceptions because `split_block` is either wrong
2966    /// there or refuses: parting a fence yields two fences with the code split
2967    /// between them, parting a heading yields a second heading where every editor
2968    /// gives a paragraph, and a blank line, an empty item, a setext heading and a
2969    /// table all report an error rather than a split.
2970    pub fn newline(&mut self) {
2971        if self.view == View::Source {
2972            self.insert_raw("\n");
2973            return;
2974        }
2975        // Enter over a selection replaces it with a paragraph break.
2976        if let Some((s, e)) = self.selection() {
2977            self.splice(s, e, "\n\n", EditKind::Other);
2978            return;
2979        }
2980        // On a blank page there is no block to push down, and a blank line
2981        // with nothing under it is not something Fold flow draws. Enter wrote
2982        // one anyway: an edit, and an undo step, that showed nothing.
2983        if self.line_flow == LineFlow::Fold && self.source[self.caret_floor()..].trim().is_empty() {
2984            return;
2985        }
2986        // A caret resting exactly between an inline mark's content and its own
2987        // closing delimiter (`**bold**` with nothing after it on the line —
2988        // the WYSIWYG caret's natural end-of-line position) must not splice a
2989        // block break there: every path below eventually does via
2990        // `insert_raw`/`self.caret`, and splicing before the hidden closing
2991        // delimiter would strand it alone on the new line.
2992        self.caret = self.skip_trailing_close_delims(self.caret);
2993        // The block the caret is in. `block_offset_for_caret` nudges off a line
2994        // end (where the caret sits at the doc level); on a bare line (e.g. an
2995        // empty list item) fall back to the caret so the enclosing list/quote is
2996        // still visible in the ancestors.
2997        let off = self.block_offset_for_caret().unwrap_or(self.caret);
2998        let kinds: Vec<Kind> = self
2999            .editor
3000            .ancestors_at(off)
3001            .map(|c| c.into_iter().map(|m| m.kind).collect())
3002            .unwrap_or_default();
3003        let has = |k: Kind| kinds.contains(&k);
3004
3005        if has(Kind::CodeBlock) {
3006            self.insert_raw("\n");
3007            return;
3008        }
3009        // An *empty* list item exits the list — the standard double-Enter — which
3010        // `split_block` reports as an error rather than a split (there is no
3011        // content to part), so it stays leaf's. `list_marker_on_line` is itself
3012        // the AST gate — it answers from the tree, so a `- ` that reads as a
3013        // marker byte-for-byte but opens no item (a setext underline, a Djot
3014        // continuation line) never reaches here.
3015        if let Some(marker) = self.list_marker_on_line(self.caret)
3016            && self.item_is_empty(&marker)
3017        {
3018            self.exit_list(&marker);
3019            return;
3020        }
3021        // Beside a rule, at the home past it, the caret's source line is the
3022        // blank one under the rule, which the branch below would take for an
3023        // empty paragraph. Mid-document its lone newline left the caret on the
3024        // next block's first line, and what was typed there joined that block.
3025        if let Some(end) = self.rule_above_caret() {
3026            self.stand_under_block(end);
3027            return;
3028        }
3029        // On an *empty* paragraph line, a lone Enter should add a single blank line,
3030        // not another full paragraph break — so it moves down one line and one
3031        // Backspace undoes it, not two. (`split_block` errors here too.)
3032        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
3033        let line_end = self.source[self.caret..]
3034            .find('\n')
3035            .map_or(self.source.len(), |i| self.caret + i);
3036        if self.source[line_start..line_end].trim().is_empty() {
3037            self.insert_raw("\n");
3038            return;
3039        }
3040        // At the start of a paragraph with a block above it, twig's split
3041        // writes a lone newline ahead of the paragraph, which Fold draws as one
3042        // more gap: the first Enter showed nothing. A heading's branch below
3043        // parted it after its `#`, leaving an empty heading over a paragraph
3044        // that had been the heading's text. Both open an empty paragraph above
3045        // instead, the caret staying with the text. In Preserve flow too: its
3046        // lone newline went inside a div, where nothing drew it, and between
3047        // a mark's delimiters, where it cut the mark.
3048        if let Some((at, text)) = self.paragraph_opening_at_caret() {
3049            let caret = self.caret;
3050            if self.splice(at, at, text, EditKind::Other) {
3051                self.caret = caret + text.len();
3052                self.record_caret();
3053            }
3054            return;
3055        }
3056        // In `Preserve` flow a soft break is a *visible* line the author means to
3057        // make, so Enter writes a single `\n` and typing continues the same
3058        // paragraph on the next line — the behaviour of an ordinary text editor.
3059        // A second Enter then lands on the blank line above and takes the
3060        // empty-line branch, so double-Enter still promotes to a full paragraph
3061        // break; and Backspace, which deletes a lone `\n` over a soft break,
3062        // undoes a single Enter symmetrically. In `Fold` flow a lone `\n` would
3063        // render as an invisible space, so Enter keeps making the paragraph break
3064        // that actually shows.
3065        //
3066        // Only in running prose. A list or a quote has a continuation of its own
3067        // to write, and a `\n` there is not a soft line but a lost container.
3068        // Nor in a heading, which a newline ends in Markdown and runs on
3069        // unseen in djot: it takes the heading's own branch below.
3070        let in_container = has(Kind::ListItem) || has(Kind::TaskListItem) || has(Kind::BlockQuote);
3071        if self.line_flow == LineFlow::Preserve && !in_container && !has(Kind::Heading) {
3072            self.insert_raw("\n");
3073            return;
3074        }
3075        // A heading gets a *paragraph*, never a second heading: Enter at the end
3076        // of a title is how every editor is asked for the body under it, and
3077        // `split_block` would repeat the `#` instead. Whitespace at the split
3078        // point goes with the break rather than opening the new paragraph, which
3079        // is what `split_block` does everywhere else.
3080        if has(Kind::Heading) {
3081            let mut end = self.caret;
3082            while self.source.as_bytes().get(end) == Some(&b' ') {
3083                end += 1;
3084            }
3085            self.splice(self.caret, end, "\n\n", EditKind::Other);
3086            return;
3087        }
3088        self.split_block_here();
3089    }
3090
3091    /// Where Enter writes to open an empty paragraph above the paragraph or
3092    /// heading the caret starts, and what — `None` when the caret does not
3093    /// start one.
3094    ///
3095    /// The caret starts a paragraph that is in no list item, quote, fence or
3096    /// table when no text of the paragraph stands before it: at its first
3097    /// byte, or past only the opening delimiters of marks that begin with it
3098    /// (`**`, a colour's `<span …>`), which is where a tap before the first
3099    /// letter lands. A heading's `#` marker is such a delimiter. Parted there, twig's split cut the mark in two. The break
3100    /// goes in front of those delimiters, and in front of any `<div>` or
3101    /// fenced div the paragraph opens — the view draws no row for a blank line
3102    /// above a container's first block, so a centred paragraph's empty line
3103    /// has to open outside its div.
3104    ///
3105    /// Inside a list twig's split already writes a marked line, which draws,
3106    /// and so it does in a quote, except above the quote's first line.
3107    ///
3108    /// What is written is what it takes to draw one more empty row. Between
3109    /// two blocks the first and last blank lines are the gap, so a paragraph
3110    /// break goes where there are fewer than two and a newline where the gap
3111    /// is already there. Above the first block only the last blank line is
3112    /// the gap, so a newline goes where there is one already. Preserve flow
3113    /// draws every blank line, so a newline is always enough there, but under
3114    /// frontmatter, whose own blank line draws nothing.
3115    fn paragraph_opening_at_caret(&mut self) -> Option<(usize, &'static str)> {
3116        let caret = self.caret.min(self.source.len());
3117        let chain = self.editor.ancestors_at(caret).ok()?;
3118        if chain.iter().any(|m| {
3119            matches!(
3120                m.kind,
3121                Kind::ListItem | Kind::TaskListItem | Kind::CodeBlock | Kind::Table
3122            )
3123        }) {
3124            return None;
3125        }
3126        let para = chain
3127            .iter()
3128            .find(|m| matches!(m.kind, Kind::Para | Kind::Heading))?;
3129        // An empty heading has nothing to push down: Enter there is still
3130        // the body under it.
3131        let end = para.span.end.min(self.source.len());
3132        if self.source[caret.min(end)..end].trim().is_empty() {
3133            return None;
3134        }
3135        let mut at = para.span.start;
3136        if at != caret {
3137            let text_before = self
3138                .editor
3139                .subtree(twig::NodeId(para.node_id))
3140                .ok()?
3141                .iter()
3142                .any(|n| {
3143                    n.span.start < caret
3144                        && (n.kind == Kind::Image
3145                            || n.text.as_deref().is_some_and(|t| !t.trim().is_empty()))
3146                });
3147            if text_before {
3148                return None;
3149            }
3150        }
3151        // Out past each container this paragraph opens, innermost first: one
3152        // whose source before it is its opening line and blank lines. A quote
3153        // opens on its first paragraph's own line, and draws no line above
3154        // that paragraph: the break goes above the quote. Further down a
3155        // quote twig's split writes a quoted line, which draws.
3156        let mut outer: Vec<_> = chain
3157            .iter()
3158            .filter(|m| matches!(m.kind, Kind::Container | Kind::BlockQuote) && m.span.start < at)
3159            .collect();
3160        outer.sort_by_key(|m| std::cmp::Reverse(m.span.start));
3161        for c in outer {
3162            let before = &self.source[c.span.start..at];
3163            let opens = match c.kind {
3164                Kind::BlockQuote => !before.contains('\n'),
3165                _ => before.lines().skip(1).all(|l| l.trim().is_empty()),
3166            };
3167            if !opens {
3168                break;
3169            }
3170            at = c.span.start;
3171        }
3172        if chain
3173            .iter()
3174            .any(|m| m.kind == Kind::BlockQuote && m.span.start < at)
3175        {
3176            return None;
3177        }
3178        let content = self.source[..at].trim_end().len();
3179        let newlines = self.source[content..at].matches('\n').count();
3180        // Every newline starts a blank line but one that ends the line of
3181        // what stands above, a block or hidden frontmatter.
3182        let blank = if content == 0 {
3183            newlines
3184        } else {
3185            newlines.saturating_sub(1)
3186        };
3187        let first = self
3188            .top_blocks()
3189            .iter()
3190            .all(|m| m.kind == Kind::Metadata || m.span.start >= at);
3191        // Preserve flow draws every blank line, but the one under frontmatter.
3192        let gap = match (self.line_flow, first) {
3193            (LineFlow::Preserve, true) => usize::from(content > 0),
3194            (LineFlow::Preserve, false) => 0,
3195            (LineFlow::Fold, true) => 1,
3196            (LineFlow::Fold, false) => 2,
3197        };
3198        Some((at, if blank >= gap { "\n" } else { "\n\n" }))
3199    }
3200
3201    /// Part the block at the caret with twig's [`Editor::split_block`], leaving
3202    /// the caret in the second half.
3203    ///
3204    /// twig reopens whatever the first half was inside of — the bullet with its
3205    /// indent, the quote's `>`, a checklist item's `[ ]` — which is the whole
3206    /// reason this replaced the markup leaf used to spell from the line's bytes.
3207    /// It renumbers nothing, though: a new item mid-list is written with its
3208    /// neighbour's number, so [`renumber_here`](Self::renumber_here) still runs
3209    /// behind it, folded into the same undo step.
3210    ///
3211    /// Falls back to a plain paragraph break if twig declines, so an unhandled
3212    /// shape still moves the caret down rather than swallowing the keystroke.
3213    fn split_block_here(&mut self) {
3214        // The read-only gate — this door reaches twig without the splice.
3215        if self.read_only {
3216            return;
3217        }
3218        match self.editor.split_block(self.caret) {
3219            Ok(change) => {
3220                self.last_edit_kind = None;
3221                self.refresh();
3222                self.anchor = None;
3223                self.caret = change.new.end;
3224                self.dirty = self.source != self.clean_source;
3225                self.status = None;
3226                self.clamp_caret();
3227                self.record_caret();
3228                // Aimed at the new block's *start*: the caret twig leaves is one
3229                // past the marker it wrote, where there is no list in reach.
3230                self.renumber_at(change.new.start);
3231            }
3232            Err(_) => self.insert_raw("\n\n"),
3233        }
3234    }
3235
3236    /// Whether the item on the marker's line carries no content — the shape
3237    /// double-Enter reads as "I'm done with this list."
3238    fn item_is_empty(&self, line: &ListMarker) -> bool {
3239        let content_start = line.content_start().min(self.source.len());
3240        let line_end = self.source[self.caret..]
3241            .find('\n')
3242            .map(|i| self.caret + i)
3243            .unwrap_or(self.source.len());
3244        self.source[content_start..line_end.max(content_start)]
3245            .trim()
3246            .is_empty()
3247    }
3248
3249    /// Leave the list: replace the empty item's marker with a blank line, so the
3250    /// caret lands in a fresh paragraph below it.
3251    ///
3252    /// Inside a quote the blank line has to stay quoted (a bare one would end the
3253    /// quote), and the caret's new line keeps the `> ` it was already behind —
3254    /// leaving the list without also leaving the quote.
3255    fn exit_list(&mut self, line: &ListMarker) {
3256        let prefix = self.quote_prefix_at(line.marker_start);
3257        let blank = prefix.trim_end();
3258        self.splice(
3259            line.line_start,
3260            self.caret,
3261            &format!("{blank}\n{prefix}"),
3262            EditKind::Other,
3263        );
3264    }
3265
3266    /// What a line continuing the containers at `off` has to open with — the
3267    /// quote markers reproduced, each enclosing item's marker as its width in
3268    /// spaces. Also the column a nested item's marker stands in, which is what
3269    /// makes it Tab's answer.
3270    fn continuation_prefix_at(&mut self, off: usize) -> String {
3271        self.editor
3272            .document()
3273            .and_then(|mut d| d.continuation_prefix(off))
3274            .map(|p| p.text)
3275            .unwrap_or_default()
3276    }
3277
3278    /// The column a *nested list* may open at inside the item at `off` — which
3279    /// is not always where the item's own text continues.
3280    ///
3281    /// twig counts a task item's `[ ] ` box as part of its marker, correctly:
3282    /// it is markup a rich view hides, and the item's own wrapped text does
3283    /// stand past it. But a nested list may only open at the *list* marker's
3284    /// column, and four columns further in is an indented continuation of the
3285    /// paragraph instead — `- [ ] a` + `      - [ ] b` is one item, not two.
3286    /// So the box's own width goes back.
3287    ///
3288    /// The one place leaf still reads a checkbox's spelling. It goes when twig
3289    /// reports the list marker's column apart from the box; `checked` is what
3290    /// says a box is there at all, so only its width is being measured here.
3291    fn nesting_prefix_at(&mut self, off: usize) -> String {
3292        let cont = self.continuation_prefix_at(off);
3293        let Some(item) = self.innermost_list_item(off) else {
3294            return cont;
3295        };
3296        if item.checked.is_none() {
3297            return cont;
3298        }
3299        let box_width = item
3300            .marker_span
3301            .and_then(|m| self.source.get(m))
3302            .and_then(|marker| marker.rfind('[').map(|i| marker.len() - i))
3303            .unwrap_or(0);
3304        // The trailing columns are the ones the item's own marker contributed,
3305        // so trimming from the end leaves any quote prefix standing.
3306        cont[..cont.len().saturating_sub(box_width)].to_string()
3307    }
3308
3309    /// Where the line of the item *containing* the item at `off` begins — the
3310    /// prefix Shift+Tab moves back to, which gives up exactly the level the
3311    /// parent contributed. The quote prefix alone for a top-level item, which
3312    /// has no level left to give.
3313    fn outdent_prefix_at(&mut self, off: usize) -> String {
3314        let items: Vec<usize> = self
3315            .editor
3316            .document()
3317            .and_then(|mut d| d.ancestors_at_caret(off))
3318            .map(|c| {
3319                c.into_iter()
3320                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
3321                    .map(|m| m.span.start)
3322                    .collect()
3323            })
3324            .unwrap_or_default();
3325        // The second-innermost item is the parent; its own line's indent is the
3326        // target. `list_marker_on_line` gives that line's prefix directly.
3327        let parent = items.len().checked_sub(2).map(|i| items[i]);
3328        match parent.and_then(|p| self.list_marker_on_line(p)) {
3329            Some(m) => self.source[m.line_start..m.marker_start].to_string(),
3330            None => self.quote_prefix_at(off),
3331        }
3332    }
3333
3334    /// The block-quote prefix in force at `off` — `""` outside a quote, `"> "`
3335    /// inside one, `"> > "` inside two.
3336    ///
3337    /// Assembled from each enclosing quote's own [`FlatNode::marker_span`], so
3338    /// the `>` and the space after it are twig's spelling rather than leaf's.
3339    /// The whole line prefix can't answer this: it also carries the indent of
3340    /// whatever the quote holds, which a blank separator line must *not* repeat.
3341    fn quote_prefix_at(&mut self, off: usize) -> String {
3342        let Ok(chain) = self
3343            .editor
3344            .document()
3345            .and_then(|mut d| d.ancestors_at_caret(off))
3346        else {
3347            return String::new();
3348        };
3349        let quotes: Vec<usize> = chain
3350            .iter()
3351            .filter(|m| m.kind == Kind::BlockQuote)
3352            .map(|m| m.node_id as usize)
3353            .collect();
3354        let Ok(nodes) = self.editor.nodes() else {
3355            return String::new();
3356        };
3357        quotes
3358            .iter()
3359            .filter_map(|id| nodes.get(*id)?.marker_span.clone())
3360            .filter_map(|s| self.source.get(s))
3361            .collect()
3362    }
3363
3364    /// Whether the item at `off` sits inside another one — the test Backspace
3365    /// uses to choose between outdenting and dropping the marker.
3366    ///
3367    /// Counted from the AST rather than from the line's leading whitespace,
3368    /// which is indentation in Markdown and, in Djot, may be nothing at all.
3369    fn item_is_nested(&mut self, off: usize) -> bool {
3370        self.editor
3371            .document()
3372            .and_then(|mut d| d.ancestors_at_caret(off))
3373            .map(|c| {
3374                c.into_iter()
3375                    .filter(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)
3376                    .count()
3377                    > 1
3378            })
3379            .unwrap_or(false)
3380    }
3381
3382    /// The innermost list item containing `probe`, under twig's **caret**
3383    /// containment rule — a block's end is inside it.
3384    ///
3385    /// Half-open containment can't answer this. An empty item's span is exactly
3386    /// its marker, so the caret sitting after `- ` is one past the end and the
3387    /// item it is plainly in tests as out of reach; that is the shape
3388    /// double-Enter has to recognise to leave the list.
3389    fn innermost_list_item(&mut self, probe: usize) -> Option<FlatNode> {
3390        let chain = self
3391            .editor
3392            .document()
3393            .and_then(|mut d| d.ancestors_at_caret(probe))
3394            .ok()?;
3395        let id = chain
3396            .iter()
3397            .rev()
3398            .find(|m| m.kind == Kind::ListItem || m.kind == Kind::TaskListItem)?
3399            .node_id as usize;
3400        self.editor.nodes().ok()?.get(id).cloned()
3401    }
3402
3403    /// The list marker opening `off`'s line, per twig — `None` when that line
3404    /// opens no list item.
3405    ///
3406    /// [`Document::line_prefix`] is the whole hidden run from the line start:
3407    /// `>   1. ` is a quote's marker, an indent, and an item's marker together,
3408    /// and it is `None` on a *continuation* line, which opens nothing. That last
3409    /// case is the one leaf could never get right by reading bytes. `- a\n  - b`
3410    /// is two items in Markdown and one in Djot, where a marker cannot interrupt
3411    /// a paragraph and `  - b` is literal text — identical bytes, and only the
3412    /// parser knows which document it is looking at.
3413    ///
3414    /// The item's own marker is separated out via its
3415    /// [`FlatNode::marker_span`], so `marker_start` splits the prefix into what
3416    /// the containers around it contribute and what the item does.
3417    fn list_marker_on_line(&mut self, off: usize) -> Option<ListMarker> {
3418        let off = off.min(self.source.len());
3419        let prefix = self.editor.document().ok()?.line_prefix(off).ok()??;
3420        // The prefix belongs to a list only when an item's marker closes it —
3421        // a heading's `# ` or a bare quote's `> ` is a prefix too.
3422        let item = self.innermost_list_item(prefix.end.min(self.source.len()))?;
3423        let marker = item.marker_span.clone()?;
3424        if marker.end != prefix.end {
3425            return None;
3426        }
3427        Some(ListMarker {
3428            line_start: prefix.start,
3429            marker_start: marker.start,
3430            text: self.source.get(prefix)?.to_string(),
3431        })
3432    }
3433
3434    /// Whether the list item on `line_start`'s line is the **first item** of its
3435    /// list — the one Tab must not nest, because nesting needs a preceding
3436    /// sibling to become the new parent and a first item has none. `false` for a
3437    /// line that isn't a list item, and for an item with a sibling above it (the
3438    /// one Tab *can* nest). Gated on the AST, not the marker bytes: `- ` reads
3439    /// the same in a setext underline that opens no list at all.
3440    fn first_item_of_list(&mut self, line_start: usize) -> bool {
3441        let Some(marker) = self.list_marker_on_line(line_start) else {
3442            return false;
3443        };
3444        // Probe just inside the marker, where the item's own node is in reach —
3445        // the marker offset itself can resolve to the enclosing list, not the
3446        // `list_item`, whose span starts at the marker.
3447        let probe = marker.content_start().min(self.source.len());
3448        let Some(item) = self.innermost_list_item(probe) else {
3449            return false;
3450        };
3451        let Ok(nodes) = self.editor.nodes() else {
3452            return false;
3453        };
3454        match item.parent {
3455            // First when the parent list opens with this very item.
3456            Some(pid) => nodes
3457                .get(pid.0 as usize)
3458                .is_some_and(|p| p.first_child == Some(item.id)),
3459            // A parentless item is trivially the first (and only) one.
3460            None => true,
3461        }
3462    }
3463
3464    pub fn backspace(&mut self) {
3465        if let Some((s, e)) = self.selection() {
3466            self.splice(s, e, "", EditKind::Other);
3467            return;
3468        }
3469        // WYSIWYG: Backspace at the very start of a list item's content is a
3470        // structural key, not a character delete — it walks the "un-indent, then
3471        // un-list" ladder every list editor gives that keystroke (outdent a
3472        // nested item, strip a top-level one's marker to a paragraph). In source
3473        // view the `- ` is visible text the user is deleting a byte of, so it
3474        // keeps its literal meaning there, like Enter does.
3475        if self.view != View::Source && self.backspace_list_start() {
3476            return;
3477        }
3478        // WYSIWYG: and the same at the start of a heading's content — the `# `
3479        // there is markup the rich view hides, not text the user typed.
3480        if self.view != View::Source && self.backspace_heading_start() {
3481            return;
3482        }
3483        // WYSIWYG: and at the start of a block whose presentation is spelled
3484        // as hidden markup before it — djot's `{.center}` line, Markdown's
3485        // `<div class="center">` — Backspace takes that markup, the way it
3486        // takes a heading's `#`, rather than a byte out of it.
3487        if self.view != View::Source && self.backspace_attributed_block_start() {
3488            return;
3489        }
3490        // WYSIWYG: at a block picture's stops, a byte-at-a-time delete would take
3491        // the markup apart under a caret that cannot see it — see
3492        // `delete_around_block_media`.
3493        if self.view != View::Source && self.delete_around_block_media(false) {
3494            return;
3495        }
3496        // WYSIWYG: Backspace at a table's trailing stop steps back into its last
3497        // cell rather than taking the byte behind the caret — the row's closing
3498        // `|`, which the rich view never drew, so the key would have looked like
3499        // it did nothing. The stop before is the last cell's end.
3500        if self.view != View::Source && self.backspace_at_table_end() {
3501            return;
3502        }
3503        // WYSIWYG: a table cell's start is a wall. The bytes behind it are the
3504        // padding and the `|` that make the grid, and taking them merges two
3505        // cells — a structural edit nobody asked for, and one no table editor
3506        // gives the key. Tab and Shift+Tab are how the caret leaves a cell.
3507        if self.view != View::Source && self.at_cell_wall(BreakEdge::Backward) {
3508            return;
3509        }
3510        // WYSIWYG: at the start of a block's content, the byte behind the caret
3511        // is a block boundary, and Backspace over one is a join — twig's, so
3512        // that what a join is in each format is not this file's to know. After
3513        // the picture and table cases, which are block starts with their own
3514        // answers.
3515        if self.view != View::Source && self.backspace_joins_block() {
3516            return;
3517        }
3518        // WYSIWYG: Backspace on a *blank line* deletes back to the previous caret
3519        // stop, not a single newline. On a line with no text of its own, the byte
3520        // before the caret is a `\n` that spells part of a block boundary — the gap
3521        // between two blocks, drawn but never a caret home. Removing just it strands
3522        // the caret in that gap and leaves an odd blank line the eye reads as one
3523        // separator but the caret can't land on: the "extra newline" left behind
3524        // after leaving a list (Enter, Enter) or a paragraph and pressing Backspace.
3525        // Deleting to the previous stop instead collapses the whole break at once,
3526        // landing the caret at the end of the block above. Two blank lines in a row
3527        // are one stop apart, so this still removes exactly one — the lone-Enter /
3528        // lone-Backspace symmetry the empty-line case is built on is untouched.
3529        if self.view != View::Source
3530            && self.caret > self.caret_floor()
3531            && self.caret_on_blank_line()
3532            && let Some(stop) = self.vmap.stop_before(self.caret)
3533        {
3534            let stop = stop.max(self.caret_floor());
3535            if stop < self.caret {
3536                if self.source[stop..self.caret].trim().is_empty() {
3537                    self.splice(stop, self.caret, "", EditKind::Delete);
3538                } else {
3539                    // Hidden markup stands between the stop and the caret — a
3540                    // `</div>`, a comment, a link reference definition — and
3541                    // collapsing to the stop would delete it. Take the blank
3542                    // line alone, with the newline that opened it, and land
3543                    // the caret where the collapse would have.
3544                    self.delete_blank_line_to(stop);
3545                }
3546                return;
3547            }
3548        }
3549        if self.caret > self.caret_floor() {
3550            // An in-cell `<br>` draws as one newline glyph, so Backspace over it
3551            // takes the whole tag — a single-byte step would leave a broken `<br`
3552            // showing in the cell. Rich view only (source view edits the literal).
3553            if self.view != View::Source
3554                && let Some((start, end)) = self.cell_break_at(BreakEdge::Backward)
3555            {
3556                let start = start.max(self.caret_floor());
3557                if start < end {
3558                    self.splice(start, end, "", EditKind::Delete);
3559                    return;
3560                }
3561            }
3562            // Aim the delete at the character the writer can *see* behind the
3563            // caret, never at a delimiter the rich view drew nothing for. Two
3564            // steps, and either can apply: from the far side of a run's closing
3565            // `**` step back into the run (the caret is drawn at the end of its
3566            // word), and at the start of a run's text step out past its opening
3567            // `**` to the character in front of it, leaving the run standing.
3568            // Without them a plain Backspace unspells the phrase it is editing
3569            // and leaves a literal asterisk on screen.
3570            let end = if self.view == View::Source {
3571                self.caret
3572            } else {
3573                let inside = self.step_inside_close_delims(self.caret);
3574                // An attributed span with no text — `<span …></span>` as the
3575                // file was written — is hidden markup around nothing, and a
3576                // byte-step here would take its `>`. Backspace takes the span
3577                // whole, with the character before it: the character the key
3578                // looks aimed at, since the span draws nothing.
3579                if let Some(span) = self.run_span_of_content(inside..inside) {
3580                    let from = if self.source[..span.start].ends_with('\n') {
3581                        span.start
3582                    } else {
3583                        prev_boundary(&self.source, span.start)
3584                    };
3585                    let from = from.max(self.caret_floor());
3586                    self.splice(from, span.end, "", EditKind::Delete);
3587                    return;
3588                }
3589                self.skip_leading_open_delims(inside)
3590                    .max(self.caret_floor())
3591            };
3592            // Never delete back across the floor — that would eat hidden
3593            // frontmatter the WYSIWYG caret can't even see.
3594            let mut prev = prev_boundary(&self.source, end).max(self.caret_floor());
3595            // Take a hidden escape backslash with the char it escapes: the rich
3596            // view draws `\*` as a single `*`, so Backspace over it must delete
3597            // both bytes, never strand the `\` as a lone visible backslash (the
3598            // mirror of the Hidden-mode typing that wrote the escape). Source view
3599            // shows the `\`, so there it is an ordinary character.
3600            if self.view != View::Source
3601                && prev > self.caret_floor()
3602                && self.is_hidden_escape(prev - 1)
3603            {
3604                prev -= 1;
3605            }
3606            // The delete that takes the last of a span's text takes the span
3607            // with it, in the same edit: `<span …>i</span>` losing its `i`
3608            // would leave an empty span the map has no stop inside, so the
3609            // caret would draw at the next stop — a line away — until a
3610            // further key removed the span. Landing on the span's start is
3611            // where the letter was.
3612            if self.view != View::Source
3613                && let Some(span) = self.run_span_of_content(prev..end)
3614            {
3615                self.splice(span.start, span.end, "", EditKind::Delete);
3616                return;
3617            }
3618            // And the same for a block: the letter that was all of a centred
3619            // paragraph's text goes with the `<div>` around it, or the `{…}`
3620            // line above it, leaving a plain blank line where the letter was.
3621            // A paragraph with no text is no block, so the markup would stand
3622            // around nothing, the map would give it no caret home, and the
3623            // next key would take the tag apart.
3624            if self.view != View::Source
3625                && let Some(block) = self.attributed_block_of_content(prev..end)
3626            {
3627                self.splice(block.start, block.end, "", EditKind::Delete);
3628                return;
3629            }
3630            if prev < end {
3631                self.splice(prev, end, "", EditKind::Delete);
3632            }
3633        }
3634    }
3635
3636    /// Remove the blank line the caret is on — its own newline and the one
3637    /// that ended the line before it — and put the caret on `stop`, the caret
3638    /// stop before it. The [`backspace`](Self::backspace) blank-line rule for a
3639    /// blank line that hidden markup separates from the block above: the
3640    /// navigable blank row after a `</div>` is always one of at least three
3641    /// newlines under the tag (the drawn separators either side of it), so
3642    /// taking two leaves the blank line the tag needs under it.
3643    fn delete_blank_line_to(&mut self, stop: usize) {
3644        let caret = self.caret;
3645        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
3646        let line_end = self.source[caret..]
3647            .find('\n')
3648            .map_or(self.source.len(), |i| caret + i);
3649        let from = line_start.saturating_sub(1).max(stop);
3650        let to = (line_end + 1).min(self.source.len());
3651        self.splice(from, to, "", EditKind::Delete);
3652        self.caret = stop;
3653        self.anchor = None;
3654        self.goal_col = None;
3655        self.record_caret();
3656    }
3657
3658    /// Move the caret to the stop before it and consume the key — what
3659    /// Backspace does where the byte behind the caret is hidden markup it
3660    /// has no structural answer for, rather than take that markup apart.
3661    fn step_back_to_stop(&mut self) {
3662        // The map answers about offsets, so it has to be this revision's — see
3663        // `open_paragraph_at_block_edge`.
3664        self.rebuild_map();
3665        if let Some(off) = self
3666            .vmap
3667            .stop_before(self.caret)
3668            .filter(|&o| o >= self.caret_floor())
3669        {
3670            self.caret = off;
3671            self.anchor = None;
3672            self.goal_col = None;
3673        }
3674    }
3675
3676    /// Backspace's presentation behaviour: with the caret exactly at the start
3677    /// of a block's content, and that block's attributes spelled as hidden
3678    /// markup before it, strip the attributes. The peer of
3679    /// [`backspace_heading_start`](Self::backspace_heading_start), and the same
3680    /// reasoning: the `{.center}` line above a djot block and the
3681    /// `<div class="center">` around a Markdown one are what the byte behind
3682    /// the caret belongs to, and the rich view draws neither. The ordinary
3683    /// delete took the newline out of `{.center}\nhello` and left
3684    /// `{.center}hello` — the attribute line fused onto the text as prose —
3685    /// and out of `<div …>\n\nhello` it took the blank line the div needs.
3686    ///
3687    /// The whole attribute set goes, the way the whole `#` marker does — the
3688    /// press is over the line that spells it, not over one key of it — and
3689    /// twig's `set_block_attrs` with an empty list is the edit: it removes the
3690    /// djot line and unwraps the Markdown div. Where the block is the first of
3691    /// several in a div, twig has no sole child to unwrap and answers with a
3692    /// no-op, so the caret steps back to the stop before instead, as it does
3693    /// at a table's end. A later child of the div has an ordinary paragraph
3694    /// above it and is not this rule's.
3695    ///
3696    /// Returns whether it acted; `false` leaves Backspace its character delete.
3697    fn backspace_attributed_block_start(&mut self) -> bool {
3698        if !matches!(self.format, Format::Markdown | Format::Djot) {
3699            return false;
3700        }
3701        let caret = self.caret;
3702        let nodes = self.nodes();
3703        let Some(block) = nodes
3704            .iter()
3705            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3706            .find(|n| n.content_span.as_ref().map_or(n.span.start, |c| c.start) == caret)
3707        else {
3708            return false;
3709        };
3710        match self.format {
3711            Format::Djot => {
3712                // twig records where the `{…}` block was written, so this is
3713                // the parser's own answer and not a scan for a `{` above the
3714                // block; `None` (a synthesized or merged set) is not a line
3715                // the caret is standing after.
3716                let spelled = self
3717                    .editor
3718                    .document()
3719                    .ok()
3720                    .and_then(|mut d| d.attrs_span(block.id).ok().flatten())
3721                    .is_some_and(|s| s.end <= caret);
3722                if !spelled {
3723                    return false;
3724                }
3725            }
3726            _ => {
3727                let Some(div) = block
3728                    .parent
3729                    .and_then(|p| nodes.iter().find(|n| n.id == p))
3730                    .filter(|p| wysiwyg::element_tag(p) == Some("div"))
3731                else {
3732                    return false;
3733                };
3734                let mut kids = nodes.iter().filter(|n| n.parent == Some(div.id));
3735                if kids.clone().any(|k| k.span.start < block.span.start) {
3736                    return false;
3737                }
3738                if kids.nth(1).is_some() {
3739                    self.step_back_to_stop();
3740                    return true;
3741                }
3742            }
3743        }
3744        self.write_block_attrs("block attributes", Vec::new());
3745        true
3746    }
3747
3748    /// Backspace at the start of a block's content: join the block into the
3749    /// block before it, as one gesture — twig's `join_blocks`, the inverse of
3750    /// the split Enter makes, spelled the format's way. Two paragraphs join
3751    /// on a soft break; a paragraph under a marker heading joins onto the
3752    /// heading's line; a paragraph after a Markdown `<div>` moves inside it,
3753    /// the hidden `</div>` carried past the joined text; HTML's `</p><p>` is
3754    /// taken as one; a quote's or an item's continuation prefix is written.
3755    /// The joined text takes the block above's presentation and containers,
3756    /// which is the rule every editor with a centred paragraph follows.
3757    ///
3758    /// Leaf used to join by deleting the one newline behind the caret, which
3759    /// is the right bytes for two Markdown paragraphs and nothing else: under
3760    /// a heading it left two blocks, in HTML it took the `>` off a tag, and
3761    /// after a div it took the newline under the hidden `</div>`, which drew
3762    /// nothing different and took the tag apart on the next press. What a
3763    /// join is in each format is twig's to know, and now it does.
3764    ///
3765    /// Where twig refuses — the block above is a code block, a table or a
3766    /// rule with no text to join into, or the caret's block would have to
3767    /// leave a div that holds more after it — the caret steps back to the
3768    /// stop before instead, as it does at a table's end: the key moves the
3769    /// caret and takes no markup apart. Where nothing precedes the block, or
3770    /// the format cannot join at all, Backspace keeps its character delete.
3771    ///
3772    /// Returns whether it acted.
3773    fn backspace_joins_block(&mut self) -> bool {
3774        let caret = self.caret;
3775        if caret <= self.caret_floor() {
3776            return false;
3777        }
3778        let Some(text) = self.text_block_opening_at(caret) else {
3779            return false;
3780        };
3781        match self.join_blocks(caret) {
3782            Ok(change) => {
3783                // The caret keeps its place at the start of the text it stood
3784                // on, wherever the join put that text — after a soft break,
3785                // a space, or a quote's prefix. Found by the bytes, as
3786                // `block_content_in` finds a re-spelled block.
3787                let region = &self.source[change.new.clone()];
3788                let at = region
3789                    .find(&text)
3790                    .map_or(change.new.start, |i| change.new.start + i);
3791                self.land_after_join(at);
3792                true
3793            }
3794            Err(twig::Error::NotEditable) => {
3795                self.step_back_to_stop();
3796                true
3797            }
3798            Err(twig::Error::NotFound | twig::Error::UnsupportedFormat) => false,
3799            Err(e) => {
3800                self.status = Some(format!("join: {e}"));
3801                true
3802            }
3803        }
3804    }
3805
3806    /// Delete at the end of a block's content: join the block after it into
3807    /// this one — [`backspace_joins_block`](Self::backspace_joins_block)'s
3808    /// mirror, and the same twig gesture aimed at the next block. The caret
3809    /// stays where it was, which is where the joined text now begins after
3810    /// the separator. Where twig refuses, the caret steps forward to the next
3811    /// stop instead; where no block follows, Delete keeps its character
3812    /// delete.
3813    fn delete_forward_joins_block(&mut self) -> bool {
3814        let caret = self.caret;
3815        let at_end = self
3816            .nodes()
3817            .iter()
3818            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3819            .any(|n| n.content_span.as_ref().is_some_and(|c| c.end == caret));
3820        if !at_end {
3821            return false;
3822        }
3823        // The next stop, across a line end, in a block: what Delete at a
3824        // block's end points at. On the same line it is a hidden delimiter's
3825        // far side, which the ordinary delete handles; on a blank line it is
3826        // the empty paragraph the byte delete has always closed.
3827        self.rebuild_map();
3828        let Some(stop) = self.vmap.stop_after(caret) else {
3829            return false;
3830        };
3831        if !self.source[caret..stop].contains('\n') || !self.has_block_at(stop) {
3832            return false;
3833        }
3834        match self.join_blocks(stop) {
3835            Ok(change) => {
3836                self.land_after_join(change.old.start);
3837                true
3838            }
3839            Err(twig::Error::NotEditable | twig::Error::NotFound) => {
3840                self.caret = stop;
3841                self.anchor = None;
3842                self.goal_col = None;
3843                true
3844            }
3845            Err(twig::Error::UnsupportedFormat) => false,
3846            Err(e) => {
3847                self.status = Some(format!("join: {e}"));
3848                true
3849            }
3850        }
3851    }
3852
3853    /// The content bytes of the paragraph or heading whose content opens
3854    /// exactly at `off` — the block a Backspace there is at the start of.
3855    fn text_block_opening_at(&mut self, off: usize) -> Option<String> {
3856        self.nodes()
3857            .into_iter()
3858            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
3859            .find_map(|n| {
3860                let c = n.content_span?;
3861                (c.start == off).then(|| self.source[c].to_string())
3862            })
3863    }
3864
3865    /// Hand the block at `offset` to twig's `join_blocks`, with the undo
3866    /// plumbing every structural gesture has; the caret is the caller's to
3867    /// place from the change, via [`land_after_join`](Self::land_after_join).
3868    fn join_blocks(&mut self, offset: usize) -> Result<Change, twig::Error> {
3869        if self.read_only {
3870            return Err(twig::Error::NotEditable);
3871        }
3872        self.record_caret();
3873        let change = self.editor.join_blocks(offset)?;
3874        self.last_edit_kind = None; // structural edit is its own undo step
3875        self.refresh();
3876        Ok(change)
3877    }
3878
3879    /// Finish a join: the caret at `at`, no selection, the map this
3880    /// revision's before the clamp — see `write_block_attrs` for why.
3881    fn land_after_join(&mut self, at: usize) {
3882        self.caret = at;
3883        self.anchor = None;
3884        self.goal_col = None;
3885        self.dirty = self.source != self.clean_source;
3886        self.status = None;
3887        self.rebuild_map();
3888        self.clamp_caret();
3889        self.record_caret();
3890    }
3891
3892    // ── moving a block ─────────────────────────────────────────────────────────
3893
3894    /// The block a move picks up at `offset` — the same one
3895    /// [`select_block_at`](Self::select_block_at) selects (the deepest node
3896    /// that is neither inline nor a multi-block container), widened to the
3897    /// list item when it is the item's first block, because that is what
3898    /// twig's `move_block` moves: a bullet's text is the bullet, and dragging
3899    /// it takes the item and everything under it. A block later in an item's
3900    /// tail moves alone. `None` on a blank line, and past the source.
3901    fn movable_block_at(&mut self, offset: usize) -> Option<FlatNode> {
3902        let off = offset.min(self.source.len());
3903        let chain = self.editor.ancestors_at(off).ok()?;
3904        let block = chain
3905            .iter()
3906            .rev()
3907            .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))?;
3908        let nodes = self.nodes();
3909        let block = nodes.get(block.node_id as usize)?.clone();
3910        let item = block
3911            .parent
3912            .and_then(|p| nodes.get(p.0 as usize))
3913            .filter(|p| matches!(p.kind, Kind::ListItem | Kind::TaskListItem))
3914            .filter(|p| p.first_child == Some(block.id));
3915        Some(item.cloned().unwrap_or(block))
3916    }
3917
3918    /// The source range of the block a move would pick up at `offset` — for
3919    /// the outline of the block being carried, without moving the caret. The
3920    /// range [`select_block_at`](Self::select_block_at) would select, except
3921    /// that it is the whole item for a bullet's text, as
3922    /// [`move_block`](Self::move_block) is.
3923    pub fn block_range_at(&mut self, offset: usize) -> Option<Range<usize>> {
3924        self.movable_block_at(offset).map(|b| b.span)
3925    }
3926
3927    /// Move the block at `from` to the boundary `to` — twig's `move_block`,
3928    /// with the undo plumbing every structural gesture has and the caret
3929    /// riding the block to its new place. `from` is any offset inside the
3930    /// block (the one [`block_range_at`](Self::block_range_at) finds); `to`
3931    /// is a position *between* blocks — a block's first byte lands before it,
3932    /// its last after it, a blank line is itself a boundary, and the source's
3933    /// length is the document's end. The block takes the line prefixes of
3934    /// the container the boundary is inside — a `> ` on the way into a quote,
3935    /// none on the way out — and the blank lines a person would have typed
3936    /// are written and removed; twig spells all of that.
3937    ///
3938    /// A move that would move nothing — `to` inside the block, or on the
3939    /// boundary it already sits on — is a quiet no-op rather than an error,
3940    /// since it is what a block dropped back where it was asks for. Any other
3941    /// refusal reaches the status line: a `to` interior to a fence or a table,
3942    /// or a format with no blocks a caret could name.
3943    ///
3944    /// In WYSIWYG the frontmatter is hidden, and a boundary above it is not
3945    /// one a person can see: `to` is raised to the first rendered offset.
3946    ///
3947    /// `true` when the document changed. A move twig accepts that rewrites
3948    /// nothing — a one-item list sent past a paragraph is still a one-item
3949    /// list past that paragraph — is taken back rather than left as an undo
3950    /// step with no difference in it, and is `false` too.
3951    pub fn move_block(&mut self, from: usize, to: usize) -> bool {
3952        if self.read_only || self.refuse_unsupported("move block", Gesture::MoveBlock) {
3953            return false;
3954        }
3955        let len = self.source.len();
3956        let from = from.min(len);
3957        let to = to.clamp(self.caret_floor().min(len), len);
3958        let Some(block) = self.movable_block_at(from) else {
3959            self.status = Some("move block: no block here".into());
3960            return false;
3961        };
3962        // Where the caret stands in the block, as (line within the block,
3963        // bytes back from that line's end) — the shape that survives a
3964        // prefix being added or stripped on the way through a container.
3965        let caret = self.caret.clamp(block.span.start, block.span.end);
3966        let block_line = self.source[block.span.start..caret].matches('\n').count();
3967        let line_end = self.source[caret..block.span.end]
3968            .find('\n')
3969            .map_or(block.span.end, |i| caret + i);
3970        let tail = line_end - caret;
3971        let block_lines = self.source[block.span.start..block.span.end]
3972            .matches('\n')
3973            .count()
3974            + 1;
3975        let upward = to <= block.span.start;
3976        self.record_caret();
3977        match self.editor.move_block(from, to) {
3978            Ok(_) if self.editor.source_str().ok().as_deref() == Some(self.source.as_str()) => {
3979                let _ = self.editor.undo();
3980                self.status = None;
3981                false
3982            }
3983            Ok(change) => {
3984                self.last_edit_kind = None; // structural edit is its own undo step
3985                self.refresh();
3986                let at = self.moved_block_caret(&change.new, upward, block_lines, block_line, tail);
3987                self.caret = at;
3988                self.anchor = None;
3989                self.goal_col = None;
3990                self.dirty = self.source != self.clean_source;
3991                self.status = None;
3992                self.rebuild_map();
3993                self.clamp_caret();
3994                self.record_caret();
3995                true
3996            }
3997            // Nothing to move: the block dropped back onto its own boundary.
3998            Err(twig::Error::InvalidArgument) => {
3999                self.status = None;
4000                false
4001            }
4002            Err(e) => {
4003                self.status = Some(format!("move block: {e}"));
4004                false
4005            }
4006        }
4007    }
4008
4009    /// The caret's place in the rewritten region after a move: the moved
4010    /// block's lines open the region when it went up (below the blank line it
4011    /// was dropped on, when it was) and close it (above the separator twig
4012    /// wrote after it) when it went down, and within them the
4013    /// caret keeps its line and its distance from that line's end. Clamped
4014    /// into the region rather than trusted, since a block can lose a line on
4015    /// the way — a quote it was the only content of goes with it.
4016    fn moved_block_caret(
4017        &self,
4018        new: &Range<usize>,
4019        upward: bool,
4020        block_lines: usize,
4021        block_line: usize,
4022        tail: usize,
4023    ) -> usize {
4024        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
4025        let mut lines: Vec<(usize, usize)> = Vec::new();
4026        let mut start = 0;
4027        loop {
4028            match region[start..].find('\n') {
4029                Some(i) => {
4030                    lines.push((start, start + i));
4031                    start += i + 1;
4032                }
4033                None => {
4034                    lines.push((start, region.len()));
4035                    break;
4036                }
4037            }
4038        }
4039        // A separator line is blank, or a quote's bare `>`; the region can
4040        // open with one (the blank line the block was dropped on) or close
4041        // with one (the one twig wrote after it).
4042        let separator = |&(s, e): &(usize, usize)| {
4043            region[s..e]
4044                .trim()
4045                .trim_start_matches('>')
4046                .trim()
4047                .is_empty()
4048        };
4049        let first = if upward {
4050            lines.iter().position(|l| !separator(l)).unwrap_or(0)
4051        } else {
4052            let filled = lines
4053                .iter()
4054                .rposition(|l| !separator(l))
4055                .map_or(0, |i| i + 1);
4056            filled.saturating_sub(block_lines)
4057        };
4058        let (s, e) = lines[(first + block_line).min(lines.len() - 1)];
4059        new.start + e.saturating_sub(tail).max(s)
4060    }
4061
4062    /// Move the caret's block one place up — Alt+↑: above the block before it,
4063    /// and out of its container, to just above it, when it is the first block
4064    /// there. Nothing above the document's first block, and nothing to do for
4065    /// a caret on a blank line; both say so in the status line.
4066    pub fn move_block_up(&mut self) {
4067        self.move_block_by(true);
4068    }
4069
4070    /// Move the caret's block one place down — Alt+↓, the mirror of
4071    /// [`move_block_up`](Self::move_block_up): below the block after it, and
4072    /// out of its container when it is the last block there.
4073    pub fn move_block_down(&mut self) {
4074        self.move_block_by(false);
4075    }
4076
4077    fn move_block_by(&mut self, up: bool) {
4078        if self.read_only || self.refuse_unsupported("move block", Gesture::MoveBlock) {
4079            return;
4080        }
4081        let Some(from) = self.block_offset_for_caret() else {
4082            self.status = Some("move block: no block here".into());
4083            return;
4084        };
4085        let Some(block) = self.movable_block_at(from) else {
4086            self.status = Some("move block: no block here".into());
4087            return;
4088        };
4089        let nodes = self.nodes();
4090        let to = if up {
4091            self.boundary_above(&nodes, &block)
4092        } else {
4093            self.boundary_below(&nodes, &block)
4094        };
4095        if to.is_none_or(|to| !self.move_block(from, to)) && self.status.is_none() {
4096            self.status = Some(if up {
4097                "move block: nothing above".into()
4098            } else {
4099                "move block: nothing below".into()
4100            });
4101        }
4102    }
4103
4104    /// The boundary one step above `block`: before its previous sibling, or
4105    /// — for the first block in a container — before the container itself.
4106    /// `None` for the document's first block.
4107    fn boundary_above(&self, nodes: &[FlatNode], block: &FlatNode) -> Option<usize> {
4108        let parent = block.parent.and_then(|p| nodes.get(p.0 as usize))?;
4109        let previous = nodes
4110            .iter()
4111            .filter(|n| n.parent == Some(parent.id))
4112            .take_while(|n| n.id != block.id)
4113            .last();
4114        match previous {
4115            Some(p) => self.before(p),
4116            None if parent.kind == Kind::Doc => None,
4117            // An item leaving a nested list upward goes before the item
4118            // holding that list, as an item of the outer one; the list's own
4119            // first byte is inside the holding item's tail.
4120            None if matches!(
4121                parent.kind,
4122                Kind::BulletList | Kind::OrderedList | Kind::TaskList
4123            ) =>
4124            {
4125                match parent.parent.and_then(|p| nodes.get(p.0 as usize)) {
4126                    Some(item) if matches!(item.kind, Kind::ListItem | Kind::TaskListItem) => {
4127                        self.before(item)
4128                    }
4129                    _ => self.before(parent),
4130                }
4131            }
4132            None => self.before(parent),
4133        }
4134    }
4135
4136    /// The boundary one step below `block`: after its next sibling, or — for
4137    /// the last block in a container — just past the container, at its
4138    /// parent's level ([`exit_below`](Self::exit_below)). `None` for the
4139    /// document's last block.
4140    fn boundary_below(&self, nodes: &[FlatNode], block: &FlatNode) -> Option<usize> {
4141        let parent = block.parent.and_then(|p| nodes.get(p.0 as usize))?;
4142        if let Some(n) = block.next_sibling.and_then(|n| nodes.get(n.0 as usize)) {
4143            return Some(self.after(n));
4144        }
4145        match parent.kind {
4146            Kind::Doc => None,
4147            _ => self.exit_below(nodes, parent),
4148        }
4149    }
4150
4151    /// The boundary just past `container` at its parent's level: before its
4152    /// next sibling, or past its parent when it is the last thing there —
4153    /// the document's end at the top. Leaving a list item is the exception
4154    /// that keeps a block in the list: the next item's tail, which is what
4155    /// [`after`](Self::after) an item names.
4156    fn exit_below(&self, nodes: &[FlatNode], container: &FlatNode) -> Option<usize> {
4157        let item = matches!(container.kind, Kind::ListItem | Kind::TaskListItem);
4158        match container.next_sibling.and_then(|n| nodes.get(n.0 as usize)) {
4159            Some(n) if item => Some(self.after(n)),
4160            Some(n) => self.before(n),
4161            None => {
4162                let parent = container.parent.and_then(|p| nodes.get(p.0 as usize))?;
4163                match parent.kind {
4164                    Kind::Doc => Some(self.source.len()),
4165                    _ => self.exit_below(nodes, parent),
4166                }
4167            }
4168        }
4169    }
4170
4171    /// The boundary before `node`: its first byte. twig reads a container's
4172    /// opening as before it — a quote's marker, a fence's first byte — so the
4173    /// span's start is the boundary at the parent's level for every kind.
4174    fn before(&self, node: &FlatNode) -> Option<usize> {
4175        Some(node.span.start)
4176    }
4177
4178    /// The boundary after `node`: its own end, which for a container proper
4179    /// (a quote, a list, a fenced or tagged container) is the end of its last
4180    /// line — after its last block, still inside it, where a block arriving
4181    /// from outside joins it. Past the container is the next line's start: a
4182    /// blank line, the next block, or the document's end.
4183    fn after(&self, node: &FlatNode) -> usize {
4184        let container = is_block_container(&node.kind)
4185            && !matches!(node.kind, Kind::ListItem | Kind::TaskListItem);
4186        let end = node.span.end.min(self.source.len());
4187        if container && self.source.as_bytes().get(end) == Some(&b'\n') {
4188            end + 1
4189        } else {
4190            end
4191        }
4192    }
4193
4194    /// Where a block dragged over rendered row `row` would land — the
4195    /// boundary before the row's block when the row is in its upper half, the
4196    /// boundary after it otherwise, and the document's end for a row below
4197    /// everything. `None` for a row that holds no block (a decoration row is
4198    /// resolved to the block under it, so this is a table's bottom rule with
4199    /// nothing after it, or a map with no rows). The frontend draws its
4200    /// indicator above [`DropTarget::row`] and hands
4201    /// [`DropTarget::offset`] to [`move_block`](Self::move_block).
4202    ///
4203    /// The block is the deepest one, not the widened item: a drop on a
4204    /// bullet's text lands before or after that bullet, and its nested
4205    /// children — rows of their own — answer for themselves.
4206    pub fn drop_target_at(&mut self, row: usize) -> Option<DropTarget> {
4207        let rows = self.vmap.rows.len();
4208        if row >= rows {
4209            return Some(DropTarget {
4210                offset: self.source.len(),
4211                row: rows,
4212            });
4213        }
4214        // A gap or a rule is not a block; the block under it is the one meant.
4215        let row = (row..rows).find(|&r| self.vmap.row_is_navigable(r))?;
4216        let start = self.vmap.row_start(row)?;
4217        let chain = self.editor.ancestors_at(start).ok()?;
4218        let block = chain
4219            .iter()
4220            .rev()
4221            .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))?;
4222        let span = block.span.clone();
4223        let (first, last) = self.vmap.row_range_for(span.clone());
4224        if row <= usize::midpoint(first, last) {
4225            Some(DropTarget {
4226                offset: span.start,
4227                row: first,
4228            })
4229        } else {
4230            Some(DropTarget {
4231                offset: span.end.min(self.source.len()),
4232                row: last + 1,
4233            })
4234        }
4235    }
4236
4237    /// Backspace at a table's trailing stop: move onto the stop before it (the
4238    /// last cell's end) and consume the key. `false` anywhere else. See
4239    /// [`VisualMap::table_end_stop`] for why the byte behind the caret there is
4240    /// not one to delete.
4241    fn backspace_at_table_end(&mut self) -> bool {
4242        // The map answers about offsets, so it has to be this revision's — see
4243        // `open_paragraph_at_block_edge`.
4244        self.rebuild_map();
4245        if !self.vmap.table_end_stop(self.caret) {
4246            return false;
4247        }
4248        if let Some(off) = self
4249            .vmap
4250            .stop_before(self.caret)
4251            .filter(|&o| o >= self.caret_floor())
4252        {
4253            self.caret = off;
4254            self.anchor = None;
4255            self.goal_col = None;
4256        }
4257        true
4258    }
4259
4260    /// Whether the caret stands at a table cell's wall on the `edge` side — at
4261    /// or before its first caret stop for Backspace, at or past its last for
4262    /// Delete — where the only bytes between it and the neighbouring cell are
4263    /// the padding and the `|` the rich view draws as the grid. The padding
4264    /// counts as the cell's: a caret placed between `| ` and the text is at the
4265    /// same wall, so the first press cannot eat the space either. An in-cell
4266    /// `<br>` at the edge is not a wall; the delete takes it whole, as ever.
4267    fn at_cell_wall(&mut self, edge: BreakEdge) -> bool {
4268        // The map answers about offsets, so it has to be this revision's.
4269        self.rebuild_map();
4270        if self.cell_break_at(edge).is_some() {
4271            return false;
4272        }
4273        let caret = self.caret;
4274        let src = self.source.as_bytes();
4275        let pad = |b: &u8| *b == b' ' || *b == b'\t';
4276        self.vmap
4277            .tables
4278            .iter()
4279            .flat_map(|t| &t.grid)
4280            .flat_map(|row| &row.cells)
4281            .any(|cell| {
4282                let lo = cell.start
4283                    - src[..cell.start]
4284                        .iter()
4285                        .rev()
4286                        .take_while(|b| pad(b))
4287                        .count();
4288                let hi = cell.end + src[cell.end..].iter().take_while(|b| pad(b)).count();
4289                (lo..=hi).contains(&caret)
4290                    && match edge {
4291                        BreakEdge::Backward => {
4292                            self.vmap.stop_before(caret).is_none_or(|s| s < cell.start)
4293                        }
4294                        BreakEdge::Forward => {
4295                            self.vmap.stop_after(caret).is_none_or(|s| s > cell.end)
4296                        }
4297                    }
4298            })
4299    }
4300
4301    /// Whether the caret's own source line holds nothing but whitespace — an
4302    /// empty paragraph, or the blank line a block boundary is spelled with. The
4303    /// test for [`backspace`](Self::backspace)'s stop-wise delete: such a line has
4304    /// no text of its own, so the newline before the caret belongs to the gap
4305    /// between blocks rather than to any word the caret is editing.
4306    fn caret_on_blank_line(&self) -> bool {
4307        let line_start = self.source[..self.caret].rfind('\n').map_or(0, |i| i + 1);
4308        let line_end = self.source[self.caret..]
4309            .find('\n')
4310            .map_or(self.source.len(), |i| self.caret + i);
4311        self.source[line_start..line_end].trim().is_empty()
4312    }
4313
4314    /// The source span of an in-cell hard break (`<br>`) touching the caret on the
4315    /// `edge` side — the byte range to delete whole. A table row is one source
4316    /// line, so its break is spelled `<br>` yet drawn as a single newline glyph
4317    /// (see `wysiwyg.rs`); a delete over it must take every byte, or a one-byte
4318    /// step strands a broken `<br` in the cell. `Backward` matches a break ending
4319    /// at the caret (Backspace), `Forward` one starting at it (Delete). `None`
4320    /// when no such break is adjacent. Only the in-cell break is spelled `<br>`
4321    /// (an ordinary hard break is `  \n`), so the leading `<` alone tells them
4322    /// apart — no ancestor walk needed. Rich view only; source view shows the
4323    /// literal tag and deletes it a byte at a time.
4324    fn cell_break_at(&mut self, edge: BreakEdge) -> Option<(usize, usize)> {
4325        let caret = self.caret;
4326        let nodes = self.nodes();
4327        let src = self.source.as_bytes();
4328        nodes
4329            .iter()
4330            .find(|n| {
4331                n.kind == Kind::HardBreak
4332                    && n.span.start < n.span.end
4333                    && src.get(n.span.start) == Some(&b'<')
4334                    && match edge {
4335                        BreakEdge::Backward => n.span.end == caret,
4336                        BreakEdge::Forward => n.span.start == caret,
4337                    }
4338            })
4339            .map(|n| (n.span.start, n.span.end))
4340    }
4341
4342    /// Whether the source byte at `off` is a backslash twig consumed as an escape
4343    /// (hidden in the rich view), as against a literal backslash (drawn). A
4344    /// backslash escapes exactly an ASCII-punctuation character (the CommonMark /
4345    /// Djot rule twig follows), so `\` + punctuation is the whole test — no AST
4346    /// round-trip needed.
4347    fn is_hidden_escape(&self, off: usize) -> bool {
4348        let b = self.source.as_bytes();
4349        b.get(off) == Some(&b'\\') && b.get(off + 1).is_some_and(u8::is_ascii_punctuation)
4350    }
4351
4352    /// Backspace's list behaviour: when the caret sits exactly at the start of a
4353    /// list item's content (right after its marker), outdent the item if it's
4354    /// nested, else strip the marker so it becomes a paragraph. Returns whether
4355    /// it acted — `false` leaves Backspace its ordinary character delete.
4356    fn backspace_list_start(&mut self) -> bool {
4357        let Some(marker) = self.list_marker_on_line(self.caret) else {
4358            return false;
4359        };
4360        // Only right after the marker. That the line opens a real item is
4361        // already settled: `list_marker_on_line` answers from the tree.
4362        if self.caret != marker.content_start() {
4363            return false;
4364        }
4365        if self.item_is_nested(marker.marker_start) {
4366            // Nested: give back one level, keeping the marker and carrying the
4367            // caret with it.
4368            self.outdent();
4369        } else {
4370            // Top level: drop the marker, leaving a paragraph, then renumber the
4371            // siblings the removed item was counted among. Only the marker goes —
4372            // a quote prefix in front of it still has a quote to hold up.
4373            self.splice(marker.marker_start, self.caret, "", EditKind::Other);
4374            self.renumber_here();
4375        }
4376        true
4377    }
4378
4379    /// Backspace's heading behaviour: with the caret exactly at the start of an
4380    /// ATX heading's content — right after the `#` marker the rich view hides —
4381    /// strip the marker so the line becomes a paragraph. The peer of
4382    /// [`backspace_list_start`](Self::backspace_list_start)'s ladder, and the same
4383    /// reasoning: hidden block markup is structure, so the keystroke over it is
4384    /// structural.
4385    ///
4386    /// Without this the ordinary delete takes the space out of `# Title` and
4387    /// leaves `#Title`, which is no longer a heading at all — the hash the view
4388    /// had been hiding surfaces as literal text the user has to delete a second
4389    /// time, having never typed it. A closing sequence (`# Title #`, hidden at the
4390    /// other end) goes with the marker for the same reason.
4391    ///
4392    /// Returns whether it acted; `false` leaves Backspace its character delete.
4393    fn backspace_heading_start(&mut self) -> bool {
4394        let caret = self.caret;
4395        // The heading whose content opens exactly at the caret. A bare `#` has no
4396        // content span at all — its content starts (and ends) where the line does.
4397        let Some((span, content_end, marker)) = self.nodes().iter().find_map(|n| {
4398            let (start, end) = match &n.content_span {
4399                Some(c) => (c.start, c.end),
4400                None => (n.span.end, n.span.end),
4401            };
4402            (n.kind == Kind::Heading && start == caret)
4403                .then(|| (n.span.clone(), end, n.marker_span.clone()))
4404        }) else {
4405            return false;
4406        };
4407        // twig reports the marker's own extent, so there is nothing to walk back
4408        // over and no `#` in this file. A setext heading has no marker — its
4409        // content opens the line — so it falls through to the ordinary delete,
4410        // as does anything else sitting at a content start.
4411        // `m.end == caret` is what excludes a setext heading, whose marker is the
4412        // underline *after* the content rather than a prefix before it.
4413        let Some(marker) = marker.filter(|m| m.end == caret) else {
4414            return false;
4415        };
4416        let start = marker.start;
4417        // A closing `#` sequence is hidden too, so it can't be left behind. Only
4418        // when the tail really is one: trailing spaces alone are nothing to strip.
4419        let tail = &self.source[content_end..span.end];
4420        if tail.contains('#') && tail.chars().all(|c| c == '#' || c.is_whitespace()) {
4421            let kept = self.source[caret..content_end].to_string();
4422            self.splice(start, span.end, &kept, EditKind::Other);
4423            // The splice leaves the caret past the text it re-wrote; the caret
4424            // belongs where the content now starts, which is where it already was.
4425            self.caret = start;
4426            self.record_caret();
4427        } else {
4428            self.splice(start, caret, "", EditKind::Other);
4429        }
4430        true
4431    }
4432
4433    pub fn delete_forward(&mut self) {
4434        if let Some((s, e)) = self.selection() {
4435            self.splice(s, e, "", EditKind::Other);
4436        } else if self.caret < self.source.len() {
4437            // The mirror of Backspace's: forward-delete in front of a picture
4438            // would eat the `!` off its markup and leave a link where a photo was.
4439            if self.view != View::Source && self.delete_around_block_media(true) {
4440                return;
4441            }
4442            // And of Backspace's cell wall: Delete at a cell's end would take
4443            // the padding and the `|` after it.
4444            if self.view != View::Source && self.at_cell_wall(BreakEdge::Forward) {
4445                return;
4446            }
4447            // And of Backspace's join: at the end of a block's content, Delete
4448            // joins the next block into this one.
4449            if self.view != View::Source && self.delete_forward_joins_block() {
4450                return;
4451            }
4452            // Delete forward over an in-cell `<br>` takes the whole tag, the mirror
4453            // of Backspace's swallow (see `cell_break_at`) — else a byte-step
4454            // strands a broken `<br` in the cell.
4455            if self.view != View::Source
4456                && let Some((start, end)) = self.cell_break_at(BreakEdge::Forward)
4457            {
4458                self.splice(start, end, "", EditKind::Delete);
4459                return;
4460            }
4461            // The mirror of Backspace's two steps: from in front of a run's
4462            // opening `**` step into it, onto the first letter of its text, and
4463            // at the end of a run's text step out past its closing `**` to the
4464            // character beyond. Either way Delete takes the character it looks
4465            // like it is pointing at, and never a delimiter drawn as nothing.
4466            // The caret then settles back inside the run it was standing in —
4467            // see `settle_inside_close_delims`.
4468            let from = if self.view == View::Source {
4469                self.caret
4470            } else {
4471                let inside = self.step_inside_open_delims(self.caret);
4472                // The mirror of Backspace's empty-span rule: an attributed
4473                // span with no text goes whole, with the character after it.
4474                if let Some(span) = self.run_span_of_content(inside..inside) {
4475                    let to = if self.source[span.end..].starts_with('\n') {
4476                        span.end
4477                    } else {
4478                        next_boundary(&self.source, span.end)
4479                    };
4480                    self.splice(span.start, to, "", EditKind::Delete);
4481                    return;
4482                }
4483                self.skip_trailing_close_delims(inside)
4484            };
4485            let next = next_boundary(&self.source, from);
4486            // And of its emptying rules: the span goes with its last letter,
4487            // and so does the block's div or `{…}` line.
4488            if self.view != View::Source
4489                && let Some(span) = self.run_span_of_content(from..next)
4490            {
4491                self.splice(span.start, span.end, "", EditKind::Delete);
4492                return;
4493            }
4494            if self.view != View::Source
4495                && let Some(block) = self.attributed_block_of_content(from..next)
4496            {
4497                self.splice(block.start, block.end, "", EditKind::Delete);
4498                return;
4499            }
4500            if from < next {
4501                self.splice(from, next, "", EditKind::Delete);
4502            }
4503        }
4504    }
4505
4506    /// Delete from the caret back to the start of the previous word (⌥⌫ /
4507    /// Ctrl+⌫). Deletes the selection instead when one is active.
4508    pub fn delete_word_back(&mut self) {
4509        if let Some((s, e)) = self.selection() {
4510            self.splice(s, e, "", EditKind::Other);
4511        } else {
4512            // A word back from just past a picture is a word *of its markup*, and
4513            // a word back from in front of one runs through the paragraph break
4514            // into the prose above — dissolving the picture either way. See
4515            // `delete_around_block_media`.
4516            if self.view != View::Source && self.delete_around_block_media(false) {
4517                return;
4518            }
4519            let start = self.word_left_from(self.caret).max(self.caret_floor());
4520            if start < self.caret {
4521                let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
4522                self.splice(s, e, "", EditKind::Delete);
4523            }
4524        }
4525    }
4526
4527    /// Delete from the caret forward to the end of the next word (⌥⌦ /
4528    /// Ctrl+Del). Deletes the selection instead when one is active.
4529    pub fn delete_word_forward(&mut self) {
4530        if let Some((s, e)) = self.selection() {
4531            self.splice(s, e, "", EditKind::Other);
4532        } else {
4533            // The mirror: a word forward from in front of a picture is its markup.
4534            if self.view != View::Source && self.delete_around_block_media(true) {
4535                return;
4536            }
4537            let end = self.word_right_from(self.caret);
4538            if end > self.caret {
4539                let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
4540                self.splice(s, e, "", EditKind::Delete);
4541            }
4542        }
4543    }
4544
4545    /// Delete from the caret back to the start of its line (⌘⌫). Deletes the
4546    /// selection instead when one is active, as every other delete here does.
4547    ///
4548    /// The line is the view's own — the one Home and End work on, so in WYSIWYG
4549    /// a soft-wrapped row is a line. It is not Home's *target*, though: Home
4550    /// stops at the first character and this takes the indentation with it, the
4551    /// way Cocoa's `deleteToBeginningOfLine:` does. Stopping at the text would
4552    /// leave an indent behind that nothing can then ask to delete, where a caret
4553    /// left at column 0 is one press of Home away from either.
4554    pub fn delete_to_line_start(&mut self) {
4555        if let Some((s, e)) = self.selection() {
4556            self.splice(s, e, "", EditKind::Other);
4557            return;
4558        }
4559        // Never back across the floor: hidden frontmatter isn't on this line, or
4560        // on any line the WYSIWYG caret can see.
4561        let (start, _) = self.line_span();
4562        let start = start.max(self.caret_floor());
4563        if start < self.caret {
4564            let (s, e) = self.widen_over_emptied_inlines(start, self.caret);
4565            self.splice(s, e, "", EditKind::Delete);
4566        }
4567    }
4568
4569    /// Kill from the caret to the end of its line (^K). Deletes the selection
4570    /// instead when one is active.
4571    ///
4572    /// At the end of the line it does nothing, rather than pulling the line
4573    /// below up into this one. Joining has no meaning to give it in both views
4574    /// at once: a WYSIWYG line ends at a soft wrap as often as at a newline, and
4575    /// there is nothing there to delete, while the newline a *source* line ends
4576    /// with is only half of the blank line that separates two paragraphs —
4577    /// deleting one leaves a soft break, which is not the join it looks like.
4578    /// The views agreeing is worth more than emacs' second press, and Delete is
4579    /// already the key that joins.
4580    pub fn delete_to_line_end(&mut self) {
4581        if let Some((s, e)) = self.selection() {
4582            self.splice(s, e, "", EditKind::Other);
4583            return;
4584        }
4585        let (_, end) = self.line_span();
4586        if end > self.caret {
4587            let (s, e) = self.widen_over_emptied_inlines(self.caret, end);
4588            self.splice(s, e, "", EditKind::Delete);
4589        }
4590    }
4591
4592    /// Grow a WYSIWYG word-delete to swallow any inline node it empties.
4593    ///
4594    /// A glyph-space range covers what the user can see, which for `**bold**` is
4595    /// the word and never the delimiters around it — so deleting the word on its
4596    /// own leaves `a **** c`, markup wrapped around nothing. They asked for the
4597    /// word, and the styling was the word's; the two go together. Only the
4598    /// node's delimiters are taken, and those are hidden here anyway, so nothing
4599    /// visible outside the range is lost.
4600    ///
4601    /// Repeated to a fixed point: emptying `***bold***` empties the emph inside
4602    /// the strong, and only then is the strong empty too.
4603    fn widen_over_emptied_inlines(&mut self, start: usize, end: usize) -> (usize, usize) {
4604        if self.view == View::Source {
4605            return (start, end);
4606        }
4607        let nodes = self.nodes();
4608        let (mut s, mut e) = (start, end);
4609        loop {
4610            let mut grew = false;
4611            for n in nodes.iter().filter(|n| wysiwyg::is_inline(n)) {
4612                let Some(text) = inline_content_span(n, &self.source) else {
4613                    continue;
4614                };
4615                // Some of its text survives, so the node still has a job.
4616                if text.start < s || text.end > e {
4617                    continue;
4618                }
4619                if n.span.start < s || n.span.end > e {
4620                    s = s.min(n.span.start);
4621                    e = e.max(n.span.end);
4622                    grew = true;
4623                }
4624            }
4625            if !grew {
4626                return (s, e);
4627            }
4628        }
4629    }
4630
4631    /// One splice of document text, keeping the **mark-edge rule**: an inline
4632    /// mark's content never begins or ends with whitespace. In Markdown and Djot
4633    /// a delimiter standing against a space is not a delimiter at all — `**bold **`
4634    /// is four literal asterisks around a word, and a rich view drawing the
4635    /// document faithfully has no choice but to show them. That is correct
4636    /// rendering of what the file says, and nobody typing a space after a bold
4637    /// word meant to say it.
4638    ///
4639    /// So the space goes *outside* the run instead — `**bold** ` — which is the
4640    /// same document to a reader and a live one to a parser. The caret follows it
4641    /// out and keeps the marks armed (see [`rearm`](Self::rearm)), so the next
4642    /// character rejoins the run (see [`rejoin_run`](Self::rejoin_run)) and the
4643    /// writer sees one unbroken bold phrase, never a flash of raw syntax.
4644    ///
4645    /// Every ordinary edit — typing, deleting, pasting, an IME step — comes
4646    /// through here, so the rule holds however the whitespace arrives at the
4647    /// edge. The repair is decided *after* the plain edit, by asking whether the
4648    /// mark actually died: a code span's backticks aren't whitespace-sensitive
4649    /// (`` `code ` `` is still code), and nothing is re-spelled when nothing broke.
4650    fn splice(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
4651        let fix = self.mark_edge_fix(start, end, text);
4652        if !self.splice_exact(start, end, text, kind) {
4653            return false;
4654        }
4655        if let Some(fix) = fix {
4656            self.repair_mark_edges(fix);
4657        }
4658        if text.is_empty() && end > start {
4659            self.settle_inside_close_delims();
4660        }
4661        true
4662    }
4663
4664    /// After a delete, take a caret left standing past a run's closing delimiters
4665    /// back inside the run.
4666    ///
4667    /// A delete leaves the caret where the deleted bytes began, and when those
4668    /// bytes were the last thing after a marked phrase — the space the mark-edge
4669    /// rule pushed out of `**bold** `, say — that spot is the far side of the
4670    /// closing `**`. The rich view has nothing to draw there: the delimiters are
4671    /// hidden, so the caret shows at the end of the word either way, and the two
4672    /// offsets are one place on screen with two different meanings. Typing at the
4673    /// outer one lands past the run, so the writer who backspaced a space out of
4674    /// their bold phrase watches the next character come out plain, and the
4675    /// toolbar button go dark, with the caret never appearing to move.
4676    ///
4677    /// The end of the run's text is the caret's home there — a delete that took
4678    /// away everything after a phrase leaves the caret at the end of that phrase,
4679    /// which is inside it — so it settles onto that
4680    /// ([`step_inside_close_delims`](Self::step_inside_close_delims) does the
4681    /// walk, through every mark closing at the point): the word stays bold, the
4682    /// button stays lit, and the next character carries on the phrase.
4683    ///
4684    /// Rich view only, and only where a mark really closes at the caret — mid-run
4685    /// or in plain prose no span ends there and the caret stays put. The opening
4686    /// edge is left alone on purpose: a caret in front of a run inherits from the
4687    /// text on its left, which is the plain text outside.
4688    fn settle_inside_close_delims(&mut self) {
4689        if self.view != View::Wysiwyg {
4690            return;
4691        }
4692        let at = self.step_inside_close_delims(self.caret);
4693        if at != self.caret {
4694            self.caret = at;
4695            self.clear_pending();
4696            self.record_caret();
4697        }
4698    }
4699
4700    /// The splice exactly as asked, with no mark-edge repair — for the callers
4701    /// that are *writing* the delimiters themselves ([`insert_with_marks`](Self::insert_with_marks)
4702    /// and [`rejoin_run`](Self::rejoin_run)) and place their own offsets around
4703    /// the bytes they inserted.
4704    ///
4705    /// One `edit_range` through twig, then re-anchor the caret from the returned
4706    /// `Change` and refresh the cached source. A reparse-breaking edit (rare for
4707    /// Markdown/Djot) leaves the document untouched and reports.
4708    ///
4709    /// Returns whether the edit landed — for a caller that has offsets of its
4710    /// own to place afterwards, which a rolled-back splice would leave pointing
4711    /// into text that never came to exist.
4712    fn splice_exact(&mut self, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
4713        // The read-only gate, for every edit at once — see the field.
4714        if self.read_only {
4715            return false;
4716        }
4717        // twig records an undo step for every edit; when this one continues a
4718        // run of the same kind (typing, deleting), tell twig to fold it into the
4719        // step before it so the whole run undoes at once.
4720        let coalesce = kind != EditKind::Other && self.last_edit_kind == Some(kind);
4721        // Hand twig the pre-edit caret before the splice, so the undo step it
4722        // retires carries where the caret was standing.
4723        self.record_caret();
4724        match self.editor.edit_range(start, end, text) {
4725            Ok(change) => {
4726                self.last_edit_kind = Some(kind);
4727                // Counted first, so the fold has the step it folds.
4728                self.refresh();
4729                if coalesce {
4730                    self.coalesce_last_undo();
4731                }
4732                self.caret = change.new.end;
4733                self.anchor = None;
4734                self.goal_col = None;
4735                self.clear_pending();
4736                self.dirty = self.source != self.clean_source;
4737                self.status = None;
4738                // And the post-edit caret, so a later redo restores it.
4739                self.record_caret();
4740                true
4741            }
4742            // The edit was rolled back, so twig's history did not move and
4743            // neither may ours: pushing here would leave a step with no edit
4744            // under it and shift every later undo onto the wrong caret.
4745            Err(e) => {
4746                self.status = Some(format!("edit: {e}"));
4747                false
4748            }
4749        }
4750    }
4751
4752    /// The re-spelling that would keep the mark-edge rule for the edit
4753    /// `[start, end)` → `text`, or `None` when the edit leaves no whitespace
4754    /// against a delimiter and the plain splice is already right. Computed
4755    /// *before* the edit, while the run's spans and delimiters can still be read
4756    /// off the document; applied afterwards, and only if the mark really died —
4757    /// see [`repair_mark_edges`](Self::repair_mark_edges).
4758    ///
4759    /// Rich view only. Source view is for typing raw markup, where a space put
4760    /// against a `**` is exactly the character it looks like.
4761    fn mark_edge_fix(&mut self, start: usize, end: usize, text: &str) -> Option<MarkEdgeFix> {
4762        if self.view != View::Wysiwyg || start > end || end > self.source.len() {
4763            return None;
4764        }
4765        // Every inline mark standing over the edit, outermost first, with the
4766        // content span that says where its delimiters are.
4767        let chain: Vec<(InlineKind, std::ops::Range<usize>, std::ops::Range<usize>)> = self
4768            .editor
4769            .ancestors_at(start)
4770            .unwrap_or_default()
4771            .into_iter()
4772            .filter_map(|m| {
4773                let kind = inline_kind(&m.kind)?;
4774                let content = m.content_span.clone()?;
4775                Some((kind, m.span.clone(), content))
4776            })
4777            .collect();
4778        // The innermost run whose *content* holds the whole edit: the one whose
4779        // text is being changed, rather than one the edit merely sits under.
4780        let (kind, span, content) = chain
4781            .iter()
4782            .rev()
4783            .find(|(_, _, c)| c.start <= start && end <= c.end)?
4784            .clone();
4785        // What that content becomes. Whitespace at either end of it is what
4786        // would put out the mark.
4787        let body = format!(
4788            "{}{text}{}",
4789            &self.source[content.start..start],
4790            &self.source[end..content.end]
4791        );
4792        let (lead, trail) = if body.trim().is_empty() {
4793            // Nothing but whitespace left: there is no content to mark at all,
4794            // and the delimiters go with it rather than closing on a space.
4795            (body.len(), 0)
4796        } else {
4797            (
4798                body.len() - body.trim_start().len(),
4799                body.len() - body.trim_end().len(),
4800            )
4801        };
4802        // Nothing against a delimiter, and something still between them: the
4803        // plain edit stands. An emptied run is broken just as surely (`**b**`
4804        // with the `b` deleted is the literal `****`) and is re-spelt as the
4805        // nothing it now says.
4806        if lead == 0 && trail == 0 && !body.is_empty() {
4807            return None;
4808        }
4809        // Marks that open or close exactly where this one does — `***both***` is
4810        // two runs sharing an edge — spell their delimiters as one run of bytes,
4811        // so the whitespace has to clear all of them together.
4812        let (mut open_at, mut close_at) = (span.start, span.end);
4813        for _ in 0..chain.len() {
4814            match chain.iter().find(|(_, _, c)| c.start == open_at) {
4815                Some((_, s, _)) => open_at = s.start,
4816                None => break,
4817            }
4818        }
4819        for _ in 0..chain.len() {
4820            match chain.iter().find(|(_, _, c)| c.end == close_at) {
4821                Some((_, s, _)) => close_at = s.end,
4822                None => break,
4823            }
4824        }
4825        let open = &self.source[open_at..content.start];
4826        let close = &self.source[content.end..close_at];
4827        let core = &body[lead..body.len() - trail];
4828        let respelt = if core.is_empty() {
4829            body.clone()
4830        } else {
4831            format!(
4832                "{}{open}{core}{close}{}",
4833                &body[..lead],
4834                &body[body.len() - trail..]
4835            )
4836        };
4837        // The caret sits just past the inserted text within the new content —
4838        // which, when that lands in the whitespace, is now outside the delimiters.
4839        let pos = (start - content.start) + text.len();
4840        let caret = if core.is_empty() || pos <= lead {
4841            open_at + pos
4842        } else if pos >= lead + core.len() {
4843            open_at + lead + open.len() + core.len() + close.len() + (pos - lead - core.len())
4844        } else {
4845            open_at + lead + open.len() + (pos - lead)
4846        };
4847        Some(MarkEdgeFix {
4848            kind,
4849            probe: content.start,
4850            start: open_at,
4851            end: close_at + text.len() - (end - start),
4852            text: respelt,
4853            caret,
4854            // The marks in force here, resolved against any armed sticky delta —
4855            // what the writer is typing in, and so what has to still be true on
4856            // the far side of the delimiter the caret just stepped over.
4857            want: chain
4858                .iter()
4859                .filter(|(_, s, _)| start < s.end)
4860                .map(|(k, _, _)| *k)
4861                .collect::<InlineMarks>()
4862                .xor(self.pending_here()),
4863        })
4864    }
4865
4866    /// Apply a [`MarkEdgeFix`] — but only if the edit it was computed for really
4867    /// did break the mark. Whether whitespace at a delimiter is fatal is the
4868    /// format's business, not leaf's: `**bold **` is no longer strong, while
4869    /// `` `code ` `` is still perfectly good verbatim, and Djot's braced spellings
4870    /// don't care either. Asking the parser afterwards settles it for every kind
4871    /// and format at once, and costs a re-spelling only where one is due.
4872    ///
4873    /// The repair rides along with the edit that caused it — one undo step puts
4874    /// back what the writer typed, not a delimiter shuffle they never saw.
4875    fn repair_mark_edges(&mut self, fix: MarkEdgeFix) {
4876        if fix.end > self.source.len() {
4877            return;
4878        }
4879        if self.marks_at(fix.probe).iter().any(|(k, _)| *k == fix.kind) {
4880            return; // still a mark: these delimiters don't mind the whitespace
4881        }
4882        let resumed = self.last_edit_kind;
4883        if !self.splice_exact(fix.start, fix.end, &fix.text, EditKind::Other) {
4884            return;
4885        }
4886        self.coalesce_last_undo();
4887        // The keystroke owns the undo step, so the run of typing it belongs to
4888        // keeps coalescing over the repair rather than breaking in two here.
4889        self.last_edit_kind = resumed;
4890        self.caret = fix.caret.min(self.source.len());
4891        self.anchor = None;
4892        self.goal_col = None;
4893        self.rearm(fix.want);
4894        self.clamp_caret();
4895        self.record_caret();
4896    }
4897
4898    /// Arm whatever sticky delta reproduces `want` at the caret — the marks the
4899    /// writer is typing in, carried across an edit that moved the caret out of
4900    /// the run holding them. Arms nothing when the caret already stands in
4901    /// exactly those marks, but still remembers the spot, so a further ⌘b starts
4902    /// a clean delta here (see [`toggle`](Self::toggle)).
4903    fn rearm(&mut self, want: InlineMarks) {
4904        let here: InlineMarks = self
4905            .marks_at(self.caret)
4906            .into_iter()
4907            .map(|(k, _)| k)
4908            .collect();
4909        self.pending_marks = want.xor(here);
4910        self.pending_at = Some(self.caret);
4911    }
4912
4913    /// Insert `text` at `at` as a *literal* run via twig's `insert_literal`,
4914    /// which backslash-escapes any character that would otherwise open markup in
4915    /// this format and position (`*` → `\*`, a line-start `#` → `\#`). The mirror
4916    /// of [`splice`](Self::splice) for the Hidden reveal mode's typing path, with
4917    /// the same caret re-anchor, coalescing, and rollback contract. `at` must be
4918    /// a collapsed point — a selection is deleted by the caller first, since
4919    /// `insert_literal` inserts rather than replaces.
4920    fn insert_literal_at(
4921        &mut self,
4922        at: usize,
4923        text: &str,
4924        kind: EditKind,
4925        force_coalesce: bool,
4926    ) -> bool {
4927        // The read-only gate: this door goes to twig directly, not through
4928        // `splice_exact`, so it guards itself — see the field.
4929        if self.read_only {
4930            return false;
4931        }
4932        // `force_coalesce` folds this into the immediately preceding edit (the
4933        // selection-delete of an overwrite) so the pair is one undo step; else it
4934        // coalesces only when it continues a run of the same-kind typing.
4935        let coalesce =
4936            force_coalesce || (kind != EditKind::Other && self.last_edit_kind == Some(kind));
4937        // The mark-edge rule holds for typed text however it is spelled — see
4938        // `splice`. Only an insert twig passed through unchanged can use it,
4939        // since a fix is measured in the bytes that actually land, and an escape
4940        // adds bytes this couldn't have counted.
4941        let fix = self.mark_edge_fix(at, at, text);
4942        #[cfg(test)]
4943        if std::mem::take(&mut self.refuse_next_literal) {
4944            self.status = Some("edit: refused".into());
4945            return false;
4946        }
4947        self.record_caret();
4948        match self.editor.insert_literal(at, text) {
4949            Ok(change) => {
4950                self.last_edit_kind = Some(kind);
4951                // Counted first, so the fold has the step it folds.
4952                self.refresh();
4953                if coalesce {
4954                    self.coalesce_last_undo();
4955                }
4956                self.caret = change.new.end;
4957                self.anchor = None;
4958                self.goal_col = None;
4959                self.clear_pending();
4960                self.dirty = self.source != self.clean_source;
4961                self.status = None;
4962                self.record_caret();
4963                if let Some(fix) = fix.filter(|_| change.new.end - change.new.start == text.len()) {
4964                    self.repair_mark_edges(fix);
4965                }
4966                true
4967            }
4968            Err(e) => {
4969                self.status = Some(format!("edit: {e}"));
4970                false
4971            }
4972        }
4973    }
4974
4975    /// After a structural list edit (a new item, a nest/unnest), renumber the
4976    /// ordered list the caret sits in so its source markers run `1, 2, 3, …`
4977    /// again — a raw splice leaves them stale (`1. 2. 2. 3.`). twig does the
4978    /// renumber as its own edit; fold it into the edit that triggered it so the
4979    /// two undo as one, and only when it actually changed the source (a no-op or
4980    /// a caret outside any ordered list must not coalesce the real edit into the
4981    /// step before it).
4982    fn renumber_here(&mut self) {
4983        self.renumber_at(self.caret);
4984    }
4985
4986    /// [`renumber_here`](Self::renumber_here) aimed somewhere other than the
4987    /// caret — for an edit that leaves the caret one past the item it just wrote,
4988    /// where twig resolves no list to renumber.
4989    fn renumber_at(&mut self, off: usize) {
4990        // The read-only gate — this door reaches twig without the splice.
4991        if self.read_only {
4992            return;
4993        }
4994        let before = self.source.clone();
4995        if self.editor.renumber_ordered_lists(off).is_err() {
4996            return; // not inside an ordered list — nothing to renumber
4997        }
4998        self.refresh();
4999        if self.source != before {
5000            self.coalesce_last_undo();
5001            self.dirty = self.source != self.clean_source;
5002            self.clamp_caret();
5003            self.record_caret();
5004        }
5005    }
5006
5007    /// Repair the one trap a list edit can spring on itself. An *empty* `-`
5008    /// sub-item written directly beneath a text line reparses that text as a
5009    /// setext heading — `- hello\n  - ` is `<h2>hello</h2>`, because a lone `-`
5010    /// is also a setext-H2 underline (twig is right; pandoc agrees). `*` and `+`
5011    /// bullets can't underline anything, so swap the dash for a `*`: the item
5012    /// stays an empty nested bullet, the parent stays prose, and the source
5013    /// round-trips instead of hiding a heading the user never asked for. Folded
5014    /// into the triggering edit's undo step, the way renumbering is.
5015    ///
5016    /// Gated on the collapse having actually happened (the swapped dash was
5017    /// swallowed into a `heading`), so a real setext heading the author wrote —
5018    /// or a `- x` with content, which can't underline anything — is never
5019    /// touched. This has to live in the *edit*, not the renderer: leaving the
5020    /// hazardous bytes on disk and only painting over them would ship a file
5021    /// every other CommonMark tool reads as a heading.
5022    ///
5023    /// This one keeps its own byte scan, and has to: the hazard is precisely
5024    /// that the dash stopped being a list marker, so [`list_marker_on_line`] —
5025    /// which asks twig which lines open an item — reports nothing here. There is
5026    /// no node to ask about. It is also the last Markdown spelling leaf writes on
5027    /// purpose rather than for want of an answer; once twig spells continuations
5028    /// itself, avoiding the trap becomes twig's, and this goes.
5029    ///
5030    /// [`list_marker_on_line`]: Self::list_marker_on_line
5031    fn avoid_setext_collapse(&mut self) {
5032        let caret = self.caret.min(self.source.len());
5033        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
5034        let bytes = self.source.as_bytes();
5035        let mut dash = line_start;
5036        while matches!(bytes.get(dash), Some(b' ' | b'\t')) {
5037            dash += 1;
5038        }
5039        // A dash bullet is the only marker that doubles as a setext underline.
5040        if bytes.get(dash) != Some(&b'-') {
5041            return;
5042        }
5043        // Only an *empty* item is a bare underline; `- x` carries content and
5044        // can't fold the line above into a heading.
5045        let line_end = self.source[dash..]
5046            .find('\n')
5047            .map_or(self.source.len(), |i| dash + i);
5048        if !self.source[dash + 1..line_end].trim().is_empty() {
5049            return;
5050        }
5051        // The tell: that dash was swallowed into a `heading`. A properly nested
5052        // empty item sits under a `list_item`, with no heading in reach. Probe
5053        // the dash byte itself (well inside the heading), not the caret, whose
5054        // end-of-line offset can fall on the half-open span boundary.
5055        let collapsed = self
5056            .editor
5057            .ancestors_at(dash)
5058            .map(|c| c.into_iter().any(|m| m.kind == Kind::Heading))
5059            .unwrap_or(false);
5060        if !collapsed {
5061            return;
5062        }
5063        let caret = self.caret;
5064        if self.splice(dash, dash + 1, "*", EditKind::Other) {
5065            // Same width, so the caret keeps its column; fold into the edit that
5066            // triggered this so Tab stays one undo step.
5067            self.coalesce_last_undo();
5068            self.caret = caret.min(self.source.len());
5069            self.clamp_caret();
5070            self.record_caret();
5071        }
5072    }
5073
5074    fn snapshot(&self) -> CaretState {
5075        CaretState {
5076            caret: self.caret,
5077            anchor: self.anchor,
5078        }
5079    }
5080
5081    /// Hand twig the current caret and selection as the blob for the live
5082    /// document state. Called before an edit — so the step twig retires records
5083    /// where the caret was, and undo can restore it — and again once the op has
5084    /// placed the caret, so redo restores where the edit left it.
5085    ///
5086    /// This is the whole of leaf's undo-caret bookkeeping now. twig carries the
5087    /// caret through its own history, so coalescing falls out for free (folding
5088    /// two twig steps into one drops the intermediate blob, keeping the run's
5089    /// first) and the parallel stacks that had to march in lockstep — and could
5090    /// silently drift out of it — are gone.
5091    fn record_caret(&mut self) {
5092        let _ = self.editor.set_caret_blob(&self.snapshot().to_blob());
5093    }
5094
5095    /// Toggle an inline mark over the selection (Bold / Italic / Code / …). Keeps
5096    /// the toggled region selected so a second press cleanly reverses it.
5097    pub fn toggle(&mut self, kind: InlineKind) {
5098        // The read-only gate — this door reaches twig without the splice.
5099        if self.read_only {
5100            return;
5101        }
5102        // Ahead of the no-selection branch below: arming a mark for text not yet
5103        // typed is a promise `insert` cannot keep in a format with no delimiters
5104        // to spell it with. Per *kind*, not per format — Markdown spells five
5105        // of the eight marks (highlight among them, under the `highlight`
5106        // extension leaf parses with), djot all eight, HTML seven.
5107        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleInline(kind)) {
5108            return;
5109        }
5110        let Some((s, e)) = self.selection() else {
5111            // No selection: arm the mark for the next text typed here, the way a
5112            // word processor does. `⌘b`, type, `⌘b` again toggles bold on and off
5113            // in the flow of typing without ever selecting anything — the delta
5114            // is realised onto the freshly typed text by `insert`. A fresh caret
5115            // position starts the delta over from the marks actually in force.
5116            if self.pending_at != Some(self.caret) {
5117                self.pending_marks = InlineMarks::empty();
5118                self.pending_at = Some(self.caret);
5119            }
5120            self.pending_marks.flip(kind);
5121            self.status = None;
5122            return;
5123        };
5124        // Whitespace at the edge of a selection is not part of what was chosen —
5125        // a double-click takes the space after the word with it — and a mark
5126        // cannot close against one anyway: `**word **` is four literal asterisks
5127        // (the mark-edge rule, see `splice`). Mark the words, leave the spaces.
5128        let picked = &self.source[s..e];
5129        let (s, e) = (
5130            s + (picked.len() - picked.trim_start().len()),
5131            e - (picked.len() - picked.trim_end().len()),
5132        );
5133        if s >= e {
5134            self.status = Some(format!("{kind:?}: nothing selected to mark"));
5135            return;
5136        }
5137        // Styling a selection is a one-shot act, not a sticky mode.
5138        self.clear_pending();
5139        self.record_caret();
5140        match self.editor.toggle_inline(s, e, kind) {
5141            Ok(change) => {
5142                self.last_edit_kind = None; // structural edit is its own undo step
5143                self.refresh();
5144                self.anchor = Some(change.new.start);
5145                self.caret = change.new.end;
5146                self.dirty = self.source != self.clean_source;
5147                self.status = None;
5148                self.record_caret();
5149            }
5150            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
5151        }
5152    }
5153
5154    /// Whether the caret stands in a highlight — what a frontend asks to enable
5155    /// or disable its highlight-colour controls, the way
5156    /// [`caret_in_table`](Self::caret_in_table) gates the grid ones.
5157    ///
5158    /// A fact about the *caret*, and the other half of
5159    /// [`Capabilities::mark_color`], which is the fact about the format. A
5160    /// frontend needs both: djot spells a highlight and no colour for it, so a
5161    /// caret standing in `{=word=}` answers `true` here and still has no palette
5162    /// to offer.
5163    ///
5164    /// The rule is [`active_inline_marks`](Self::active_inline_marks)' rule, so
5165    /// the palette appears exactly where the Highlight button is lit — with one
5166    /// deliberate exception: a mark *armed* at a bare caret and not yet typed
5167    /// into lights the button and answers `false` here, because there is no node
5168    /// to colour until the text exists.
5169    pub fn caret_in_mark(&mut self) -> bool {
5170        self.mark_offset().is_some()
5171    }
5172
5173    /// The offset [`set_mark_color`](Self::set_mark_color) speaks for — the one
5174    /// standing in the highlight the gesture means — or `None` when neither end
5175    /// of what is selected is in one.
5176    ///
5177    /// The caret first, and the selection's *start* after it, because of what
5178    /// [`toggle`](Self::toggle) leaves behind: a fresh `==word==` is selected
5179    /// whole, with the caret at its far edge, one past the closing `==` and so
5180    /// (by `marks_at`' half-open rule) not in the mark at all. Highlight a word
5181    /// and colour it — the two presses a coloured highlight is made of — would
5182    /// otherwise refuse on the second, having just written the highlight the
5183    /// author is pointing at.
5184    fn mark_offset(&mut self) -> Option<usize> {
5185        let in_mark = |d: &mut Self, off: usize| {
5186            d.marks_at(off)
5187                .into_iter()
5188                .any(|(k, _)| k == InlineKind::Mark)
5189                .then_some(off)
5190        };
5191        let caret = self.caret.min(self.source.len());
5192        in_mark(self, caret).or_else(|| {
5193            let start = self.selection()?.0;
5194            in_mark(self, start)
5195        })
5196    }
5197
5198    /// The colour of the highlight at the caret — `None` both when the caret is
5199    /// in no highlight and when the highlight it is in names no colour, which
5200    /// are the same answer to "which swatch is lit".
5201    ///
5202    /// The innermost mark, by span, for the same reason
5203    /// [`current_heading_level`](Self::current_heading_level) walks the tree:
5204    /// what the caret is *in* is the deepest node containing it. A `data-color`
5205    /// naming a colour this build has no variant for reads as `None` — the
5206    /// renderer already draws that as a plain highlight rather than guessing,
5207    /// and the toolbar agrees with the renderer.
5208    pub fn mark_color_at_caret(&mut self) -> Option<MarkColor> {
5209        let at = self.mark_offset()?;
5210        self.mark_color_at(at)
5211    }
5212
5213    /// [`mark_color_at_caret`](Self::mark_color_at_caret) at a given offset —
5214    /// the innermost `mark` covering it, and the colour it names.
5215    fn mark_color_at(&mut self, off: usize) -> Option<MarkColor> {
5216        self.nodes()
5217            .into_iter()
5218            .filter(|n| n.kind == Kind::Mark)
5219            .filter(|n| n.span.start <= off && off < n.span.end)
5220            .min_by_key(|n| n.span.end - n.span.start)
5221            .and_then(|n| MarkColor::from_attrs(&n.attrs))
5222    }
5223
5224    /// Colour the highlight at the caret, or clear its colour with `None` — the
5225    /// palette behind a toolbar's Highlight button.
5226    ///
5227    /// Markdown only, and the one gesture whose availability is a fact about the
5228    /// *parse extensions* rather than about the format alone: the colour is
5229    /// spelled `==🔴 text==`, an emoji twig reads back out of the content and
5230    /// records as the mark's `data-color`, and only an editor parsing with
5231    /// `highlight_colors` (which [`parse_extensions`] turns on for every leaf
5232    /// document) reads it back that way. Djot spells the highlight and no colour
5233    /// for it, so this refuses there — see [`Capabilities::mark_color`].
5234    ///
5235    /// **A colour is a property of a highlight that already exists.** There is
5236    /// no "highlight this in red" here, because that is two splices and would be
5237    /// two undo steps under one press; a frontend that wants it calls
5238    /// [`toggle`](Self::toggle) with [`InlineKind::Mark`] first, which is the
5239    /// order the two buttons already sit in. With no highlight at the caret this
5240    /// says so in the status line and writes nothing.
5241    ///
5242    /// The caret keeps its place in the *text*: the splice is entirely in the
5243    /// prefix between the opening `==` and the first word, so an offset past it
5244    /// rides the emoji's width, and one standing on the prefix itself lands
5245    /// where the prefix now ends.
5246    pub fn set_mark_color(&mut self, color: Option<MarkColor>) {
5247        // The read-only gate — this door reaches twig without the splice.
5248        if self.read_only {
5249            return;
5250        }
5251        if self.refuse_unsupported("highlight colour", Gesture::SetMarkColor) {
5252            return;
5253        }
5254        let Some(at) = self.mark_offset() else {
5255            self.status = Some("highlight colour: no highlight at the caret".into());
5256            return;
5257        };
5258        // Clearing a colour a highlight hasn't got is twig's one *successful*
5259        // no-op, and the `Change` it hands back then describes whatever edit came
5260        // before it — a stale span that would drag the caret somewhere it never
5261        // was. Answer it here, where the question is cheap, rather than trusting
5262        // a change that isn't one.
5263        if color.is_none() && self.mark_color_at(at).is_none() {
5264            self.status = None;
5265            return;
5266        }
5267        self.record_caret();
5268        match self.editor.set_mark_color(at, color.map(twig_mark_color)) {
5269            Ok(change) => {
5270                // Re-anchored from the offsets as they were, *before* `refresh`
5271                // sees the new bytes: the caret it clamps is one standing inside
5272                // a prefix that didn't exist a moment ago, and walking it back to
5273                // a char boundary of the emoji loses the place this is restoring.
5274                let caret = reanchor(self.caret, &change);
5275                let anchor = self.anchor.map(|a| reanchor(a, &change));
5276                self.last_edit_kind = None; // structural edit is its own undo step
5277                self.refresh();
5278                self.caret = caret;
5279                self.anchor = anchor;
5280                self.dirty = self.source != self.clean_source;
5281                self.status = None;
5282                self.clamp_caret();
5283                self.record_caret();
5284            }
5285            Err(e) => self.status = Some(format!("highlight colour: {e}")),
5286        }
5287    }
5288
5289    /// One press of a colour swatch: colour the highlight at the caret, or —
5290    /// over a selection that isn't highlighted yet — highlight it and colour it,
5291    /// as **one** undo step.
5292    ///
5293    /// [`set_mark_color`](Self::set_mark_color) is the exact gesture and stays
5294    /// one splice; this is the compound every toolbar actually presses, and it
5295    /// lives here rather than in each frontend because the rule it encodes —
5296    /// what a swatch means when there is no highlight under it yet — is one
5297    /// answer, not one per frontend. The two splices are folded into a single
5298    /// history step, so the press that made a red highlight is taken back by a
5299    /// single undo rather than leaving an uncoloured one behind.
5300    ///
5301    /// `None` clears the colour, and over an unhighlighted selection means
5302    /// simply "highlight this" — the same thing the Highlight button does.
5303    /// A bare caret in no highlight is left alone with a status line, because
5304    /// [`toggle`](Self::toggle) there arms a mark for text not yet typed and a
5305    /// colour cannot be armed with it.
5306    pub fn highlight(&mut self, color: Option<MarkColor>) {
5307        if self.caret_in_mark() || self.selection().is_none() {
5308            self.set_mark_color(color);
5309            return;
5310        }
5311        self.toggle(InlineKind::Mark);
5312        // The format may not spell a highlight at all (`toggle` said so), and
5313        // there is nothing to colour if it doesn't.
5314        if self.status.is_some() {
5315            return;
5316        }
5317        let before = self.revision;
5318        self.set_mark_color(color);
5319        // Only fold when the colour really spliced. `highlight(None)` over a
5320        // fresh highlight is a no-op by design, and coalescing there would eat
5321        // the *previous* edit into the toggle instead.
5322        if self.revision != before {
5323            self.coalesce_last_undo();
5324        }
5325    }
5326
5327    // ── the presentation vocabulary ─────────────────────────────────────────
5328    //
5329    // Six gestures and five queries over twig's two attribute ops. Each gesture
5330    // edits **one key and keeps the rest**: it reads the node's attributes,
5331    // removes its own key (and, for alignment, its own tokens out of `class`),
5332    // adds the new value or nothing, and passes the list back whole — twig's
5333    // contract is replace-not-merge, so the read is the caller's job. A
5334    // paragraph that came in as `class="lead center" id="intro"
5335    // data-line-height="1.5"` and is right-aligned goes out as `class="lead
5336    // right" id="intro" data-line-height="1.5"`. Nothing leaf did not write is
5337    // touched, which is what lets a document from elsewhere pass through the
5338    // editor unharmed.
5339    //
5340    // Clearing is the same gesture with `None`: the key goes, and an empty list
5341    // at the end unwraps the span or the Markdown div, which twig does.
5342
5343    /// Set — or with `None` clear — the alignment of the block the caret is in.
5344    ///
5345    /// A block property, so the gesture is `set_block_attrs` on the caret's
5346    /// block **whatever is selected**: a line is a block's, and "centre this"
5347    /// with three words selected means the paragraph, not the words. The
5348    /// vocabulary is [`Align`], written as `class` tokens; other tokens on the
5349    /// same `class` are kept.
5350    ///
5351    /// In Markdown the attributes live on a `<div>` around the block — twig has
5352    /// no paragraph attribute syntax to write — and this reads them back off
5353    /// that div when the block is its sole child, so a second press rewrites
5354    /// the div rather than nesting a second one.
5355    pub fn set_alignment(&mut self, align: Option<Align>) {
5356        let attrs = self.block_attrs_at_caret();
5357        if align.is_none()
5358            && self.refuse_clear_from_div("alignment", &attrs, |a| Align::from_attrs(a).is_some())
5359        {
5360            return;
5361        }
5362        let attrs = with_class_token(
5363            &attrs,
5364            |t| Align::from_token(t).is_some(),
5365            align.map(Align::name),
5366        );
5367        self.write_block_attrs("alignment", attrs);
5368    }
5369
5370    /// Set — or with `None` clear — the line spacing of the block the caret is
5371    /// in. [`set_alignment`](Self::set_alignment)'s peer in every respect but
5372    /// the key: [`LineHeight`] under `data-line-height`, one of the menu's
5373    /// three names or an exact ratio, written in its canonical spelling.
5374    pub fn set_line_spacing(&mut self, spacing: Option<LineHeight>) {
5375        let attrs = self.block_attrs_at_caret();
5376        if spacing.is_none()
5377            && self.refuse_clear_from_div("line spacing", &attrs, |a| {
5378                LineHeight::from_attrs(a).is_some()
5379            })
5380        {
5381            return;
5382        }
5383        let spelling = spacing.map(LineHeight::name);
5384        let attrs = with_attr(&attrs, "data-line-height", spelling.as_deref());
5385        self.write_block_attrs("line spacing", attrs);
5386    }
5387
5388    /// Set — or with `None` clear — the size of the selected run, or of the
5389    /// caret's whole block when nothing is selected.
5390    ///
5391    /// Size, face and colour are the *run's*, and the block's when no run is
5392    /// chosen. With a selection the gesture is `wrap_range_attrs`, which wraps
5393    /// the range in an attributed span or re-styles the span it already lies in
5394    /// (never nesting a second, and unwrapping it when the last key goes). With
5395    /// no selection it is `set_block_attrs` on the caret's block, so that "make
5396    /// this paragraph larger" is a click with the caret in it rather than a
5397    /// select-all first.
5398    ///
5399    /// The walker reads the key at both levels with the nearer winning, so a
5400    /// span's `data-size` inside a block carrying its own applies to the span.
5401    ///
5402    /// The vocabulary is [`FontSize`]: one of CSS's seven keywords, which is
5403    /// what a menu offers first because a step reads as a step up under every
5404    /// theme, or the point size an author asked for, which is exact and is all
5405    /// it is. Either is written in its canonical spelling, so a size set twice
5406    /// from the same field writes the same bytes both times.
5407    pub fn set_font_size(&mut self, size: Option<FontSize>) {
5408        let spelling = size.map(FontSize::name);
5409        self.set_run_attr("size", "data-size", spelling.as_deref());
5410    }
5411
5412    /// Set — or with `None` clear — the face of the selected run, or of the
5413    /// caret's whole block. [`set_font_size`](Self::set_font_size)'s peer, with
5414    /// [`FontFace`] under `data-font` — one of the four generics, or the family
5415    /// the author named, which the frontends resolve through the platform's
5416    /// font registry and fall back to the body face without.
5417    pub fn set_font_family(&mut self, font: Option<FontFace>) {
5418        let spelling = font.as_ref().map(FontFace::name);
5419        self.set_run_attr("font", "data-font", spelling.as_deref());
5420    }
5421
5422    /// Set — or with `None` clear — the *text* colour of the selected run, or of
5423    /// the caret's whole block. [`set_font_size`](Self::set_font_size)'s peer,
5424    /// with [`TextColor`] under `data-color` — one of the seven names, whose
5425    /// two inks the theme owns, or the triple the author picked, which is
5426    /// painted as written in both appearances.
5427    ///
5428    /// The same key and the same seven names [`set_mark_color`](Self::set_mark_color)
5429    /// writes, and a different thing: that one colours a highlight's
5430    /// *background* and rides the `mark` node twig owns the spelling of, this
5431    /// one colours the letters and rides an attributed span. The two never
5432    /// collide, because a `mark` is a `mark` and a span is a span — and they
5433    /// share a vocabulary on purpose, so that a frontend with a red for a
5434    /// highlight has a red for text and both are *that* red.
5435    pub fn set_text_color(&mut self, color: Option<TextColor>) {
5436        let spelling = color.map(TextColor::name);
5437        self.set_run_attr("text colour", "data-color", spelling.as_deref());
5438    }
5439
5440    /// Insert a page break at the caret — `::page-break`, a leaf directive with
5441    /// no label and no attributes, which twig spells in every format that names
5442    /// a leaf container (Markdown under the `directives` extension
5443    /// [`parse_extensions`] turns on, and djot, where it is an empty `:::
5444    /// page-break` fence).
5445    ///
5446    /// Placed exactly as [`insert_thematic_break`](Self::insert_thematic_break)
5447    /// places a rule, and for the same reason: a directive is a block, so twig
5448    /// alone has nowhere to put one mid-paragraph and lands it after the
5449    /// caret's whole block. A bare paragraph is therefore parted at the caret
5450    /// first and the break aimed at the *first* half. See that method for the
5451    /// whole of the rule, including why a code block, a list item, a table and
5452    /// a setext heading are left unsplit.
5453    ///
5454    /// The frontends that paginate read the row's
5455    /// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) and open a page there;
5456    /// the ones that do not draw the `⧉ page-break` placeholder every leaf
5457    /// directive gets.
5458    pub fn insert_page_break(&mut self) {
5459        if self.read_only || self.refuse_unsupported("page break", Gesture::InsertDirective) {
5460            return;
5461        }
5462        self.caret = self.skip_trailing_close_delims(self.caret);
5463        // A selection is replaced by the break, as a rule replaces one.
5464        if let Some((s, e)) = self.selection() {
5465            self.splice(s, e, "", EditKind::Other);
5466        }
5467        self.anchor = None;
5468        self.record_caret();
5469        let at = self.caret;
5470        // A failure here is not fatal: the break still lands after the
5471        // block, which is what this call was trying to improve on.
5472        let parted = self.part_for_block(at);
5473        match self.editor.insert_directive(at, PAGE_BREAK, None, &[]) {
5474            Ok(change) => {
5475                self.last_edit_kind = None;
5476                self.refresh();
5477                if parted {
5478                    self.coalesce_last_undo();
5479                }
5480                self.anchor = None;
5481                self.caret = change.new.end;
5482                self.dirty = self.source != self.clean_source;
5483                self.status = None;
5484                self.clamp_caret();
5485                self.record_caret();
5486                self.caret_under_written_block(change.new, parted);
5487            }
5488            Err(e) => self.status = Some(format!("page break: {e}")),
5489        }
5490    }
5491
5492    /// The alignment in force at the caret, or `None` for the theme's default —
5493    /// which swatch of an alignment control is lit.
5494    ///
5495    /// Read off the nearest node that names one: the block the caret is in, and
5496    /// the `div`s around it after that. [`mark_color_at_caret`](Self::mark_color_at_caret)'s
5497    /// shape, one property along.
5498    pub fn alignment_at_caret(&mut self) -> Option<Align> {
5499        self.presentation_chain()
5500            .iter()
5501            .find_map(|attrs| Align::from_attrs(attrs))
5502    }
5503
5504    /// The line spacing in force at the caret, or `None` for the theme's own.
5505    /// [`alignment_at_caret`](Self::alignment_at_caret)'s peer.
5506    pub fn line_spacing_at_caret(&mut self) -> Option<LineHeight> {
5507        self.presentation_chain()
5508            .iter()
5509            .find_map(|attrs| LineHeight::from_attrs(attrs))
5510    }
5511
5512    /// The size in force at the caret, or `None` for the theme's own — the
5513    /// entry a size menu shows ticked.
5514    ///
5515    /// Run-level, so the chain starts one node deeper: the attributed span the
5516    /// caret stands in, then its block, then the `div`s around it. The nearest
5517    /// wins, which is the rule the walker draws by.
5518    ///
5519    /// A name or a value, whichever the nearest node wrote. A `data-size` the
5520    /// grammar does not cover — a `huge` from elsewhere — is not a size this
5521    /// can answer, so the answer is `None` and the menu ticks *Default*, the
5522    /// same thing it did before the vocabulary opened.
5523    pub fn font_size_at_caret(&mut self) -> Option<FontSize> {
5524        self.presentation_chain()
5525            .iter()
5526            .find_map(|attrs| FontSize::from_attrs(attrs))
5527    }
5528
5529    /// The face in force at the caret, or `None` for the theme's body face.
5530    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer.
5531    pub fn font_family_at_caret(&mut self) -> Option<FontFace> {
5532        self.presentation_chain()
5533            .iter()
5534            .find_map(|attrs| FontFace::from_attrs(attrs))
5535    }
5536
5537    /// The *text* colour in force at the caret, or `None` for the theme's.
5538    /// [`font_size_at_caret`](Self::font_size_at_caret)'s peer, and not
5539    /// [`mark_color_at_caret`](Self::mark_color_at_caret) — that one reads a
5540    /// highlight's background off a `mark`, and a `mark` is never in this chain.
5541    pub fn text_color_at_caret(&mut self) -> Option<TextColor> {
5542        self.presentation_chain()
5543            .iter()
5544            .find_map(|attrs| TextColor::from_attrs(attrs))
5545    }
5546
5547    /// The selection-or-caret half of the three run-level gestures: a span over
5548    /// a real selection, the caret's block over none.
5549    fn set_run_attr(&mut self, what: &str, key: &str, value: Option<&str>) {
5550        match self.selection() {
5551            Some((start, end)) => {
5552                let attrs = with_attr(&self.run_attrs_over(start, end), key, value);
5553                self.write_run_attrs(what, start, end, attrs);
5554            }
5555            None => {
5556                let own = self.block_attrs_at_caret();
5557                if value.is_none()
5558                    && self.refuse_clear_from_div(what, &own, |a| a.iter().any(|(k, _)| k == key))
5559                {
5560                    return;
5561                }
5562                let attrs = with_attr(&own, key, value);
5563                self.write_block_attrs(what, attrs);
5564            }
5565        }
5566    }
5567
5568    /// A clear this gesture cannot carry out, said out loud instead of written:
5569    /// the node it rewrites — the caret's block, or the `<div>` around it that
5570    /// [`block_attrs_at_caret`](Self::block_attrs_at_caret) folds to in Markdown
5571    /// — does not name the property at all, and a `div` further out does.
5572    ///
5573    /// Handing twig the block's attributes with the key already absent changes
5574    /// no byte, and the query goes on answering `Some` off the div: the menu
5575    /// entry the author pressed stays unticked, and nothing says why. Twig's
5576    /// `set_block_attrs` reaches one node, so leaf cannot clear a key it did not
5577    /// write on a node it is not rewriting — the honest answer is the status
5578    /// line, in the voice the other refusals use.
5579    ///
5580    /// `names` is the property's own reading of an attribute list, because
5581    /// alignment lives in a `class` token rather than a key of its own. Spans
5582    /// are skipped: one inside the block is not what a *block* gesture writes
5583    /// either, but neither is it "the div around the block", and the run-level
5584    /// gestures reach it through a selection.
5585    fn refuse_clear_from_div(
5586        &mut self,
5587        what: &str,
5588        own: &Attrs,
5589        names: impl Fn(&Attrs) -> bool,
5590    ) -> bool {
5591        if names(own) {
5592            return false;
5593        }
5594        let caret = self.caret.min(self.source.len());
5595        if !self
5596            .attr_chain_at(caret)
5597            .iter()
5598            .any(|(span, attrs)| !span && names(attrs))
5599        {
5600            return false;
5601        }
5602        self.status = Some(format!("{what}: set on the div around the block"));
5603        true
5604    }
5605
5606    /// Hand `attrs` to twig as the caret's block's whole attribute set, with the
5607    /// status, undo and caret plumbing [`set_mark_color`](Self::set_mark_color)
5608    /// has.
5609    ///
5610    /// **The caret keeps its place in the text, not its byte offset.** How a
5611    /// format spells a block's attributes is markup written *around* the block
5612    /// — djot's `{…}` line above it, a `<div …>` and two blank lines in front of
5613    /// it in Markdown, a longer opening tag in HTML — and every one of those
5614    /// grows or shrinks above the author's own bytes. Where twig's change
5615    /// rewrites the block whole (Markdown's div is spliced as one region, block
5616    /// included) the plain arithmetic of [`reanchor`] has nothing to shift by
5617    /// and parks the caret at the end of the splice, past the closing `</div>`:
5618    /// the caret is then in no block at all, so a second press of the same menu
5619    /// answers "no block at the caret" and the toolbar's queries read nothing.
5620    /// [`reanchor_in_block`] is what carries it across instead — the block's
5621    /// content span before and after, which is the one thing the respelling
5622    /// leaves alone.
5623    ///
5624    /// Read *before* the splice and applied *after* `refresh`, because both
5625    /// halves of that mapping are facts about a tree twig is between: the
5626    /// block's old bytes are gone once the edit lands, and its new ones are not
5627    /// in `self.source` until the refresh puts them there.
5628    fn write_block_attrs(&mut self, what: &str, attrs: Attrs) {
5629        if self.read_only || self.refuse_unsupported(what, Gesture::SetBlockAttrs) {
5630            return;
5631        }
5632        // A blank line has no block to carry an attribute, and twig answers
5633        // `NotFound` there — say so in leaf's own words instead.
5634        let Some(at) = self.block_offset_for_caret() else {
5635            self.status = Some(format!("{what}: no block at the caret"));
5636            return;
5637        };
5638        self.record_caret();
5639        let pairs = attr_pairs(&attrs);
5640        let was = self.block_content_at(at);
5641        let text = was.clone().map(|s| self.source[s].to_string());
5642        match self.editor.set_block_attrs(at, &pairs) {
5643            Ok(change) => {
5644                let (caret, anchor) = (self.caret, self.anchor);
5645                self.last_edit_kind = None; // structural edit is its own undo step
5646                self.refresh();
5647                let now = self.block_content_in(&change.new, text.as_deref());
5648                // A block the two halves cannot both name — a code block, a
5649                // caret in a list's marker — takes the plain arithmetic, which
5650                // is what it had before.
5651                let block = was.as_ref().zip(now.as_ref());
5652                self.caret = reanchor_in_block(caret, &change, block);
5653                self.anchor = anchor.map(|a| reanchor_in_block(a, &change, block));
5654                self.dirty = self.source != self.clean_source;
5655                self.status = None;
5656                // The clamp reads the caret floor off the map, and this edit
5657                // can move the floor: taking the `{…}` line off a djot
5658                // document's first block moves the first rendered offset to 0,
5659                // and a floor read from the old map stood the caret past the
5660                // block's text. So the map is this revision's before the clamp
5661                // — see `open_paragraph_at_block_edge`.
5662                self.rebuild_map();
5663                self.clamp_caret();
5664                self.record_caret();
5665            }
5666            Err(e) => self.status = Some(format!("{what}: {e}")),
5667        }
5668    }
5669
5670    /// The content span of the innermost paragraph or heading covering `off` —
5671    /// the author's own bytes, without the `# ` or the `<p>` that spells the
5672    /// block around them.
5673    ///
5674    /// The same two kinds [`block_attrs_at_caret`](Self::block_attrs_at_caret)
5675    /// reads, so that what a gesture re-anchors by is the block it wrote to.
5676    fn block_content_at(&mut self, off: usize) -> Option<Range<usize>> {
5677        self.nodes()
5678            .into_iter()
5679            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
5680            .filter(|n| n.span.start <= off && off <= n.span.end)
5681            .min_by_key(|n| n.span.end - n.span.start)
5682            .map(|n| n.content_span.unwrap_or(n.span))
5683    }
5684
5685    /// [`block_content_at`](Self::block_content_at)'s other half: the content
5686    /// span of the block `region` holds now, found by the bytes it held before.
5687    ///
5688    /// Matched on the text rather than taken as the first block in the region,
5689    /// because a rewritten region is markup and all — `<div class="center">`
5690    /// carries words of its own — and because the block this gesture moved is
5691    /// the one whose content the respelling did not touch. `None` where the
5692    /// region holds no block at all, which is djot's every case: the `{…}` line
5693    /// is spliced above the block and the block itself never moves through the
5694    /// change at all, only past it.
5695    fn block_content_in(
5696        &mut self,
5697        region: &Range<usize>,
5698        text: Option<&str>,
5699    ) -> Option<Range<usize>> {
5700        let text = text?;
5701        let spans: Vec<Range<usize>> = self
5702            .nodes()
5703            .into_iter()
5704            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
5705            .filter(|n| region.start <= n.span.start && n.span.end <= region.end)
5706            .map(|n| n.content_span.unwrap_or(n.span))
5707            .collect();
5708        spans
5709            .into_iter()
5710            .find(|s| self.source.get(s.clone()) == Some(text))
5711    }
5712
5713    /// Hand `attrs` to twig as the attribute set of the span over `[start,
5714    /// end)` — wrapping one, or re-styling the one the range already lies in,
5715    /// or unwrapping it when `attrs` is empty.
5716    ///
5717    /// What the splice leaves selected is the span's **content** — the author's
5718    /// words — and not the whole of `change.new`, which is markup and all:
5719    /// `[big]{data-size="large"}` in djot, `<span …>big</span>` in Markdown. A
5720    /// selection reaching past the node's own span lies in no span at all, so a
5721    /// second press of the menu would nest a fresh one instead of re-styling
5722    /// the one just written.
5723    fn write_run_attrs(&mut self, what: &str, start: usize, end: usize, attrs: Attrs) {
5724        if self.read_only || self.refuse_unsupported(what, Gesture::WrapRangeAttrs) {
5725            return;
5726        }
5727        self.record_caret();
5728        let pairs = attr_pairs(&attrs);
5729        match self.editor.wrap_range_attrs(start, end, &pairs) {
5730            Ok(change) => {
5731                self.last_edit_kind = None;
5732                self.refresh();
5733                let content = self.span_content_in(&change.new);
5734                self.anchor = Some(content.start);
5735                self.caret = content.end;
5736                self.dirty = self.source != self.clean_source;
5737                self.status = None;
5738                self.clamp_caret();
5739                self.record_caret();
5740            }
5741            Err(e) => self.status = Some(format!("{what}: {e}")),
5742        }
5743    }
5744
5745    /// The content range of the attributed span `spliced` now holds — the
5746    /// outermost one inside it, since that is the one just written — or
5747    /// `spliced` itself where the splice left no span, which is what an unwrap
5748    /// leaves behind.
5749    fn span_content_in(&mut self, spliced: &Range<usize>) -> Range<usize> {
5750        self.nodes()
5751            .into_iter()
5752            .filter(wysiwyg::is_run_span)
5753            .filter(|n| spliced.start <= n.span.start && n.span.end <= spliced.end)
5754            .max_by_key(|n| n.span.end - n.span.start)
5755            .and_then(|n| n.content_span)
5756            .unwrap_or_else(|| spliced.clone())
5757    }
5758
5759    /// The attribute set `set_block_attrs` is about to **replace** at the caret
5760    /// — which is the block's own, except in Markdown, where twig writes a
5761    /// block's attributes onto a `<div>` around it and rewrites that div when
5762    /// the block is its sole child. Reading the paragraph there would hand back
5763    /// an empty list and quietly drop everything the div said.
5764    ///
5765    /// Empty when the caret is in no block at all, which is the same list a
5766    /// block carrying no attributes gives — and the right one either way, since
5767    /// the gesture then refuses on its own.
5768    fn block_attrs_at_caret(&mut self) -> Attrs {
5769        let Some(off) = self.block_offset_for_caret() else {
5770            return Vec::new();
5771        };
5772        let nodes = self.nodes();
5773        let Some(block) = nodes
5774            .iter()
5775            .filter(|n| matches!(n.kind, Kind::Para | Kind::Heading))
5776            .filter(|n| n.span.start <= off && off <= n.span.end)
5777            .min_by_key(|n| n.span.end - n.span.start)
5778        else {
5779            return Vec::new();
5780        };
5781        if self.format == Format::Markdown
5782            && let Some(parent) = block.parent.and_then(|p| nodes.iter().find(|n| n.id == p))
5783            && wysiwyg::element_tag(parent) == Some("div")
5784            && nodes.iter().filter(|n| n.parent == Some(parent.id)).count() == 1
5785        {
5786            return parent.attrs.clone();
5787        }
5788        block.attrs.clone()
5789    }
5790
5791    /// The attribute set `wrap_range_attrs` is about to **replace** over
5792    /// `[start, end)` — the innermost attributed span the range lies inside,
5793    /// which twig re-styles rather than nesting a second one in. Empty when the
5794    /// range lies in no span, where the gesture mints a fresh one.
5795    fn run_attrs_over(&mut self, start: usize, end: usize) -> Attrs {
5796        self.nodes()
5797            .into_iter()
5798            .filter(wysiwyg::is_run_span)
5799            .filter(|n| n.span.start <= start && end <= n.span.end)
5800            .min_by_key(|n| n.span.end - n.span.start)
5801            .map(|n| n.attrs)
5802            .unwrap_or_default()
5803    }
5804
5805    /// The attribute lists that bear on a presentation query, **nearest first**:
5806    /// the attributed spans the caret stands in (innermost first), then its
5807    /// block, then the `div`s around it. A `find_map` down this is the whole of
5808    /// each query, and the order is the rule the walker draws by.
5809    ///
5810    /// Read at the caret, and at the selection's *start* when the caret stands
5811    /// in no span there. [`write_run_attrs`](Self::write_run_attrs) leaves the
5812    /// caret one past the span it just wrote — `toggle`'s convention — so
5813    /// asking the menu which entry that press just ticked must not answer
5814    /// `None`. Exactly the reason [`mark_offset`](Self::mark_offset) tries both.
5815    fn presentation_chain(&mut self) -> Vec<Attrs> {
5816        let caret = self.caret.min(self.source.len());
5817        let mut chain = self.attr_chain_at(caret);
5818        if !chain.iter().any(|(span, _)| *span)
5819            && let Some((start, _)) = self.selection()
5820        {
5821            let alt = self.attr_chain_at(start);
5822            if alt.iter().any(|(span, _)| *span) {
5823                chain = alt;
5824            }
5825        }
5826        chain.into_iter().map(|(_, attrs)| attrs).collect()
5827    }
5828
5829    /// [`presentation_chain`](Self::presentation_chain) at one offset — every
5830    /// node bearing the vocabulary that covers it, innermost first, each paired
5831    /// with whether it is an attributed span (which is what tells the caller
5832    /// its run-level answer came from a run).
5833    ///
5834    /// Sorted by span length, which *is* the nesting order: a span lies inside
5835    /// its block and a block inside its div, so shortest-first is
5836    /// nearest-first without a second tree walk.
5837    fn attr_chain_at(&mut self, off: usize) -> Vec<(bool, Attrs)> {
5838        let off = off.min(self.source.len());
5839        let mut hits: Vec<(usize, bool, Attrs)> = Vec::new();
5840        for n in self.nodes() {
5841            let span = wysiwyg::is_run_span(&n);
5842            let block = matches!(n.kind, Kind::Para | Kind::Heading);
5843            let div = wysiwyg::element_tag(&n) == Some("div");
5844            if !(span || block || div) {
5845                continue;
5846            }
5847            // A span is half-open, the way a mark is: the offset one past it is
5848            // the text after it. A block and a div claim their end too, so a
5849            // caret resting at the end of a line still reads its paragraph.
5850            let inside = if span {
5851                n.span.start <= off && off < n.span.end
5852            } else {
5853                n.span.start <= off && off <= n.span.end
5854            };
5855            if !inside {
5856                continue;
5857            }
5858            hits.push((n.span.end - n.span.start, span, n.attrs));
5859        }
5860        hits.sort_by_key(|(len, _, _)| *len);
5861        hits.into_iter()
5862            .map(|(_, span, attrs)| (span, attrs))
5863            .collect()
5864    }
5865
5866    /// Convert the block at the caret to a heading level or paragraph.
5867    pub fn set_block(&mut self, kind: BlockKind) {
5868        // The read-only gate — this door reaches twig without the splice.
5869        if self.read_only {
5870            return;
5871        }
5872        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::SetBlock) {
5873            return;
5874        }
5875        self.record_caret();
5876        // A blank line has no node to convert, and twig opens a block there
5877        // rather than declining — so the caret's own offset is the right thing
5878        // to hand it when `block_offset_for_caret` finds nothing.
5879        let offset = self.block_offset_for_caret().unwrap_or(self.caret);
5880        match self.editor.set_block(offset, kind) {
5881            Ok(change) => {
5882                self.last_edit_kind = None;
5883                self.refresh();
5884                // Opening a block on a blank line writes a marker the caret
5885                // belongs *after*; converting an existing one moves nothing.
5886                self.caret = self.caret.max(change.new.end);
5887                self.clamp_caret();
5888                self.anchor = None;
5889                self.dirty = self.source != self.clean_source;
5890                self.status = None;
5891                self.record_caret();
5892            }
5893            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
5894        }
5895    }
5896
5897    /// Whether `off` is inside a text block (paragraph, heading, code block…).
5898    fn has_block_at(&mut self, off: usize) -> bool {
5899        self.editor.ancestors_at(off).ok().is_some_and(|chain| {
5900            chain
5901                .iter()
5902                .any(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
5903        })
5904    }
5905
5906    /// The offset to hand twig's `set_block`: the caret when it is already inside
5907    /// a block, otherwise nudged onto the previous character (a caret at a line
5908    /// end sits at the doc level, outside the block). `None` when the caret is on
5909    /// a blank line — a new paragraph with no block node to convert.
5910    fn block_offset_for_caret(&mut self) -> Option<usize> {
5911        let caret = self.caret.min(self.source.len());
5912        if self.has_block_at(caret) {
5913            return Some(caret);
5914        }
5915        // Nudge to the previous character — but never across a newline: that would
5916        // target the previous block, and a blank line genuinely has no block.
5917        if let Some((i, ch)) = self.source[..caret].char_indices().next_back()
5918            && ch != '\n'
5919            && self.has_block_at(i)
5920        {
5921            return Some(i);
5922        }
5923        None
5924    }
5925
5926    /// The heading level of the text block at the caret, or `None` when that
5927    /// block is not a heading.
5928    pub fn current_heading_level(&mut self) -> Option<u32> {
5929        let caret = self.caret;
5930        self.nodes()
5931            .into_iter()
5932            .filter(|n| n.kind == Kind::Heading)
5933            .find(|n| n.span.start <= caret && caret <= n.span.end)
5934            .and_then(|n| n.level)
5935    }
5936
5937    /// The inline marks in force at the caret (or over the selection) — what a
5938    /// toolbar draws lit, and the block-level [`Doc::current_heading_level`]'s
5939    /// inline counterpart. Cheap enough to call every frame: one twig
5940    /// `ancestors_at` query per caret (two with a selection), each walking root
5941    /// → deepest node at one offset. It never snapshots the tree the way
5942    /// `current_heading_level` does, and the returned set is a `Copy` bitset, so
5943    /// the only allocation is twig's own small ancestor `Vec`.
5944    ///
5945    /// **A selection reports a mark only when the mark covers *all* of it.**
5946    /// That's what every real toolbar means by an active button — Bold lit over
5947    /// a half-bold selection would claim a press turns bold *off*, when
5948    /// [`Doc::toggle`] hands the range to twig and gets the whole thing bolded.
5949    /// Whole-coverage is asked as "is the same mark node standing over both the
5950    /// first and the last character?": inline nodes are contiguous, so one node
5951    /// covering both ends covers every byte between them. Two touching runs
5952    /// (`**a****b**`) are two nodes, and correctly light nothing.
5953    ///
5954    /// At a bare caret a mark is active when the caret stands inside the mark's
5955    /// span — `span.start <= caret < span.end`, delimiters included, which is
5956    /// what makes the boundaries behave. In `a **bold** b` the offsets from the
5957    /// opening `*` (2) through the last byte of the closing `**` (9) are all
5958    /// bold, so the WYSIWYG caret both before `b` and after `d` (the delimiters
5959    /// are hidden, and those offsets are 4 and 8) reports bold — matching where
5960    /// typing would actually land inside the marked run. The offset one past the
5961    /// mark (10) is the text after it and reports nothing, at the end of the
5962    /// buffer exactly as in the middle.
5963    pub fn active_inline_marks(&mut self) -> InlineMarks {
5964        let Some((start, end)) = self.selection() else {
5965            // The marks actually in force at the caret, flipped by any armed
5966            // sticky delta — so `⌘b` at a bare caret lights the Bold button
5967            // immediately, before a single character is typed.
5968            let base: InlineMarks = self
5969                .marks_at(self.caret)
5970                .into_iter()
5971                .map(|(k, _)| k)
5972                .collect();
5973            return base.xor(self.pending_here());
5974        };
5975        // The selection's *last character*, not its exclusive end: `end` is the
5976        // offset one past the selection, which for a selection ending exactly at
5977        // a mark's close is already outside it (`[4,10)` of `a **bold** b` is
5978        // entirely bold, but offset 10 is the space after).
5979        let last = prev_boundary(&self.source, end);
5980        let head = self.marks_at(start);
5981        let tail = self.marks_at(last);
5982        head.into_iter()
5983            .filter(|m| tail.contains(m))
5984            .map(|(k, _)| k)
5985            .collect()
5986    }
5987
5988    /// The inline marks whose span covers `off`, each with the id of the node
5989    /// carrying it — the id is what lets a selection tell one mark node from
5990    /// another of the same kind.
5991    fn marks_at(&mut self, off: usize) -> Vec<(InlineKind, u32)> {
5992        let off = off.min(self.source.len());
5993        self.editor
5994            .ancestors_at(off)
5995            .unwrap_or_default()
5996            .into_iter()
5997            // `span.end` is the offset one *past* the mark, so it isn't in it.
5998            // twig already resolves a boundary to whatever starts there — in
5999            // `**bold** x` offset 8 is the following text, not the strong — but
6000            // when nothing follows, the tie has nobody to break for and the
6001            // chain still ends at the mark. That would make the answer at the
6002            // last offset of the document depend on whether the file happens to
6003            // end in a newline; the rule is `span.start <= off < span.end`, and
6004            // it's the same rule at the end of a buffer as in the middle.
6005            .filter(|m| off < m.span.end)
6006            .filter_map(|m| inline_kind(&m.kind).map(|k| (k, m.node_id)))
6007            .collect()
6008    }
6009
6010    /// Toggle a heading at the caret: if the block is already this heading level,
6011    /// revert it to a paragraph; otherwise convert it to this heading level.
6012    /// This gives the heading commands the same toggle feel as bold/italic/code —
6013    /// re-applying a heading a line already has turns it back into body text.
6014    pub fn toggle_heading(&mut self, level: u32) {
6015        if self.current_heading_level() == Some(level) {
6016            self.set_block(BlockKind::Paragraph);
6017        } else {
6018            self.set_block(BlockKind::Heading(level));
6019        }
6020    }
6021
6022    /// Toggle a block quote around the selection, or around the block at the
6023    /// caret — the toolbar's Quote button.
6024    pub fn toggle_blockquote(&mut self) {
6025        self.toggle_container(BlockContainerKind::BlockQuote);
6026    }
6027
6028    /// Toggle a numbered (`ordered`) or bulleted list over the selection, or
6029    /// over the block at the caret — one op with the kind as a flag, the way
6030    /// `toggle_heading` takes its level, so a frontend needs no twig type to
6031    /// name the two buttons.
6032    ///
6033    /// Pressing the *other* list's button while in a list converts in place
6034    /// rather than nesting, so the pair reads as one three-state control
6035    /// (bulleted / numbered / neither) rather than two independent wrappers.
6036    pub fn toggle_list(&mut self, ordered: bool) {
6037        self.toggle_container(if ordered {
6038            BlockContainerKind::OrderedList
6039        } else {
6040            BlockContainerKind::BulletList
6041        });
6042    }
6043
6044    /// Toggle a fenced code block over the selection, or over the block at the
6045    /// caret — the toolbar's Code Block button, and the only way the rich view
6046    /// offers to open one: a typed backtick is escaped there, since it is a
6047    /// character the author wrote and not markup they meant.
6048    ///
6049    /// Fencing is twig's ([`Editor::toggle_code_block`]): it measures the fence
6050    /// against the body, keeps a quote's `> ` on every line, and peels a fence
6051    /// (or dedents an indented block) on the way back. What is leaf's is the
6052    /// shape twig declines: a blank line holds no block to fence, and the
6053    /// gesture nobody should have to learn is "type something first" — so leaf
6054    /// spells the empty fence itself, with the caret on the empty line inside it
6055    /// and a blank line either side, which is what typing into a new block and
6056    /// then Backspacing out of it would have left.
6057    ///
6058    /// Inside a list item twig refuses in both directions (a fence at column
6059    /// zero would swallow the item's marker), and the refusal is reported rather
6060    /// than worked around.
6061    pub fn toggle_code_block(&mut self) {
6062        // The read-only gate — this door reaches twig without the splice.
6063        if self.read_only {
6064            return;
6065        }
6066        if self.refuse_unsupported("code block", Gesture::ToggleCodeBlock) {
6067            return;
6068        }
6069        let selected = self.selection();
6070        // The caret at a code block's rows resolves to its *content*, and twig
6071        // finds the block from any offset inside its span — but a caret parked
6072        // on the closing fence's own line end is past it, so the block's start
6073        // is handed over whenever the caret is in one at all.
6074        let (start, end) = match selected {
6075            Some(range) => range,
6076            None => match self.code_block_start_at_caret() {
6077                Some(start) => (start, start),
6078                None => match self.block_offset_for_caret() {
6079                    Some(off) => (off, off),
6080                    None => return self.open_empty_code_block(),
6081                },
6082            },
6083        };
6084        self.record_caret();
6085        match self.editor.toggle_code_block(start, end, None) {
6086            Ok(change) => {
6087                // Read the caret's place out of the *pre-edit* source, before
6088                // `refresh` swaps it out — and how many lines the region held,
6089                // which is what says whether a fence line went in above the
6090                // caret's line or came off it.
6091                let place = selected
6092                    .is_none()
6093                    .then(|| self.caret_line_tail(&change.old));
6094                let old_lines = self.source[change.old.clone()].matches('\n').count();
6095                self.last_edit_kind = None; // structural edit is its own undo step
6096                self.refresh();
6097                match place {
6098                    // From a selection: keep the block selected, so a second
6099                    // press reverses the first (twig unfences from any offset in
6100                    // the fence's span, the region's start included).
6101                    None => {
6102                        self.anchor = Some(change.new.start);
6103                        self.caret = change.new.end;
6104                    }
6105                    // From a caret: the same line, the same distance from its
6106                    // end, shifted by the opening fence that was written above
6107                    // it (or peeled off). Dedenting an indented block keeps the
6108                    // lines one-to-one, and shifts nothing.
6109                    Some((line, tail)) => {
6110                        let new_lines = self.source[change.new.start.min(self.source.len())
6111                            ..change.new.end.min(self.source.len())]
6112                            .matches('\n')
6113                            .count();
6114                        let line = match new_lines.cmp(&old_lines) {
6115                            std::cmp::Ordering::Greater => line + 1,
6116                            std::cmp::Ordering::Less => line.saturating_sub(1),
6117                            std::cmp::Ordering::Equal => line,
6118                        };
6119                        self.anchor = None;
6120                        self.caret = self.line_tail_offset(&change.new, (line, tail));
6121                    }
6122                }
6123                self.dirty = self.source != self.clean_source;
6124                self.status = None;
6125                self.clamp_caret();
6126                self.record_caret();
6127            }
6128            Err(e) => self.status = Some(format!("code block: {e}")),
6129        }
6130    }
6131
6132    /// Write an empty fenced block on the blank line the caret stands on, and
6133    /// put the caret on the empty line inside it — the half of
6134    /// [`toggle_code_block`](Self::toggle_code_block) that is leaf's, because
6135    /// twig reports `NotFound` for a range no block covers.
6136    ///
6137    /// Inside a quote the fence lines and the empty line keep the quote's
6138    /// prefix, as twig's own fencing does. A blank line goes in on whichever
6139    /// side has text against it, since a fence may interrupt a paragraph in
6140    /// Markdown but a block standing tight against its neighbours is not the
6141    /// document any editor writes.
6142    fn open_empty_code_block(&mut self) {
6143        let caret = self.caret.min(self.source.len());
6144        let prefix = self.quote_prefix_at(caret);
6145        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
6146        let line_end = self.source[caret..]
6147            .find('\n')
6148            .map_or(self.source.len(), |i| caret + i);
6149        let prev_blank = line_start == 0
6150            || self.source[..line_start - 1]
6151                .rsplit('\n')
6152                .next()
6153                .is_some_and(|l| l.trim_start_matches(['>', ' ']).is_empty());
6154        let next_blank = line_end >= self.source.len()
6155            || self.source[line_end + 1..]
6156                .split('\n')
6157                .next()
6158                .is_some_and(|l| l.trim_start_matches(['>', ' ']).is_empty());
6159        // A blank line inside a quote is a bare `>`: the space after it is
6160        // the content's, and there is none.
6161        let blank = prefix.trim_end();
6162        let mut text = String::new();
6163        if !prev_blank {
6164            text.push_str(blank);
6165            text.push('\n');
6166        }
6167        text.push_str(&prefix);
6168        text.push_str("```\n");
6169        text.push_str(&prefix);
6170        let inside = text.len();
6171        text.push('\n');
6172        text.push_str(&prefix);
6173        text.push_str("```");
6174        if !next_blank {
6175            text.push('\n');
6176            text.push_str(blank);
6177        }
6178        // Over whatever the blank line held (its quote prefix, trailing
6179        // spaces), so the block's own prefix is the one twig will read back.
6180        let at = line_start;
6181        if !self.splice(at, line_end, &text, EditKind::Other) {
6182            return;
6183        }
6184        self.caret = at + inside;
6185        self.anchor = None;
6186        self.clamp_caret();
6187        self.record_caret();
6188    }
6189
6190    /// Whether the caret stands in a code block, fenced or indented — what
6191    /// lights the Code Block button. Wider than
6192    /// [`caret_in_fenced_code`](Self::caret_in_fenced_code), which asks the
6193    /// narrower question a language prompt needs.
6194    pub fn caret_in_code_block(&mut self) -> bool {
6195        self.code_block_start_at_caret().is_some()
6196    }
6197
6198    // ── Task list items ──────────────────────────────────────────────────────
6199    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
6200    // inline content of the item's first paragraph rather than part of its
6201    // marker, so adding or removing one must leave the item's continuation
6202    // indentation alone, and an item inside a quote is found past the quote
6203    // markers. leaf names the gesture and the offset; the spelling is twig's.
6204
6205    /// Whether the list item at the caret carries a checkbox, and which way it
6206    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
6207    /// item or no item at all. What a toolbar reads to light its checkbox button.
6208    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
6209        self.task_checked_at(self.caret)
6210    }
6211
6212    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
6213    /// offset — what a frontend asks before deciding a click landed on a box.
6214    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
6215        self.innermost_list_item(offset.min(self.source.len()))?
6216            .checked
6217    }
6218
6219    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
6220    /// A no-op with a reported reason when the caret is in no task item — minting
6221    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
6222    pub fn toggle_task_checked(&mut self) {
6223        self.toggle_task_at(self.caret);
6224    }
6225
6226    /// Tick or untick the task item covering `offset` — what a *click* on a
6227    /// rendered checkbox is. Separate from the caret form because a click carries
6228    /// its own offset and must not first move the caret there: ticking a box
6229    /// three paragraphs away should not take the cursor with it.
6230    pub fn toggle_task_at(&mut self, offset: usize) {
6231        // The read-only gate — this door reaches twig without the splice.
6232        if self.read_only {
6233            return;
6234        }
6235        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
6236            return;
6237        }
6238        let offset = offset.min(self.source.len());
6239        self.record_caret();
6240        match self.editor.toggle_task_checked(offset) {
6241            Ok(_) => self.after_task_edit(),
6242            Err(e) => self.status = Some(format!("task: {e}")),
6243        }
6244    }
6245
6246    /// Give the list item at the caret a checkbox, or take its checkbox away —
6247    /// the gesture that converts between a plain bullet and a task. A new box
6248    /// arrives unticked.
6249    ///
6250    /// Outside a list the caret's block becomes a bullet first, and the box
6251    /// goes on the new item — one undo step. twig's gesture only converts an
6252    /// item that is already there, and a Checklist button that did nothing on
6253    /// a paragraph read as broken.
6254    pub fn toggle_task_item(&mut self) {
6255        // The read-only gate — this door reaches twig without the splice.
6256        if self.read_only {
6257            return;
6258        }
6259        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
6260            return;
6261        }
6262        if self
6263            .innermost_list_item(self.caret.min(self.source.len()))
6264            .is_none()
6265        {
6266            if self.refuse_unsupported(
6267                "task",
6268                Gesture::ToggleBlockContainer(BlockContainerKind::BulletList),
6269            ) {
6270                return;
6271            }
6272            self.begin_undo_group();
6273            self.toggle_list(false);
6274            if self
6275                .innermost_list_item(self.caret.min(self.source.len()))
6276                .is_some()
6277            {
6278                self.box_item_at_caret();
6279            }
6280            self.end_undo_group();
6281            return;
6282        }
6283        self.box_item_at_caret();
6284    }
6285
6286    /// twig's half of [`toggle_task_item`](Self::toggle_task_item): the box on
6287    /// the item the caret is already in.
6288    fn box_item_at_caret(&mut self) {
6289        let caret = self.caret.min(self.source.len());
6290        self.record_caret();
6291        match self.editor.toggle_task_item(caret) {
6292            Ok(_) => self.after_task_edit(),
6293            Err(e) => self.status = Some(format!("task: {e}")),
6294        }
6295    }
6296
6297    /// Settle after a task gesture. The caret rides its old byte offset and is
6298    /// clamped back in: a box is three or four bytes on the item's first line, so
6299    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
6300    /// real stop either way.
6301    fn after_task_edit(&mut self) {
6302        self.last_edit_kind = None;
6303        self.refresh();
6304        self.anchor = None;
6305        self.dirty = self.source != self.clean_source;
6306        self.status = None;
6307        self.clamp_caret();
6308        self.record_caret();
6309    }
6310
6311    // ── Tables ───────────────────────────────────────────────────────────────
6312    // A table is a grid, and twig edits it as one — add/remove/move a row or
6313    // column, set a column's alignment — re-spelling the whole table in a single
6314    // splice. Every gesture is anchored at the caret's cell. leaf just names the
6315    // gesture and re-reads the result; the whole table's numbering, borders, and
6316    // delimiter are twig's to keep straight.
6317
6318    /// Whether the caret is inside a table — what a frontend asks to enable or
6319    /// disable its table controls.
6320    ///
6321    /// An HTML `<table>` still answers `true`: the caret really is in a table,
6322    /// and the reason the grid controls stay dark there is
6323    /// [`Capabilities::table`], which is a fact about the document's format
6324    /// rather than about the caret. A frontend needs both.
6325    pub fn caret_in_table(&mut self) -> bool {
6326        let caret = self.caret.min(self.source.len());
6327        self.editor
6328            .ancestors_at(caret)
6329            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
6330            .unwrap_or(false)
6331    }
6332
6333    /// One grid op, guarded and settled — the shared body of the seven below.
6334    ///
6335    /// The guard is why this exists rather than seven copies of the same three
6336    /// lines, and it is the one guard leaf cannot delegate to twig. The table
6337    /// editor is the gesture family that consults no `Syntax` table (it spells a
6338    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
6339    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
6340    /// grid as a *pipe table* and reports success, swapping the element out for
6341    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
6342    /// downstream could tell that from a successful edit — the splice is real,
6343    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
6344    /// stopping at the door rather than detecting after the fact. See
6345    /// [`spells_pipe_tables`].
6346    fn table_op(
6347        &mut self,
6348        what: &str,
6349        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
6350    ) {
6351        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
6352            return;
6353        }
6354        self.record_caret();
6355        let at = self.caret;
6356        let r = op(&mut self.editor, at);
6357        self.apply_table(r, what);
6358    }
6359
6360    /// Insert an empty row below (`below`) or above the caret's row.
6361    pub fn table_insert_row(&mut self, below: bool) {
6362        self.table_op("table row", |e, at| e.table_insert_row(at, below));
6363    }
6364
6365    /// Delete the caret's row (not the header, not the last body row).
6366    pub fn table_delete_row(&mut self) {
6367        self.table_op("table row", |e, at| e.table_delete_row(at));
6368    }
6369
6370    /// Insert an empty column right (`right`) or left of the caret's column.
6371    pub fn table_insert_column(&mut self, right: bool) {
6372        self.table_op("table column", |e, at| e.table_insert_column(at, right));
6373    }
6374
6375    /// Delete the caret's column (unless it is the only one).
6376    pub fn table_delete_column(&mut self) {
6377        self.table_op("table column", |e, at| e.table_delete_column(at));
6378    }
6379
6380    /// Set the caret's column to `alignment`.
6381    pub fn table_set_alignment(&mut self, alignment: Alignment) {
6382        self.table_op("table alignment", |e, at| {
6383            e.table_set_alignment(at, alignment)
6384        });
6385    }
6386
6387    /// Move the caret's row one place down (`down`) or up, within the body rows.
6388    pub fn table_move_row(&mut self, down: bool) {
6389        self.table_op("table row", |e, at| e.table_move_row(at, down));
6390    }
6391
6392    /// Move the caret's column one place right (`right`) or left.
6393    pub fn table_move_column(&mut self, right: bool) {
6394        self.table_op("table column", |e, at| e.table_move_column(at, right));
6395    }
6396
6397    /// Settle the caret and document flags after a table op (or report its
6398    /// error). twig re-spells the whole table, so the caret rides its old byte
6399    /// offset and is clamped back into the rebuilt bytes — near enough to where
6400    /// it was, since the op preserves the cells' content and order around it.
6401    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
6402        match result {
6403            Ok(()) => {
6404                self.last_edit_kind = None;
6405                self.refresh();
6406                self.anchor = None;
6407                self.clamp_caret();
6408                self.dirty = self.source != self.clean_source;
6409                self.status = None;
6410                self.record_caret();
6411            }
6412            Err(e) => self.status = Some(format!("{what}: {e}")),
6413        }
6414    }
6415
6416    /// One `toggle_block_container` over the block-level target.
6417    ///
6418    /// leaf says *where*; twig decides everything else — which blocks the range
6419    /// covers, whether that means wrapping, unwrapping, nesting or converting,
6420    /// and how this document's format spells the prefix. The rule that a
6421    /// container only comes off when the range covers every block it holds is
6422    /// what the re-anchoring below is built around.
6423    fn toggle_container(&mut self, kind: BlockContainerKind) {
6424        // The read-only gate — this door reaches twig without the splice.
6425        if self.read_only {
6426            return;
6427        }
6428        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
6429            return;
6430        }
6431        let selected = self.selection();
6432        // A blank line holds no block, and twig opens an *empty* container on one
6433        // — since 3.2.0; it used to decline the range with `NotFound`, which is
6434        // why this used to lend it a scratch paragraph to wrap. Worth knowing
6435        // here because the line-for-line caret mapping below cannot describe it:
6436        // opening one under a paragraph writes the blank line the format needs
6437        // above the marker too, so the rewritten region has a line the old one
6438        // didn't, and "the same line, the same distance from its end" lands on
6439        // that new blank instead of in the container.
6440        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
6441        // Without a selection the target is the caret's own block, resolved the
6442        // way `set_block` resolves it — a caret at a line end sits at the doc
6443        // level and has to be nudged back onto the block it looks like it's in.
6444        // An empty range is enough: twig widens to the whole lines it touches.
6445        let (start, end) = match selected {
6446            Some(range) => range,
6447            None => {
6448                let off = self.block_offset_for_caret().unwrap_or(self.caret);
6449                (off, off)
6450            }
6451        };
6452        self.record_caret();
6453        match self.editor.toggle_block_container(start, end, kind) {
6454            Ok(change) => {
6455                // Read the caret's place out of the *pre-edit* source, before
6456                // `refresh` swaps that source out from under it.
6457                let place = (selected.is_none() && !opened_empty)
6458                    .then(|| self.caret_line_tail(&change.old));
6459                self.last_edit_kind = None; // structural edit is its own undo step
6460                self.refresh();
6461                match place {
6462                    // Both land the caret at the far end of what twig wrote, and
6463                    // differ only in what they leave selected.
6464                    //
6465                    // From a selection: select what the container now holds, the
6466                    // way `toggle` keeps its marked region selected — and for a
6467                    // stronger reason than symmetry: a container comes *off* only
6468                    // a range covering every block it holds, so a selection left
6469                    // on its old bytes (now short by a prefix per line) would nest
6470                    // on the second press instead of reversing the first.
6471                    //
6472                    // From a blank line: nothing to select, and the end of the
6473                    // region is exactly past the bare `> ` / `- ` twig wrote —
6474                    // the caret standing inside the container that was asked for.
6475                    None => {
6476                        self.anchor = (!opened_empty).then_some(change.new.start);
6477                        self.caret = change.new.end;
6478                    }
6479                    Some(place) => {
6480                        self.anchor = None;
6481                        self.caret = self.line_tail_offset(&change.new, place);
6482                    }
6483                }
6484                self.dirty = self.source != self.clean_source;
6485                self.status = None;
6486                self.clamp_caret();
6487                self.record_caret();
6488            }
6489            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
6490        }
6491    }
6492
6493    /// The caret's place inside the region a container toggle is rewriting, in
6494    /// the only terms the rewrite preserves: which of the region's lines it sits
6495    /// on, and how many bytes of that line lie ahead of it.
6496    ///
6497    /// A container's markup goes in at column 0 and never touches what follows
6498    /// on the line, so that pair survives the edit exactly where a byte offset
6499    /// does not — a caret left on its old offset slides back by one prefix per
6500    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
6501    /// `> ` it just asked for.
6502    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
6503        let caret = self.caret.clamp(old.start, old.end);
6504        let line = self.source[old.start..caret].matches('\n').count();
6505        let end = self.source[caret..old.end]
6506            .find('\n')
6507            .map_or(old.end, |i| caret + i);
6508        (line, end - caret)
6509    }
6510
6511    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
6512    /// region: the offset `tail` bytes back from the end of the region's `line`.
6513    ///
6514    /// Both walks are clamped rather than trusted, because the one op that does
6515    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
6516    /// the items back apart with blank lines between them — and a caret landing
6517    /// on the nearest line of the right item beats one landing out of the region
6518    /// entirely.
6519    fn line_tail_offset(
6520        &self,
6521        new: &std::ops::Range<usize>,
6522        (line, tail): (usize, usize),
6523    ) -> usize {
6524        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
6525        let mut start = 0;
6526        for _ in 0..line {
6527            match region[start..].find('\n') {
6528                Some(i) => start += i + 1,
6529                None => break,
6530            }
6531        }
6532        let end = region[start..]
6533            .find('\n')
6534            .map_or(region.len(), |i| start + i);
6535        new.start + end.saturating_sub(tail).max(start)
6536    }
6537
6538    /// Link the selection to `destination` — the toolbar's Link button. With no
6539    /// selection it acts at the caret, which re-points a link the caret is
6540    /// already standing in (twig replaces an existing link's destination and
6541    /// keeps its text) and otherwise spells a link that has no text of its own:
6542    /// an autolink (`<https://x.dev>`) where the destination is one, and
6543    /// `[destination](destination)` where it isn't.
6544    ///
6545    /// `destination` reaches twig raw. Escaping it is format knowledge and the
6546    /// two formats genuinely disagree — Markdown ends a destination at the first
6547    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
6548    /// itself — so the side holding the document is the side that gets to spell
6549    /// it. A destination twig can't carry at all (one with a newline) comes back
6550    /// as an error rather than a quietly rewritten URL.
6551    pub fn insert_link(&mut self, destination: &str) {
6552        if self.read_only || self.refuse_unsupported("link", Gesture::InsertLink) {
6553            return;
6554        }
6555        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6556        self.record_caret();
6557        match self.editor.insert_link(start, end, destination) {
6558            Ok(change) => {
6559                self.last_edit_kind = None;
6560                self.refresh();
6561                match self.link_text_span(change.new.start) {
6562                    // A link with text of its own: select it, so typing replaces
6563                    // a `[dest](dest)`'s stand-in label and a second press
6564                    // re-points what the first one linked.
6565                    Some(text) => {
6566                        self.anchor = (text.start != text.end).then_some(text.start);
6567                        self.caret = text.end;
6568                    }
6569                    // An autolink is finished the moment it's written — its text
6570                    // *is* the URL. Leaving it selected would aim the next press
6571                    // at the one shape twig still wraps instead of re-points.
6572                    None => {
6573                        self.anchor = None;
6574                        self.caret = change.new.end;
6575                    }
6576                }
6577                self.dirty = self.source != self.clean_source;
6578                self.status = None;
6579                self.clamp_caret();
6580                self.record_caret();
6581            }
6582            Err(e) => self.status = Some(format!("link: {e}")),
6583        }
6584    }
6585
6586    /// Insert a block-level image at the caret: `![alt](destination)`. Any
6587    /// selection becomes the alt text (so "select a caption, insert image" labels
6588    /// it); with no selection, `alt` is used — empty for none. The caret lands
6589    /// just past the inserted image.
6590    ///
6591    /// Both halves go through twig (`insert_literal` for the alt text,
6592    /// `insert_image` for the image), so neither is spelled here. That used to be a
6593    /// `format!`, and it was wrong the first time an app inserted a real filename:
6594    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
6595    /// not an image at all — and the fix is per-format, since moving into the
6596    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
6597    pub fn insert_image(&mut self, destination: &str, alt: &str) {
6598        if self.read_only || self.refuse_unsupported("image", Gesture::InsertImage) {
6599            return;
6600        }
6601        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6602        self.record_caret();
6603        // With no selection and an explicit `alt`, the alt text has to exist in the
6604        // document before it can be the image's — and it is raw caller input, so
6605        // it goes in through `insert_literal`, which escapes it for the format
6606        // rather than letting a `]` in someone's caption close the image early.
6607        let (start, end) = if start == end && !alt.is_empty() {
6608            match self.editor.insert_literal(start, alt) {
6609                Ok(change) => (change.new.start, change.new.end),
6610                Err(e) => {
6611                    self.status = Some(format!("image: {e}"));
6612                    return;
6613                }
6614            }
6615        } else {
6616            (start, end)
6617        };
6618        match self.editor.insert_image(start, end, destination) {
6619            Ok(change) => {
6620                self.last_edit_kind = None;
6621                self.refresh();
6622                // Just past the image, nothing selected — where a caret belongs
6623                // after inserting one.
6624                self.anchor = None;
6625                self.caret = change.new.end;
6626                self.dirty = self.source != self.clean_source;
6627                self.status = None;
6628                self.clamp_caret();
6629                self.record_caret();
6630            }
6631            Err(e) => self.status = Some(format!("image: {e}")),
6632        }
6633    }
6634
6635    /// Insert a block-level image, video, or audio at the caret. The image case
6636    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
6637    /// HTML elements, which is the only spelling Markdown and Djot have for them:
6638    ///
6639    /// ```text
6640    /// <video src="clip.mp4" controls>alt</video>
6641    /// <audio src="take.mp3" controls>alt</audio>
6642    /// ```
6643    ///
6644    /// HTML rather than a `::video{…}` directive deliberately. A directive means
6645    /// something only to an app that knows the vocabulary, so the document would
6646    /// read as literal punctuation everywhere else; `<video>` is what every other
6647    /// renderer already understands, and what leaf's own reader picks back up
6648    /// through `html_elements` promotion (see [`parse_extensions`]).
6649    ///
6650    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
6651    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
6652    /// `html_elements`. Before that only the multi-line form parsed as a block at
6653    /// all, and this wrote three lines to work around it.
6654    ///
6655    /// `controls` is always written: a player with no transport is a still frame
6656    /// the reader can't do anything with. Any selection becomes the element's
6657    /// fallback text, exactly as it becomes an image's alt.
6658    ///
6659    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
6660    /// applies, and bites harder here: a `"` in `destination` closes the
6661    /// attribute. A frontend taking these from a file picker is fine; one taking
6662    /// them from free text should keep them tame.
6663    ///
6664    /// [`MediaInfo`]: crate::MediaInfo
6665    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
6666        if kind == MediaKind::Image {
6667            return self.insert_image(destination, alt);
6668        }
6669        // Gated on the *image* gesture, not on one of its own — there isn't one,
6670        // since the bytes below are spelled here rather than by twig, and an HTML
6671        // document would in fact parse them. The button is one control with three
6672        // kinds behind it, and two of them working in a format where the third
6673        // cannot is a worse surface than three that agree — especially as
6674        // `insert_image` is the kind anyone reaches for first.
6675        if self.refuse_unsupported("media", Gesture::InsertImage) {
6676            return;
6677        }
6678        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6679        let alt_text = self
6680            .selected_text()
6681            .map(str::to_string)
6682            .unwrap_or_else(|| alt.to_string());
6683        let tag = match kind {
6684            MediaKind::Audio => "audio",
6685            _ => "video",
6686        };
6687        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
6688        self.edit(start, end, &markup);
6689    }
6690
6691    /// Append media at the **end** of the document, as a block of its own —
6692    /// the verb for a picture that *arrives* rather than one the writer
6693    /// places: an attachment imported while the caret was wherever it last
6694    /// was, a drawing placed from a tray under the body. At the caret it
6695    /// would land inline in front of whatever word the caret happened to be
6696    /// beside, which for an editor nobody has tapped yet is the first word
6697    /// of the document.
6698    ///
6699    /// The document is ended with a blank line first, where it does not
6700    /// already end with one, so the media is a paragraph of its own rather
6701    /// than a lazy continuation of the last one; an empty document needs no
6702    /// separator. Then [`insert_media`](Self::insert_media) at the new end,
6703    /// with everything that means: the same markup per kind, the same
6704    /// refusal on a format without images. The selection is dropped — the
6705    /// verb is about the end of the document, not about what was selected —
6706    /// and the caret is left past the media, as `insert_media` leaves it.
6707    pub fn append_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
6708        if self.read_only || self.refuse_unsupported("media", Gesture::InsertImage) {
6709            return;
6710        }
6711        let separator = if self.source.is_empty() || self.source.ends_with("\n\n") {
6712            ""
6713        } else if self.source.ends_with('\n') {
6714            "\n"
6715        } else {
6716            "\n\n"
6717        };
6718        let end = self.source.len();
6719        self.anchor = None;
6720        self.caret = end;
6721        if !separator.is_empty() {
6722            self.edit(end, end, separator);
6723        }
6724        self.anchor = None;
6725        self.caret = self.source.len();
6726        self.insert_media(kind, destination, alt);
6727    }
6728
6729    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
6730    /// button. Spelling and placement are both twig's; leaf used to write `---`
6731    /// itself, which was the Markdown spelling in a djot document too.
6732    ///
6733    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
6734    /// mid-paragraph and lands it after the caret's whole block. To get a rule
6735    /// *at* the caret — the paragraph parted in two around it, which is what a
6736    /// rule button is understood to do — the paragraph is first divided with
6737    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
6738    /// the offset `split_block` returns puts the rule after the *second* half
6739    /// instead, which is a rule in the right document and the wrong place.
6740    ///
6741    /// Only a plain paragraph is split, and only where there is something to
6742    /// part: at the paragraph's end the split has no second half to mint and
6743    /// would write the separator anyway — a blank line and the empty slot Enter
6744    /// leaves for the next paragraph, which the rule then lands above and
6745    /// nothing fills — so there the rule goes straight after the paragraph,
6746    /// which is where the split-and-aim was sending it regardless. At the
6747    /// paragraph's *start* the split is kept, though it parts nothing either:
6748    /// `|para` becomes `\npara` with the caret on the new blank line, and a
6749    /// rule aimed at a blank line is written on it (twig ≥ 3.5.2), which is how
6750    /// "before the paragraph" is said through a gesture that only knows
6751    /// "after" — `---\n\npara`, and `prev\n\n---\n\npara` mid-document. Everywhere
6752    /// else the rule simply lands after the block, which is both twig's own
6753    /// answer and the better one: splitting a fenced code block would leave two
6754    /// fences with a rule between them, and splitting a list item would mint an
6755    /// item nobody asked for on the way to a rule that lands after the list
6756    /// regardless. A table and a setext heading refuse the split outright, so
6757    /// they take the same path by themselves.
6758    ///
6759    /// The caret ends on the line under the rule, which is where the writer
6760    /// goes on: at the start of the paragraph's second half when the rule
6761    /// parted one, and otherwise on an empty line opened under the rule — see
6762    /// [`stand_under_block`](Self::stand_under_block). It used to be left at
6763    /// the end of what twig wrote, which is the rule's own row: the caret was
6764    /// drawn beside the rule, and mid-document the next keystroke joined the
6765    /// block below.
6766    pub fn insert_thematic_break(&mut self) {
6767        if self.read_only || self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak)
6768        {
6769            return;
6770        }
6771        self.caret = self.skip_trailing_close_delims(self.caret);
6772        // A selection is replaced by the rule, so collapse it first and let the
6773        // split-and-rule below run from the caret it leaves behind.
6774        if let Some((s, e)) = self.selection() {
6775            self.splice(s, e, "", EditKind::Other);
6776        }
6777        self.anchor = None;
6778        self.record_caret();
6779        let at = self.caret;
6780        // A failure here is not fatal: the rule still lands after the block,
6781        // which is exactly what this call was trying to improve on.
6782        let parted = self.part_for_block(at);
6783        match self.editor.insert_thematic_break(at) {
6784            Ok(change) => {
6785                self.last_edit_kind = None;
6786                self.refresh();
6787                if parted {
6788                    self.coalesce_last_undo();
6789                }
6790                self.anchor = None;
6791                self.caret = change.new.end;
6792                self.dirty = self.source != self.clean_source;
6793                self.status = None;
6794                self.clamp_caret();
6795                self.record_caret();
6796                self.caret_under_written_block(change.new, parted);
6797            }
6798            Err(e) => self.status = Some(format!("thematic break: {e}")),
6799        }
6800    }
6801
6802    /// Part the bare paragraph at `at` for a block gesture, where
6803    /// [`caret_parts_bare_paragraph`](Self::caret_parts_bare_paragraph) says
6804    /// to, and say whether it was parted.
6805    ///
6806    /// The split is counted as a step of its own, so the gesture can fold the
6807    /// block it writes next into it. It used to go to twig uncounted: twig
6808    /// kept it as a step and leaf's count did not, so one Undo took back the
6809    /// block and left the paragraph parted, with Undo then reporting nothing
6810    /// left to undo.
6811    fn part_for_block(&mut self, at: usize) -> bool {
6812        if !self.caret_parts_bare_paragraph() || self.editor.split_block(at).is_err() {
6813            return false;
6814        }
6815        self.refresh();
6816        true
6817    }
6818
6819    /// Where a block gesture leaves the caret once twig has written the block
6820    /// `new` spans — a rule, a page break: on the line under it. That is the
6821    /// start of the paragraph's second half when the gesture `parted` one,
6822    /// and otherwise the line [`stand_under_block`](Self::stand_under_block)
6823    /// finds or writes, folded into the gesture's step.
6824    ///
6825    /// The block is the outermost node twig's change opens, whatever its
6826    /// kind, since the kind a leaf directive comes back as is the format's.
6827    fn caret_under_written_block(&mut self, new: Range<usize>, parted: bool) {
6828        let block = self
6829            .nodes()
6830            .into_iter()
6831            .filter(|n| n.kind != Kind::Doc && new.contains(&n.span.start))
6832            .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)));
6833        let Some(block) = block else {
6834            return;
6835        };
6836        let (end, _) = wysiwyg::block_line(&self.source, block.span.end);
6837        if parted {
6838            // The second half starts at the first text under the block; the
6839            // split left it no leading whitespace.
6840            let rest = &self.source[end..];
6841            self.caret = end + (rest.len() - rest.trim_start().len());
6842            self.record_caret();
6843        } else if self.stand_under_block(end) {
6844            self.coalesce_last_undo();
6845        }
6846    }
6847
6848    /// Stand the caret on the line under the block whose last line's text ends
6849    /// at `end` — a thematic break, a page break — first writing that line if
6850    /// the block has none: where the rule and page-break buttons leave the
6851    /// caret, and where Enter on a rule takes it. Whether anything was
6852    /// written, so a caller can fold it into its own step.
6853    ///
6854    /// The caret's line is the first under the block that the view gives a
6855    /// home: the second blank line in [`LineFlow::Fold`], which draws the
6856    /// first as the gap closing the block, and the first in
6857    /// [`LineFlow::Preserve`], where every blank line is somewhere to type.
6858    /// When anything follows, one more blank line has to stand between the
6859    /// caret's line and it, or what is typed there runs on into the next
6860    /// block. Only what that shape is missing is written. A block twig wrote on
6861    /// a blank line still has the blank lines that were under the caret and
6862    /// needs one line more, or none, where a rule written under a paragraph
6863    /// needs two.
6864    ///
6865    /// Blank means blank inside the block's container: a quote's blank lines
6866    /// keep their `>`, and the caret's line wears the quote's whole prefix, as
6867    /// the line Enter opens in a quote does. The document's last line, when no
6868    /// newline ends it, counts only once a blank line stands above it, since
6869    /// only then does the view draw it as a row. Fold always writes the gap
6870    /// above it if it isn't there, so there a block ending the document takes
6871    /// one newline more and the caret its end.
6872    fn stand_under_block(&mut self, end: usize) -> bool {
6873        let prefix = self.continuation_prefix_at(end);
6874        let blank = prefix.trim_end();
6875        let gap = usize::from(self.line_flow == LineFlow::Fold);
6876        // The blank lines directly under the block's own, by where each starts,
6877        // and whether the line that ends the run has anything on it.
6878        let mut blanks = Vec::new();
6879        let mut follows = false;
6880        let mut at = end;
6881        while let Some(nl) = self.source[at..].find('\n') {
6882            let start = at + nl + 1;
6883            let len = self.source[start..].find('\n');
6884            let line = &self.source[start..len.map_or(self.source.len(), |len| start + len)];
6885            let line = line.trim_end();
6886            if line != blank {
6887                follows = !line.trim().is_empty();
6888                break;
6889            }
6890            let Some(len) = len else {
6891                if gap > 0 || !blanks.is_empty() {
6892                    blanks.push(start);
6893                }
6894                break;
6895            };
6896            blanks.push(start);
6897            at = start + len;
6898        }
6899        let missing = (gap + 1 + usize::from(follows)).saturating_sub(blanks.len());
6900        // What is missing goes in at the rule's end, above the blank lines
6901        // already there, so the caret's line is the same one counted from
6902        // the rule either way: written here, or one of those, moved down.
6903        let mut text = String::new();
6904        let mut caret = None;
6905        for line in 1..=missing {
6906            text.push('\n');
6907            if line == gap + 1 {
6908                text.push_str(&prefix);
6909                caret = Some(end + text.len());
6910            } else {
6911                text.push_str(blank);
6912            }
6913        }
6914        let caret = caret.unwrap_or_else(|| {
6915            let start = blanks[gap - missing];
6916            let line = self.source[start..].split('\n').next().unwrap_or("");
6917            start + text.len() + line.trim_end_matches('\r').len().min(prefix.len())
6918        });
6919        if !text.is_empty() && !self.splice(end, end, &text, EditKind::Other) {
6920            return false;
6921        }
6922        self.caret = caret.min(self.source.len());
6923        self.anchor = None;
6924        self.goal_col = None;
6925        self.record_caret();
6926        !text.is_empty()
6927    }
6928
6929    /// The thematic break the caret stands under, as its text's end, when
6930    /// Enter there belongs to the rule: the caret at the rule's home past it
6931    /// (the start of the line under it), that line blank, and the caret drawn
6932    /// on the rule's own row.
6933    ///
6934    /// Drawn on the rule's row, because the home past a rule is also the start
6935    /// of the line under it, and which of the two the view draws it on is the
6936    /// flow's. [`LineFlow::Fold`] draws that line as the gap under the rule,
6937    /// no caret's home, so the caret is beside the rule. [`LineFlow::Preserve`]
6938    /// makes every blank line a home, so it draws the caret there and Enter is
6939    /// an ordinary blank line's — unless it is the document's unterminated
6940    /// last line, which is no row in either flow.
6941    fn rule_above_caret(&mut self) -> Option<usize> {
6942        let caret = self.caret.min(self.source.len());
6943        let above = self.source[..caret].strip_suffix('\n')?;
6944        let above_start = above.rfind('\n').map_or(0, |i| i + 1);
6945        let text = above[above_start..].trim_end();
6946        let (last, _) = text.char_indices().next_back()?;
6947        let rule = self
6948            .editor
6949            .ancestors_at(above_start + last)
6950            .ok()?
6951            .into_iter()
6952            .find(|m| m.kind == Kind::ThematicBreak)?;
6953        let (end, home) = wysiwyg::block_line(&self.source, rule.span.end);
6954        if home != caret {
6955            return None;
6956        }
6957        let blank = self.continuation_prefix_at(end);
6958        let line_end = self.source[caret..].find('\n').map(|i| caret + i);
6959        let line = &self.source[caret..line_end.unwrap_or(self.source.len())];
6960        if line.trim_end() != blank.trim_end() && !line.trim().is_empty() {
6961            return None;
6962        }
6963        (self.line_flow == LineFlow::Fold || line_end.is_none()).then_some(end)
6964    }
6965
6966    /// Insert a fresh table at the caret — the toolbar's Table button. One
6967    /// header row, `rows` empty body rows, `cols` columns, spelled by twig in
6968    /// the document's own dialect and placed the way its thematic break is:
6969    /// after the caret's block, blank-separated. A bare paragraph is parted
6970    /// around the caret first, exactly as
6971    /// [`insert_thematic_break`](Self::insert_thematic_break) parts it, so the
6972    /// table lands *at* the caret rather than after everything the caret's
6973    /// paragraph says.
6974    ///
6975    /// The caret ends in the first header cell, selected the way Tab selects
6976    /// a cell — the natural next act is to type the heading, and Tab then
6977    /// walks the grid. That cell is read back from the rebuilt table map
6978    /// rather than computed from the splice, because twig's blank line and
6979    /// quote prefix put the first bar at an offset only the reparse knows.
6980    ///
6981    /// The shape is the caller's: a menu offers a few, a dialog asks. Zero
6982    /// rows or columns is twig's refusal (a header with nothing under it is
6983    /// what its row delete refuses to leave), reported through `status` —
6984    /// and refused here before the paragraph is parted, which would otherwise
6985    /// be left parted around a table never written.
6986    pub fn insert_table(&mut self, rows: usize, cols: usize) {
6987        if self.read_only || self.refuse_unsupported("table", Gesture::InsertTable) {
6988            return;
6989        }
6990        // twig's one refusal of a shape, asked before the paragraph is parted
6991        // for a table that would never be written into it.
6992        if rows == 0 || cols == 0 {
6993            self.status = Some("table: needs at least one row and one column".into());
6994            return;
6995        }
6996        self.caret = self.skip_trailing_close_delims(self.caret);
6997        if let Some((s, e)) = self.selection() {
6998            self.splice(s, e, "", EditKind::Other);
6999        }
7000        self.anchor = None;
7001        self.record_caret();
7002        let at = self.caret;
7003        let parted = self.part_for_block(at);
7004        match self.editor.insert_table(at, rows, cols) {
7005            Ok(change) => {
7006                self.last_edit_kind = None;
7007                self.refresh();
7008                if parted {
7009                    self.coalesce_last_undo();
7010                }
7011                self.anchor = None;
7012                self.caret = change.new.end;
7013                self.dirty = self.source != self.clean_source;
7014                self.status = None;
7015                self.clamp_caret();
7016                // Into the first header cell of the table just written: the
7017                // first table whose grid begins inside the splice.
7018                self.rebuild_map();
7019                let first_cell = self
7020                    .vmap
7021                    .tables
7022                    .iter()
7023                    .filter_map(|t| t.grid.first().and_then(|row| row.cells.first()))
7024                    .find(|cell| cell.start >= change.new.start && cell.start < change.new.end)
7025                    .map(|cell| (cell.start, cell.end));
7026                if let Some((start, end)) = first_cell {
7027                    self.select_cell(start, end);
7028                }
7029                self.record_caret();
7030            }
7031            Err(e) => self.status = Some(format!("table: {e}")),
7032        }
7033    }
7034
7035    /// Whether the caret sits in a paragraph and nothing else — no list item, no
7036    /// quote, no fence, no table — with paragraph text still ahead of it. The
7037    /// one shape where parting the block around the caret is unambiguously what
7038    /// a rule button means; see
7039    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
7040    /// container is left to take the rule after itself.
7041    ///
7042    /// The "text ahead" half is what keeps `split_block` from running at the
7043    /// one edge where its output composes badly. At a paragraph's end twig
7044    /// cannot mint the empty second half (no format spells an empty
7045    /// paragraph), so it writes only the separator — a blank line and the
7046    /// slot Enter leaves for the paragraph to come — and a block then aimed at
7047    /// the first half lands above a slot that nothing fills: `para\n` with the
7048    /// caret at 4 came out as `para\n\n* * *\n\n\n`. Trailing whitespace counts
7049    /// as nothing ahead, since the split would shed it as the second half's
7050    /// leading indent and leave the same slot. Which end of the newline a
7051    /// paragraph's span stops at differs between the formats (Markdown before
7052    /// it, djot after), which is why this reads the remaining bytes rather
7053    /// than comparing offsets. The paragraph's
7054    /// start is deliberately not the same case — see
7055    /// [`insert_thematic_break`](Self::insert_thematic_break) for why that
7056    /// split is kept.
7057    fn caret_parts_bare_paragraph(&mut self) -> bool {
7058        let caret = self.caret.min(self.source.len());
7059        let Ok(chain) = self.editor.ancestors_at(caret) else {
7060            return false;
7061        };
7062        let mut para_end = None;
7063        for m in chain {
7064            match m.kind {
7065                Kind::Para => para_end = Some(m.span.end.min(self.source.len())),
7066                Kind::ListItem
7067                | Kind::TaskListItem
7068                | Kind::BlockQuote
7069                | Kind::CodeBlock
7070                | Kind::Table => return false,
7071                _ => {}
7072            }
7073        }
7074        match para_end {
7075            Some(end) if end > caret => !self.source[caret..end].trim().is_empty(),
7076            _ => false,
7077        }
7078    }
7079
7080    /// The destination of the link under the caret — what a Link prompt shows so
7081    /// ⌘K on an existing link edits its URL instead of asking for it again.
7082    /// `None` when the caret stands in no link.
7083    ///
7084    /// An autolink carries no separate destination: its text *is* the URL, so
7085    /// that's what comes back for one.
7086    pub fn link_destination_at_caret(&mut self) -> Option<String> {
7087        self.link_destination_at(self.caret)
7088    }
7089
7090    /// The destination of the link at `off`.
7091    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
7092    /// the caret isn't.
7093    ///
7094    /// The offset form exists for the same reason
7095    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
7096    /// the document somewhere else — a footnote's text in a popover, say — has
7097    /// rows and runs but no caret in them, and still needs to know which of those
7098    /// runs a reader can follow.
7099    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
7100        self.nodes()
7101            .into_iter()
7102            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
7103            .filter(|n| n.span.start <= off && off < n.span.end)
7104            .max_by_key(|n| n.span.start)
7105            .and_then(|n| n.destination.or(n.text))
7106    }
7107
7108    /// The heading the caret is under — the nearest heading at or above it,
7109    /// whatever its level. See [`heading_at`](Self::heading_at).
7110    pub fn heading_at_caret(&mut self) -> Option<Heading> {
7111        self.heading_at(self.caret)
7112    }
7113
7114    /// The heading `off` is under: the last heading that starts at or before
7115    /// it, or the one `off` stands in. `None` above the first heading.
7116    ///
7117    /// The question between [`link_destination_at`](Self::link_destination_at)
7118    /// ("which link is this") and [`locate`](Self::locate) ("where does this
7119    /// fragment land"): a host writing a link *to* a place needs the heading
7120    /// that place is under, to name it by `#slug`. Nearest, not enclosing —
7121    /// a level-3 heading under a level-2 is the answer for the text below the
7122    /// level-3, because it is the finer place to land.
7123    pub fn heading_at(&mut self, off: usize) -> Option<Heading> {
7124        let nodes = self.nodes();
7125        let h = nodes
7126            .iter()
7127            .filter(|n| n.kind == Kind::Heading && n.span.start <= off)
7128            .max_by_key(|n| n.span.start)?;
7129        let mut text = String::new();
7130        inline_text(&nodes, h.first_child, &mut text);
7131        Some(Heading {
7132            text: text.trim().to_string(),
7133            level: h.level.unwrap_or(1),
7134            span: h.span.clone(),
7135        })
7136    }
7137
7138    /// Where the locator `id` lands in this document — the `#v2` half of a
7139    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
7140    /// answers to it.
7141    ///
7142    /// The other end of a link, and the reason this exists: without it a
7143    /// destination has only file granularity, so following a citation into a
7144    /// chapter drops the reader at the top of it to hunt for the verse. Which is
7145    /// also why it is a *document* query rather than a caret one — the document
7146    /// being asked is usually not the one the reader is in.
7147    ///
7148    /// Three readings, tried in order, because the same `#some-heading` is
7149    /// written three ways across the formats leaf opens:
7150    ///
7151    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
7152    ///    the auto-ids djot mints for its headings. The only exact answer, so it
7153    ///    goes first — a document that says `{#v1}` has settled the question.
7154    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
7155    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
7156    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
7157    ///    authored anywhere land on a djot heading.
7158    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
7159    ///    none and `{#custom}` is literal text in a Markdown heading — so for
7160    ///    the format most vaults are written in, the heading's own words are the
7161    ///    only thing a fragment can name. This is the rule every Markdown
7162    ///    renderer already follows, which is what makes `#a-heading` mean in
7163    ///    diaryx what it means on the web.
7164    ///
7165    /// Ties go to the earliest match, then to the widest: a duplicated id is the
7166    /// document's mistake and the first one is the answer every anchor
7167    /// implementation gives, while preferring the wider span picks the section
7168    /// over the heading that opens it — more for a peek to show, same place to
7169    /// land.
7170    pub fn locate(&mut self, id: &str) -> Option<Landing> {
7171        let id = id.trim();
7172        if id.is_empty() {
7173            return None;
7174        }
7175        let nodes = self.nodes();
7176
7177        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
7178        // is picking, among nodes that start together, the one that ends last.
7179        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
7180            matches
7181                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
7182                .map(|n| Landing {
7183                    start: n.span.start,
7184                    end: n.span.end,
7185                })
7186        };
7187
7188        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
7189            return Some(landing);
7190        }
7191        let want = slug(id);
7192        if want.is_empty() {
7193            return None;
7194        }
7195        if let Some(landing) = pick(
7196            &mut nodes
7197                .iter()
7198                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
7199        ) {
7200            return Some(landing);
7201        }
7202
7203        // A heading by its words. Its span is one line, so the end comes from
7204        // where the *section* it opens gives out — the next heading that is not
7205        // under it, or the end of the document. A Markdown heading has no
7206        // section node to ask (twig only builds those for djot), and a peek that
7207        // showed the heading alone would answer "what does that say" with the
7208        // title of the thing it says.
7209        let heading = nodes
7210            .iter()
7211            .filter(|n| n.kind == Kind::Heading)
7212            .filter(|n| {
7213                n.content_span
7214                    .clone()
7215                    .and_then(|s| self.source.get(s))
7216                    .is_some_and(|text| slug(text) == want)
7217            })
7218            .min_by_key(|n| n.span.start)?;
7219        let level = heading.level.unwrap_or(u32::MAX);
7220        let end = nodes
7221            .iter()
7222            .filter(|n| n.kind == Kind::Heading)
7223            .filter(|n| n.span.start > heading.span.start)
7224            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
7225            .map(|n| n.span.start)
7226            .min()
7227            .unwrap_or(self.source.len());
7228        Some(Landing {
7229            start: heading.span.start,
7230            end,
7231        })
7232    }
7233
7234    /// Write a footnote at the caret — the toolbar's Footnote button, and the
7235    /// one gesture in the footnote story that *authors* rather than follows.
7236    ///
7237    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
7238    /// the `[^1]:` definition at the end of the document. Half a footnote is not
7239    /// a footnote — a bare reference with nothing defining it renders as literal
7240    /// brackets — so a single button that wrote only the reference would leave
7241    /// the author to hand-spell the other half in a document that had just
7242    /// stopped showing them what the first half meant. One edit also means one
7243    /// undo takes both back.
7244    ///
7245    /// The definition's body is left empty and **the caret lands in it**, which
7246    /// is the whole point of pressing the button: nobody wants a reference to a
7247    /// note they have not written yet. Getting back to where they were writing
7248    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
7249    /// the same return leg a reader following a reference already uses, so the
7250    /// author is left standing on the near end of a round trip that works.
7251    ///
7252    /// A selection collapses to its *end* rather than being replaced: a
7253    /// reference annotates the words before it, so "select the claim, add a
7254    /// footnote" should mark that claim, not consume it.
7255    pub fn insert_footnote(&mut self) {
7256        if self.read_only || self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
7257            return;
7258        }
7259        let at = self.selection().map_or(self.caret, |(_, end)| end);
7260        self.anchor = None;
7261        self.caret = at;
7262        self.record_caret();
7263        let label = self.next_footnote_label();
7264        match self.editor.insert_footnote(at, &label) {
7265            Ok(change) => {
7266                self.last_edit_kind = None;
7267                self.refresh();
7268                self.anchor = None;
7269                // `change.new` runs from the reference to the end of the
7270                // document, so its start is the `[^1]` just written and
7271                // `footnote_at` resolves it to the note the same way a reader's
7272                // tap does — and to the note's *body*, which is already a caret
7273                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
7274                // and has none), so this needs no snap on top. The fallback is
7275                // the reference's own offset: a format that spelled the pair some
7276                // way leaf can't read back should still leave the caret on the
7277                // edit rather than at the far end of a document it just grew.
7278                self.caret = self
7279                    .footnote_at(change.new.start)
7280                    .and_then(|note| note.offset)
7281                    .unwrap_or(change.new.start);
7282                self.dirty = self.source != self.clean_source;
7283                self.status = None;
7284                self.clamp_caret();
7285                self.record_caret();
7286            }
7287            Err(e) => self.status = Some(format!("footnote: {e}")),
7288        }
7289    }
7290
7291    /// The label to give a footnote the author has not named: the lowest counting
7292    /// number no footnote in the document is already wearing.
7293    ///
7294    /// twig takes the label rather than minting one, because it holds no opinion
7295    /// about what a document's footnotes should be called — and it is right not
7296    /// to. Numbering them is what every author of a numbered note expects, and
7297    /// re-using a taken number would silently point the new reference at somebody
7298    /// else's note (twig reuses an existing definition rather than appending a
7299    /// second one, which is the right rule for citing a note twice on purpose and
7300    /// exactly the wrong accident to have by default).
7301    ///
7302    /// *References* are counted alongside definitions, not just definitions: a
7303    /// document carrying a dangling `[^2]` has a 2 that means something to
7304    /// whoever wrote it, and minting a definition for it here would answer a
7305    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
7306    /// count entirely — they take no number, so they block none.
7307    fn next_footnote_label(&mut self) -> String {
7308        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
7309            .into_iter()
7310            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
7311            .filter_map(|label| label.parse().ok())
7312            .collect();
7313        taken.extend(
7314            self.nodes()
7315                .into_iter()
7316                .filter(|n| n.kind == Kind::FootnoteReference)
7317                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
7318                .filter_map(|label| label.parse::<u32>().ok()),
7319        );
7320        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
7321    }
7322
7323    /// The footnote reference under the caret, resolved to the note it names.
7324    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
7325    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
7326        self.footnote_at(self.caret)
7327    }
7328
7329    /// The footnote reference at `off`, resolved to the note it names — what a
7330    /// frontend shows when a reader activates a `[^1]`.
7331    ///
7332    /// A reference is not a link node, so
7333    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
7334    /// (and should not) answer for one: a link names a destination to leave for,
7335    /// a reference names a note that is already in this document. Following one
7336    /// is a move within the page, which is why this hands back an `offset`
7337    /// rather than something to open.
7338    ///
7339    /// Offset-based rather than caret-only because the gesture that wants this
7340    /// most is the one that must not move the caret: a pointer hovering a `[1]`
7341    /// asks what note it names without disturbing where the reader was typing.
7342    /// The caret is just the offset a click already placed —
7343    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
7344    ///
7345    /// `None` when `off` stands in no reference. A reference whose note the
7346    /// document never defines is *not* `None` — it answers with the label it
7347    /// looked for and no text, which is what lets a frontend say so instead of
7348    /// silently doing nothing.
7349    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
7350        // Innermost-wins by latest start, the rule its link sibling uses.
7351        let span = self
7352            .nodes()
7353            .into_iter()
7354            .filter(|n| n.kind == Kind::FootnoteReference)
7355            .filter(|n| n.span.start <= off && off < n.span.end)
7356            .max_by_key(|n| n.span.start)?
7357            .span;
7358        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();
7359
7360        // The note itself. Definitions are roots beside `doc` rather than
7361        // children of it, so they're asked for directly — see
7362        // `wysiwyg::footnote_definitions`.
7363        let note = wysiwyg::footnote_definitions(&mut self.editor)
7364            .into_iter()
7365            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
7366        let Some(note) = note else {
7367            return Some(FootnoteRef {
7368                label,
7369                text: None,
7370                offset: None,
7371                end: None,
7372            });
7373        };
7374        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
7375        Some(FootnoteRef {
7376            label,
7377            text: body
7378                .clone()
7379                .and_then(|b| self.source.get(b))
7380                .map(str::to_string),
7381            // The body's start, not the definition's — see `FootnoteRef::offset`.
7382            offset: body.clone().map(|b| b.start),
7383            end: body.map(|b| b.end),
7384        })
7385    }
7386
7387    /// The footnote *definition* the caret stands in, and where the reference
7388    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
7389    /// at the caret's offset.
7390    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
7391        self.footnote_definition_at(self.caret)
7392    }
7393
7394    /// The footnote definition spanning `off`, and where the reference that
7395    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
7396    ///
7397    /// The mirror image, deliberately: the same gesture that takes a reader from
7398    /// `[1]` down to the note takes them from the note back up to `[1]`, so
7399    /// following a footnote is a round trip rather than a fall. It needs no
7400    /// memory of how the reader arrived — the document says where the reference
7401    /// is — which is what makes it work for a reader who scrolled to the notes
7402    /// themselves, and what keeps it right after an edit moves either end.
7403    ///
7404    /// `None` when `off` stands in no definition. A definition nothing cites is
7405    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
7406    /// its label and no offset, so a frontend can say "nothing refers to this"
7407    /// rather than offer a jump that goes nowhere.
7408    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
7409        // Definitions are roots beside `doc`, so `nodes()` — which walks the
7410        // document body — never reports one. They're asked for directly, the way
7411        // `footnote_at` asks for the note it resolves to.
7412        //
7413        // Closed at the end, unlike the half-open test its neighbours use. A
7414        // definition's span stops at its last content byte — the newline ending
7415        // the line is outside it — so `span.end` is the caret stop at the end of
7416        // the note's own row, not the first byte of anything after. Excluding it
7417        // meant the one caret an author is guaranteed to have, the one left
7418        // sitting at the end of the note they just typed, was in no definition at
7419        // all: writing a note and then asking to go back to its reference
7420        // answered nothing. Two definitions in a row still can't both match —
7421        // there is a blank line between them — and `max_by_key` decides anyway.
7422        let note = wysiwyg::footnote_definitions(&mut self.editor)
7423            .into_iter()
7424            .filter(|m| m.span.start <= off && off <= m.span.end)
7425            .max_by_key(|m| m.span.start)?;
7426        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();
7427
7428        // The earliest reference carrying this label. `min` rather than a `find`,
7429        // because `nodes()` reports a flattened walk whose order is twig's
7430        // business, not document order. Bound first: the walk needs `&mut self`
7431        // and reading the labels back out needs `&self.source`.
7432        let nodes = self.nodes();
7433        let offset = nodes
7434            .into_iter()
7435            .filter(|n| n.kind == Kind::FootnoteReference)
7436            .filter(|n| {
7437                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
7438            })
7439            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
7440            .map(|n| n.span.start + 2)
7441            .min();
7442        Some(FootnoteDef { label, offset })
7443    }
7444
7445    /// The destination of the image under the caret — what an image prompt shows
7446    /// so editing an existing image starts from its current URL instead of blank,
7447    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
7448    /// `None` when the caret stands in no image. A caret resting just after a
7449    /// block image (its trailing stop) is still "in" it — the half-open span test
7450    /// excludes that offset, which is the intended precision: past the image is
7451    /// past it.
7452    pub fn image_destination_at_caret(&mut self) -> Option<String> {
7453        let off = self.caret;
7454        self.nodes()
7455            .into_iter()
7456            .filter(|n| n.kind == Kind::Image)
7457            .filter(|n| n.span.start <= off && off < n.span.end)
7458            .max_by_key(|n| n.span.start)
7459            .and_then(|n| n.destination)
7460    }
7461
7462    /// The language of the fenced code block the caret stands in — what a
7463    /// language prompt shows so editing it starts from the current value rather
7464    /// than blank. `None` when the caret is in no code block, or in one whose
7465    /// fence carries no language (or an indented block, which has no fence).
7466    pub fn code_language_at_caret(&mut self) -> Option<String> {
7467        let start = self.code_block_start_at_caret()?;
7468        wysiwyg::code_language(&self.source, start)
7469    }
7470
7471    /// Whether the caret stands in a fenced code block — the one a language
7472    /// prompt could edit. A frontend gates its "set language" affordance on this
7473    /// (an indented block, which can't carry a language, reports `false`).
7474    pub fn caret_in_fenced_code(&mut self) -> bool {
7475        self.code_block_start_at_caret()
7476            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
7477    }
7478
7479    /// Set (or clear, with `""`) the language of the fenced code block the caret
7480    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
7481    /// block, and a reported error for a language the format's fence cannot
7482    /// carry.
7483    ///
7484    /// twig rewrites the info string, so the fence's own width — measured
7485    /// against a body neither side touches — is kept, and a language holding a
7486    /// space, a line end or the fence character is refused rather than written
7487    /// out to reparse as something else. Leaf used to splice over the info span
7488    /// itself and `trim()` the input, which handled the one bad case it had
7489    /// thought of.
7490    pub fn set_code_language(&mut self, lang: &str) {
7491        // The read-only gate — this door reaches twig without the splice.
7492        if self.read_only {
7493            return;
7494        }
7495        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
7496            return;
7497        }
7498        if self.code_block_start_at_caret().is_none() {
7499            return;
7500        }
7501        let lang = lang.trim();
7502        // `None` clears the info string; `Some("")` asks for an empty one. Both
7503        // write a bare fence, and the prompt's empty value means "clear".
7504        let want = (!lang.is_empty()).then_some(lang);
7505        self.record_caret();
7506        match self.editor.set_code_language(self.caret, want) {
7507            Ok(_) => {
7508                self.last_edit_kind = None;
7509                self.refresh();
7510                self.anchor = None;
7511                self.dirty = self.source != self.clean_source;
7512                self.status = None;
7513                self.clamp_caret();
7514                self.record_caret();
7515            }
7516            Err(e) => self.status = Some(format!("code language: {e}")),
7517        }
7518    }
7519
7520    /// The `span.start` of the code block covering the caret — the anchor
7521    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
7522    /// in none.
7523    fn code_block_start_at_caret(&mut self) -> Option<usize> {
7524        let off = self.caret;
7525        self.nodes()
7526            .into_iter()
7527            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
7528            .max_by_key(|n| n.span.start)
7529            .map(|n| n.span.start)
7530    }
7531
7532    /// The source range of the text inside the link covering `off` — what sits
7533    /// between its `[` and `]`. `None` when twig reports no link there.
7534    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
7535        self.nodes()
7536            .into_iter()
7537            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
7538            // the other's `span.start`; the link that starts latest at or before
7539            // `off` is the one `off` is actually in.
7540            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
7541            .max_by_key(|n| n.span.start)
7542            .and_then(|n| n.content_span)
7543    }
7544
7545    // ── undo / redo ───────────────────────────────────────────────────────────
7546    // twig owns the history of *bytes* (it owns the buffer) and now carries the
7547    // caret through it too: `record_caret` stashes each state's caret in twig's
7548    // opaque per-step blob, and undo/redo hand it back with the source they
7549    // restore. So leaf keeps no history of its own — no parallel stacks to march
7550    // in lockstep and silently drift out of it.
7551
7552    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
7553    /// where they were when that step began. Whether it did: `false` when
7554    /// there was nothing to undo, the document is read-only, or twig refused —
7555    /// the answer a host composing several histories into one walks on by.
7556    pub fn undo(&mut self) -> bool {
7557        if self.read_only {
7558            return false;
7559        }
7560        // Stepping through the history ends a group: what comes after is not
7561        // part of the step just taken back.
7562        self.close_undo_group();
7563        let (undone, redoable) = (self.undo_steps, self.redo_steps);
7564        match self.editor.undo() {
7565            Ok(Some(change)) => {
7566                self.after_history(change);
7567                // `refresh` counted the restore as an edit; it was a step back.
7568                self.undo_steps = undone.saturating_sub(1);
7569                self.redo_steps = redoable + 1;
7570                true
7571            }
7572            Ok(None) => {
7573                self.undo_steps = 0;
7574                self.status = Some("nothing to undo".into());
7575                false
7576            }
7577            Err(e) => {
7578                self.status = Some(format!("undo: {e}"));
7579                false
7580            }
7581        }
7582    }
7583
7584    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
7585    /// selection back where that step originally left them. Whether it did,
7586    /// as [`undo`](Self::undo) reports.
7587    pub fn redo(&mut self) -> bool {
7588        if self.read_only {
7589            return false;
7590        }
7591        self.close_undo_group();
7592        let (undone, redoable) = (self.undo_steps, self.redo_steps);
7593        match self.editor.redo() {
7594            Ok(Some(change)) => {
7595                self.after_history(change);
7596                // `refresh` counted the restore as an edit; it was a step forward.
7597                self.undo_steps = (undone + 1).min(UNDO_CAP);
7598                self.redo_steps = redoable.saturating_sub(1);
7599                true
7600            }
7601            Ok(None) => {
7602                self.redo_steps = 0;
7603                self.status = Some("nothing to redo".into());
7604                false
7605            }
7606            Err(e) => {
7607                self.status = Some(format!("redo: {e}"));
7608                false
7609            }
7610        }
7611    }
7612
7613    /// Fold the edit just made into the undo step before it — twig's
7614    /// `coalesce_last_undo`, with the `undo_steps` mirror following
7615    /// it. twig merges only when there are two steps to merge. Call it after
7616    /// [`refresh`](Self::refresh) has counted the edit being folded.
7617    ///
7618    /// Inside an [undo group](Self::begin_undo_group) it does nothing: the
7619    /// group's edits are already one step, which [`refresh`](Self::refresh)
7620    /// folds as they come, so a fold here could only reach across the group's
7621    /// start into the step before it.
7622    fn coalesce_last_undo(&mut self) {
7623        if self.undo_group.is_some() {
7624            return;
7625        }
7626        self.fold_last_undo();
7627    }
7628
7629    /// twig's `coalesce_last_undo`, unconditionally, with the mirror following.
7630    fn fold_last_undo(&mut self) {
7631        if self.editor.coalesce_last_undo().is_ok() && self.undo_steps >= 2 {
7632            self.undo_steps -= 1;
7633        }
7634    }
7635
7636    /// Open an undo group: every edit from here to the matching
7637    /// [`end_undo_group`](Self::end_undo_group) is one step, which a single
7638    /// [`undo`](Self::undo) takes back whole and a single [`redo`](Self::redo)
7639    /// puts back — a Replace All over twelve matches, or a Writing Tools
7640    /// session, rather than twelve presses of ⌘Z.
7641    ///
7642    /// Groups nest, and only the outermost end closes one. The step is folded
7643    /// as each edit lands (twig's `coalesce_last_undo`, one edit at a time),
7644    /// so a group of a thousand edits holds one step on the history and never
7645    /// meets twig's cap. Nothing typed before the group folds into it, and
7646    /// nothing typed after: it is a step of its own, even when it is a single
7647    /// edit. A group no edit landed in leaves no step at all.
7648    ///
7649    /// An [`undo`](Self::undo) or [`redo`](Self::redo) closes any open group,
7650    /// whatever its depth — the history has moved, and an edit made after it
7651    /// is not part of the step it moved past. A later `end_undo_group` is
7652    /// then a no-op.
7653    pub fn begin_undo_group(&mut self) {
7654        match &mut self.undo_group {
7655            Some(g) => g.depth += 1,
7656            None => {
7657                self.undo_group = Some(UndoGroup {
7658                    depth: 1,
7659                    has_step: false,
7660                });
7661                // The first edit inside is not a continuation of the typing
7662                // before it.
7663                self.last_edit_kind = None;
7664            }
7665        }
7666    }
7667
7668    /// Close the undo group [`begin_undo_group`](Self::begin_undo_group)
7669    /// opened. A no-op when none is open.
7670    pub fn end_undo_group(&mut self) {
7671        let Some(g) = &mut self.undo_group else {
7672            return;
7673        };
7674        if g.depth > 1 {
7675            g.depth -= 1;
7676        } else {
7677            self.close_undo_group();
7678        }
7679    }
7680
7681    /// Whether an undo group is open.
7682    pub fn in_undo_group(&self) -> bool {
7683        self.undo_group.is_some()
7684    }
7685
7686    /// Close any open group, however deeply nested.
7687    fn close_undo_group(&mut self) {
7688        if self.undo_group.take().is_some() {
7689            // Typing after the group is not a continuation of the last edit
7690            // in it.
7691            self.last_edit_kind = None;
7692        }
7693    }
7694
7695    /// Refresh the cached source and put the caret back where the step being
7696    /// undone/redone had it, clearing any active run.
7697    ///
7698    /// The caret comes from twig's blob for the restored state (what
7699    /// `record_caret` stored). `change` is only the fallback for a state with no
7700    /// blob — a caret at the end of the restored text, which is where this always
7701    /// landed before the blobs were kept. It is the edit site, not where the user
7702    /// was standing, so it's a floor and not the behaviour: undoing should hand
7703    /// back the document *and* the place you were working, which for an edit made
7704    /// anywhere but under the caret are two different places.
7705    fn after_history(&mut self, change: Change) {
7706        self.refresh();
7707        match self
7708            .editor
7709            .caret_blob()
7710            .ok()
7711            .and_then(|b| CaretState::from_blob(&b))
7712        {
7713            Some(state) => {
7714                self.caret = state.caret.min(self.source.len());
7715                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
7716            }
7717            None => {
7718                self.caret = change.new.end.min(self.source.len());
7719                self.anchor = None;
7720            }
7721        }
7722        self.goal_col = None;
7723        self.last_edit_kind = None;
7724        self.dirty = self.source != self.clean_source;
7725        self.status = None;
7726        self.clamp_caret();
7727    }
7728
7729    // ── the file ──────────────────────────────────────────────────────────────
7730
7731    #[cfg(feature = "fs")]
7732    pub fn save(&mut self) {
7733        if self.is_untitled() {
7734            // No path to write and no name to invent: ⌘S on an untitled document
7735            // is a Save As, and only a frontend has a picker to ask with. Say so
7736            // rather than failing at the filesystem with an empty path.
7737            self.status = Some("untitled — save as…".into());
7738            return;
7739        }
7740        let path = self.path.clone();
7741        if self.write(&path) {
7742            self.mark_saved();
7743        }
7744    }
7745
7746    /// Save As: write the document to `path` and *move* it there — `self.path`
7747    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
7748    /// what Save As means; a copy would leave the user editing a document whose
7749    /// name is no longer where their keystrokes go.
7750    ///
7751    /// The move only happens if the bytes actually landed. A failed write leaves
7752    /// the path, `dirty`, and the disk watermark exactly as they were, with the
7753    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
7754    /// must never come away believing it was saved.
7755    ///
7756    /// An existing `path` is overwritten, and the caller is the one that knows
7757    /// whether to ask first: a Save As picker has already run that prompt, and a
7758    /// second confirmation from down here would be the same question twice.
7759    ///
7760    /// `format` does **not** follow the new extension. The buffer is parsed as
7761    /// the format it was opened with, and re-reading it as another one is a
7762    /// conversion — a different, lossy operation that would throw away the undo
7763    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
7764    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
7765    /// until it's reopened.
7766    #[cfg(feature = "fs")]
7767    pub fn save_as(&mut self, path: PathBuf) {
7768        if !self.write(&path) {
7769            return;
7770        }
7771        self.path = path;
7772        self.mark_saved();
7773    }
7774
7775    /// Put `source` on disk at `path`, reporting whether it got there. The one
7776    /// place leaf writes a document, so a save and a Save As can't disagree
7777    /// about what a failure looks like.
7778    #[cfg(feature = "fs")]
7779    fn write(&mut self, path: &Path) -> bool {
7780        match std::fs::write(path, self.source.as_bytes()) {
7781            Ok(()) => true,
7782            Err(e) => {
7783                self.status = Some(format!("save failed: {e}"));
7784                false
7785            }
7786        }
7787    }
7788
7789    /// Re-base the document's saved watermark to the current bytes: clears
7790    /// `dirty`, records `source` as the new clean state (so undoing back to here
7791    /// clears the flag again), and re-stamps the on-disk hash.
7792    ///
7793    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
7794    /// the hook a **filesystem-free host** calls itself once it has persisted
7795    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
7796    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
7797    /// are already where that host wants them, and this just tells the model they
7798    /// are safe.
7799    pub fn mark_saved(&mut self) {
7800        self.clean_source = self.source.clone();
7801        self.dirty = false;
7802        // The bytes on disk are now ours, so this is the new watermark: without
7803        // re-stamping it, every save would report its own work as an external
7804        // change forever after.
7805        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
7806        self.status = Some(format!("saved {}", self.file_name()));
7807    }
7808
7809    /// What the file looks like now against the bytes leaf last read or wrote.
7810    ///
7811    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
7812    /// so this is a filesystem round-trip, not a per-frame question — ask it
7813    /// when a window regains focus, on a timer, or before a save.
7814    ///
7815    /// This *only* reports the file. Whether the document also has unsaved edits
7816    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
7817    /// [`DiskState::Changed`] means a save overwrites someone's work and a
7818    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
7819    /// it has no way to ask — so it hands a frontend both halves and lets it put
7820    /// the question to the person who can answer it.
7821    #[cfg(feature = "fs")]
7822    pub fn disk_state(&self) -> DiskState {
7823        let Some(want) = self.disk_hash else {
7824            return DiskState::Untitled;
7825        };
7826        match std::fs::read(&self.path) {
7827            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
7828            Ok(_) => DiskState::Changed,
7829            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
7830            Err(_) => DiskState::Unreadable,
7831        }
7832    }
7833
7834    /// Re-read the file and replace the document with what's there — the other
7835    /// answer to a [`DiskState::Changed`].
7836    ///
7837    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
7838    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
7839    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
7840    /// document shouldn't have to argue with a guard.
7841    ///
7842    /// **The undo history survives, and the reload is one step in it.** The
7843    /// whole buffer is spliced with the file's bytes through the same door every
7844    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
7845    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
7846    /// swapped the document out from under a reader gives them back what they
7847    /// were looking at, marked dirty, and ^Z again carries on into whatever they
7848    /// had done before it. This used to build a fresh parse and drop the stack,
7849    /// on the reasoning that twig's history belongs to the buffer and these are
7850    /// different bytes; that is true of *rebasing* a step onto them and not of
7851    /// recording the swap itself as one, which is all this is. A splice twig
7852    /// won't take falls back to the fresh parse, and only that path still costs
7853    /// the history.
7854    ///
7855    /// The caret keeps its byte offset, clamped to the new length; the selection
7856    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
7857    /// file changed, so it can't know where the caret "still" is. Clamping keeps
7858    /// it where the user left it in the common case (a change further down the
7859    /// file, or none in the text they're sitting in), and never puts it
7860    /// somewhere invalid. A selection has two such offsets and no such excuse —
7861    /// silently reinterpreting one over changed bytes would arm the *next*
7862    /// keystroke to delete something the user never selected.
7863    ///
7864    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
7865    /// document alone with a status.
7866    #[cfg(feature = "fs")]
7867    pub fn reload(&mut self) {
7868        if self.is_untitled() {
7869            self.status = Some("no file to reload".into());
7870            return;
7871        }
7872        let bytes = match std::fs::read(&self.path) {
7873            Ok(b) => b,
7874            Err(e) => {
7875                self.status = Some(format!("reload failed: {e}"));
7876                return;
7877            }
7878        };
7879        let Ok(source) = String::from_utf8(bytes) else {
7880            self.status = Some("reload failed: file is not UTF-8".into());
7881            return;
7882        };
7883        // Already these bytes — someone saved a file back unchanged, or leaf's
7884        // own write is being read back. Re-baseline against it and stop: a
7885        // splice of the text onto itself would put an undo step on the stack for
7886        // something nobody did.
7887        if source == self.source {
7888            self.disk_hash = Some(hash_bytes(source.as_bytes()));
7889            self.clean_source = source;
7890            self.dirty = false;
7891            self.status = Some(format!("reloaded {}", self.file_name()));
7892            return;
7893        }
7894        let caret = self.caret;
7895        // The pre-reload caret, so undoing the swap puts it back where the
7896        // reader was standing — the same bracketing `splice_exact` does.
7897        self.record_caret();
7898        if self
7899            .editor
7900            .edit_range(0, self.source.len(), &source)
7901            .is_ok()
7902        {
7903            self.refresh();
7904        } else {
7905            // twig wouldn't take the splice. Start over from the bytes, which is
7906            // what this always did, and is the one path that still costs the
7907            // history — `format` is the format this document *is*, not what the
7908            // (unchanged) name now says, see `save_as`.
7909            match new_editor(source.as_bytes(), self.format) {
7910                Ok(editor) => {
7911                    self.editor = editor;
7912                    // A fresh editor, and so a fresh history — with no
7913                    // step in it for an open group to fold into.
7914                    self.undo_steps = 0;
7915                    self.redo_steps = 0;
7916                    if let Some(g) = &mut self.undo_group {
7917                        g.has_step = false;
7918                    }
7919                    self.source = source.clone();
7920                    // Not going through `refresh`, so the revision has to move
7921                    // here or every frontend keeps painting the old file from
7922                    // cache.
7923                    self.revision += 1;
7924                }
7925                Err(e) => {
7926                    self.status = Some(format!("reload failed: {e}"));
7927                    return;
7928                }
7929            }
7930        }
7931        self.disk_hash = Some(hash_bytes(source.as_bytes()));
7932        self.clean_source = self.source.clone();
7933        self.caret = caret.min(self.source.len());
7934        self.anchor = None;
7935        self.goal_col = None;
7936        self.last_edit_kind = None;
7937        self.dirty = false;
7938        self.status = Some(format!("reloaded {}", self.file_name()));
7939        self.clamp_caret();
7940        // And the post-reload caret, so a redo restores it.
7941        self.record_caret();
7942    }
7943
7944    /// Re-read the source from twig after it has changed the document. The one
7945    /// funnel every edit, undo, and redo comes through — so it's where the
7946    /// revision moves, and anything cached against the text dies here.
7947    fn refresh(&mut self) {
7948        if let Ok(s) = self.editor.source_str() {
7949            self.source = s;
7950        }
7951        self.revision += 1;
7952        // An edit is a step onto the history and the end of anything undone;
7953        // `undo`/`redo` come through here too and correct this after.
7954        self.undo_steps = (self.undo_steps + 1).min(UNDO_CAP);
7955        self.redo_steps = 0;
7956        // Inside a group, fold each step into the group's first as it lands.
7957        // Not for `undo`/`redo`, which close the group before they get here.
7958        if let Some(g) = &mut self.undo_group {
7959            if g.has_step {
7960                self.fold_last_undo();
7961            } else {
7962                g.has_step = true;
7963            }
7964        }
7965        self.clamp_caret();
7966    }
7967
7968    /// Whether [`undo`](Self::undo) has a step to take back — for a native
7969    /// Edit menu to enable its item by, and exactly when `undo` would move.
7970    pub fn can_undo(&self) -> bool {
7971        !self.read_only && self.undo_steps > 0
7972    }
7973
7974    /// Whether [`redo`](Self::redo) has an undone step to restore.
7975    pub fn can_redo(&self) -> bool {
7976        !self.read_only && self.redo_steps > 0
7977    }
7978
7979    // ── caret movement ─────────────────────────────────────────────────────────
7980    // `extend` grows the selection (Shift+motion): it pins the anchor on the
7981    // first extended step and moves only the caret; an un-extended motion drops
7982    // the selection.
7983
7984    /// Place the caret at byte `offset` (clamped to a char boundary), extending
7985    /// the selection when `extend` is set. The public form of `move_to`, for a
7986    /// frontend that hit-tests pixels straight to a source offset.
7987    pub fn place_caret(&mut self, offset: usize, extend: bool) {
7988        self.goal_col = None;
7989        let before = self.caret;
7990        // A pixel hit-test can land between the visible caret stops — in the
7991        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
7992        // Snap to the nearest real stop so the caret can't come to rest where it
7993        // would draw in one place and type in another. The `(row, col)` click
7994        // path (`click`) already snaps this way through `offset_of_pos`; the
7995        // source view reaches every byte, so it snaps to nothing.
7996        let target = match self.view {
7997            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
7998            // The source view reaches every byte, so there is no stop to snap
7999            // to — but "every byte" still means every *character* boundary. A
8000            // caret resting inside a multi-byte character draws nowhere real
8001            // and panics the next time anything slices there.
8002            View::Source => self.char_boundary_at_or_before(offset),
8003        };
8004        self.move_to(target, extend);
8005        self.clamp_caret();
8006        self.debug_assert_on_a_stop(before);
8007    }
8008
8009    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
8010    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
8011    /// grab the metadata) while the source view still selects the literal whole.
8012    pub fn select_all(&mut self) {
8013        self.anchor = Some(self.caret_floor());
8014        self.caret = self.source.len();
8015        self.goal_col = None;
8016        self.last_edit_kind = None;
8017        self.status = None;
8018    }
8019
8020    /// Select the word (or whitespace / punctuation run) at `offset` — the
8021    /// double-click gesture. Anchors on the run's start with the caret at its
8022    /// end so a following Shift-motion extends from the far edge.
8023    pub fn select_word_at(&mut self, offset: usize) {
8024        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
8025        self.anchor = Some(s);
8026        self.caret = e;
8027        self.goal_col = None;
8028        self.last_edit_kind = None;
8029        self.status = None;
8030        self.clamp_caret();
8031    }
8032
8033    /// Select the whole enclosing text block (paragraph, heading, list item's
8034    /// text…) at `offset` — the triple-click gesture. Reads the range straight
8035    /// from the AST (twig's `content_span`), so it selects the entire *logical*
8036    /// paragraph even when that paragraph soft-wraps across several visual rows —
8037    /// where a visual-row-based select breaks down, because one source offset at
8038    /// a wrap boundary belongs to two rows at once.
8039    pub fn select_block_at(&mut self, offset: usize) {
8040        let off = offset.min(self.source.len());
8041        let range = self
8042            .editor
8043            .ancestors_at(off)
8044            .ok()
8045            .and_then(|chain| {
8046                // Ancestors run root → deepest; the deepest node that is neither
8047                // an inline span nor a multi-block container is the text block
8048                // the caret sits in (a paragraph, a heading, a code block…).
8049                chain
8050                    .into_iter()
8051                    .rev()
8052                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
8053                    .map(|m| m.content_span.unwrap_or(m.span))
8054            })
8055            .unwrap_or_else(|| source_line_range(&self.source, off));
8056        self.anchor = Some(range.start.min(self.source.len()));
8057        self.caret = range.end.min(self.source.len());
8058        self.goal_col = None;
8059        self.last_edit_kind = None;
8060        self.status = None;
8061        self.clamp_caret();
8062    }
8063
8064    /// Select the exact source range `[start, end)` — anchor at `start`, caret
8065    /// at `end` — without snapping either end to a visible caret stop.
8066    ///
8067    /// The one caret verb that takes a range it was *handed* rather than one it
8068    /// worked out, for a host that already knows the bytes it means: a search
8069    /// hit, an annotation's footprint, a quote re-anchored through
8070    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
8071    /// wrong tool for that, and not by a little — it snaps to the nearest
8072    /// *visible* stop, and where a range butts up against a hidden delimiter
8073    /// the nearest stop is the one before it, so selecting the "needle" of
8074    /// `**needle**` comes back with "needl" and an edit against it strands the
8075    /// "e".
8076    ///
8077    /// What `place_caret` does that is bookkeeping rather than snapping still
8078    /// happens here, because a host handing in a range is not asking to opt out
8079    /// of the invariants:
8080    ///
8081    /// - both ends are clamped into the document and up to
8082    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
8083    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
8084    ///   types into the metadata;
8085    /// - both land on character boundaries, so nothing slices a `é` in half;
8086    /// - the sticky vertical goal column is dropped, and any armed inline mark
8087    ///   disarmed, since a range from outside inherits neither.
8088    ///
8089    /// An empty range is a caret rather than a selection —
8090    /// [`selection`](Self::selection) reports `None` for it, as it does for any
8091    /// anchor that has met the caret.
8092    pub fn select_range(&mut self, start: usize, end: usize) {
8093        let floor = self.caret_floor();
8094        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
8095        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
8096        self.anchor = Some(anchor);
8097        self.caret = caret;
8098        self.goal_col = None;
8099        self.status = None;
8100        self.last_edit_kind = None;
8101        self.clear_pending();
8102    }
8103
8104    /// `offset` itself if it is a character boundary, else the boundary before
8105    /// it. An offset that isn't one draws nowhere real and panics the next time
8106    /// anything slices there.
8107    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
8108        let mut o = offset.min(self.source.len());
8109        while o > 0 && !self.source.is_char_boundary(o) {
8110            o -= 1;
8111        }
8112        o
8113    }
8114
8115    /// The lowest source offset the caret may occupy in the active view. In
8116    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
8117    /// the first rendered offset; the source view reaches everything, so it's 0.
8118    fn caret_floor(&self) -> usize {
8119        match self.view {
8120            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
8121            View::Source => 0,
8122        }
8123    }
8124
8125    /// Land in a table cell with its whole content selected — the anchor at the
8126    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
8127    /// like tabbing into a form field: the text comes up selected, so typing
8128    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
8129    /// end`) collapses to a plain caret home (an empty selection is no selection).
8130    fn select_cell(&mut self, start: usize, end: usize) {
8131        self.select_range(start, end);
8132    }
8133
8134    fn move_to(&mut self, offset: usize, extend: bool) {
8135        if extend {
8136            if self.anchor.is_none() {
8137                self.anchor = Some(self.caret);
8138            }
8139        } else {
8140            self.anchor = None;
8141        }
8142        self.caret = offset.min(self.source.len()).max(self.caret_floor());
8143        self.status = None;
8144        // A caret move ends the current typing/deletion run, so the next edit
8145        // starts a fresh undo group rather than coalescing across the gap.
8146        self.last_edit_kind = None;
8147        // Moving away disarms any sticky mark — "start bold" applies only where
8148        // it was asked for, not wherever the caret next lands.
8149        self.clear_pending();
8150    }
8151
8152    // In the source view, motion walks source bytes / source lines. In the
8153    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
8154    // what steps the caret cleanly over hidden delimiters.
8155
8156    pub fn move_left(&mut self, extend: bool) {
8157        self.goal_col = None;
8158        if !extend && let Some((s, _e)) = self.selection() {
8159            self.move_to(s, false);
8160            return;
8161        }
8162        let target = match self.view {
8163            View::Source => {
8164                if self.caret > 0 {
8165                    prev_boundary(&self.source, self.caret)
8166                } else {
8167                    0
8168                }
8169            }
8170            // Walks caret *stops*, not columns: decoration (a table border, a
8171            // cell's padding) is stepped over in one press, and a hidden
8172            // delimiter never holds the caret up — though the end of a mark's
8173            // content is a stop of its own (`VisualMap::mark_ends`), so
8174            // leaving `**bold**` from past its `**` is a press onto the end of
8175            // the bold and another onto the `d`.
8176            View::Wysiwyg => self
8177                .vmap
8178                .caret_stop_before(self.caret)
8179                .unwrap_or(self.caret),
8180        };
8181        let before = self.caret;
8182        self.move_to(target, extend);
8183        self.debug_assert_on_a_stop(before);
8184    }
8185
8186    pub fn move_right(&mut self, extend: bool) {
8187        self.goal_col = None;
8188        if !extend && let Some((_s, e)) = self.selection() {
8189            self.move_to(e, false);
8190            return;
8191        }
8192        let target = match self.view {
8193            View::Source => {
8194                if self.caret < self.source.len() {
8195                    next_boundary(&self.source, self.caret)
8196                } else {
8197                    self.caret
8198                }
8199            }
8200            View::Wysiwyg => self.vmap.caret_stop_after(self.caret).unwrap_or(self.caret),
8201        };
8202        let before = self.caret;
8203        self.move_to(target, extend);
8204        self.debug_assert_on_a_stop(before);
8205    }
8206
8207    /// Move to the start of the previous word (⌥← / Ctrl+←).
8208    pub fn move_word_left(&mut self, extend: bool) {
8209        self.goal_col = None;
8210        let before = self.caret;
8211        let target = self.word_left_from(self.caret);
8212        self.move_to(target, extend);
8213        self.debug_assert_on_a_stop(before);
8214    }
8215
8216    /// Move to the end of the next word (⌥→ / Ctrl+→).
8217    pub fn move_word_right(&mut self, extend: bool) {
8218        self.goal_col = None;
8219        let before = self.caret;
8220        let target = self.word_right_from(self.caret);
8221        self.move_to(target, extend);
8222        self.debug_assert_on_a_stop(before);
8223    }
8224
8225    // Word boundaries are found in the space the *view* is in. The source view
8226    // walks the source, because there the source is what's rendered. WYSIWYG
8227    // walks the rendered text instead: `**` is invisible to the user, so it has
8228    // to be invisible to word motion too — a caret parked inside one draws in
8229    // the column after `bold` and types two bytes earlier, and a word-delete
8230    // that stops there shreds the markup into `a ** c`.
8231
8232    /// The word boundary to the left of `off` in the active view's space.
8233    fn word_left_from(&self, off: usize) -> usize {
8234        match self.view {
8235            View::Source => prev_word(&self.source, off),
8236            View::Wysiwyg => self.glyph_word_left(off),
8237        }
8238    }
8239
8240    /// The word boundary to the right of `off` in the active view's space.
8241    fn word_right_from(&self, off: usize) -> usize {
8242        match self.view {
8243            View::Source => next_word(&self.source, off),
8244            View::Wysiwyg => self.glyph_word_right(off),
8245        }
8246    }
8247
8248    /// The character class of the glyph drawn at stop `off`.
8249    ///
8250    /// Read from the source, because a stop points at the source byte its glyph
8251    /// came from — the source *is* where the rendered character is written. What
8252    /// makes the walk glyph space rather than source space is that it only ever
8253    /// visits stops, and the hidden bytes between them have none.
8254    fn class_at(&self, off: usize) -> Class {
8255        self.source
8256            .get(off..)
8257            .and_then(|s| s.chars().next())
8258            .map_or(Class::Space, classify)
8259    }
8260
8261    /// [`next_word`] in glyph space: skip any leading separators, then consume
8262    /// the following word run, with the stop table standing in for the source's
8263    /// characters.
8264    fn glyph_word_right(&self, from: usize) -> usize {
8265        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
8266            return from;
8267        };
8268        let mut in_word = false;
8269        loop {
8270            match self.class_at(off) {
8271                Class::Word => in_word = true,
8272                _ if in_word => return off,
8273                _ => {}
8274            }
8275            match self.vmap.stop_after(off) {
8276                Some(next) => off = next,
8277                None => return off,
8278            }
8279        }
8280    }
8281
8282    /// [`prev_word`] in glyph space: skip separators walking left, then consume
8283    /// the preceding word run.
8284    fn glyph_word_left(&self, from: usize) -> usize {
8285        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
8286            return from;
8287        };
8288        let mut in_word = false;
8289        while let Some(prev) = self.vmap.stop_before(off) {
8290            match self.class_at(prev) {
8291                Class::Word => in_word = true,
8292                _ if in_word => return off,
8293                _ => {}
8294            }
8295            off = prev;
8296        }
8297        off
8298    }
8299
8300    /// After a motion that walks the visual map, the caret must be *on* the map.
8301    /// A stop is the only offset where the caret draws and edits in the same
8302    /// place, and it's the invariant both a caret parked inside an emoji and one
8303    /// parked inside a `**` were quietly breaking.
8304    ///
8305    /// Only when the caret actually moved: a walk with nowhere to go leaves it
8306    /// where it was, which is wherever the floor or a frontend put it rather
8307    /// than somewhere this motion chose.
8308    fn debug_assert_on_a_stop(&self, before: usize) {
8309        debug_assert!(
8310            self.view != View::Wysiwyg
8311                || self.vmap.num_rows() == 0
8312                || self.caret == before
8313                || self.vmap.is_stop(self.caret),
8314            "motion left the caret at {}, which is not a caret stop: it would draw in \
8315             one place and type in another",
8316            self.caret
8317        );
8318    }
8319
8320    // Up and Down run off the ends of the document rather than stopping dead at
8321    // them: Up from the first row lands at the document's start, Down from the
8322    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
8323    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
8324    // reaching the end of the text is what a reader means by it.
8325    //
8326    // The views used to disagree here by accident rather than by decision: the
8327    // source view fell into the edge behaviour through `row_col_to_offset`
8328    // clamping an out-of-range row to the end of the string, while WYSIWYG had
8329    // no row below to walk to and did nothing at all. They share the rule now,
8330    // each in its own space — the source view reaches every byte, WYSIWYG only
8331    // the offsets it draws.
8332
8333    pub fn move_up(&mut self, extend: bool) {
8334        let (row, col) = self.caret_pos();
8335        let goal = self.goal_col.unwrap_or(col);
8336        let target = match self.view {
8337            View::Source => match row.checked_sub(1) {
8338                Some(r) => row_col_to_offset(&self.source, r, goal),
8339                None => self.reachable_start(),
8340            },
8341            // A table's border rules are drawn but hold no caret, so Up steps
8342            // over them to the row that does.
8343            View::Wysiwyg => match self.vmap.navigable_above(row) {
8344                Some(r) => self.row_target(r, goal),
8345                None => self.reachable_start(),
8346            },
8347        };
8348        self.step_vertical(target, goal, extend);
8349    }
8350
8351    pub fn move_down(&mut self, extend: bool) {
8352        let (row, col) = self.caret_pos();
8353        let goal = self.goal_col.unwrap_or(col);
8354        let target = match self.view {
8355            View::Source => match self.source_row_below(row) {
8356                Some(r) => row_col_to_offset(&self.source, r, goal),
8357                None => self.reachable_end(),
8358            },
8359            View::Wysiwyg => match self.vmap.navigable_below(row) {
8360                Some(r) => self.row_target(r, goal),
8361                None => self.reachable_end(),
8362            },
8363        };
8364        self.step_vertical(target, goal, extend);
8365    }
8366
8367    /// Land a vertical motion at `target`, latching the `goal` column it aimed
8368    /// with so the rest of the run keeps aiming there.
8369    ///
8370    /// A motion with nowhere to go changes *nothing*, the goal column included:
8371    /// the latch used to run before the early return at the top of the document,
8372    /// so an Up that did nothing still armed a column, and the next Down aimed
8373    /// at one the caret had never been in.
8374    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
8375        let before = self.caret;
8376        if target == before {
8377            return;
8378        }
8379        self.goal_col = Some(goal);
8380        self.move_to(target, extend);
8381        self.debug_assert_on_a_stop(before);
8382    }
8383
8384    /// The source line below `row`, or `None` when `row` is the last one. Lines
8385    /// are counted by newline, so a trailing one leaves a real, empty last line
8386    /// for the caret to sit on — the document ends below it, not on it.
8387    fn source_row_below(&self, row: usize) -> Option<usize> {
8388        let last = self.source.bytes().filter(|&b| b == b'\n').count();
8389        (row < last).then_some(row + 1)
8390    }
8391
8392    /// Where a vertical motion aiming at the `goal` column lands on visual row
8393    /// `r`: the column clamped to the row, mapped to its offset, then held
8394    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
8395    /// column belongs to the row below, and a gutter's column 0 points at the
8396    /// block rather than at this row.
8397    fn row_target(&self, r: usize, goal: usize) -> usize {
8398        let (start, end) = self.row_bounds(r);
8399        self.vmap
8400            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
8401            .clamp(start, end)
8402    }
8403
8404    /// The first and last offsets the caret can reach in the active view.
8405    ///
8406    /// Not the same span in both: the source view shows every byte, so it can
8407    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
8408    /// sits below the first stop, and a document's trailing newline is drawn
8409    /// nowhere and so sits past the last.
8410    fn reachable_start(&self) -> usize {
8411        match self.view {
8412            View::Source => 0,
8413            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
8414        }
8415    }
8416
8417    fn reachable_end(&self) -> usize {
8418        match self.view {
8419            View::Source => self.source.len(),
8420            View::Wysiwyg => self
8421                .vmap
8422                .stop_at_or_before(self.source.len())
8423                .unwrap_or(self.caret),
8424        }
8425    }
8426
8427    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
8428    /// including the space a soft wrap ate off its end, which is drawn on this
8429    /// row however much the offset past it belongs to the next one.
8430    fn row_span(&self, r: usize) -> (usize, usize) {
8431        let start = self
8432            .vmap
8433            .row_start(r)
8434            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
8435        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
8436        (start.min(end), end)
8437    }
8438
8439    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
8440    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
8441    /// this row's last position is the one before it — the offset before the
8442    /// space the wrap ate, where the caret draws just past the row's last word
8443    /// and types there too.
8444    ///
8445    /// Aiming at the shared offset instead is what stalled End: it is the row's
8446    /// last *column*, so End pressed on the row reached it and then read back as
8447    /// the row below's start, where a second press ran on to that row's end and
8448    /// the next to the one after — End walking down the paragraph a row a press.
8449    fn row_bounds(&self, r: usize) -> (usize, usize) {
8450        let (start, end) = self.row_span(r);
8451        let wraps = self
8452            .vmap
8453            .navigable_below(r)
8454            .and_then(|b| self.vmap.row_start(b))
8455            .is_some_and(|off| off == end);
8456        match wraps {
8457            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
8458            false => (start, end),
8459        }
8460    }
8461
8462    /// The `[start, end]` of the line Home and End aim at: the visual row in
8463    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
8464    ///
8465    /// A soft-wrapped row is a line here, because it is one to the eye and the
8466    /// eye is what these keys are aimed by — a reader pressing End means the end
8467    /// of the line they can see. (`select_block_at` wants the opposite and reads
8468    /// the AST for it: a triple-click grabs the whole paragraph, however many
8469    /// rows it folds into.)
8470    fn line_bounds(&self) -> (usize, usize) {
8471        let (row, _) = self.caret_pos();
8472        match self.view {
8473            View::Source => {
8474                let start = line_start(&self.source, row);
8475                (start, line_end_from(&self.source, start))
8476            }
8477            View::Wysiwyg => self.row_bounds(row),
8478        }
8479    }
8480
8481    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
8482    /// *drawn* — what a kill takes.
8483    ///
8484    /// The two part only at a soft wrap, over the space the wrap ate: the caret
8485    /// can't stand after it (that offset opens the row below, and End stopping
8486    /// there would walk), but it is on this row, and a kill that spared it would
8487    /// leave a double space behind where the row's text had been. Deleting it
8488    /// joins nothing — a wrap is drawn, not written.
8489    fn line_span(&self) -> (usize, usize) {
8490        let (row, _) = self.caret_pos();
8491        match self.view {
8492            View::Source => self.line_bounds(),
8493            View::Wysiwyg => self.row_span(row),
8494        }
8495    }
8496
8497    /// The first offset in `[start, end]` holding something other than
8498    /// whitespace, or `end` when the line holds nothing else — where Home aims.
8499    ///
8500    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
8501    /// so a hidden delimiter is never taken for the line's first character (nor
8502    /// landed on), and the source view steps the source it is showing.
8503    fn first_non_space(&self, start: usize, end: usize) -> usize {
8504        let mut off = start;
8505        while off < end {
8506            if self.class_at(off) != Class::Space {
8507                return off;
8508            }
8509            off = match self.view {
8510                View::Source => next_boundary(&self.source, off),
8511                View::Wysiwyg => match self.vmap.stop_after(off) {
8512                    Some(next) => next,
8513                    None => return end,
8514                },
8515            };
8516        }
8517        end
8518    }
8519
8520    /// Home: to the first character on the line, or to column 0 when the caret
8521    /// is already on it — the two-press toggle every editor spells this way.
8522    /// The indentation is somewhere the caret has to be able to reach and almost
8523    /// never where a reader is headed, so it costs the second press.
8524    pub fn move_home(&mut self, extend: bool) {
8525        self.goal_col = None;
8526        let (start, end) = self.line_bounds();
8527        let text = self.first_non_space(start, end);
8528        let target = if self.caret == text { start } else { text };
8529        let before = self.caret;
8530        self.move_to(target, extend);
8531        self.debug_assert_on_a_stop(before);
8532    }
8533
8534    /// End: to the end of the line.
8535    pub fn move_end(&mut self, extend: bool) {
8536        self.goal_col = None;
8537        let (_, end) = self.line_bounds();
8538        let before = self.caret;
8539        self.move_to(end, extend);
8540        self.debug_assert_on_a_stop(before);
8541    }
8542
8543    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
8544    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
8545    /// when the caret isn't in a table, or is already in the last/first cell — the
8546    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
8547    /// meaning everywhere else.
8548    pub fn cell_hop(&mut self, forward: bool) -> bool {
8549        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8550            return false;
8551        };
8552        // Flatten to document (row-major) order and step one cell either way.
8553        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
8554        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
8555        let next = if forward {
8556            i.checked_add(1)
8557        } else {
8558            i.checked_sub(1)
8559        };
8560        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
8561            return false; // at the table's edge; leave Tab to the frontend
8562        };
8563        self.select_cell(start, end);
8564        true
8565    }
8566
8567    /// Move the caret to the cell directly above (`down == false`) or below in
8568    /// the same column, landing with the cell's whole content selected (see
8569    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
8570    /// when the caret isn't in a table), so the frontend can fall through — the
8571    /// vertical counterpart of [`Self::cell_hop`].
8572    ///
8573    /// A ragged row that is short a column clamps to its last cell, so Down never
8574    /// falls out of the table over a gap the row above happened to have.
8575    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
8576        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8577            return false;
8578        };
8579        let target = match down {
8580            true => r + 1,
8581            false if r == 0 => return false,
8582            false => r - 1,
8583        };
8584        let Some(row) = grid.get(target) else {
8585            return false;
8586        };
8587        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
8588            return false;
8589        };
8590        self.select_cell(start, end);
8591        true
8592    }
8593
8594    /// The table containing `off` as a row-major grid of `(start, end)` cell
8595    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
8596    /// isn't in a table. Read straight off the visual map's laid-out grid, so
8597    /// every cell (an empty one included, whose derived home twig gives no
8598    /// `content_span` for) is present and in the order Tab walks them.
8599    // Grid, row, column — three returns that only ever travel together, and a
8600    // named type for the pair of them would be read at one call site.
8601    #[allow(clippy::type_complexity)]
8602    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
8603        for t in &self.vmap.tables {
8604            let mut pos = None;
8605            let grid: Vec<Vec<(usize, usize)>> = t
8606                .grid
8607                .iter()
8608                .enumerate()
8609                .map(|(r, row)| {
8610                    row.cells
8611                        .iter()
8612                        .enumerate()
8613                        .map(|(c, cell)| {
8614                            if pos.is_none() && off >= cell.start && off <= cell.end {
8615                                pos = Some((r, c));
8616                            }
8617                            (cell.start, cell.end)
8618                        })
8619                        .collect()
8620                })
8621                .collect();
8622            if let Some((r, c)) = pos {
8623                return Some((grid, r, c));
8624            }
8625        }
8626        None
8627    }
8628
8629    // ── table key policy ──────────────────────────────────────────────────────
8630    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
8631    // as one policy every frontend shares, rather than each re-deriving it. Each
8632    // reports whether it acted *as a table key*; a `false` hands the key back to
8633    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
8634    // everywhere else.
8635
8636    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
8637    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
8638    /// back and simply stays put at the very first cell. `false` when the caret
8639    /// isn't in a table.
8640    pub fn cell_tab(&mut self, forward: bool) -> bool {
8641        if !self.caret_in_table() {
8642            return false;
8643        }
8644        if self.cell_hop(forward) {
8645            return true;
8646        }
8647        // Off the last cell: grow the table by a row and step into its first
8648        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
8649        if forward {
8650            self.append_row_and_enter(0);
8651        }
8652        true
8653    }
8654
8655    /// Return inside a table: drop to the cell below in the same column,
8656    /// appending a new row when the caret is already in the last one. `false`
8657    /// when the caret isn't in a table, so the frontend inserts a newline.
8658    pub fn cell_return(&mut self) -> bool {
8659        if !self.caret_in_table() {
8660            return false;
8661        }
8662        if self.cell_move_vertical(true) {
8663            return true;
8664        }
8665        // Already on the last row: grow one below and drop into the same column.
8666        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
8667        self.append_row_and_enter(col);
8668        true
8669    }
8670
8671    /// Append a row below the caret's (last) row and land in `col` of it. The
8672    /// caret is in the last row, so twig's "insert below" makes the fresh row the
8673    /// table's new last — but twig re-spells the whole table, moving every byte,
8674    /// so the destination is read back from the rebuilt grid by the table's
8675    /// position (stable across a row insert), not from the pre-edit caret.
8676    fn append_row_and_enter(&mut self, col: usize) {
8677        let table = self.caret_table_index();
8678        self.table_insert_row(true);
8679        self.rebuild_map();
8680        let Some((start, end)) = table
8681            .and_then(|ti| self.vmap.tables.get(ti))
8682            .and_then(|t| t.grid.last())
8683            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
8684            .map(|cell| (cell.start, cell.end))
8685        else {
8686            return;
8687        };
8688        self.select_cell(start, end);
8689    }
8690
8691    /// The index, among the document's tables, of the one the caret sits in —
8692    /// `None` when it's in none. Used to re-find a table after an edit re-spells
8693    /// it (a row insert leaves the table order unchanged).
8694    fn caret_table_index(&self) -> Option<usize> {
8695        let off = self.caret;
8696        self.vmap.tables.iter().position(|t| {
8697            t.grid
8698                .iter()
8699                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
8700        })
8701    }
8702
8703    /// Shift+Return inside a table: insert a hard line break *within* the current
8704    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
8705    /// table, so the frontend inserts an ordinary line break.
8706    ///
8707    /// A table row is a single source line, so the newline-spelled hard break
8708    /// can't live in a cell. twig spells the in-cell break the format's way
8709    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
8710    /// break round-trips as structure the renderer reads back as a line — not the
8711    /// opaque raw HTML the old raw-splice left behind.
8712    ///
8713    /// Djot has no idiomatic in-cell break, so twig refuses it
8714    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
8715    /// would render as the literal text `<br>`. The gesture is still *consumed*
8716    /// there — returning `false` would let the frontend insert a real newline,
8717    /// which splits the one-line row — it just leaves the cell unchanged and says
8718    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
8719    ///
8720    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
8721    /// have to be read together: djot is not the only `false`, and naming it in
8722    /// the message was already a guess that HTML — which spells the break as its
8723    /// own `<br>` — would have made wrong.
8724    pub fn cell_line_break(&mut self) -> bool {
8725        if self.read_only || !self.caret_in_table() {
8726            return false;
8727        }
8728        self.record_caret();
8729        match self.editor.insert_line_break(self.caret) {
8730            Ok(change) => {
8731                self.last_edit_kind = None;
8732                self.refresh();
8733                self.caret = change.new.end;
8734                self.anchor = None;
8735                self.goal_col = None;
8736                self.clamp_caret();
8737                self.dirty = self.source != self.clean_source;
8738                self.status = None;
8739                self.record_caret();
8740            }
8741            Err(twig::Error::UnsupportedFormat) => {
8742                self.status = Some(format!(
8743                    "in-cell line breaks aren't supported in {}",
8744                    self.format_name()
8745                ));
8746            }
8747            Err(_) => {}
8748        }
8749        true
8750    }
8751
8752    /// Rebuild the visual map at the width the last build used. A structural edit
8753    /// bumps the revision and swaps the source in, but leaves the *map* stale;
8754    /// when a single gesture edits and then moves over the result (Tab appending
8755    /// a row, then stepping into it), the move needs the map to already show the
8756    /// edit rather than waiting for the frontend's next frame.
8757    fn rebuild_map(&mut self) {
8758        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
8759        self.build_map(wrap);
8760    }
8761
8762    /// Move the caret to the very start of the document (⌘↑ on macOS,
8763    /// Ctrl+Home on Windows/Linux).
8764    pub fn move_doc_start(&mut self, extend: bool) {
8765        self.goal_col = None;
8766        self.move_to(0, extend);
8767    }
8768
8769    /// Move the caret to the very end of the document (⌘↓ on macOS,
8770    /// Ctrl+End on Windows/Linux).
8771    pub fn move_doc_end(&mut self, extend: bool) {
8772        self.goal_col = None;
8773        let end = self.source.len();
8774        self.move_to(end, extend);
8775    }
8776
8777    /// Point the caret at the body cell `(row, col)` the mouse landed on —
8778    /// `col` being a cell of the terminal grid, which is what a display column
8779    /// is. A click on the far cell of a wide character lands at that
8780    /// character's start; the mapping's own doc-comments carry the rule.
8781    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
8782        self.goal_col = None;
8783        let target = match self.view {
8784            View::Source => row_col_to_offset(&self.source, row, col),
8785            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
8786        };
8787        let before = self.caret;
8788        self.move_to(target, extend);
8789        self.debug_assert_on_a_stop(before);
8790    }
8791
8792    /// A click in the blank space under the document's last block.
8793    ///
8794    /// Not a click *on* anything, so it lands on nothing in particular: the
8795    /// caret goes onto an empty paragraph under the last block, wherever the
8796    /// pointer was horizontally — and if the document does not end with one,
8797    /// one is opened, which is the only way to get out from under a block Enter
8798    /// cannot leave. Enter inside a fenced code block is a literal newline (see
8799    /// [`newline`](Self::newline)), so a document that *ends* in a fence had no
8800    /// way out at all; and a click under any last block used to land at the
8801    /// pointer's x on the block's last line, which is what a click on that line
8802    /// means and not what a click under it does.
8803    ///
8804    /// "Ends with an empty paragraph" is two trailing newlines: the first closes
8805    /// the last line and the second opens the blank line the visual map lays
8806    /// out as a navigable empty row (see `emit_trailing_blank_lines`). A
8807    /// document ending inside an *unclosed* fence gets the fence closed first,
8808    /// since a newline written there would only be another line of code. An
8809    /// empty document has nothing to be under, and the caret simply goes to its
8810    /// start.
8811    ///
8812    /// In the source view the gesture is the ordinary one: the caret goes to the
8813    /// end of the source, and nothing is written. A read-only document likewise.
8814    pub fn click_past_end(&mut self) {
8815        self.goal_col = None;
8816        let len = self.source.len();
8817        if self.view == View::Source || self.read_only || self.source.trim().is_empty() {
8818            self.move_to(len, false);
8819            return;
8820        }
8821        let mut tail = String::new();
8822        if let Some(fence) = self.unclosed_fence_at_end() {
8823            if !self.source.ends_with('\n') {
8824                tail.push('\n');
8825            }
8826            tail.push_str(&fence);
8827            tail.push('\n');
8828        }
8829        let joined = format!("{}{tail}", self.source);
8830        let trailing = joined.len() - joined.trim_end_matches('\n').len();
8831        for _ in trailing..2 {
8832            tail.push('\n');
8833        }
8834        if !tail.is_empty() && !self.splice(len, len, &tail, EditKind::Other) {
8835            return;
8836        }
8837        let end = self.source.len();
8838        self.move_to(end, false);
8839    }
8840
8841    /// The closing fence a document ending inside an unclosed fenced code block
8842    /// needs — the opening fence's own run, behind the quote prefix the block
8843    /// wears — or `None` when the last block is closed, indented, or not a code
8844    /// block at all.
8845    ///
8846    /// Unclosed is when twig's content span reaches the block's end: a closing
8847    /// fence line would lie between the two. `code_info_span`'s read of the
8848    /// fence is not used because it starts at the block's span, which inside a
8849    /// quote is the quote marker rather than the fence.
8850    fn unclosed_fence_at_end(&mut self) -> Option<String> {
8851        let content_end = self.source.trim_end_matches('\n').len();
8852        let block = self
8853            .nodes()
8854            .into_iter()
8855            .filter(|n| n.kind == Kind::CodeBlock && n.span.end >= content_end)
8856            .max_by_key(|n| n.span.start)?;
8857        if block.content_span.as_ref()?.end < block.span.end {
8858            return None;
8859        }
8860        let line = self.source[block.span.start..].lines().next()?;
8861        let opening = line.trim_start_matches(['>', ' ', '\t']);
8862        let fence = opening.chars().next().filter(|c| matches!(c, '`' | '~'))?;
8863        let run: String = opening.chars().take_while(|&c| c == fence).collect();
8864        let prefix = self.quote_prefix_at(block.span.start);
8865        Some(format!("{prefix}{run}"))
8866    }
8867
8868    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
8869    /// screen if it has moved since the last frame, and never scroll past the
8870    /// last of `rows`.
8871    ///
8872    /// Only if it has *moved* — that's the whole point. Revealing the caret on
8873    /// every frame ties the viewport to it, and a scroll wheel that fights the
8874    /// caret for the viewport loses: the view snaps back the instant it tries to
8875    /// pass the caret's row, so the document can't be scrolled beyond what's
8876    /// already on screen. A caret move is the frontend's cue to follow; a scroll
8877    /// with the caret sitting still is the reader's cue to leave it alone.
8878    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
8879        if self.drawn_caret != Some(self.caret) {
8880            if caret_row < self.scroll {
8881                self.scroll = caret_row;
8882            } else if height > 0 && caret_row >= self.scroll + height {
8883                self.scroll = caret_row + 1 - height;
8884            }
8885            self.drawn_caret = Some(self.caret);
8886        }
8887        self.scroll = self.scroll.min(rows.saturating_sub(1));
8888    }
8889
8890    /// The caret's screen position `(row, col)` in the active view's grid, with
8891    /// `col` a display column: the cell to draw the caret in, which on a line of
8892    /// `你好` or emoji is not the count of characters before it.
8893    pub fn caret_pos(&self) -> (usize, usize) {
8894        match self.view {
8895            View::Source => offset_to_row_col(&self.source, self.caret),
8896            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
8897        }
8898    }
8899
8900    fn clamp_caret(&mut self) {
8901        if self.caret > self.source.len() {
8902            self.caret = self.source.len();
8903        }
8904        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
8905        // any selection anchor) to the first rendered offset.
8906        let floor = self.caret_floor();
8907        if self.caret < floor {
8908            self.caret = floor;
8909        }
8910        if let Some(a) = self.anchor
8911            && a < floor
8912        {
8913            self.anchor = Some(floor);
8914        }
8915        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
8916            self.caret -= 1;
8917        }
8918    }
8919}
8920
8921// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
8922
8923// Left/right motion and backspace/delete step by *grapheme cluster*, not
8924// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
8925// marks moves and deletes as the single character a user sees. Grapheme
8926// boundaries are a superset of char boundaries, so the caret stays valid for twig.
8927
8928/// How an insert of `text` groups for undo: a single typed character folds into
8929/// the run of typing around it, while a newline or a multi-character insert is a
8930/// step of its own.
8931fn typed_edit_kind(text: &str) -> EditKind {
8932    if text.chars().take(2).count() == 1 && text != "\n" {
8933        EditKind::Insert
8934    } else {
8935        EditKind::Other
8936    }
8937}
8938
8939fn prev_boundary(s: &str, i: usize) -> usize {
8940    let mut cursor = GraphemeCursor::new(i, s.len(), true);
8941    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
8942}
8943
8944fn next_boundary(s: &str, i: usize) -> usize {
8945    let mut cursor = GraphemeCursor::new(i, s.len(), true);
8946    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
8947}
8948
8949// ── word boundaries ──────────────────────────────────────────────────────────
8950// The shared primitive behind word-wise motion, word deletion, and
8951// double-click-to-select-a-word. A "word" is a maximal run of one character
8952// class; whitespace and punctuation are their own classes, so motion skips
8953// cleanly between them the way native text fields do.
8954
8955#[derive(PartialEq, Eq, Clone, Copy)]
8956enum Class {
8957    Word,
8958    Space,
8959    Other,
8960}
8961
8962/// The source range of an inline node's own visible text — the part of it a
8963/// WYSIWYG caret can reach, as against the delimiters that only spell it.
8964/// `None` for a node with no interior to empty (a `str`, a break).
8965///
8966/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
8967/// one delimiter in from the span — the same place the renderer maps it to. A
8968/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
8969/// against the source rather than trusted: a range guessed wrong here is text
8970/// deleted wrong.
8971fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
8972    if let Some(span) = n.content_span.clone() {
8973        return Some(span);
8974    }
8975    match n.kind.as_str() {
8976        "verbatim" | "inline_math" => {
8977            let text = n.text.as_ref()?;
8978            let start = n.span.start + 1;
8979            let range = start..start + text.len();
8980            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
8981        }
8982        _ => None,
8983    }
8984}
8985
8986/// The `id` a node declares, or `None` for one that declares none — the
8987/// attribute djot writes for a `{#v1}` and mints for a heading.
8988///
8989/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
8990/// names nothing, so it reads as absent rather than as the empty string.
8991fn declared_id(n: &FlatNode) -> Option<&str> {
8992    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
8993}
8994
8995/// A heading's words reduced to the form a link fragment spells them in:
8996/// lowercase, runs of anything else collapsed to a single `-`, with none left
8997/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
8998///
8999/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
9000/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
9001/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
9002/// any other language is still a heading someone will link to. Underscores
9003/// survive for the same reason they do on the web: they are word characters
9004/// wherever identifiers are written.
9005fn slug(text: &str) -> String {
9006    let mut out = String::new();
9007    let mut pending = false;
9008    for c in text.chars() {
9009        if c.is_alphanumeric() || c == '_' {
9010            if pending && !out.is_empty() {
9011                out.push('-');
9012            }
9013            pending = false;
9014            out.extend(c.to_lowercase());
9015        } else {
9016            pending = true;
9017        }
9018    }
9019    out
9020}
9021
9022/// The text of the inline run starting at `first` and its siblings, markup
9023/// stripped: each leaf's payload in order, a line break as a space. `nodes` is
9024/// the arena `Doc::nodes` returns, indexed by id.
9025fn inline_text(nodes: &[FlatNode], first: Option<NodeId>, out: &mut String) {
9026    let mut next = first;
9027    while let Some(id) = next {
9028        let Some(n) = nodes.get(id.0 as usize) else {
9029            return;
9030        };
9031        match (&n.text, &n.kind) {
9032            (Some(text), _) => out.push_str(text),
9033            (None, Kind::SoftBreak | Kind::HardBreak) => out.push(' '),
9034            (None, _) => inline_text(nodes, n.first_child, out),
9035        }
9036        next = n.next_sibling;
9037    }
9038}
9039
9040fn is_block_container(kind: &Kind) -> bool {
9041    matches!(
9042        kind,
9043        Kind::Doc
9044            | Kind::Section
9045            | Kind::BlockQuote
9046            | Kind::BulletList
9047            | Kind::OrderedList
9048            | Kind::TaskList
9049            | Kind::ListItem
9050            | Kind::TaskListItem
9051            // Every `container` — a directive in any of its three forms, or a
9052            // promoted HTML element. A *text* directive is really inline, so
9053            // claiming it here is a small overreach, and the deliberate one this
9054            // function's kind-only peer `is_inline_kind` documents: the pair is
9055            // consulted together, and answering "block container" for something
9056            // inline is what keeps an ancestor walk from stopping short of the
9057            // paragraph that actually holds it.
9058            | Kind::Container
9059    )
9060}
9061
9062/// The `[start, end)` byte range of the source line containing `off` (newline
9063/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
9064/// line between paragraphs).
9065fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
9066    let off = off.min(s.len());
9067    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
9068    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
9069    start..end
9070}
9071
9072/// How many leading bytes an outdent takes off `line`: a whole indent level
9073/// where the line has one, and whatever it has where it has less.
9074///
9075/// A leading tab counts as a level on its own. It's indentation some other
9076/// editor wrote, and one tab is one level everywhere it came from — measuring it
9077/// in spaces it doesn't contain would leave it untouchable.
9078fn outdent_width(line: &str, unit: usize) -> usize {
9079    if line.starts_with('\t') {
9080        return 1;
9081    }
9082    line.bytes().take(unit).take_while(|b| *b == b' ').count()
9083}
9084
9085/// A list marker found at the head of a line, together with everything before it
9086/// that a sibling line has to repeat.
9087///
9088/// The three offsets differ only inside a block quote, where `>   - b` opens with
9089/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
9090/// `line_start == marker_start`, and `text` is the plain `"  - "`.
9091#[derive(Clone, Debug)]
9092struct ListMarker {
9093    /// The line's first byte.
9094    line_start: usize,
9095    /// Where the marker proper begins, past any quote prefix. The offset to hand
9096    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
9097    marker_start: usize,
9098    /// `line_start` through the marker's trailing space — quote prefix, indent
9099    /// and bullet together, which is what the next item's line opens with.
9100    text: String,
9101}
9102
9103impl ListMarker {
9104    /// Where the item's content starts — one past the marker's trailing space.
9105    fn content_start(&self) -> usize {
9106        self.line_start + self.text.len()
9107    }
9108}
9109
9110fn classify(c: char) -> Class {
9111    if c == '_' || c.is_alphanumeric() {
9112        Class::Word
9113    } else if c.is_whitespace() {
9114        Class::Space
9115    } else {
9116        Class::Other
9117    }
9118}
9119
9120/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
9121/// skip any leading separators, then consume the following word run.
9122fn next_word(s: &str, i: usize) -> usize {
9123    let mut off = i;
9124    let mut in_word = false;
9125    for c in s[i..].chars() {
9126        if classify(c) == Class::Word {
9127            in_word = true;
9128        } else if in_word {
9129            break;
9130        }
9131        off += c.len_utf8();
9132    }
9133    off
9134}
9135
9136/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
9137/// skip separators walking left, then consume the preceding word run.
9138fn prev_word(s: &str, i: usize) -> usize {
9139    let mut off = i;
9140    let mut in_word = false;
9141    for c in s[..i].chars().rev() {
9142        if classify(c) == Class::Word {
9143            in_word = true;
9144        } else if in_word {
9145            break;
9146        }
9147        off -= c.len_utf8();
9148    }
9149    off
9150}
9151
9152/// The `[start, end)` run of same-class characters surrounding `off` — the
9153/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
9154/// the run ending there is used.
9155fn word_range_at(s: &str, off: usize) -> (usize, usize) {
9156    if s.is_empty() {
9157        return (0, 0);
9158    }
9159    let off = off.min(s.len());
9160    let reference = if off < s.len() {
9161        s[off..].chars().next()
9162    } else {
9163        s[..off].chars().next_back()
9164    };
9165    let Some(rc) = reference else {
9166        return (off, off);
9167    };
9168    let class = classify(rc);
9169
9170    let mut start = off;
9171    for c in s[..start].chars().rev() {
9172        if classify(c) == class {
9173            start -= c.len_utf8();
9174        } else {
9175            break;
9176        }
9177    }
9178    let mut end = off;
9179    for c in s[end..].chars() {
9180        if classify(c) == class {
9181            end += c.len_utf8();
9182        } else {
9183            break;
9184        }
9185    }
9186    (start, end)
9187}
9188
9189/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
9190/// the line's start — terminal cells, not characters, so the column names the
9191/// cell the caret is drawn in even on a line of `你好` or emoji.
9192fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
9193    let off = off.min(s.len());
9194    let mut row = 0;
9195    let mut line_start = 0;
9196    for (i, &b) in s.as_bytes().iter().enumerate() {
9197        if i >= off {
9198            break;
9199        }
9200        if b == b'\n' {
9201            row += 1;
9202            line_start = i + 1;
9203        }
9204    }
9205    (row, wysiwyg::text_width(&s[line_start..off]))
9206}
9207
9208/// The byte offset at display column `col` of `row` (clamped to that line's
9209/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
9210///
9211/// A column landing *inside* a character — the second cell of `你`, or any cell
9212/// but the first of an emoji — resolves to that character's start, which is the
9213/// column the caret would have been drawn at to begin with. So both cells of a
9214/// wide character mean the character, and every offset survives the round trip
9215/// out to a column and back. The walk steps by grapheme cluster for the same
9216/// reason the caret does: a cluster is the character, and the cells belong to it
9217/// rather than to the codepoints spelling it.
9218fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
9219    let start = line_start(s, row);
9220    let end = line_end_from(s, start);
9221    let mut off = start;
9222    let mut at = 0; // the display column `off` sits at
9223    while off < end {
9224        let next = next_boundary(s, off).min(end);
9225        let cells = wysiwyg::text_width(&s[off..next]);
9226        if at + cells > col {
9227            break; // `col` is one of this cluster's own cells
9228        }
9229        at += cells;
9230        off = next;
9231    }
9232    off
9233}
9234
9235fn line_start(s: &str, row: usize) -> usize {
9236    if row == 0 {
9237        return 0;
9238    }
9239    let mut r = 0;
9240    for (i, &b) in s.as_bytes().iter().enumerate() {
9241        if b == b'\n' {
9242            r += 1;
9243            if r == row {
9244                return i + 1;
9245            }
9246        }
9247    }
9248    s.len()
9249}
9250
9251fn line_end_from(s: &str, start: usize) -> usize {
9252    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
9253}
9254
9255/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
9256/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
9257/// twig applies writing the mark out, so the toolbar can light the same button
9258/// that made the node.
9259///
9260/// `None` for every other kind, including the inline nodes that aren't marks at
9261/// all (`str`, `link`, `image`, the math and break kinds): they're things a
9262/// caret stands in, not formatting a button toggles.
9263/// Whether a match from an ancestor chain is an inline run whose delimiters
9264/// the rich view draws nothing for — a mark (`**`, `_`, `==`), or an
9265/// attributed span: `<span data-size="large">…</span>`, djot's `[…]{…}`. The
9266/// span is a [`Kind::Container`], which the kind alone cannot tell from a
9267/// block `<div>`, so the chain's caller passes [`Doc::run_span_ids`] and the
9268/// answer is the node's own. Every delete and caret step that walks over a
9269/// `**` walks over a span's tags by this test; without it Backspace after
9270/// `</span>` took the `>` and left the paragraph unparseable.
9271fn hides_delims(m: &QueryMatch, run_spans: &[NodeId]) -> bool {
9272    inline_kind(&m.kind).is_some() || run_spans.contains(&NodeId(m.node_id))
9273}
9274
9275fn inline_kind(kind: &Kind) -> Option<InlineKind> {
9276    Some(match kind {
9277        Kind::Strong => InlineKind::Strong,
9278        Kind::Emph => InlineKind::Emph,
9279        Kind::Verbatim => InlineKind::Verbatim,
9280        Kind::Mark => InlineKind::Mark,
9281        Kind::Superscript => InlineKind::Superscript,
9282        Kind::Subscript => InlineKind::Subscript,
9283        Kind::Insert => InlineKind::Insert,
9284        Kind::Delete => InlineKind::Delete,
9285        _ => return None,
9286    })
9287}
9288
9289/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
9290/// a highlight's opening `==`.
9291///
9292/// Two enums for one closed vocabulary, and the duplication is the boundary
9293/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
9294/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
9295/// the editor writes. Spelled as a match rather than routed through the two
9296/// crates' name strings so that a colour added on either side is a compile
9297/// error here, where the pairing is decided, rather than a runtime `None` that
9298/// would read as "clear the colour".
9299fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
9300    match color {
9301        MarkColor::Red => twig::MarkColor::Red,
9302        MarkColor::Orange => twig::MarkColor::Orange,
9303        MarkColor::Yellow => twig::MarkColor::Yellow,
9304        MarkColor::Green => twig::MarkColor::Green,
9305        MarkColor::Blue => twig::MarkColor::Blue,
9306        MarkColor::Purple => twig::MarkColor::Purple,
9307        MarkColor::Brown => twig::MarkColor::Brown,
9308    }
9309}
9310
9311/// Where an offset lands after a splice it didn't make — twig's own rule, from
9312/// [`Change`]: shift anything at or past the replaced range's end by the length
9313/// the replacement gained or lost, and leave anything before it alone.
9314///
9315/// An offset *inside* the replaced range has no text of its own to ride any
9316/// more, and lands at the end of what replaced it: for
9317/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
9318/// the prefix is cleared, which then sits where the highlighted text begins.
9319/// One node's attribute list, twig's own `(key, value)` pairs owned — what
9320/// every presentation gesture reads, edits one key of, and passes back whole.
9321type Attrs = Vec<(String, Option<String>)>;
9322
9323/// The name of the leaf directive a page break is — [`Doc::insert_page_break`]
9324/// writes it and the walker draws it, and a frontend that paginates matches a
9325/// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) against it. One spelling,
9326/// stated once.
9327pub const PAGE_BREAK: &str = "page-break";
9328
9329/// `attrs` with `key` set to `value`, or removed when `value` is `None`, and
9330/// every other attribute kept in its place — the read-edit-write half of twig's
9331/// replace-not-merge contract for a `data-` key.
9332///
9333/// **A key that is already there is rewritten where it stands**, and only a key
9334/// the node did not have goes on the end. That is what makes the proposal's
9335/// worked example true: `class="lead center" id="intro"
9336/// data-line-height="1.5"`, right-aligned, is `class="lead right" id="intro"
9337/// data-line-height="1.5"` — the same document with one token changed, and a
9338/// one-line diff. Removing the key and pushing it back would reorder the
9339/// author's attributes on every press, so a document that passed through the
9340/// editor came out shuffled even where nothing about it had changed.
9341///
9342/// A duplicate key — which no format leaf opens can spell, but twig reports
9343/// verbatim — collapses onto the first of its copies, since twig is handed one
9344/// value for one key either way.
9345fn with_attr(attrs: &[(String, Option<String>)], key: &str, value: Option<&str>) -> Attrs {
9346    let mut out: Attrs = Vec::with_capacity(attrs.len() + 1);
9347    let mut written = false;
9348    for (k, v) in attrs {
9349        if k != key {
9350            out.push((k.clone(), v.clone()));
9351            continue;
9352        }
9353        if let Some(new) = value.filter(|_| !written) {
9354            out.push((k.clone(), Some(new.to_string())));
9355            written = true;
9356        }
9357    }
9358    if let Some(new) = value.filter(|_| !written) {
9359        out.push((key.to_string(), Some(new.to_string())));
9360    }
9361    out
9362}
9363
9364/// [`with_attr`] for a `class` token: every token `mine` claims is removed, and
9365/// `token` added, with the rest of the list kept in order.
9366///
9367/// `class` is a space-separated token list, and leaf owns three of the tokens in
9368/// it. A paragraph that arrives as `class="lead center"` and is right-aligned
9369/// goes out as `class="lead right"`; one whose last owned token goes and which
9370/// carried nothing else loses the key, so a block that has lost its whole
9371/// vocabulary is spelled bare again. `class` itself keeps its place among the
9372/// attributes, because [`with_attr`] does the writing.
9373fn with_class_token(
9374    attrs: &[(String, Option<String>)],
9375    mine: impl Fn(&str) -> bool,
9376    token: Option<&str>,
9377) -> Attrs {
9378    let kept: Vec<&str> = attrs
9379        .iter()
9380        .find(|(k, _)| k == "class")
9381        .and_then(|(_, v)| v.as_deref())
9382        .unwrap_or_default()
9383        .split_whitespace()
9384        .filter(|t| !mine(t))
9385        .collect();
9386    let class = kept.into_iter().chain(token).collect::<Vec<_>>().join(" ");
9387    with_attr(
9388        attrs,
9389        "class",
9390        (!class.is_empty()).then_some(class.as_str()),
9391    )
9392}
9393
9394/// An owned attribute list as the borrowed pairs twig's two attribute ops take.
9395///
9396/// A **bare** attribute — one twig reports with no value, such as HTML's `<p
9397/// hidden>` — is passed back as an empty one. Twig refuses a `None` outright
9398/// (djot has no bare attribute, so no format reads one back everywhere), and
9399/// `hidden=""` is the same document where `hidden` is; dropping it instead
9400/// would lose what the author wrote, which is the one thing these gestures
9401/// promise not to do.
9402fn attr_pairs(attrs: &[(String, Option<String>)]) -> Vec<(&str, Option<&str>)> {
9403    attrs
9404        .iter()
9405        .map(|(k, v)| (k.as_str(), Some(v.as_deref().unwrap_or_default())))
9406        .collect()
9407}
9408
9409fn reanchor(off: usize, change: &Change) -> usize {
9410    if off < change.old.start {
9411        return off;
9412    }
9413    if off < change.old.end {
9414        return change.new.end;
9415    }
9416    (off + change.new.end).saturating_sub(change.old.end)
9417}
9418
9419/// [`reanchor`] for an edit that respells the markup *around* a block and
9420/// leaves the block's own bytes alone — which is every attribute gesture.
9421///
9422/// `block` is that block's content span before and after the splice, so an
9423/// offset standing in the text keeps its distance from the text's start and how
9424/// many bytes twig wrote above it never enters the arithmetic. That is the whole
9425/// rule, and it is why nothing here knows how long a `<div …>` is: a second key
9426/// on the same div lengthens the attribute line, clearing the last one takes the
9427/// div away entirely, and both are the same sum. `None` where the splice named
9428/// no block at either end, which is every djot case — the `{…}` line is written
9429/// above the block, and the block itself only shifts past it.
9430///
9431/// Anywhere else it is `reanchor`'s own answer: untouched before the splice,
9432/// shifted by its delta after it, and at the splice's end for an offset that
9433/// stood in markup being rewritten — a caret inside djot's `{…}` line has no
9434/// text to keep.
9435fn reanchor_in_block(
9436    off: usize,
9437    change: &Change,
9438    block: Option<(&Range<usize>, &Range<usize>)>,
9439) -> usize {
9440    if let Some((was, now)) = block
9441        && was.start <= off
9442        && off <= was.end
9443    {
9444        return now.start + (off - was.start).min(now.end - now.start);
9445    }
9446    reanchor(off, change)
9447}
9448
9449/// A watermark for a file's contents (see `Doc::disk_hash`).
9450///
9451/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
9452/// watermark is compared only against one taken by the same process moments
9453/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
9454/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
9455fn hash_bytes(bytes: &[u8]) -> u64 {
9456    use std::hash::{Hash, Hasher};
9457    let mut h = std::collections::hash_map::DefaultHasher::new();
9458    bytes.hash(&mut h);
9459    h.finish()
9460}
9461
9462#[cfg(feature = "fs")]
9463fn detect_format(path: &Path) -> Result<Format> {
9464    let ext = path
9465        .extension()
9466        .and_then(|e| e.to_str())
9467        .unwrap_or("")
9468        .to_ascii_lowercase();
9469    Ok(match ext.as_str() {
9470        "dj" | "djot" => Format::Djot,
9471        "md" | "markdown" => Format::Markdown,
9472        "xml" => Format::Xml,
9473        "html" | "htm" => Format::Html,
9474        other => return Err(anyhow!("unknown document extension: .{other}")),
9475    })
9476}
9477
9478#[cfg(test)]
9479mod tests {
9480    use super::*;
9481    use crate::style::{FontFamily, LineSpacing, SizeStep};
9482
9483    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
9484    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
9485    /// without one is a view no user is ever in.
9486    fn doc_in(view: View, name: &str, body: &str) -> Doc {
9487        // The fixture name doubles as the temp file's, so two tests picking the
9488        // same one raced under the parallel runner and read each other's body —
9489        // a green suite proving the wrong thing. The counter makes that
9490        // unreachable rather than asking every future caller to notice.
9491        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
9492        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9493        let mut p = std::env::temp_dir();
9494        p.push(format!("leaf_test_{name}_{seq}.md"));
9495        std::fs::write(&p, body).unwrap();
9496        let mut d = Doc::open(p).unwrap();
9497        d.view = view;
9498        if view == View::Wysiwyg {
9499            d.build_visual(80);
9500        }
9501        d
9502    }
9503
9504    // Source-view document for the source-behaviour tests. `Doc::open` now
9505    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
9506    // `wysiwyg_doc` builds the rich-text variant on top of this.
9507    fn doc_with(name: &str, body: &str) -> Doc {
9508        doc_in(View::Source, name, body)
9509    }
9510
9511    /// Every visual row's drawn text — what the reader actually sees, which is
9512    /// the only thing the reveal preference is supposed to change.
9513    fn drawn_rows(d: &Doc) -> Vec<String> {
9514        d.vmap
9515            .rows
9516            .iter()
9517            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9518            .collect()
9519    }
9520
9521    /// Put the caret at the first byte of `needle` and rebuild, so the row under
9522    /// it becomes the revealed line.
9523    fn caret_at(d: &mut Doc, needle: &str) {
9524        d.caret = d.source.find(needle).expect("needle in source");
9525        d.build_visual(80);
9526    }
9527
9528    #[test]
9529    fn blockquote_after_a_list_is_not_bulleted() {
9530        // twig nests a following top-level block quote under the `bullet_list`
9531        // (a direct child, not a `list_item`). The map must render it de-nested —
9532        // `│ quote`, never `• │ quote` — with a blank separator, like any block
9533        // that follows a list. Regression for the "combined list + blockquote" bug.
9534        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
9535        d.build_visual(80);
9536        let rows: Vec<String> = d
9537            .vmap
9538            .rows
9539            .iter()
9540            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9541            .collect();
9542        assert!(
9543            rows.iter().any(|r| r == "│ quote"),
9544            "block quote should render on its own gutter, got rows: {rows:?}"
9545        );
9546        assert!(
9547            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
9548            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
9549        );
9550    }
9551
9552    // ── the map is built at most once per (revision, wrap) ───────────────────
9553    //
9554    // A frontend repaints for reasons that have nothing to do with the text — a
9555    // blinking caret, a scroll — and rebuilding the map is O(document). These
9556    // pin *that the cache fires*, which a passing suite can't tell you: a cache
9557    // that never hits is invisible to every other test in this file.
9558    //
9559    // The probe is to wreck the built map and ask for it again. A rebuild
9560    // repairs it; a cache hit hands the wreckage straight back. Nothing else
9561    // can distinguish the two from outside.
9562
9563    #[test]
9564    fn a_rebuild_with_nothing_changed_reuses_the_map() {
9565        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
9566        d.build_visual(80);
9567        assert!(!d.vmap.rows.is_empty());
9568        d.vmap.rows.clear(); // wreck it
9569        d.build_visual(80);
9570        assert!(
9571            d.vmap.rows.is_empty(),
9572            "the map was rebuilt though nothing changed — the cache never fired"
9573        );
9574    }
9575
9576    #[test]
9577    fn an_edit_rebuilds_the_map() {
9578        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
9579        d.build_visual(80);
9580        let before = d.revision();
9581        d.vmap.rows.clear();
9582        d.insert("x");
9583        d.build_visual(80);
9584        assert!(d.revision() > before, "an edit must move the revision");
9585        assert!(
9586            !d.vmap.rows.is_empty(),
9587            "an edited document must not paint from a stale map"
9588        );
9589    }
9590
9591    #[test]
9592    fn a_width_change_rebuilds_the_map() {
9593        // The map is a function of the wrap width too, so a resize is a miss
9594        // even though the text is untouched.
9595        let mut d = doc_in(
9596            View::Wysiwyg,
9597            "cache_width",
9598            "one two three four five six\n",
9599        );
9600        d.build_visual(80);
9601        d.vmap.rows.clear();
9602        d.build_visual(12);
9603        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
9604        // And the unwrapped map is its own key, not the same as any width.
9605        d.vmap.rows.clear();
9606        d.build_visual_unwrapped();
9607        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
9608    }
9609
9610    #[test]
9611    fn a_motion_does_not_rebuild_the_map() {
9612        // The whole point: moving the caret changes nothing the map is built
9613        // from. If a motion bumped the revision, every arrow key would cost a
9614        // full rebuild and the cache would be worthless.
9615        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
9616        d.build_visual(80);
9617        let rev = d.revision();
9618        d.move_right(false);
9619        d.move_right(true);
9620        d.move_down(false);
9621        assert_eq!(d.revision(), rev, "a motion must not move the revision");
9622        d.vmap.rows.clear();
9623        d.build_visual(80);
9624        assert!(
9625            d.vmap.rows.is_empty(),
9626            "a motion should not rebuild the map"
9627        );
9628    }
9629
9630    #[test]
9631    fn saving_does_not_rebuild_the_map() {
9632        // Saving changes `dirty`, not the text.
9633        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
9634        d.insert("x");
9635        d.build_visual(80);
9636        let rev = d.revision();
9637        d.save();
9638        assert_eq!(d.revision(), rev, "a save must not move the revision");
9639        assert!(!d.dirty, "the save should have cleaned the document");
9640    }
9641
9642    #[test]
9643    fn a_reload_rebuilds_the_map() {
9644        // Reload replaces the text without going through `refresh`, so it has to
9645        // move the revision itself — else the editor paints the old file.
9646        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
9647        d.build_visual(80);
9648        let rev = d.revision();
9649        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
9650        d.reload();
9651        assert!(d.revision() > rev, "a reload must move the revision");
9652        d.build_visual(80);
9653        let text: String = d
9654            .vmap
9655            .rows
9656            .iter()
9657            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
9658            .collect();
9659        assert!(
9660            text.contains("wholly new"),
9661            "the reloaded text should be on screen, got {text:?}"
9662        );
9663    }
9664
9665    // ── golden-case harness ──────────────────────────────────────────────────
9666    // The pattern the whole parity suite can reuse: write a fixture with the
9667    // caret marked by `|`, run one action, and compare the rendered result —
9668    // also caret-marked — against the expected string. One readable line per
9669    // behavior, and it exercises the exact `Doc` ops both frontends call.
9670
9671    /// Split a `|`-marked fixture into `(source, caret_offset)`.
9672    fn parse_caret(marked: &str) -> (String, usize) {
9673        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
9674        (marked.replacen('|', "", 1), caret)
9675    }
9676
9677    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
9678    /// selection) so a result reads like the fixtures.
9679    fn render_caret(d: &Doc) -> String {
9680        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
9681        // so the caret always renders inside its own selection.
9682        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
9683        if let Some((s, e)) = d.selection() {
9684            marks.push((s, 0, '['));
9685            marks.push((e, 2, ']'));
9686        }
9687        // Insert right-to-left: descending offset, then descending rank.
9688        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
9689        let mut out = d.source.clone();
9690        for (at, _, ch) in marks {
9691            out.insert(at, ch);
9692        }
9693        out
9694    }
9695
9696    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
9697    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9698        golden_in(View::Source, name, marked, action)
9699    }
9700
9701    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
9702    /// the same fixture has to read the same way in both.
9703    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9704        let (src, caret) = parse_caret(marked);
9705        let mut d = doc_in(view, name, &src);
9706        d.caret = caret;
9707        action(&mut d);
9708        render_caret(&d)
9709    }
9710
9711    #[test]
9712    fn word_motion_walks_word_by_word() {
9713        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
9714        assert_eq!(
9715            g("hello wor|ld", |d| d.move_word_left(false)),
9716            "hello |world"
9717        );
9718        assert_eq!(
9719            g("hello| world", |d| d.move_word_left(false)),
9720            "|hello world"
9721        );
9722        assert_eq!(
9723            g("hel|lo world", |d| d.move_word_right(false)),
9724            "hello| world"
9725        );
9726        assert_eq!(
9727            g("hello| world", |d| d.move_word_right(false)),
9728            "hello world|"
9729        );
9730        // Punctuation is its own class, so motion stops at the boundary.
9731        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
9732    }
9733
9734    #[test]
9735    fn word_motion_extends_the_selection_when_asked() {
9736        assert_eq!(
9737            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
9738            "hello [world|]"
9739        );
9740    }
9741
9742    #[test]
9743    fn delete_word_removes_a_whole_word() {
9744        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
9745        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
9746        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
9747        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
9748    }
9749
9750    // ── Home / End ───────────────────────────────────────────────────────────
9751
9752    #[test]
9753    fn home_toggles_between_the_line_s_text_and_its_margin() {
9754        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
9755        // indent to the markup it spells everywhere it means one, so the fixture
9756        // with whitespace left to walk is a code block, which is verbatim.
9757        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
9758        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
9759        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
9760        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
9761        // A line with no indentation has one place to go, so the toggle is a
9762        // no-op rather than a trip to nowhere.
9763        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
9764        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
9765
9766        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
9767        let indent = d.source.find("    indented").unwrap();
9768        d.caret = indent + 6; // inside "indented"
9769        d.move_home(false);
9770        assert_eq!(
9771            d.caret,
9772            indent + 4,
9773            "wysiwyg: Home aims at the code line's text"
9774        );
9775        d.move_home(false);
9776        assert_eq!(
9777            d.caret, indent,
9778            "wysiwyg: the second press takes the indent"
9779        );
9780        d.move_home(false);
9781        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
9782    }
9783
9784    #[test]
9785    fn end_takes_the_line_the_view_is_showing() {
9786        // The line differs by view for the same document, and that is the point:
9787        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
9788        // as a space on one row and the source view as two lines.
9789        let mut d = doc_with("end_src", "one two\nthree\n");
9790        d.caret = 1;
9791        d.move_end(false);
9792        assert_eq!(d.caret, 7, "source: the end of the source line");
9793
9794        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
9795        d.caret = 1;
9796        d.move_end(false);
9797        assert_eq!(
9798            d.caret, 13,
9799            "wysiwyg: the end of the row, soft break and all"
9800        );
9801    }
9802
9803    #[test]
9804    fn home_and_end_extend_the_selection_when_asked() {
9805        for (view, tag) in VIEWS {
9806            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
9807            d.caret = 6;
9808            d.move_end(true);
9809            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
9810            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
9811            d.caret = 6;
9812            d.move_home(true);
9813            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
9814        }
9815    }
9816
9817    // ── kill to the line's start / end ───────────────────────────────────────
9818
9819    #[test]
9820    fn kill_to_the_line_start_and_end_in_both_views() {
9821        for (view, tag) in VIEWS {
9822            // The gap that reads as a paragraph break in each view: the source
9823            // view's lines are the renderer's rows only where the source says so.
9824            let gap = if view == View::Source { "\n" } else { "\n\n" };
9825            let mut d = doc_in(
9826                view,
9827                &format!("kill_end_{tag}"),
9828                &format!("one two{gap}three\n"),
9829            );
9830            d.caret = 3;
9831            d.delete_to_line_end();
9832            assert_eq!(
9833                d.source,
9834                format!("one{gap}three\n"),
9835                "{tag}: ^K to the line's end"
9836            );
9837            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
9838
9839            let mut d = doc_in(
9840                view,
9841                &format!("kill_start_{tag}"),
9842                &format!("one two{gap}three\n"),
9843            );
9844            d.caret = 7; // the end of the first line
9845            d.delete_to_line_start();
9846            assert_eq!(
9847                d.source,
9848                format!("{gap}three\n"),
9849                "{tag}: ⌘⌫ to the line's start"
9850            );
9851            assert_eq!(d.caret, 0, "{tag}");
9852        }
9853    }
9854
9855    #[test]
9856    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
9857        // The decision: at the boundary both kills do nothing, rather than
9858        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
9859        // at a soft wrap as often as at a newline, where there is nothing
9860        // written to delete — and a source newline is only half of the blank
9861        // line between two paragraphs, so taking it leaves a soft break rather
9862        // than the join it looks like. Backspace and Delete are the keys for it.
9863        for (view, tag) in VIEWS {
9864            let gap = if view == View::Source { "\n" } else { "\n\n" };
9865            let src = format!("one{gap}three\n");
9866            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
9867            d.caret = 3; // the end of "one"
9868            d.delete_to_line_end();
9869            assert_eq!(
9870                d.source, src,
9871                "{tag}: ^K at the line's end joined it to the next"
9872            );
9873
9874            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
9875            d.caret = 3 + gap.len(); // the start of "three"
9876            d.delete_to_line_start();
9877            assert_eq!(
9878                d.source, src,
9879                "{tag}: ⌘⌫ at the line's start joined it to the last"
9880            );
9881        }
9882    }
9883
9884    #[test]
9885    fn a_kill_takes_the_selection_when_there_is_one() {
9886        // What every other delete here does with one, so these two as well.
9887        for (view, tag) in VIEWS {
9888            for (name, kill) in [
9889                (
9890                    "end",
9891                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
9892                ),
9893                ("start", |d: &mut Doc| d.delete_to_line_start()),
9894            ] {
9895                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
9896                d.anchor = Some(4);
9897                d.caret = 7; // "two"
9898                kill(&mut d);
9899                assert_eq!(
9900                    d.source, "one  three\n",
9901                    "{tag}: {name} ignored the selection"
9902                );
9903                assert_eq!(d.selection(), None, "{tag}: {name}");
9904            }
9905        }
9906    }
9907
9908    #[test]
9909    fn a_kill_takes_the_markup_it_empties_with_it() {
9910        // The same hazard a word-delete has: a WYSIWYG range covers what the
9911        // user can see, which for `**bold**` is the word and never the
9912        // delimiters, so a kill that stopped at the text would leave `a ****` —
9913        // markup wrapped around nothing.
9914        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
9915        d.caret = d.source.find("bold").unwrap();
9916        d.delete_to_line_end();
9917        assert_eq!(d.source, "a \n");
9918    }
9919
9920    #[test]
9921    fn a_kill_is_undone_in_one_step() {
9922        for (view, tag) in VIEWS {
9923            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
9924            d.caret = 3;
9925            d.delete_to_line_end();
9926            assert_eq!(d.source, "one\n", "{tag}");
9927            d.undo();
9928            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
9929        }
9930    }
9931
9932    #[test]
9933    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
9934        // Regression: triple-click used move_home/move_end over visual rows, so
9935        // it only worked on a paragraph's first row (a wrap-boundary offset maps
9936        // to the earlier row). select_block_at reads the AST, so every offset in
9937        // the paragraph selects the whole thing.
9938        let body = "one two three four five six seven eight\n";
9939        let mut d = doc_with("sel_block", body);
9940        d.view = View::Wysiwyg;
9941        d.build_visual(12); // force the paragraph to wrap into several rows
9942        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
9943        let para = (0, "one two three four five six seven eight".len());
9944        for off in [0usize, 8, 19, 28, 38] {
9945            d.caret = 0;
9946            d.anchor = None;
9947            d.select_block_at(off);
9948            assert_eq!(
9949                d.selection(),
9950                Some(para),
9951                "offset {off} should select the paragraph"
9952            );
9953        }
9954    }
9955
9956    #[test]
9957    fn select_block_uses_content_span_for_a_heading() {
9958        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
9959        d.select_block_at(4); // inside "Title"
9960        // content_span excludes the "# " marker.
9961        assert_eq!(d.selected_text(), Some("Title"));
9962        d.select_block_at(10); // inside "body"
9963        assert_eq!(d.selected_text(), Some("body"));
9964    }
9965
9966    #[test]
9967    fn select_all_spans_the_document() {
9968        let mut d = doc_with("sel_all", "abc\n\ndef\n");
9969        d.select_all();
9970        assert_eq!(d.selection(), Some((0, d.source.len())));
9971    }
9972
9973    #[test]
9974    fn select_word_at_picks_the_surrounding_word() {
9975        let mut d = doc_with("sel_word", "hello world\n");
9976        d.select_word_at(8); // inside "world"
9977        assert_eq!(d.selection(), Some((6, 11)));
9978        // Double-clicking at end-of-word still grabs the word to its left.
9979        d.select_word_at(5); // the space between the words
9980        assert_eq!(d.selection(), Some((5, 6)));
9981    }
9982
9983    #[test]
9984    fn word_helpers_respect_utf8_boundaries() {
9985        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
9986        assert_eq!(
9987            golden("utf8", "|café ok", |d| d.move_word_right(false)),
9988            "café| ok"
9989        );
9990        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
9991    }
9992
9993    #[test]
9994    fn typing_inserts_at_the_caret_and_advances_it() {
9995        let mut d = doc_with("type", "hello\n");
9996        d.insert("Hi ");
9997        assert_eq!(d.source, "Hi hello\n");
9998        assert_eq!(d.caret, 3);
9999        assert!(d.dirty);
10000    }
10001
10002    #[test]
10003    fn backspace_deletes_the_char_before_the_caret() {
10004        let mut d = doc_with("bs", "hello\n");
10005        d.caret = 3; // after "hel"
10006        d.backspace();
10007        assert_eq!(d.source, "helo\n");
10008        assert_eq!(d.caret, 2);
10009    }
10010
10011    #[test]
10012    fn typing_replaces_the_selection() {
10013        let mut d = doc_with("replace", "a word b\n");
10014        d.anchor = Some(2);
10015        d.caret = 6; // "word" selected
10016        d.insert("X");
10017        assert_eq!(d.source, "a X b\n");
10018        assert_eq!(d.caret, 3);
10019        assert_eq!(d.anchor, None);
10020    }
10021
10022    #[test]
10023    fn toggle_bold_wraps_then_unwraps_the_selection() {
10024        let mut d = doc_with("bold", "a word b\n");
10025        d.anchor = Some(2);
10026        d.caret = 6;
10027        d.toggle(InlineKind::Strong);
10028        assert_eq!(d.source, "a **word** b\n");
10029        // The toggled region stays selected, so a second toggle reverses it.
10030        d.toggle(InlineKind::Strong);
10031        assert_eq!(d.source, "a word b\n");
10032        d.toggle(InlineKind::Strong);
10033        assert_eq!(d.source, "a **word** b\n");
10034    }
10035
10036    #[test]
10037    fn toggle_code_wraps_then_unwraps_the_selection() {
10038        let mut d = doc_with("code_rt", "a word b\n");
10039        d.anchor = Some(2);
10040        d.caret = 6;
10041        d.toggle(InlineKind::Verbatim);
10042        assert_eq!(d.source, "a `word` b\n");
10043        d.toggle(InlineKind::Verbatim);
10044        assert_eq!(d.source, "a word b\n");
10045    }
10046
10047    #[test]
10048    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
10049        // ⌘b at a bare caret, then type: the text comes out bold with no
10050        // selection ever made — the word-processor "start bold here" gesture.
10051        let mut d = doc_with("sticky_wrap", "xy\n");
10052        d.caret = 1; // between x and y
10053        d.toggle(InlineKind::Strong);
10054        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
10055        d.insert("A");
10056        assert_eq!(d.source, "x**A**y\n");
10057    }
10058
10059    #[test]
10060    fn sticky_bold_lights_the_toolbar_before_any_typing() {
10061        // The button must light the instant ⌘b is pressed, or the mode is
10062        // invisible until the first character lands.
10063        let mut d = doc_with("sticky_light", "xy\n");
10064        d.caret = 1;
10065        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10066        d.toggle(InlineKind::Strong);
10067        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10068    }
10069
10070    #[test]
10071    fn sticky_bold_toggled_off_types_normally_again() {
10072        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
10073        // in the flow of typing, the exact sequence the user described.
10074        let mut d = doc_with("sticky_off", "\n");
10075        d.caret = 0;
10076        d.toggle(InlineKind::Strong);
10077        d.insert("a");
10078        d.insert("b"); // continues inside the run, no re-arming
10079        assert_eq!(d.source, "**ab**\n");
10080        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
10081        d.insert("c");
10082        assert_eq!(d.source, "**ab**c\n");
10083    }
10084
10085    #[test]
10086    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
10087        // Once a mark is realised the caret sits inside the run, so plain typing
10088        // extends it rather than starting a second, adjacent bold span.
10089        let mut d = doc_with("sticky_cont", "\n");
10090        d.caret = 0;
10091        d.toggle(InlineKind::Emph);
10092        d.insert("h");
10093        d.insert("i");
10094        assert_eq!(d.source, "*hi*\n");
10095    }
10096
10097    #[test]
10098    fn moving_the_caret_disarms_a_sticky_mark() {
10099        // Arming a mark and then moving away must not style text elsewhere.
10100        let mut d = doc_with("sticky_disarm", "xy\n");
10101        d.caret = 0;
10102        d.toggle(InlineKind::Strong);
10103        d.move_right(false); // caret 0 → 1, disarms
10104        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10105        d.insert("A");
10106        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
10107    }
10108
10109    #[test]
10110    fn stacked_sticky_marks_apply_together() {
10111        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
10112        let mut d = doc_with("sticky_stack", "\n");
10113        d.caret = 0;
10114        d.toggle(InlineKind::Strong);
10115        d.toggle(InlineKind::Emph);
10116        d.insert("x");
10117        // Land the caret on the styled character and confirm both marks are live.
10118        d.anchor = Some(d.source.find('x').unwrap());
10119        d.caret = d.anchor.unwrap() + 1;
10120        let marks = d.active_inline_marks();
10121        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
10122        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
10123    }
10124
10125    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
10126
10127    #[test]
10128    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
10129        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
10130        // The space inside the run made `**bold **`, which is *not* bold — four
10131        // literal asterisks — so the rich view drew them, correctly and
10132        // uselessly, until the next character happened to close the run again.
10133        let mut d = wysiwyg_doc("edge_typing", "a \n");
10134        d.caret = 2;
10135        d.toggle(InlineKind::Strong);
10136        for c in "bold".chars() {
10137            d.insert(&c.to_string());
10138        }
10139        assert_eq!(d.source, "a **bold**\n");
10140        d.insert(" ");
10141        assert_eq!(
10142            d.source, "a **bold** \n",
10143            "the space belongs outside the run"
10144        );
10145        assert!(
10146            d.active_inline_marks().contains(InlineKind::Strong),
10147            "bold is still what's being typed, so the button stays lit"
10148        );
10149        // What the writer is looking at while all this happens: their words.
10150        d.build_visual(80);
10151        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
10152        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
10153        for c in "hey".chars() {
10154            d.insert(&c.to_string());
10155        }
10156        assert_eq!(
10157            d.source, "a **bold hey**\n",
10158            "one bold phrase, not two runs"
10159        );
10160    }
10161
10162    #[test]
10163    fn typing_past_a_space_can_still_leave_the_bold_behind() {
10164        // The other half: the marks stay armed across the space, so ⌘b turns
10165        // them off again there and the next word is plain — the run isn't
10166        // rejoined by a caret that was told not to.
10167        let mut d = wysiwyg_doc("edge_shed", "\n");
10168        d.caret = 0;
10169        d.toggle(InlineKind::Strong);
10170        for c in "bold ".chars() {
10171            d.insert(&c.to_string());
10172        }
10173        assert_eq!(d.source, "**bold** \n");
10174        d.toggle(InlineKind::Strong);
10175        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10176        d.insert("x");
10177        assert_eq!(d.source, "**bold** x\n");
10178    }
10179
10180    #[test]
10181    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
10182        // ⌘b and then a space before any word: the space is not marked (nothing
10183        // is), and the word after it is.
10184        let mut d = wysiwyg_doc("edge_space_first", "a\n");
10185        d.caret = 1;
10186        d.toggle(InlineKind::Strong);
10187        d.insert(" ");
10188        assert_eq!(d.source, "a \n");
10189        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10190        d.insert("b");
10191        assert_eq!(d.source, "a **b**\n");
10192    }
10193
10194    #[test]
10195    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
10196        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
10197        d.caret = 8; // the caret's home at the end of the run's text
10198        d.insert(" ");
10199        assert_eq!(
10200            d.source, "x **bold** \n",
10201            "the space lands past the delimiters"
10202        );
10203        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
10204
10205        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
10206        d.caret = 4; // in front of the "b"
10207        d.insert(" ");
10208        assert_eq!(d.source, "x  **bold** y\n");
10209        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
10210    }
10211
10212    #[test]
10213    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
10214        // Backspace over the last letter of a bold phrase.
10215        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
10216        d.caret = 10; // past the "h"
10217        d.backspace();
10218        assert_eq!(d.source, "a **bold** \n");
10219        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
10220        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10221        d.insert("x");
10222        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
10223    }
10224
10225    #[test]
10226    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
10227        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
10228        // mark, which is only text. The marks live on in the caret instead.
10229        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
10230        d.caret = 5;
10231        d.backspace();
10232        assert_eq!(d.source, "a  c\n");
10233        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10234        d.insert("x");
10235        assert_eq!(d.source, "a **x** c\n");
10236    }
10237
10238    #[test]
10239    fn typing_over_a_whole_bold_word_keeps_it_bold() {
10240        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
10241        d.anchor = Some(4);
10242        d.caret = 8; // the word, not its delimiters
10243        d.insert("x");
10244        assert_eq!(d.source, "a **x** c\n");
10245    }
10246
10247    #[test]
10248    fn a_code_span_keeps_the_space_it_is_given() {
10249        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
10250        // is still verbatim, so nothing is re-spelt. The repair asks the parser
10251        // rather than a table of kinds, and this is the answer it gets.
10252        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
10253        d.caret = 7;
10254        d.insert(" ");
10255        assert_eq!(d.source, "a `code ` c\n");
10256    }
10257
10258    #[test]
10259    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
10260        // A run's closing delimiter has a caret home on each side of it, one
10261        // column apart on screen — and a plain ← off the space after a bold word
10262        // lands on the outer one. The character drawn behind the caret there is
10263        // still the last letter of the phrase, so that is what Backspace takes;
10264        // the byte behind it is a `*` nobody can see.
10265        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
10266        d.caret = 9;
10267        d.move_left(false);
10268        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
10269        d.backspace();
10270        assert_eq!(
10271            d.source, "**bol** x\n",
10272            "a letter of the phrase, not its `*`"
10273        );
10274        assert_eq!(d.caret, 5);
10275
10276        // And the mirror in front of the opening delimiter, where Delete's
10277        // character is the first letter of the run.
10278        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
10279        d.caret = 1;
10280        d.delete_forward();
10281        assert_eq!(d.source, "x**old**\n");
10282        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
10283    }
10284
10285    #[test]
10286    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
10287        // The byte beside the caret at either edge of a bold word is a `*` the
10288        // rich view draws nothing for. Taking it is not the character delete the
10289        // key was pressed for — it unspells the run and puts a literal asterisk
10290        // on screen (`a *bold** c`). The visible character is the one that goes.
10291        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
10292        d.caret = 4; // in front of the "b"
10293        d.backspace();
10294        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
10295
10296        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
10297        d.caret = 8; // past the "d"
10298        d.delete_forward();
10299        assert_eq!(d.source, "a **bold**c\n");
10300        assert_eq!(d.caret, 8, "and the caret stays inside the run");
10301        d.insert("x");
10302        assert_eq!(d.source, "a **boldx**c\n");
10303
10304        // A code span's backticks are hidden the same way, so they are covered
10305        // by the same rule and not by a list of kinds.
10306        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
10307        d.caret = 3;
10308        d.backspace();
10309        assert_eq!(d.source, "a`code` c\n");
10310    }
10311
10312    #[test]
10313    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
10314        // The asterisks are on the screen there and the caret can stand between
10315        // them, so a delete takes exactly the byte it is aimed at.
10316        let mut d = doc_with("edge_open_src", "a **bold** c\n");
10317        d.caret = 4;
10318        d.backspace();
10319        assert_eq!(d.source, "a *bold** c\n");
10320
10321        let mut d = doc_with("edge_close_src", "a **bold** c\n");
10322        d.caret = 8;
10323        d.delete_forward();
10324        assert_eq!(d.source, "a **bold* c\n");
10325    }
10326
10327    #[test]
10328    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
10329        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
10330        // The space had stepped outside the run (the mark-edge rule), taking the
10331        // caret with it, so the delete put it back down on the far side of the
10332        // closing `**` — one place on screen, and the wrong side of it. Typing
10333        // came out plain and the toolbar went dark, with nothing to see.
10334        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
10335        d.caret = 0;
10336        d.toggle(InlineKind::Strong);
10337        for c in "bold".chars() {
10338            d.insert(&c.to_string());
10339        }
10340        d.insert(" ");
10341        assert_eq!(d.source, "**bold** \n");
10342        d.backspace();
10343        assert_eq!(
10344            d.source, "**bold**\n",
10345            "the space goes, the delimiters stay"
10346        );
10347        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
10348        assert!(
10349            d.active_inline_marks().contains(InlineKind::Strong),
10350            "so the button is still lit"
10351        );
10352        d.insert("x");
10353        assert_eq!(
10354            d.source, "**boldx**\n",
10355            "and the next character is still bold"
10356        );
10357    }
10358
10359    #[test]
10360    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
10361        // What the stranded caret did next: the byte behind it was the closing
10362        // `*`, so a second press took that instead of a letter — `**bold*`, the
10363        // styling gone and an asterisk on the screen where the word had been.
10364        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
10365        d.caret = 0;
10366        d.toggle(InlineKind::Strong);
10367        for c in "bold ".chars() {
10368            d.insert(&c.to_string());
10369        }
10370        assert_eq!(d.source, "**bold** \n");
10371        d.backspace();
10372        d.backspace();
10373        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
10374        assert_eq!(d.caret, 5);
10375    }
10376
10377    #[test]
10378    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
10379        // `***both***` closes two runs with one stack of asterisks: the caret has
10380        // to walk in through all of them, or it lands between the emph and the
10381        // strong and types half-marked.
10382        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
10383        d.caret = 11;
10384        d.backspace();
10385        assert_eq!(d.source, "***both***\n");
10386        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
10387        d.insert("x");
10388        assert_eq!(d.source, "***bothx***\n");
10389    }
10390
10391    #[test]
10392    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
10393        // The settle only moves a caret a run actually closed over. Ordinary
10394        // deletes — inside a run, or in plain prose — are untouched.
10395        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
10396        d.caret = 8;
10397        d.backspace();
10398        assert_eq!(d.source, "a **bol** c\n");
10399        assert_eq!(d.caret, 7);
10400
10401        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
10402        d.caret = 5;
10403        d.backspace();
10404        assert_eq!(d.source, "plai\n");
10405        assert_eq!(d.caret, 4);
10406    }
10407
10408    #[test]
10409    fn the_source_view_leaves_a_delete_where_it_landed() {
10410        // The delimiters are on the screen there, so the offset past them is a
10411        // place the caret can be seen to be — nothing to settle.
10412        let mut d = doc_with("edge_bksp_src", "**bold** \n");
10413        d.caret = 9;
10414        d.backspace();
10415        assert_eq!(d.source, "**bold**\n");
10416        assert_eq!(d.caret, 8);
10417    }
10418
10419    #[test]
10420    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
10421        // `***both***` closes two runs with one stack of asterisks; a space that
10422        // clears only the inner one lands against the outer's and breaks that
10423        // instead.
10424        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
10425        d.caret = 9;
10426        d.insert(" ");
10427        assert_eq!(d.source, "a ***both*** \n");
10428        assert_eq!(d.caret, 13);
10429        d.insert("x");
10430        assert_eq!(d.source, "a ***both x***\n");
10431    }
10432
10433    #[test]
10434    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
10435        // The delimiter shuffle is not an edit the writer made, so it is not a
10436        // step they have to undo past.
10437        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
10438        d.caret = 8;
10439        d.insert(" ");
10440        assert_eq!(d.source, "a **bold** \n");
10441        d.undo();
10442        assert_eq!(d.source, "a **bold**\n");
10443    }
10444
10445    #[test]
10446    fn the_source_view_types_the_space_where_it_was_asked_to() {
10447        // The rule is a rich-view courtesy. In the source view the delimiters are
10448        // on the screen and the user is editing the bytes they can see.
10449        let mut d = doc_with("edge_src", "a **bold** c\n");
10450        d.caret = 8;
10451        d.insert(" ");
10452        assert_eq!(d.source, "a **bold ** c\n");
10453    }
10454
10455    #[test]
10456    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
10457        // Double-clicking a word takes the space after it; bolding that must not
10458        // spell `**word **`, which is not bold at all.
10459        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
10460        d.anchor = Some(2);
10461        d.caret = 7; // "word "
10462        d.toggle(InlineKind::Strong);
10463        assert_eq!(d.source, "a **word** b\n");
10464        d.toggle(InlineKind::Strong);
10465        assert_eq!(d.source, "a word b\n");
10466        d.toggle(InlineKind::Strong);
10467        assert_eq!(
10468            d.source, "a **word** b\n",
10469            "reapplying the mark must not wrap stale delimiter offsets"
10470        );
10471        // And a selection of nothing but whitespace has no word to mark.
10472        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
10473        d.anchor = Some(6);
10474        d.caret = 7;
10475        d.toggle(InlineKind::Strong);
10476        assert_eq!(d.source, "a word b\n");
10477        assert!(d.status.is_some());
10478    }
10479
10480    #[test]
10481    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
10482        let mut d = doc_with("head_set", "hello\n");
10483        d.caret = 2; // caret inside the paragraph, no selection
10484        d.set_block(BlockKind::Heading(1));
10485        assert_eq!(d.source, "# hello\n");
10486    }
10487
10488    #[test]
10489    fn set_block_heading_works_in_wysiwyg_view() {
10490        // The app defaults to WYSIWYG; the caret is a source offset either way.
10491        let mut d = wysiwyg_doc("head_wys", "hello\n");
10492        d.caret = 2;
10493        d.set_block(BlockKind::Heading(1));
10494        assert_eq!(d.source, "# hello\n");
10495    }
10496
10497    #[test]
10498    fn toggle_heading_applies_switches_and_reverts() {
10499        let mut d = doc_with("head_toggle", "hello\n");
10500        d.caret = 2;
10501        d.toggle_heading(1);
10502        assert_eq!(d.source, "# hello\n"); // paragraph → H1
10503        d.toggle_heading(2);
10504        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
10505        d.toggle_heading(2);
10506        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
10507    }
10508
10509    #[test]
10510    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
10511        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
10512        // the blank line but the caret rendered on the *next* line, because the
10513        // separator was a non-navigable decoration row. In Preserve flow that
10514        // blank line is a real caret home — the caret must resolve onto it, and
10515        // typing there makes the soft break that continues the paragraph.
10516        let src = "line one:\nsecond line\n";
10517        let mut d = wysiwyg_doc("pre_enter_lineend", src);
10518        d.set_line_flow(LineFlow::Preserve);
10519        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
10520        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
10521        d.newline();
10522        d.build_visual_unwrapped();
10523        assert_eq!(d.source, "line one:\n\nsecond line\n");
10524        assert_eq!(
10525            d.caret, 10,
10526            "caret sits on the new blank line, not the next line"
10527        );
10528        // The blank line is row 1, and the caret resolves onto it — not row 2.
10529        assert_eq!(
10530            d.vmap.pos_of_offset(10),
10531            (1, 0),
10532            "caret renders on the blank row"
10533        );
10534        assert!(
10535            !d.vmap.rows[1].decoration,
10536            "the blank line is navigable in Preserve"
10537        );
10538        // Typing there makes a soft break: one paragraph, three lines.
10539        d.insert("new clause,");
10540        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
10541    }
10542
10543    #[test]
10544    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
10545        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
10546        // that keeps it one paragraph — where Fold would open a second paragraph.
10547        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
10548        d.set_line_flow(LineFlow::Preserve);
10549        d.caret = 3;
10550        d.newline();
10551        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
10552
10553        // End-of-paragraph: Enter then typing continues the same paragraph on a
10554        // new line (a soft break), not a fresh paragraph.
10555        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
10556        d.set_line_flow(LineFlow::Preserve);
10557        d.caret = 3;
10558        d.newline();
10559        d.insert("def");
10560        assert_eq!(
10561            d.source, "abc\ndef\n",
10562            "end-of-line Enter + typing is a soft break"
10563        );
10564    }
10565
10566    #[test]
10567    fn preserve_double_enter_still_makes_a_paragraph() {
10568        // Two Enters in a row promote to a real paragraph break: the second lands
10569        // on the blank line the first opened and takes the empty-line branch.
10570        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
10571        d.set_line_flow(LineFlow::Preserve);
10572        d.caret = 3;
10573        d.newline();
10574        d.newline();
10575        d.insert("def");
10576        assert_eq!(
10577            d.source, "abc\n\ndef\n",
10578            "double Enter is a paragraph break"
10579        );
10580    }
10581
10582    #[test]
10583    fn preserve_backspace_joins_across_a_soft_break() {
10584        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
10585        // soft break it deletes the single newline and joins the two lines.
10586        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
10587        d.set_line_flow(LineFlow::Preserve);
10588        d.build_visual(80);
10589        d.caret = 4; // start of "def", just past the soft break
10590        d.backspace();
10591        assert_eq!(
10592            d.source, "abcdef\n",
10593            "Backspace joins across the soft break"
10594        );
10595        assert_eq!(d.caret, 3, "caret lands where the lines meet");
10596    }
10597
10598    #[test]
10599    fn fold_enter_still_starts_a_new_paragraph() {
10600        // The default flow is unchanged: a lone `\n` would render as an invisible
10601        // space, so Enter keeps opening the paragraph break that actually shows.
10602        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
10603        d.caret = 3;
10604        d.newline();
10605        assert_eq!(
10606            d.source, "abc\n\ndef\n",
10607            "Fold mid-line Enter is a paragraph break"
10608        );
10609    }
10610
10611    #[test]
10612    fn wysiwyg_one_enter_starts_a_new_paragraph() {
10613        // Regression: one Enter left the caret between the two newlines, so typing
10614        // made a soft break (one paragraph) and you needed a second Enter.
10615        let mut d = wysiwyg_doc("wys_enter", "abc\n");
10616        d.caret = 3;
10617        d.newline();
10618        d.insert("def");
10619        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
10620    }
10621
10622    #[test]
10623    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
10624        // Regression: Enter at the caret's natural End-of-line resting place
10625        // after a bold run with nothing following it (on screen: right after
10626        // "bold", before the hidden closing "**") spliced the paragraph break
10627        // at that very byte offset — which sits *before* the closing "**" in
10628        // the source, since the delimiter is hidden and emits no glyph of its
10629        // own for `push_row`'s "end of row" fallback to count. That severed the
10630        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
10631        // "**" alone on the new line instead of leaving "**bold**" intact with
10632        // a fresh empty paragraph after it.
10633        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
10634        d.move_end(false); // the WYSIWYG End key, from caret 0
10635        assert_eq!(
10636            d.caret, 6,
10637            "caret rests right after \"bold\", before the hidden \"**\""
10638        );
10639        d.newline();
10640        assert!(
10641            d.source.starts_with("**bold**"),
10642            "the closing ** must stay attached to \"bold\": got {:?}",
10643            d.source
10644        );
10645        assert_eq!(
10646            d.source, "**bold**\n\n\n",
10647            "a fresh empty paragraph follows the still-intact bold run"
10648        );
10649    }
10650
10651    #[test]
10652    fn source_view_enter_is_a_single_newline() {
10653        let mut d = doc_with("src_enter", "abc\n");
10654        d.caret = 3;
10655        d.newline();
10656        assert_eq!(d.source, "abc\n\n");
10657    }
10658
10659    #[test]
10660    fn heading_applies_at_the_end_of_a_paragraph() {
10661        // The caret at a line end sits at the doc level; set_block must still find
10662        // the block on that line.
10663        let mut d = doc_with("head_end", "abc\n");
10664        d.caret = 3; // end of "abc"
10665        d.toggle_heading(1);
10666        assert_eq!(d.source, "# abc\n");
10667    }
10668
10669    #[test]
10670    fn heading_on_an_empty_new_paragraph_creates_one() {
10671        let mut d = wysiwyg_doc("head_empty", "abc\n");
10672        d.caret = 3;
10673        d.newline(); // caret now on a fresh, empty paragraph
10674        d.toggle_heading(1);
10675        d.insert("Title");
10676        assert!(d.source.contains("# Title"), "got {:?}", d.source);
10677    }
10678
10679    #[test]
10680    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
10681        // The reported bug, end to end: click a blank line with another one under
10682        // it, press H1, type. The text landed in the heading and the caret's
10683        // offset was right (the source view drew it there), but the rich view
10684        // drew it two rows lower, on the trailing blank line — the empty `# `
10685        // heading had left every row below it short by the marker's two bytes,
10686        // and the blank line ended up claiming the heading's own end offset.
10687        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
10688        d.build_visual_unwrapped();
10689        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
10690        d.toggle_heading(1);
10691        for c in "title".chars() {
10692            d.insert(&c.to_string());
10693            d.build_visual_unwrapped(); // as a frontend does, one frame per key
10694        }
10695        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
10696        assert_eq!(
10697            d.caret_pos(),
10698            (4, 5),
10699            "the caret draws at the end of the heading"
10700        );
10701    }
10702
10703    #[test]
10704    fn clicking_an_empty_heading_types_after_its_marker() {
10705        // The same anchor from the other side: the empty heading's row is its own
10706        // caret home, so a click on it must land past the hidden `# `. Landing in
10707        // front of the hashes made the first keystroke un-heading the line.
10708        let mut d = wysiwyg_doc("head_click", "# \n");
10709        d.build_visual_unwrapped();
10710        d.caret = d.vmap.offset_of_pos(0, 0);
10711        d.insert("x");
10712        assert_eq!(d.source, "# x\n");
10713    }
10714
10715    #[test]
10716    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
10717        let mut d = wysiwyg_doc("head_enter", "# Title\n");
10718        d.caret = 7; // end of the heading
10719        d.newline();
10720        d.insert("body");
10721        assert_eq!(d.source, "# Title\n\nbody\n");
10722    }
10723
10724    #[test]
10725    fn wysiwyg_enter_continues_a_bullet_list() {
10726        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
10727        d.caret = 6; // end of "item"
10728        d.newline();
10729        d.insert("two");
10730        assert_eq!(d.source, "- item\n- two\n");
10731    }
10732
10733    #[test]
10734    fn wysiwyg_enter_increments_an_ordered_list() {
10735        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
10736        d.caret = 6; // end of "one"
10737        d.newline();
10738        d.insert("two");
10739        assert_eq!(d.source, "1. one\n2. two\n");
10740    }
10741
10742    #[test]
10743    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
10744        // Regression for the "extra newline" left between a list and the paragraph
10745        // below it. Enter, Enter leaves the list on a fresh empty paragraph
10746        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
10747        // Backspace should then take the caret cleanly back to the end of the list
10748        // item, `- item\n\nnext`, not delete a single newline and strand it on the
10749        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
10750        // no caret can land on. The map is rebuilt between keystrokes exactly as a
10751        // frontend does, since Backspace reads the stop table to place the delete.
10752        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
10753        d.caret = 6; // end of "item"
10754        d.newline();
10755        d.build_visual(80);
10756        d.newline(); // leave the list onto a fresh empty paragraph
10757        d.build_visual(80);
10758        assert_eq!(
10759            d.source, "- item\n\n\n\nnext\n",
10760            "double-Enter opens the empty paragraph"
10761        );
10762        d.backspace();
10763        assert_eq!(
10764            d.source, "- item\n\nnext\n",
10765            "one Backspace collapses the whole gap"
10766        );
10767        assert_eq!(
10768            d.caret, 6,
10769            "and lands the caret back at the end of the list item"
10770        );
10771    }
10772
10773    #[test]
10774    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
10775        // The stop-wise delete must not over-reach when there is no block boundary
10776        // to cross: two blank lines in a row are one caret stop apart, so pressing
10777        // Enter on an empty line and then Backspace removes exactly the one newline
10778        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
10779        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
10780        d.caret = 5; // the empty paragraph the first Enter already opened
10781        d.build_visual(80);
10782        d.newline();
10783        d.build_visual(80);
10784        assert_eq!(
10785            d.source, "abc\n\n\n\n",
10786            "Enter on the blank line adds one newline"
10787        );
10788        d.backspace();
10789        assert_eq!(
10790            d.source, "abc\n\n\n",
10791            "Backspace takes back exactly that one newline"
10792        );
10793    }
10794
10795    #[test]
10796    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
10797        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
10798        d.caret = 6; // end of the empty "- " item
10799        d.newline();
10800        d.insert("p");
10801        assert_eq!(d.source, "- a\n\np\n");
10802    }
10803
10804    #[test]
10805    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
10806        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
10807        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
10808        // not take the list-exit path (which would splice the `- ` away as if
10809        // leaving an empty item); the AST guard sends it to a normal break and
10810        // leaves the underline intact.
10811        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
10812        assert!(
10813            d.nodes().iter().any(|n| n.kind == Kind::Heading),
10814            "precondition: twig parses this as a heading, not a list",
10815        );
10816        d.caret = 7; // on the `- ` underline line
10817        d.newline();
10818        assert!(
10819            d.source.contains("- "),
10820            "the setext underline survives, not spliced away as a list item: {:?}",
10821            d.source,
10822        );
10823    }
10824
10825    #[test]
10826    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
10827        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
10828        d.caret = 7; // end of "abc" inside the fence
10829        d.newline();
10830        d.insert("def");
10831        assert_eq!(d.source, "```\nabc\ndef\n```\n");
10832    }
10833
10834    #[test]
10835    fn wysiwyg_enter_continues_a_block_quote() {
10836        // Enter opens a new *paragraph* inside the quote, not a second line of
10837        // the same one. `> quote\n> more` is a soft break, which under
10838        // `LineFlow::Fold` renders as a space — the keystroke would look like it
10839        // did nothing. The quoted blank line is what makes the break visible, and
10840        // it's the same thing Enter does in running prose.
10841        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
10842        d.caret = 7; // end of "quote"
10843        d.newline();
10844        d.insert("more");
10845        assert_eq!(d.source, "> quote\n>\n> more\n");
10846        // Still one quote, now holding two paragraphs — not a quote and a stray
10847        // line that fell out of it.
10848        let quotes = d
10849            .nodes()
10850            .iter()
10851            .filter(|n| n.kind == Kind::BlockQuote)
10852            .count();
10853        assert_eq!(quotes, 1);
10854    }
10855
10856    #[test]
10857    fn set_block_makes_a_heading_at_the_caret() {
10858        let mut d = doc_with("head", "Title\n\nbody\n");
10859        d.caret = 0;
10860        d.set_block(BlockKind::Heading(2));
10861        assert_eq!(d.source, "## Title\n\nbody\n");
10862        d.set_block(BlockKind::Paragraph);
10863        assert_eq!(d.source, "Title\n\nbody\n");
10864    }
10865
10866    // ── block containers (quote / list) ──────────────────────────────────────
10867
10868    #[test]
10869    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
10870        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
10871        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
10872        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
10873        // A caret at a line end sits at the doc level; the block is still found.
10874        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
10875    }
10876
10877    #[test]
10878    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
10879        // Every source line of the paragraph gets its own `> `, so a caret left
10880        // on its old byte offset falls one prefix per line above it too far
10881        // back — inside the markup it just asked for rather than in its word.
10882        assert_eq!(
10883            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
10884            "> aaa\n> b|bb\n> ccc\n"
10885        );
10886    }
10887
10888    #[test]
10889    fn toggle_blockquote_works_in_wysiwyg_view() {
10890        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
10891        assert_eq!(
10892            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
10893            "> hel|lo\n"
10894        );
10895        assert_eq!(
10896            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
10897            "hel|lo\n"
10898        );
10899    }
10900
10901    #[test]
10902    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
10903        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
10904        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
10905        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
10906        // The *other* kind converts in place instead of nesting, which is what
10907        // makes the two buttons one three-state control.
10908        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
10909        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
10910        // Its own kind, over the only item the list holds, takes it off.
10911        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
10912    }
10913
10914    #[test]
10915    fn toggle_list_works_in_wysiwyg_view() {
10916        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
10917        assert_eq!(
10918            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
10919            "1. hel|lo\n"
10920        );
10921        assert_eq!(
10922            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
10923            "- hel|lo\n"
10924        );
10925        assert_eq!(
10926            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
10927            "hel|lo\n"
10928        );
10929    }
10930
10931    #[test]
10932    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
10933        // The selection has to grow with the markup: twig takes a container off
10934        // only a range covering every block it holds, so the second press can
10935        // reverse the first only if the result is what's selected.
10936        let mut d = doc_with("list_sel", "abc\n\ndef\n");
10937        d.select_all();
10938        d.toggle_list(true);
10939        assert_eq!(d.source, "1. abc\n\n2. def\n");
10940        assert_eq!(d.selection(), Some((0, d.source.len())));
10941        d.toggle_list(true);
10942        assert_eq!(d.source, "abc\n\ndef\n");
10943    }
10944
10945    #[test]
10946    fn toggle_blockquote_nests_a_partly_covered_quote() {
10947        // twig's rule: covering only some of a container's blocks nests, because
10948        // taking the quote off would drag its uncovered siblings out with it.
10949        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
10950        d.caret = 2; // in the first quoted paragraph only
10951        d.toggle_blockquote();
10952        assert_eq!(d.source, "> > a\n>\n> b\n");
10953    }
10954
10955    #[test]
10956    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
10957        // A blank line used to be no block for twig to wrap —
10958        // `toggle_block_container` answered `NotFound` — so Quote and the list
10959        // buttons did nothing on the very line the H1 button works on, and leaf
10960        // lent twig a scratch paragraph to wrap and took it back out again.
10961        // twig 3.2.0 opens an empty container there itself, so what is left here
10962        // is where the caret lands: inside the marker that was just written.
10963        let mut d = doc_with("quote_blank", "\nabc\n");
10964        d.caret = 0;
10965        d.toggle_blockquote();
10966        assert_eq!(d.source, "> \nabc\n");
10967        assert_eq!(
10968            d.caret, 2,
10969            "the caret belongs inside the quote it just opened"
10970        );
10971        assert!(d.status.is_none(), "{:?}", d.status);
10972        assert!(d.dirty);
10973
10974        // And the paragraph below is still its own block: an empty container one
10975        // soft break from `abc` would take that paragraph into the quote with it.
10976        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
10977        d.caret = 0;
10978        d.toggle_blockquote();
10979        d.build_visual(80);
10980        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
10981
10982        // The same from the other side: a blank line directly under a paragraph
10983        // earns the blank line an empty block needs, rather than being read as a
10984        // soft break inside that paragraph.
10985        let mut d = doc_with("list_blank_below", "abc\n");
10986        d.caret = 4;
10987        d.toggle_list(false);
10988        assert_eq!(d.source, "abc\n\n- ");
10989        assert_eq!(d.caret, 7);
10990    }
10991
10992    #[test]
10993    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
10994        // The gesture the rendering fix is for. `newline` inside a quote already
10995        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
10996        // spelling — but the two marker lines it adds belonged to no node until
10997        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
10998        // just made drew as plain prose under the quote.
10999        let mut d = wysiwyg_doc("quote_enter", "> a\n");
11000        d.caret = 3; // past `a`, at the end of the quoted line
11001        d.newline();
11002        assert_eq!(d.source, "> a\n>\n> \n");
11003        d.build_visual(80);
11004        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
11005        // And the caret is on the new line, not stranded on the old one.
11006        assert_eq!(d.caret, 8);
11007    }
11008
11009    #[test]
11010    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
11011        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
11012        // now it is twig's single edit. Either way one ⌘z has to put the blank
11013        // line back rather than undoing into a half-built document.
11014        for open in [
11015            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
11016            &|d: &mut Doc| d.toggle_list(false),
11017            &|d: &mut Doc| d.toggle_list(true),
11018        ] {
11019            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
11020            d.caret = 3;
11021            open(&mut d);
11022            assert_ne!(d.source, "a\n\n\n\nb\n");
11023            d.undo();
11024            assert_eq!(d.source, "a\n\n\n\nb\n");
11025        }
11026    }
11027
11028    #[test]
11029    fn a_container_toggle_is_one_undo_step() {
11030        let mut d = doc_with("quote_undo", "hello\n");
11031        d.caret = 3;
11032        d.insert("X"); // a typing run the structural edit must not fold into
11033        d.toggle_blockquote();
11034        assert_eq!(d.source, "> helXlo\n");
11035        d.undo();
11036        assert_eq!(d.source, "helXlo\n");
11037    }
11038
11039    // ── links ────────────────────────────────────────────────────────────────
11040
11041    #[test]
11042    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
11043        let mut d = doc_with("link_sel", "word here\n");
11044        d.anchor = Some(0);
11045        d.caret = 4;
11046        d.insert_link("http://x.dev");
11047        assert_eq!(d.source, "[word](http://x.dev) here\n");
11048        // The text, not the destination — so a second press re-points the link
11049        // the first one made rather than nesting one inside it.
11050        assert_eq!(d.selected_text(), Some("word"));
11051        d.insert_link("http://y.dev");
11052        assert_eq!(d.source, "[word](http://y.dev) here\n");
11053        assert_eq!(d.selected_text(), Some("word"));
11054    }
11055
11056    #[test]
11057    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
11058        let mut d = doc_with("img_caret", "before after\n");
11059        d.caret = 7; // between "before " and "after"
11060        d.insert_image("cat.png", "a cat");
11061        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
11062        // The caret sits just past the inserted image, nothing selected.
11063        assert_eq!(d.selection(), None);
11064        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
11065    }
11066
11067    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
11068    /// destination at the first space, so the `format!` this used to be wrote
11069    /// something that was not an image at all — and the reader saw the markup as
11070    /// text. twig owns the spelling now, and moves it into the angle form.
11071    #[test]
11072    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
11073        let mut d = doc_with("img_space", "x\n");
11074        d.caret = 0;
11075        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
11076        assert_eq!(
11077            d.source,
11078            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
11079        );
11080        // And it reads back as an image pointing at the unescaped path — the angle
11081        // brackets are spelling, not part of the destination.
11082        d.caret = 2;
11083        assert_eq!(
11084            d.image_destination_at_caret(),
11085            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
11086        );
11087    }
11088
11089    /// A `)` in a caption or a filename must not close the image early.
11090    #[test]
11091    fn insert_image_escapes_a_paren_in_either_half() {
11092        let mut d = doc_with("img_paren", "x\n");
11093        d.caret = 0;
11094        d.insert_image("a)b.png", "");
11095        assert_eq!(d.source, "![](a\\)b.png)x\n");
11096        d.caret = 2;
11097        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
11098    }
11099
11100    #[test]
11101    fn insert_image_uses_the_selection_as_alt_text() {
11102        let mut d = doc_with("img_sel", "caption here\n");
11103        d.anchor = Some(0);
11104        d.caret = 7; // "caption"
11105        d.insert_image("p.png", "ignored fallback");
11106        assert_eq!(d.source, "![caption](p.png) here\n");
11107    }
11108
11109    #[test]
11110    fn insert_image_with_no_alt_leaves_empty_brackets() {
11111        let mut d = doc_with("img_noalt", "\n");
11112        d.caret = 0;
11113        d.insert_image("logo.svg", "");
11114        assert_eq!(d.source, "![](logo.svg)\n");
11115    }
11116
11117    // ── move_block ─────────────────────────────────────────────────────────────
11118
11119    /// A move, then its undo: one step takes the whole thing back.
11120    fn moved(name: &str, body: &str, from: usize, to: usize) -> (String, Doc) {
11121        let mut d = doc_with(name, body);
11122        d.caret = from;
11123        let steps = d.undo_steps;
11124        d.move_block(from, to);
11125        let after = d.source.clone();
11126        assert_eq!(d.undo_steps, steps + 1, "one undo step");
11127        assert!(d.dirty);
11128        d.undo();
11129        assert_eq!(d.source, body, "one undo restores the original");
11130        (after, d)
11131    }
11132
11133    #[test]
11134    fn move_block_carries_a_paragraph_between_two_paragraphs_and_to_the_end() {
11135        let body = "a\n\nb\n\nc\n";
11136        assert_eq!(moved("mv_p1", body, 6, 3).0, "a\n\nc\n\nb\n");
11137        assert_eq!(moved("mv_p2", body, 0, body.len()).0, "b\n\nc\n\na\n");
11138        assert_eq!(moved("mv_p3", body, 3, 0).0, "b\n\na\n\nc\n");
11139    }
11140
11141    #[test]
11142    fn move_block_carries_an_image_block() {
11143        let body = "a\n\n![p](x.png)\n\nc\n";
11144        assert_eq!(moved("mv_img1", body, 4, 0).0, "![p](x.png)\n\na\n\nc\n");
11145        assert_eq!(
11146            moved("mv_img2", body, 4, body.len()).0,
11147            "a\n\nc\n\n![p](x.png)\n"
11148        );
11149    }
11150
11151    #[test]
11152    fn move_block_carries_a_table() {
11153        let body = "a\n\n| h |\n|---|\n| c |\n\nc\n";
11154        assert_eq!(
11155            moved("mv_tbl1", body, 5, 0).0,
11156            "| h |\n|---|\n| c |\n\na\n\nc\n"
11157        );
11158        assert_eq!(
11159            moved("mv_tbl2", body, 5, body.len()).0,
11160            "a\n\nc\n\n| h |\n|---|\n| c |\n"
11161        );
11162    }
11163
11164    #[test]
11165    fn move_block_carries_a_code_block() {
11166        let body = "a\n\n```rs\nx\n```\n\nc\n";
11167        assert_eq!(moved("mv_code1", body, 8, 0).0, "```rs\nx\n```\n\na\n\nc\n");
11168        assert_eq!(
11169            moved("mv_code2", body, 8, body.len()).0,
11170            "a\n\nc\n\n```rs\nx\n```\n"
11171        );
11172    }
11173
11174    #[test]
11175    fn move_block_onto_its_own_boundary_is_a_quiet_no_op() {
11176        let mut d = doc_with("mv_noop", "a\n\nb\n");
11177        let steps = d.undo_steps;
11178        d.move_block(0, 0);
11179        d.move_block(0, 3);
11180        assert_eq!(d.source, "a\n\nb\n");
11181        assert_eq!(d.undo_steps, steps);
11182        assert_eq!(d.status, None);
11183        assert!(!d.dirty);
11184    }
11185
11186    #[test]
11187    fn move_block_into_a_fence_is_refused_with_a_status() {
11188        let mut d = doc_with("mv_fence", "a\n\n```\nx\ny\n```\n");
11189        d.move_block(0, 7);
11190        assert_eq!(d.source, "a\n\n```\nx\ny\n```\n");
11191        assert!(
11192            d.status
11193                .as_deref()
11194                .is_some_and(|s| s.starts_with("move block"))
11195        );
11196    }
11197
11198    #[test]
11199    fn move_block_rides_the_caret_with_the_block() {
11200        // Down: "second" is line 0 of its block, caret 3 bytes from its end.
11201        let mut d = doc_with("mv_caret1", "first\n\nsecond\n\nthird\n");
11202        d.caret = 10; // "sec|ond"
11203        d.move_block(10, d.source.len());
11204        assert_eq!(d.source, "first\n\nthird\n\nsecond\n");
11205        assert_eq!(&d.source[d.caret..], "ond\n");
11206        // Up, across a wrapped paragraph's second line.
11207        let mut d = doc_with("mv_caret2", "first\n\nsecond\nline two\n");
11208        d.caret = 16; // "li|ne two"
11209        d.move_block(16, 0);
11210        assert_eq!(d.source, "second\nline two\n\nfirst\n");
11211        assert_eq!(&d.source[d.caret..], "ne two\n\nfirst\n");
11212        assert_eq!(d.selection(), None);
11213    }
11214
11215    #[test]
11216    fn move_block_keeps_the_caret_on_its_line_through_a_quotes_prefix() {
11217        let mut d = doc_with("mv_quote_caret", "para\n\n> a\n");
11218        d.caret = 2; // "pa|ra"
11219        d.move_block(2, 9); // after a, inside the quote
11220        assert_eq!(d.source, "> a\n>\n> para\n");
11221        assert_eq!(&d.source[d.caret..], "ra\n");
11222    }
11223
11224    #[test]
11225    fn move_block_up_and_down_step_over_siblings() {
11226        let mut d = doc_with("mv_updown", "a\n\nb\n\nc\n");
11227        d.caret = 3;
11228        d.move_block_down();
11229        assert_eq!(d.source, "a\n\nc\n\nb\n");
11230        assert_eq!(&d.source[d.caret..], "b\n");
11231        d.move_block_down();
11232        assert_eq!(d.source, "a\n\nc\n\nb\n", "nothing below the last block");
11233        assert_eq!(d.status.as_deref(), Some("move block: nothing below"));
11234        d.move_block_up();
11235        d.move_block_up();
11236        assert_eq!(d.source, "b\n\na\n\nc\n");
11237        assert_eq!(&d.source[d.caret..], "b\n\na\n\nc\n");
11238        d.move_block_up();
11239        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11240    }
11241
11242    #[test]
11243    fn move_block_up_and_down_reorder_list_items_with_their_children() {
11244        let mut d = doc_with("mv_items", "- a\n  - x\n- b\n- c\n");
11245        d.caret = 12; // in "b"
11246        d.move_block_up();
11247        assert_eq!(d.source, "- b\n- a\n  - x\n- c\n");
11248        assert_eq!(&d.source[d.caret..], "b\n- a\n  - x\n- c\n");
11249        d.caret = 6; // in "a"
11250        d.move_block_down();
11251        assert_eq!(d.source, "- b\n- c\n- a\n  - x\n");
11252        assert_eq!(&d.source[d.caret..], "a\n  - x\n");
11253        // A nested item leaves its list upward, as an item of the outer one.
11254        d.caret = 16; // in "x"
11255        d.move_block_up();
11256        assert_eq!(d.source, "- b\n- c\n- x\n- a\n");
11257    }
11258
11259    #[test]
11260    fn move_block_on_a_lone_item_that_stays_a_bullet_is_no_step() {
11261        let mut d = doc_with("mv_lone_item", "x\n\n- b\n\ny\n");
11262        d.caret = 5;
11263        let steps = d.undo_steps;
11264        d.move_block_up();
11265        assert_eq!(d.source, "x\n\n- b\n\ny\n");
11266        assert_eq!(
11267            d.undo_steps, steps,
11268            "a move that rewrote nothing is no undo step"
11269        );
11270        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11271    }
11272
11273    #[test]
11274    fn move_block_up_leaves_a_container_at_its_first_block_and_down_at_its_last() {
11275        let mut d = doc_with("mv_leave", "x\n\n> a\n>\n> b\n\ny\n");
11276        d.caret = 5; // "a"
11277        d.move_block_up();
11278        assert_eq!(d.source, "x\n\na\n\n> b\n\ny\n");
11279        d.caret = 8; // "b"
11280        d.move_block_down();
11281        assert_eq!(d.source, "x\n\na\n\nb\n\ny\n");
11282        // A tail block leaves its item into the next item's tail, then the list.
11283        let mut d = doc_with("mv_tail", "- a\n\n  t\n- b\n");
11284        d.caret = 7;
11285        d.move_block_down();
11286        assert_eq!(d.source, "- a\n- b\n\n  t\n");
11287        d.move_block_down();
11288        assert_eq!(d.source, "- a\n- b\n\nt\n");
11289        // And a paragraph after a quote steps over the whole quote, not into it.
11290        let mut d = doc_with("mv_over", "x\n\n> a\n>\n> b\n\ny\n");
11291        d.caret = 14;
11292        d.move_block_up();
11293        assert_eq!(d.source, "x\n\ny\n\n> a\n>\n> b\n");
11294        assert_eq!(d.caret, 3);
11295        d.move_block_down();
11296        assert_eq!(d.status, None);
11297        assert_eq!(d.source, "x\n\n> a\n>\n> b\n\ny\n");
11298        // Above a quote that opens the document is offset 0 — before the
11299        // quote, not inside it.
11300        let mut d = doc_with("mv_over_top", "> a\n\ny\n");
11301        d.caret = 5;
11302        d.move_block_up();
11303        assert_eq!(d.source, "y\n\n> a\n");
11304        assert_eq!(d.caret, 0);
11305    }
11306
11307    #[test]
11308    fn move_block_up_from_the_first_block_of_a_quote_that_opens_the_document_leaves_it() {
11309        let mut d = doc_with("mv_top_quote", "> a\n>\n> b\n");
11310        d.caret = 2;
11311        d.move_block_up();
11312        assert_eq!(d.source, "a\n\n> b\n");
11313        assert_eq!(d.caret, 0);
11314        assert_eq!(d.status, None);
11315    }
11316
11317    #[test]
11318    fn move_block_on_a_blank_line_or_read_only_does_nothing() {
11319        let mut d = doc_with("mv_blank", "a\n\nb\n");
11320        d.caret = 2;
11321        d.move_block_down();
11322        assert_eq!(d.source, "a\n\nb\n");
11323        assert_eq!(d.status.as_deref(), Some("move block: no block here"));
11324        d.read_only = true;
11325        d.caret = 0;
11326        d.move_block_down();
11327        d.move_block(0, 5);
11328        assert_eq!(d.source, "a\n\nb\n");
11329    }
11330
11331    #[test]
11332    fn move_block_never_lands_above_hidden_frontmatter() {
11333        let mut d = wysiwyg_doc("mv_fm", "---\nt: x\n---\n\na\n\nb\n");
11334        let b = d.source.find('b').unwrap();
11335        d.move_block(b, 0);
11336        assert_eq!(d.source, "---\nt: x\n---\n\nb\n\na\n");
11337    }
11338
11339    #[test]
11340    fn block_range_at_is_the_block_a_move_picks_up() {
11341        let mut d = doc_with("mv_range", "a\n\n- b\n  - c\n\nd\n");
11342        assert_eq!(d.block_range_at(0), Some(0..1));
11343        assert_eq!(d.block_range_at(5), Some(3..12), "the item with its child");
11344        assert_eq!(d.block_range_at(10), Some(7..12), "the nested item alone");
11345        assert_eq!(d.block_range_at(2), None, "a blank line");
11346    }
11347
11348    #[test]
11349    fn drop_target_at_splits_a_block_at_its_middle_row_and_ends_below_everything() {
11350        let long = "two ".repeat(40).trim_end().to_string(); // wraps to three rows at 80
11351        let mut d = wysiwyg_doc("drop", &format!("one\n\n{long} four\n\nfive\n"));
11352        let rows = d.vmap.rows.len();
11353        assert_eq!(rows, 7, "one, gap, three wrapped rows, gap, five");
11354        assert_eq!(d.drop_target_at(0), Some(DropTarget { offset: 0, row: 0 }));
11355        let two = d.source.find("two").unwrap();
11356        assert_eq!(
11357            d.drop_target_at(1),
11358            Some(DropTarget {
11359                offset: two,
11360                row: 2
11361            }),
11362            "the gap resolves to the block under it"
11363        );
11364        assert_eq!(
11365            d.drop_target_at(2),
11366            Some(DropTarget {
11367                offset: two,
11368                row: 2
11369            })
11370        );
11371        assert_eq!(
11372            d.drop_target_at(3),
11373            Some(DropTarget {
11374                offset: two,
11375                row: 2
11376            })
11377        );
11378        let four_end = d.source.find("four").unwrap() + 4;
11379        assert_eq!(
11380            d.drop_target_at(4),
11381            Some(DropTarget {
11382                offset: four_end,
11383                row: 5
11384            })
11385        );
11386        assert_eq!(
11387            d.drop_target_at(rows + 3),
11388            Some(DropTarget {
11389                offset: d.source.len(),
11390                row: rows
11391            })
11392        );
11393        // And the offsets are ones move_block takes.
11394        let five = d.source.find("five").unwrap();
11395        let t = d.drop_target_at(2).unwrap();
11396        d.move_block(five, t.offset);
11397        assert_eq!(d.source, format!("one\n\nfive\n\n{long} four\n"));
11398    }
11399
11400    #[test]
11401    fn append_media_lands_at_the_end_as_its_own_block() {
11402        let mut d = doc_with("append_mid", "first word and more\n");
11403        d.caret = 0; // an editor nobody has tapped: the caret is at the start
11404        d.append_media(MediaKind::Image, "cat.png", "");
11405        assert_eq!(d.source, "first word and more\n\n![](cat.png)");
11406        assert_eq!(d.selection(), None);
11407        assert_eq!(d.caret, "first word and more\n\n![](cat.png)".len());
11408    }
11409
11410    #[test]
11411    fn append_media_needs_no_separator_after_a_blank_line_or_in_an_empty_document() {
11412        let mut d = doc_with("append_blank", "para\n\n");
11413        d.append_media(MediaKind::Image, "a.png", "");
11414        assert_eq!(d.source, "para\n\n![](a.png)");
11415
11416        let mut e = doc_with("append_empty", "");
11417        e.append_media(MediaKind::Image, "b.png", "");
11418        assert_eq!(e.source, "![](b.png)");
11419
11420        let mut f = doc_with("append_noeol", "no newline at end");
11421        f.anchor = Some(0);
11422        f.caret = 2; // a selection, which the verb ignores
11423        f.append_media(MediaKind::Video, "clip.mp4", "");
11424        assert_eq!(
11425            f.source,
11426            "no newline at end\n\n<video src=\"clip.mp4\" controls></video>"
11427        );
11428    }
11429
11430    #[test]
11431    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
11432        // The round trip is the point: it's no use writing markup the reader
11433        // can't pick up again. This is the pair that only holds from twig 2.5.1
11434        // on — before it, the one-line form went in fine and came back as a
11435        // paragraph of raw tags, publishing no media at all.
11436        let mut d = doc_with("vid_rt", "\n");
11437        d.caret = 0;
11438        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
11439        assert_eq!(
11440            d.source,
11441            "<video src=\"clip.mp4\" controls>a clip</video>\n"
11442        );
11443
11444        d.build_visual(80);
11445        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
11446        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
11447        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
11448        assert_eq!(d.vmap.media[0].alt, "a clip");
11449    }
11450
11451    #[test]
11452    fn insert_media_spells_audio_with_its_own_tag() {
11453        let mut d = doc_with("aud_rt", "\n");
11454        d.caret = 0;
11455        d.insert_media(MediaKind::Audio, "take.mp3", "");
11456        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
11457        d.build_visual(80);
11458        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
11459    }
11460
11461    #[test]
11462    fn insert_media_uses_the_selection_as_fallback_text() {
11463        // The same courtesy `insert_image` does with alt: select a caption,
11464        // insert, and the caption labels the thing rather than being replaced.
11465        let mut d = doc_with("vid_sel", "the talk here\n");
11466        d.anchor = Some(0);
11467        d.caret = 8; // "the talk"
11468        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
11469        assert_eq!(
11470            d.source,
11471            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
11472        );
11473    }
11474
11475    #[test]
11476    fn insert_media_with_an_image_kind_is_just_insert_image() {
11477        let mut d = doc_with("img_via_media", "\n");
11478        d.caret = 0;
11479        d.insert_media(MediaKind::Image, "logo.svg", "x");
11480        assert_eq!(d.source, "![x](logo.svg)\n");
11481    }
11482
11483    // ── thematic breaks ─────────────────────────────────────────────────────
11484
11485    /// The node the source parses as at `caret` — what confirms an inserted
11486    /// `---` actually reads back as a rule, not stray text or a setext heading.
11487    ///
11488    /// The *narrowest* node covering the offset. Every ancestor covers it too,
11489    /// and since twig 2.8 that includes the `doc` root, which now carries a real
11490    /// span (it reported none before, so taking the first match used to land on
11491    /// the block by luck and now always answers `"doc"`).
11492    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
11493        d.nodes()
11494            .into_iter()
11495            .filter(|n| n.span.start <= caret && caret < n.span.end)
11496            .min_by_key(|n| n.span.end - n.span.start)
11497            .map(|n| n.kind)
11498    }
11499
11500    #[test]
11501    fn a_task_box_toggles_at_the_caret_and_reads_back() {
11502        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
11503        d.caret = 8; // inside "todo"
11504        assert_eq!(d.task_checked_at_caret(), Some(false));
11505        d.toggle_task_checked();
11506        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
11507        assert_eq!(d.task_checked_at_caret(), Some(true));
11508        d.toggle_task_checked();
11509        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
11510    }
11511
11512    #[test]
11513    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
11514        // The whole reason `toggle_task_at` exists apart from the caret form:
11515        // ticking a box elsewhere must not move the cursor out of what's being
11516        // typed.
11517        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
11518        d.caret = 8; // inside "first"
11519        let second = d.source.find("second").unwrap();
11520        d.toggle_task_at(second);
11521        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
11522        assert_eq!(d.caret, 8, "the caret stayed in the first item");
11523    }
11524
11525    #[test]
11526    fn a_paragraph_becomes_a_task_item_in_one_undo_step() {
11527        let mut d = doc_with("task_para", "first\n\nplain para\n");
11528        d.caret = d.source.find("para").unwrap();
11529        d.toggle_task_item();
11530        assert_eq!(d.source, "first\n\n- [ ] plain para\n");
11531        assert_eq!(d.task_checked_at_caret(), Some(false));
11532        assert_eq!(d.status, None);
11533        d.undo();
11534        assert_eq!(
11535            d.source, "first\n\nplain para\n",
11536            "one step takes both back"
11537        );
11538    }
11539
11540    #[test]
11541    fn a_blank_line_becomes_an_empty_task_item() {
11542        let mut d = doc_with("task_blank", "first\n\n");
11543        d.caret = d.source.len();
11544        d.toggle_task_item();
11545        assert_eq!(d.task_checked_at_caret(), Some(false), "{:?}", d.source);
11546        assert_eq!(d.status, None);
11547    }
11548
11549    #[test]
11550    fn a_plain_item_gains_and_loses_a_box() {
11551        let mut d = doc_with("task_mint", "- plain\n");
11552        d.caret = 4;
11553        assert_eq!(d.task_checked_at_caret(), None);
11554        d.toggle_task_item();
11555        assert_eq!(d.source, "- [ ] plain\n");
11556        assert_eq!(
11557            d.task_checked_at_caret(),
11558            Some(false),
11559            "a new box arrives unticked"
11560        );
11561        d.toggle_task_item();
11562        assert_eq!(d.source, "- plain\n");
11563    }
11564
11565    #[test]
11566    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
11567        // `set checked` must not silently convert a bullet into a task — that is
11568        // `toggle_task_item`'s job, and twig refuses it here.
11569        let mut d = doc_with("task_none", "- plain\n");
11570        d.caret = 4;
11571        d.toggle_task_checked();
11572        assert_eq!(d.source, "- plain\n", "nothing written");
11573        assert!(
11574            d.status.is_some(),
11575            "the refusal should reach the status line"
11576        );
11577    }
11578
11579    #[test]
11580    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
11581        let mut d = doc_with("task_quote", "> - [ ] nested\n");
11582        d.caret = d.source.find("nested").unwrap();
11583        assert_eq!(d.task_checked_at_caret(), Some(false));
11584        d.toggle_task_checked();
11585        assert_eq!(d.source, "> - [x] nested\n");
11586    }
11587
11588    #[test]
11589    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
11590        // A rule is a block, so twig's `insert_thematic_break` alone lands it
11591        // after the whole paragraph. `split_block` parts the paragraph first and
11592        // the rule is aimed at the *first* half, which is what a rule button is
11593        // understood to do — and what leaf spelled by hand until twig grew both
11594        // halves of the gesture.
11595        let mut d = doc_with("hr_mid", "before after\n");
11596        d.caret = 7; // between "before " and "after"
11597        d.insert_thematic_break();
11598        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11599        assert_eq!(d.selection(), None);
11600        assert_eq!(
11601            kind_at(&mut d, "before \n\n".len()),
11602            Some(Kind::ThematicBreak)
11603        );
11604    }
11605
11606    #[test]
11607    fn insert_thematic_break_at_a_paragraph_s_end_splits_nothing() {
11608        // At the end there is nothing to part, and a split there writes the
11609        // separator anyway — a blank line and the empty slot the next paragraph
11610        // would fill — which the rule then landed above: `para\n\n* * *\n\n\n`,
11611        // two blank lines nothing fills. Now the rule lands after the paragraph,
11612        // where the split-and-aim was sending it regardless. Both formats, and
11613        // both shapes of a last line — terminated, and still being typed —
11614        // because the two reach the split through different doors: Markdown's
11615        // paragraph span stops before its newline, so `para\n` at 4 never split
11616        // there, but `para` at 4 did.
11617        //
11618        // What stands under the rule is the line the caret goes on to, not a
11619        // slot: nothing above the rule but the one blank line, and the caret on
11620        // the line beneath it.
11621        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11622            for src in ["para\n", "para"] {
11623                let mut d = Doc::from_source(src.into(), fmt).unwrap();
11624                d.caret = 4;
11625                d.insert_thematic_break();
11626                assert_eq!(d.source, format!("para\n\n{rule}\n\n"), "{fmt:?} {src:?}");
11627                assert_eq!(d.caret, d.source.len());
11628            }
11629            // Mid-document the slot sat between the rule and the next block;
11630            // the caret's line does now, a blank line either side of it.
11631            let mut d = Doc::from_source("para\n\nnext\n".into(), fmt).unwrap();
11632            d.caret = 4;
11633            d.insert_thematic_break();
11634            assert_eq!(d.source, format!("para\n\n{rule}\n\n\n\nnext\n"), "{fmt:?}");
11635            // Trailing whitespace is nothing to part either.
11636            let mut d = Doc::from_source("para  \n".into(), fmt).unwrap();
11637            d.caret = 4;
11638            d.insert_thematic_break();
11639            assert_eq!(d.source, format!("para  \n\n{rule}\n\n"), "{fmt:?}");
11640        }
11641    }
11642
11643    #[test]
11644    fn insert_thematic_break_at_a_paragraph_s_start_lands_before_it() {
11645        // The split at the start parts nothing, but it is kept on purpose:
11646        // `|para` becomes `\npara` with the caret on a blank line, and twig
11647        // (3.5.2) writes a rule aimed at a blank line ON that line — the only
11648        // way "before the paragraph" is reachable through a gesture that only
11649        // places after. Before 3.5.2 this came out as `\n\n---\n\npara`.
11650        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11651            let mut d = Doc::from_source("para\n".into(), fmt).unwrap();
11652            d.caret = 0;
11653            d.insert_thematic_break();
11654            assert_eq!(d.source, format!("{rule}\n\npara\n"), "{fmt:?}");
11655            let mut d = Doc::from_source("prev\n\npara\n".into(), fmt).unwrap();
11656            d.caret = 6;
11657            d.insert_thematic_break();
11658            assert_eq!(d.source, format!("prev\n\n{rule}\n\npara\n"), "{fmt:?}");
11659        }
11660    }
11661
11662    #[test]
11663    fn insert_thematic_break_on_a_blank_line_takes_that_line() {
11664        // The gap between two blocks is where a click lands the caret; the
11665        // rule goes on the blank, one blank each side, and the caret on the
11666        // line opened under it.
11667        let mut d = doc_with("hr_gap", "a\n\nb\n");
11668        d.caret = 2;
11669        d.insert_thematic_break();
11670        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11671        assert_eq!(d.caret, "a\n\n---\n\n".len());
11672    }
11673
11674    #[test]
11675    fn insert_thematic_break_leaves_the_caret_on_a_line_under_the_rule() {
11676        // The caret used to be left where twig's splice ended, the home past
11677        // the rule, which is drawn on the rule's own row: the writer saw the
11678        // caret beside the rule, and mid-document what they typed next ran
11679        // into the block below. Now it goes on to an empty row under the
11680        // rule's gap from every place a rule is asked for — the end of a
11681        // paragraph, the empty paragraph Enter opened, a list and the line
11682        // Enter leaves a list for, closing the document and before another
11683        // block — and what is typed there is a paragraph of its own.
11684        for (body, caret, typed) in [
11685            ("para\n", 4, "para\n\n---\n\nX"),
11686            ("para\n\n\n", 6, "para\n\n---\n\nX"),
11687            ("- one\n- two\n", 11, "- one\n- two\n\n---\n\nX"),
11688            ("- one\n- two\n\n\n", 13, "- one\n- two\n\n---\n\nX"),
11689            ("a\n\nb\n", 1, "a\n\n---\n\nX\n\nb\n"),
11690            ("a\n\n\n\nb\n", 3, "a\n\n---\n\nX\n\nb\n"),
11691        ] {
11692            let mut d = wysiwyg_doc("hr_caret", body);
11693            d.build_visual(80);
11694            d.caret = caret;
11695            d.insert_thematic_break();
11696            d.build_visual(80);
11697            let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11698            let (row, col) = d.vmap.pos_of_offset(d.caret);
11699            assert_eq!((row, col), (rule + 2, 0), "{body:?} → {:?}", d.source);
11700            assert!(d.vmap.rows[rule + 1].decoration, "the gap under the rule");
11701            assert!(d.vmap.rows[row].glyphs.is_empty(), "an empty line");
11702            d.insert("X");
11703            assert_eq!(d.source, typed, "{body:?}");
11704            let rule_at = d.source.find("---").unwrap();
11705            assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
11706        }
11707        // djot's rule takes in its newline; the line under it is the same.
11708        let mut d = Doc::from_source("a\n\nb\n".into(), Format::Djot).unwrap();
11709        d.view = View::Wysiwyg;
11710        d.caret = 1;
11711        d.insert_thematic_break();
11712        d.build_visual(80);
11713        assert_eq!(d.source, "a\n\n* * *\n\n\n\nb\n");
11714        assert_eq!(d.vmap.pos_of_offset(d.caret), (4, 0));
11715    }
11716
11717    #[test]
11718    fn a_rule_parting_a_paragraph_leaves_the_caret_before_its_second_half() {
11719        // The line under the rule is the paragraph's second half, so that is
11720        // where the caret goes: the text it was standing in front of is still
11721        // in front of it.
11722        let mut d = wysiwyg_doc("hr_parted", "before after\n");
11723        d.caret = 7;
11724        d.insert_thematic_break();
11725        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11726        assert_eq!(d.caret, d.source.find("after").unwrap());
11727        // At the start of a paragraph too, the rule landing above it.
11728        let mut d = wysiwyg_doc("hr_parted_start", "prev\n\npara\n");
11729        d.caret = 6;
11730        d.insert_thematic_break();
11731        assert_eq!(d.caret, d.source.find("para").unwrap());
11732    }
11733
11734    #[test]
11735    fn the_line_under_a_new_rule_is_one_undo_step_with_it() {
11736        let mut d = wysiwyg_doc("hr_undo", "a\n\nb\n");
11737        d.caret = 1;
11738        d.insert_thematic_break();
11739        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11740        d.undo();
11741        assert_eq!(d.source, "a\n\nb\n");
11742        assert!(!d.can_undo());
11743        d.redo();
11744        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11745    }
11746
11747    #[test]
11748    fn a_rule_in_preserve_flow_leaves_the_caret_on_the_first_line_under_it() {
11749        // Preserve draws every blank line as somewhere to type, the first under
11750        // the rule included, so that is the caret's line and the one written.
11751        let mut d = wysiwyg_doc("hr_preserve", "para\n");
11752        d.set_line_flow(LineFlow::Preserve);
11753        d.caret = 4;
11754        d.insert_thematic_break();
11755        assert_eq!(d.source, "para\n\n---\n\n");
11756        assert_eq!(d.caret, "para\n\n---\n".len());
11757        d.build_visual(80);
11758        let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11759        assert_eq!(d.vmap.pos_of_offset(d.caret), (rule + 1, 0));
11760        // Before another block, one blank line more keeps it off that block.
11761        let mut d = wysiwyg_doc("hr_preserve_mid", "a\n\nb\n");
11762        d.set_line_flow(LineFlow::Preserve);
11763        d.caret = 1;
11764        d.insert_thematic_break();
11765        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
11766        assert_eq!(d.caret, "a\n\n---\n".len());
11767    }
11768
11769    #[test]
11770    fn insert_page_break_leaves_the_caret_on_a_line_under_it() {
11771        // The rule button's placement, for the other block the toolbar writes:
11772        // the caret was left at the end of twig's splice, beside the break at
11773        // the end of the document and on the next block's first letter before
11774        // one. djot spells the break as a fence of two lines; the line under
11775        // it is under the closing `:::`.
11776        for (fmt, body, want, typed) in [
11777            (
11778                Format::Markdown,
11779                "a\n\nb\n",
11780                "a\n\n::page-break\n\n\n\nb\n",
11781                "a\n\n::page-break\n\nX\n\nb\n",
11782            ),
11783            (
11784                Format::Markdown,
11785                "a\n",
11786                "a\n\n::page-break\n\n",
11787                "a\n\n::page-break\n\nX",
11788            ),
11789            (
11790                Format::Djot,
11791                "a\n\nb\n",
11792                "a\n\n::: page-break\n:::\n\n\n\nb\n",
11793                "a\n\n::: page-break\n:::\n\nX\n\nb\n",
11794            ),
11795        ] {
11796            let mut d = Doc::from_source(body.into(), fmt).unwrap();
11797            d.view = View::Wysiwyg;
11798            d.caret = 1;
11799            d.insert_page_break();
11800            assert_eq!(d.source, want, "{fmt:?}");
11801            d.build_visual(80);
11802            let (row, col) = d.vmap.pos_of_offset(d.caret);
11803            assert_eq!(col, 0);
11804            assert!(d.vmap.rows[row].glyphs.is_empty(), "{fmt:?}: an empty line");
11805            assert!(
11806                d.vmap.rows[row - 2].leaf_directive.is_some(),
11807                "{fmt:?}: under the break"
11808            );
11809            d.insert("X");
11810            assert_eq!(d.source, typed, "{fmt:?}");
11811            d.undo();
11812            d.undo();
11813            assert_eq!(
11814                d.source, body,
11815                "{fmt:?}: the break and its line are one step"
11816            );
11817        }
11818    }
11819
11820    #[test]
11821    fn a_block_parting_a_paragraph_is_one_undo_step() {
11822        // The split went to twig without leaf counting it, so the first Undo
11823        // took back the block, left the paragraph parted, and reported nothing
11824        // more to undo.
11825        let mut rule = wysiwyg_doc("part_undo_rule", "before after\n");
11826        rule.caret = 7;
11827        rule.insert_thematic_break();
11828        let mut table = wysiwyg_doc("part_undo_table", "before after\n");
11829        table.caret = 7;
11830        table.insert_table(1, 1);
11831        let mut page = wysiwyg_doc("part_undo_page", "before after\n");
11832        page.caret = 7;
11833        page.insert_page_break();
11834        for (name, d) in [
11835            ("rule", &mut rule),
11836            ("table", &mut table),
11837            ("page break", &mut page),
11838        ] {
11839            assert_ne!(d.source, "before after\n", "{name}");
11840            d.undo();
11841            assert_eq!(d.source, "before after\n", "{name}: one Undo");
11842            assert_eq!(d.caret, 7, "{name}: the caret back where it was");
11843            assert!(!d.can_undo(), "{name}");
11844            assert!(d.can_redo(), "{name}");
11845            d.redo();
11846            assert!(!d.source.starts_with("before after"), "{name}: one Redo");
11847            assert!(!d.can_redo(), "{name}");
11848        }
11849        // A table twig would refuse parts nothing: the refusal comes first.
11850        let mut d = wysiwyg_doc("part_undo_zero", "before after\n");
11851        d.caret = 7;
11852        d.insert_table(0, 1);
11853        assert_eq!(d.source, "before after\n");
11854        assert!(!d.can_undo());
11855    }
11856
11857    #[test]
11858    fn enter_at_a_paragraph_s_start_opens_an_empty_paragraph_above_it() {
11859        // twig's split at a paragraph's start writes one newline ahead of it,
11860        // which Fold draws as one more gap, so the first Enter showed nothing.
11861        // A paragraph break opens a line above, the caret staying before the
11862        // text. Past a mark's opening delimiters — where a tap before the
11863        // first letter lands — the split used to cut the mark in two
11864        // (`**\n\nb**`); the break goes in front of them, as it goes in
11865        // front of a heading's `#`, where the heading's own Enter left an
11866        // empty heading over its text as a paragraph. A paragraph that
11867        // opens a div gets its line outside the div, where it draws.
11868        for (body, caret, want, want_caret) in [
11869            ("a\n\nb\n", 3, "a\n\n\n\nb\n", 5),
11870            ("# H\n\nb\n", 5, "# H\n\n\n\nb\n", 7),
11871            ("a\n\n# H\n", 5, "a\n\n\n\n# H\n", 7),
11872            ("a\n\n**b** c\n", 3, "a\n\n\n\n**b** c\n", 5),
11873            ("a\n\n**b** c\n", 5, "a\n\n\n\n**b** c\n", 7),
11874            (
11875                "a\n\n<span data-color=\"orange\">b</span>\n",
11876                29,
11877                "a\n\n\n\n<span data-color=\"orange\">b</span>\n",
11878                31,
11879            ),
11880            (
11881                "a\n\n<div class=\"center\">\n\nb\n\n</div>\n",
11882                25,
11883                "a\n\n\n\n<div class=\"center\">\n\nb\n\n</div>\n",
11884                27,
11885            ),
11886        ] {
11887            let mut d = wysiwyg_doc("enter_para_start", body);
11888            d.build_visual(80);
11889            d.caret = caret;
11890            d.newline();
11891            assert_eq!(d.source, want, "{body:?}");
11892            assert_eq!(d.caret, want_caret, "{body:?}");
11893            d.build_visual(80);
11894            let (row, _) = d.vmap.pos_of_offset(d.caret);
11895            assert!(
11896                d.vmap.rows[row - 2].glyphs.is_empty(),
11897                "{body:?}: an empty line above"
11898            );
11899            assert!(
11900                !d.vmap.rows[row - 2].decoration,
11901                "{body:?}: one the caret can stand on"
11902            );
11903        }
11904        // Past the first letter it is an ordinary split.
11905        let mut d = wysiwyg_doc("enter_para_mid", "a\n\n**b** c\n");
11906        d.caret = 8;
11907        d.newline();
11908        assert_eq!(d.source, "a\n\n**b**\n\nc\n");
11909    }
11910
11911    #[test]
11912    fn enter_again_at_a_paragraph_s_start_opens_one_more_line() {
11913        // The first Enter's paragraph break leaves a gap either side of the
11914        // empty line. A second break drew two lines more; a newline draws one.
11915        let mut d = wysiwyg_doc("enter_para_again", "a\n\nb\n");
11916        d.build_visual(80);
11917        d.caret = 3;
11918        for (want, lines) in [("a\n\n\n\nb\n", 1), ("a\n\n\n\n\nb\n", 2)] {
11919            d.newline();
11920            assert_eq!(d.source, want);
11921            assert_eq!(&d.source[d.caret..], "b\n");
11922            d.build_visual(80);
11923            let empty = d
11924                .vmap
11925                .rows
11926                .iter()
11927                .filter(|r| r.glyphs.is_empty() && !r.decoration)
11928                .count();
11929            assert_eq!(empty, lines, "{want:?}");
11930        }
11931    }
11932
11933    #[test]
11934    fn enter_at_the_first_block_s_start_pushes_it_down() {
11935        // No row was drawn for a blank line above the first block, so Enter
11936        // there wrote a line and the text stayed where it was. Each Enter now
11937        // draws one empty line above it, the caret staying with the text;
11938        // past frontmatter, the line conventionally under it still draws
11939        // nothing until Enter adds to it.
11940        for (body, caret, wants) in [
11941            ("b\n", 0, ["\n\nb\n", "\n\n\nb\n"]),
11942            ("**b** c\n", 2, ["\n\n**b** c\n", "\n\n\n**b** c\n"]),
11943            ("# H\n", 2, ["\n\n# H\n", "\n\n\n# H\n"]),
11944            (
11945                "---\nt: x\n---\n\nb\n",
11946                14,
11947                ["---\nt: x\n---\n\n\nb\n", "---\nt: x\n---\n\n\n\nb\n"],
11948            ),
11949        ] {
11950            let mut d = wysiwyg_doc("enter_first_block", body);
11951            d.build_visual(80);
11952            let empty = |d: &Doc| {
11953                d.vmap
11954                    .rows
11955                    .iter()
11956                    .filter(|r| r.glyphs.is_empty() && !r.decoration)
11957                    .count()
11958            };
11959            assert_eq!(empty(&d), 0, "{body:?}: nothing above the text yet");
11960            d.caret = caret;
11961            for (lines, want) in wants.into_iter().enumerate() {
11962                d.newline();
11963                assert_eq!(d.source, want, "{body:?}");
11964                assert!(d.source[d.caret..].starts_with(&body[caret..]), "{body:?}");
11965                d.build_visual(80);
11966                assert_eq!(empty(&d), lines + 1, "{want:?}");
11967            }
11968            // The caret can go up onto the lines it opened.
11969            d.move_up(false);
11970            let (row, _) = d.vmap.pos_of_offset(d.caret);
11971            assert!(d.vmap.rows[row].glyphs.is_empty(), "{body:?}");
11972            assert!(!d.vmap.rows[row].decoration, "{body:?}");
11973        }
11974    }
11975
11976    /// What a reader sees of a map: each row's text, whether it is a gap,
11977    /// and the presentation it is drawn with. Offsets are left out, since an
11978    /// edit shifts them without anything on screen changing.
11979    fn drawn(d: &Doc) -> Vec<String> {
11980        d.vmap
11981            .rows
11982            .iter()
11983            .map(|r| {
11984                let text: String = r.glyphs.iter().map(|g| g.ch).collect();
11985                format!(
11986                    "{}{text:?} h={:?} lh={:?} a={:?}",
11987                    if r.decoration { "~" } else { "" },
11988                    r.heading,
11989                    r.line_height,
11990                    r.align
11991                )
11992            })
11993            .collect()
11994    }
11995
11996    #[test]
11997    fn enter_and_backspace_anywhere_show_what_they_write_and_undo_in_one_step() {
11998        // Enter that writes what the view does not draw looks like a key that
11999        // did nothing, so it gets pressed again, and the lines pile up unseen
12000        // until something redraws them all at once. The rule, the page break,
12001        // a paragraph's start, the first block's start and the blank page
12002        // were each that bug once. So: at every place the caret can stand, in
12003        // both flows, Enter either changes what is drawn or writes nothing,
12004        // and one Undo takes back whatever it wrote. Enter and Backspace both
12005        // leave the view a fresh open of the text would draw, so nothing
12006        // moves when the view is next rebuilt from scratch.
12007        let cases: &[(Format, &str)] = &[
12008            (
12009                Format::Markdown,
12010                "I talk to myself\n\nI laugh\n\nI cry\n\nknees to nose\n\nlet me go\n",
12011            ),
12012            (Format::Markdown, "I talk to myself\nI laugh\nI cry\n"),
12013            (
12014                Format::Markdown,
12015                "<div data-line-height=\"1.5\">\n\nI laugh\n\nI cry\n\nknees to nose\n\n</div>\n",
12016            ),
12017            (
12018                Format::Markdown,
12019                "<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",
12020            ),
12021            (
12022                Format::Markdown,
12023                "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n",
12024            ),
12025            (
12026                Format::Markdown,
12027                "---\ntitle: x\n---\n\n# Title\n\nbody **bold** and <span data-color=\"red\">red</span>\n",
12028            ),
12029            (Format::Markdown, "\n\n\nafter blank lines\n\n\n\nmid\n\n\n"),
12030            (
12031                Format::Markdown,
12032                "- one\n- two\n\n1. a\n2. b\n\n- [ ] task\n",
12033            ),
12034            (Format::Markdown, "> quoted\n> more\n\n> - in a quote\n"),
12035            (Format::Markdown, "a\n\n---\n\nb\n\n::page-break\n\nc\n"),
12036            (Format::Markdown, "Title\n=====\n\nSub\n---\n\ntext\n"),
12037            (
12038                Format::Markdown,
12039                "```\ncode\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n",
12040            ),
12041            (Format::Djot, "I laugh\n\nI cry\n\nknees to nose\n"),
12042            (
12043                Format::Djot,
12044                "{data-line-height=\"2\"}\nI cry\n\n{data-line-height=\"2\"}\nknees to nose\n",
12045            ),
12046            (Format::Djot, "# Title\n\na\n\n* * *\n\nb\n"),
12047            // HTML is not here: Enter writes blank lines there, which the
12048            // view draws and HTML does not keep. See
12049            // docs/tasks/enter-in-html-writes-whitespace.md.
12050        ];
12051        let mut failures = Vec::new();
12052        for &(format, body) in cases {
12053            for flow in [LineFlow::Fold, LineFlow::Preserve] {
12054                let open = || {
12055                    let mut d = Doc::from_source(body.into(), format).unwrap();
12056                    d.view = View::Wysiwyg;
12057                    d.set_line_flow(flow);
12058                    d.build_visual_unwrapped();
12059                    d
12060                };
12061                // The map a fresh open of the same text would draw. The
12062                // edited map differing from it is a view that changes on the
12063                // next full rebuild, seconds after the key, with no key.
12064                let fresh = |source: &str| {
12065                    let mut ed =
12066                        twig::Editor::new_ext(source.as_bytes(), format, parse_extensions())
12067                            .unwrap();
12068                    let nodes = ed.nodes().unwrap();
12069                    crate::wysiwyg::build(
12070                        &nodes,
12071                        source,
12072                        None,
12073                        flow == LineFlow::Preserve,
12074                        &wysiwyg::Surface::default(),
12075                        None,
12076                    )
12077                };
12078                let probe = open();
12079                let stops: Vec<usize> = (0..=body.len())
12080                    .filter(|&o| probe.vmap.is_stop(o))
12081                    .collect();
12082                for at in stops {
12083                    for enter in [true, false] {
12084                        let mut d = open();
12085                        d.caret = at;
12086                        d.anchor = None;
12087                        let before = drawn(&d);
12088                        if enter {
12089                            d.newline();
12090                        } else {
12091                            d.backspace();
12092                        }
12093                        d.build_visual_unwrapped();
12094                        let key = if enter { "enter" } else { "backspace" };
12095                        let what = format!(
12096                            "{key} {format:?} {flow:?} caret {at} in {body:?} -> {:?}",
12097                            d.source
12098                        );
12099                        if maps_differ(&d.vmap, &fresh(&d.source)) {
12100                            failures.push(format!("redraws differently: {what}"));
12101                        }
12102                        if d.source == body {
12103                            continue;
12104                        }
12105                        if enter && drawn(&d) == before {
12106                            failures.push(format!("drew nothing: {what}"));
12107                        }
12108                        d.undo();
12109                        if d.source != body {
12110                            failures.push(format!("undo left {:?}: {what}", d.source));
12111                        }
12112                    }
12113                }
12114            }
12115        }
12116        assert!(
12117            failures.is_empty(),
12118            "{} failures:\n{}",
12119            failures.len(),
12120            failures.join("\n")
12121        );
12122    }
12123
12124    #[test]
12125    fn enter_opens_a_line_that_draws_inside_a_div_a_quote_and_preserve_flow() {
12126        // Each of these wrote a line the view did not draw, so Enter looked
12127        // dead and every press left one more.
12128        let enter = |format, flow, body: &str, at: usize| {
12129            let mut d = Doc::from_source(body.into(), format).unwrap();
12130            d.view = View::Wysiwyg;
12131            d.set_line_flow(flow);
12132            d.build_visual(80);
12133            d.caret = at;
12134            d.newline();
12135            d.build_visual(80);
12136            d
12137        };
12138        let div = "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n</div>\n";
12139        let end = div.find("knees").unwrap() + "knees".len();
12140
12141        // At the end of a div's last paragraph, the empty paragraph opens
12142        // inside the div, drawn with its line height, and what is typed
12143        // there stays in it.
12144        let mut d = enter(Format::Markdown, LineFlow::Fold, div, end);
12145        let (row, _) = d.vmap.pos_of_offset(d.caret);
12146        let r = &d.vmap.rows[row];
12147        assert!(r.glyphs.is_empty() && !r.decoration, "{:?}", drawn(&d));
12148        assert!(
12149            r.line_height.is_some(),
12150            "the new line keeps the div's spacing"
12151        );
12152        d.insert("x");
12153        assert_eq!(
12154            d.source,
12155            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\nx\n\n</div>\n"
12156        );
12157        // Preserve flow's soft line there draws too.
12158        let d = enter(Format::Markdown, LineFlow::Preserve, div, end);
12159        assert_eq!(
12160            d.source,
12161            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n\n</div>\n"
12162        );
12163        assert_eq!(d.vmap.rows.len(), 4, "{:?}", drawn(&d));
12164        // Between two of the div's paragraphs, the empty line takes its
12165        // spacing as well.
12166        let d = enter(
12167            Format::Markdown,
12168            LineFlow::Fold,
12169            div,
12170            div.find("knees").unwrap(),
12171        );
12172        let (row, _) = d.vmap.pos_of_offset(d.caret);
12173        assert!(
12174            d.vmap.rows[row - 2].line_height.is_some(),
12175            "{:?}",
12176            drawn(&d)
12177        );
12178
12179        // Under `</div>` the blank line is the one Markdown needs to end the
12180        // div. Preserve flow drew it as a line to type on, and Backspace
12181        // there glued the next paragraph to the tag (`</div>after`).
12182        let below = "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n";
12183        let mut d = Doc::from_source(below.into(), Format::Markdown).unwrap();
12184        d.view = View::Wysiwyg;
12185        d.set_line_flow(LineFlow::Preserve);
12186        d.build_visual(80);
12187        assert_eq!(d.vmap.rows.len(), 2, "{:?}", drawn(&d));
12188        d.caret = below.find("after").unwrap();
12189        d.backspace();
12190        assert!(!d.source.contains("</div>after"), "{:?}", d.source);
12191
12192        // At a quote's first line, the line opens above the quote; twig's
12193        // split wrote a quoted blank line above the text, which drew nothing.
12194        let d = enter(
12195            Format::Markdown,
12196            LineFlow::Fold,
12197            "a\n\n> quoted\n> more\n",
12198            5,
12199        );
12200        assert_eq!(d.source, "a\n\n\n\n> quoted\n> more\n");
12201        assert_eq!(&d.source[d.caret..], "quoted\n> more\n");
12202
12203        // Preserve flow at a paragraph's start: past a mark's delimiters its
12204        // newline cut the mark (`**\nb**`), and in djot a heading ran on
12205        // over it unseen.
12206        let d = enter(Format::Markdown, LineFlow::Preserve, "a\n\n**b** c\n", 5);
12207        assert_eq!(d.source, "a\n\n\n**b** c\n");
12208        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 5);
12209        assert_eq!(d.source, "a\n\n\n# Title\n");
12210        // Inside a heading it parts the heading, as in Fold flow.
12211        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 7);
12212        assert_eq!(d.source, "a\n\n# Ti\n\ntle\n");
12213    }
12214
12215    #[test]
12216    fn enter_on_a_blank_page_writes_nothing() {
12217        // With no block to push down, Fold flow draws no line for Enter to
12218        // open, and the newline it wrote was an edit and an undo step that
12219        // showed nothing. Preserve flow draws every line, so there it writes.
12220        for body in ["", "\n", "\n\n  \n", "---\nt: x\n---\n"] {
12221            let mut d = wysiwyg_doc("enter_blank_page", body);
12222            d.build_visual(80);
12223            d.caret = d.source.len();
12224            d.newline();
12225            assert_eq!(d.source, body);
12226            assert!(!d.can_undo(), "{body:?}");
12227            assert!(!d.dirty, "{body:?}");
12228        }
12229        let mut d = wysiwyg_doc("enter_blank_page_preserve", "");
12230        d.set_line_flow(LineFlow::Preserve);
12231        d.build_visual(80);
12232        d.newline();
12233        assert_eq!(d.source, "\n");
12234    }
12235
12236    #[test]
12237    fn enter_beside_a_rule_opens_a_line_under_it() {
12238        // Beside a rule the caret stands at the home past it, which in source is
12239        // the start of the blank line under the rule, and Enter took it for an
12240        // empty paragraph: a lone newline, drawn as one more gap, and the caret
12241        // put on the next block's first line — where typing joined that block.
12242        // It goes on under the rule instead, as the rule button leaves it.
12243        let mut d = wysiwyg_doc("enter_rule", "a\n\n---\n\nb\n");
12244        d.build_visual(80);
12245        d.caret = "a\n\n---\n".len();
12246        d.newline();
12247        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
12248        assert_eq!(d.caret, "a\n\n---\n\n".len());
12249        d.insert("X");
12250        assert_eq!(d.source, "a\n\n---\n\nX\n\nb\n");
12251
12252        // Closing the document.
12253        let mut d = wysiwyg_doc("enter_rule_end", "a\n\n---\n");
12254        d.caret = d.source.len();
12255        d.newline();
12256        assert_eq!(d.source, "a\n\n---\n\n");
12257        assert_eq!(d.caret, d.source.len());
12258
12259        // In a quote, where the lines it writes keep the quote's prefix.
12260        let mut d = wysiwyg_doc("enter_rule_quote", "> a\n>\n> ---\n>\n> b\n");
12261        d.caret = "> a\n>\n> ---\n".len();
12262        d.newline();
12263        assert_eq!(d.source, "> a\n>\n> ---\n>\n> \n>\n> b\n");
12264        d.insert("X");
12265        assert_eq!(d.source, "> a\n>\n> ---\n>\n> X\n>\n> b\n");
12266
12267        // Preserve draws the blank line under a rule as a line, and the caret
12268        // on it: Enter there is a blank line's, one line down.
12269        let mut d = wysiwyg_doc("enter_rule_preserve", "a\n\n---\n\nb\n");
12270        d.set_line_flow(LineFlow::Preserve);
12271        d.caret = "a\n\n---\n".len();
12272        d.newline();
12273        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
12274        assert_eq!(d.caret, "a\n\n---\n\n".len());
12275    }
12276
12277    #[test]
12278    fn insert_table_at_a_paragraph_s_end_splits_nothing() {
12279        // The same door as the rule's, through the placement they share.
12280        let mut d = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12281        d.caret = 4;
12282        d.insert_table(1, 1);
12283        assert_eq!(d.source, "para\n\n|  |\n|---|\n|  |\n");
12284        let mut d = doc_with("table_end_typed", "para");
12285        d.caret = 4;
12286        d.insert_table(1, 1);
12287        assert_eq!(d.source, "para\n\n|  |\n| --- |\n|  |\n");
12288        assert!(d.caret_in_table());
12289    }
12290
12291    #[test]
12292    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
12293        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
12294        // and leaf wrote the first into both until twig started spelling it.
12295        let mut md = doc_with("hr_md", "para\n");
12296        md.caret = 2;
12297        md.insert_thematic_break();
12298        assert_eq!(md.source, "pa\n\n---\n\nra\n");
12299
12300        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12301        dj.caret = 2;
12302        dj.insert_thematic_break();
12303        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
12304    }
12305
12306    #[test]
12307    fn insert_table_parts_the_paragraph_and_lands_in_the_first_header_cell() {
12308        // The table goes *at* the caret the way the rule does: the paragraph is
12309        // parted first, and twig writes the grid after its first half. The
12310        // caret then sits in the first header cell — selected, as Tab would
12311        // leave it — so the next keystroke is the heading.
12312        let mut d = doc_with("table_mid", "before after\n");
12313        d.caret = 7;
12314        d.insert_table(2, 3);
12315        assert_eq!(
12316            d.source,
12317            "before \n\n|  |  |  |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |\n\nafter\n"
12318        );
12319        assert!(d.caret_in_table());
12320        let first_bar = d.source.find('|').unwrap();
12321        assert!(
12322            d.caret > first_bar && d.caret < d.source.find("| ---").unwrap(),
12323            "caret {} is not in the header row",
12324            d.caret
12325        );
12326        d.insert("Name");
12327        assert!(d.source.starts_with("before \n\n| Name |  |  |\n"));
12328        // And the grid the table was written into is one the table keys walk
12329        // (over the map a frontend rebuilds after every edit).
12330        d.build_visual(80);
12331        assert!(d.cell_tab(true));
12332        d.insert("Qty");
12333        assert!(d.source.starts_with("before \n\n| Name | Qty |  |\n"));
12334    }
12335
12336    #[test]
12337    fn insert_table_spells_the_grid_the_format_s_own_way() {
12338        // Djot's delimiter row is unpadded, and leaf never has to know that.
12339        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12340        dj.caret = 2;
12341        dj.insert_table(1, 2);
12342        assert_eq!(dj.source, "pa\n\n|  |  |\n|---|---|\n|  |  |\n\nra\n");
12343        assert!(dj.caret_in_table());
12344    }
12345
12346    #[test]
12347    fn insert_table_refuses_where_the_format_spells_no_table() {
12348        let mut d = Doc::from_source("<p>ab</p>\n".into(), Format::Html).unwrap();
12349        d.caret = 4;
12350        d.insert_table(1, 1);
12351        assert_eq!(d.source, "<p>ab</p>\n");
12352        assert!(d.status.as_deref().unwrap_or("").contains("not supported"));
12353        assert!(!d.capabilities().table);
12354    }
12355
12356    #[test]
12357    fn insert_table_reports_a_zero_shape_and_writes_nothing() {
12358        let mut d = doc_with("table_zero", "para\n");
12359        d.caret = 2;
12360        d.insert_table(0, 2);
12361        assert_eq!(d.source, "para\n");
12362        assert!(d.status.as_deref().unwrap_or("").starts_with("table:"));
12363    }
12364
12365    #[test]
12366    fn clicking_below_a_final_thematic_break_can_type_after_it() {
12367        let mut d = wysiwyg_doc("hr_final_click", "---\n");
12368        d.build_visual(80);
12369        d.click(d.vmap.num_rows() + 2, 0, false);
12370        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
12371        d.insert("after");
12372        assert_eq!(d.source, "---\nafter");
12373    }
12374
12375    #[test]
12376    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
12377        // The same bytes are two documents. In Markdown `  - b` is a nested item
12378        // and the next one belongs beside it, at its indent. In Djot a list
12379        // marker can't interrupt a paragraph, so those bytes are literal text in
12380        // item `a` and there is only one item — writing `  - ` under it would add
12381        // no item at all, just more text, and the new sibling has to go to
12382        // column zero. Both spellings come out of the *enclosing item's* line.
12383        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
12384        md.caret = "- a\n  - b".len();
12385        md.newline();
12386        assert_eq!(md.source, "- a\n  - b\n  - \n");
12387        assert_eq!(list_items(&mut md), 3);
12388
12389        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
12390        dj.view = View::Wysiwyg;
12391        dj.build_visual(80);
12392        dj.caret = "- a\n  - b".len();
12393        dj.newline();
12394        assert_eq!(dj.source, "- a\n  - b\n- \n");
12395        assert_eq!(list_items(&mut dj), 2);
12396
12397        // Where Djot's nesting is real — opened by a blank line — the indent is
12398        // reproduced there too, and the two formats agree again.
12399        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
12400        dj.view = View::Wysiwyg;
12401        dj.build_visual(80);
12402        dj.caret = "- a\n\n  - b".len();
12403        dj.newline();
12404        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
12405        assert_eq!(list_items(&mut dj), 3);
12406    }
12407
12408    #[test]
12409    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
12410        // Tab replaces the line's whole prefix with the one twig spells, so the
12411        // quote markers, the parent's indent and an ordered marker's extra
12412        // column are all its answer rather than leaf's arithmetic.
12413        for (name, body, caret, want) in [
12414            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
12415            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
12416            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
12417            // A checkbox is markup the item's own text wraps past, but a nested
12418            // list may only open at the *list* marker's column — four in from
12419            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
12420            // parses as one item, not two.
12421            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
12422            (
12423                "quoted task",
12424                "> - [ ] a\n> - [ ] b\n",
12425                18,
12426                "> - [ ] a\n>   - [ ] b\n",
12427            ),
12428        ] {
12429            let mut doc = wysiwyg_doc(name, body);
12430            doc.caret = caret;
12431            doc.indent();
12432            assert_eq!(doc.source, want, "{name}");
12433            // The nesting is real, not just indented text.
12434            assert_eq!(list_items(&mut doc), 2, "{name}");
12435        }
12436    }
12437
12438    #[test]
12439    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
12440        // The same bytes, the two formats disagreeing, and a gesture that used
12441        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
12442        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
12443        // so those bytes are literal text inside item `a` — there is nothing to
12444        // outdent, and treating them as a marker turned one item into two, a
12445        // structural edit from a keystroke that should delete one character.
12446        //
12447        // twig's `line_prefix` is what tells them apart: it reports the marker
12448        // on the Markdown line and nothing on the Djot one, which is a
12449        // continuation. No byte scan can reach that answer.
12450        let src = "- a\n  - b\n";
12451        let at = "- a\n  - ".len();
12452
12453        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
12454        md.view = View::Wysiwyg;
12455        md.build_visual(80);
12456        md.caret = at;
12457        md.backspace();
12458        assert_eq!(md.source, "- a\n- b\n");
12459        assert_eq!(list_items(&mut md), 2);
12460
12461        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
12462        dj.view = View::Wysiwyg;
12463        dj.build_visual(80);
12464        dj.caret = at;
12465        dj.backspace();
12466        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
12467        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
12468    }
12469
12470    #[test]
12471    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
12472        // Leaf used to spell the next item from the marker bytes it scanned, and
12473        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
12474        // and dropped out of the checklist. twig reproduces the whole
12475        // continuation, and a fresh item is always unticked however the one above
12476        // it stands.
12477        for (name, body, want) in [
12478            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
12479            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
12480        ] {
12481            let mut doc = wysiwyg_doc(name, body);
12482            doc.caret = body.trim_end_matches('\n').len();
12483            doc.newline();
12484            assert_eq!(doc.source, want, "{name}");
12485            // Both items are checklist items — the new one is a box, not the
12486            // plain bullet the old marker scan left behind — and it is unticked
12487            // whichever way the one above it faces.
12488            let boxes: Vec<Option<bool>> = doc
12489                .nodes()
12490                .iter()
12491                .filter(|n| n.kind == Kind::TaskListItem)
12492                .map(|n| n.checked)
12493                .collect();
12494            assert_eq!(boxes.len(), 2, "{name}");
12495            assert_eq!(boxes[1], Some(false), "{name}");
12496        }
12497    }
12498
12499    #[test]
12500    fn a_split_takes_the_space_the_caret_was_in_front_of() {
12501        // Splicing a break at the caret strands the space the words were parted
12502        // at on the head of the second block, where it reads as an indent nobody
12503        // typed. twig's split consumes it.
12504        for (name, body, caret, want) in [
12505            ("para", "one two\n", 3, "one\n\ntwo\n"),
12506            ("item", "- one two\n", 5, "- one\n- two\n"),
12507            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
12508            // A heading takes leaf's own path, which has to match.
12509            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
12510        ] {
12511            let mut doc = wysiwyg_doc(name, body);
12512            doc.caret = caret;
12513            doc.newline();
12514            assert_eq!(doc.source, want, "{name}");
12515        }
12516    }
12517
12518    #[test]
12519    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
12520        // The one place leaf keeps its own break: `split_block` repeats the `#`,
12521        // and Enter after a title is how the body under it is asked for.
12522        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
12523        doc.caret = "# Title".len();
12524        doc.newline();
12525        doc.insert("body");
12526        assert_eq!(doc.source, "# Title\n\nbody\n");
12527        assert_eq!(
12528            doc.nodes()
12529                .iter()
12530                .filter(|n| n.kind == Kind::Heading)
12531                .count(),
12532            1
12533        );
12534    }
12535
12536    #[test]
12537    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
12538        // A quoted item's marker doesn't open its line, so a scan that starts at
12539        // column zero finds a `>` where it wanted a bullet, calls the line "not a
12540        // list" and hands Enter to the plain-quote branch — which writes `> ` and
12541        // drops the list. The next item has to carry the whole prefix.
12542        for (name, body, want) in [
12543            ("flat", "> - a\n", "> - a\n> - \n"),
12544            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
12545            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
12546            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
12547            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
12548        ] {
12549            let mut doc = wysiwyg_doc(name, body);
12550            doc.caret = body.trim_end_matches('\n').len();
12551            doc.newline();
12552            assert_eq!(doc.source, want, "{name}");
12553            // The marker isn't just spelled right, it parses as an item.
12554            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
12555        }
12556    }
12557
12558    #[test]
12559    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
12560        // Double-Enter exits the list. Unquoted that means a blank line, but a
12561        // *bare* blank line would end the quote too and drop the caret out of it,
12562        // so the separator keeps its `>` and the caret's line keeps its `> `.
12563        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
12564        doc.caret = "> - a\n> - ".len();
12565        doc.newline();
12566        assert_eq!(doc.source, "> - a\n>\n> \n");
12567        assert_eq!(list_items(&mut doc), 1);
12568        // What "still in the quote" means for the next keystroke: the caret sits
12569        // behind the prefix, and what's typed there lands inside the quote as a
12570        // paragraph of its own — not as more of item `a`.
12571        doc.insert("x");
12572        assert_eq!(doc.source, "> - a\n>\n> x\n");
12573        assert!(
12574            doc.editor
12575                .ancestors_at(doc.caret - 1)
12576                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
12577        );
12578    }
12579
12580    #[test]
12581    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
12582        // The marker is hidden block markup, so Backspace over it is structural —
12583        // but only the marker is the list's. Splicing from the line start would
12584        // take the `>` with it and silently unquote the line.
12585        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
12586        doc.caret = "> - ".len();
12587        doc.backspace();
12588        assert_eq!(doc.source, "> a\n");
12589        assert_eq!(list_items(&mut doc), 0);
12590
12591        // A nested one outdents instead, moving the bullet within the quote
12592        // rather than moving the quote.
12593        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
12594        doc.caret = "> - a\n>   - ".len();
12595        doc.backspace();
12596        assert_eq!(doc.source, "> - a\n> - b\n");
12597        assert_eq!(list_items(&mut doc), 2);
12598    }
12599
12600    #[test]
12601    fn only_a_bare_paragraph_is_parted_around_the_caret() {
12602        // The split is deliberately narrow. Parting a fenced block would leave
12603        // two fences with a rule between them, and parting a list item would
12604        // mint an item nobody asked for on the way to a rule that lands after
12605        // the list either way — so both keep the whole block intact and take the
12606        // rule after it. A caret in a quote is likewise left alone.
12607        for (name, body, caret, want) in [
12608            (
12609                "code",
12610                "```\nfn x() {}\n```\n",
12611                8,
12612                "```\nfn x() {}\n```\n\n---\n\n",
12613            ),
12614            ("list", "- one two\n", 6, "- one two\n\n---\n\n"),
12615            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n>\n> \n"),
12616        ] {
12617            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
12618            d.caret = caret;
12619            d.insert_thematic_break();
12620            assert_eq!(d.source, want, "{name}: the block should stay whole");
12621        }
12622    }
12623
12624    #[test]
12625    fn insert_thematic_break_replaces_the_selection() {
12626        // Now that the rule lands *at* the caret again, replacing the selection
12627        // is coherent once more: the text goes, and the rule takes its place.
12628        // The space the deletion left leading the second half is consumed by the
12629        // split rather than opening the new paragraph with it.
12630        let mut d = doc_with("hr_sel", "one two three\n");
12631        d.anchor = Some(4);
12632        d.caret = 7; // "two"
12633        d.insert_thematic_break();
12634        assert_eq!(d.source, "one \n\n---\n\nthree\n");
12635        assert_eq!(d.selection(), None);
12636    }
12637
12638    #[test]
12639    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
12640        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
12641        // because writing `---` into one is code, not a rule — twig now walks out
12642        // to the block that owns the caret's line, so there is nothing to refuse.
12643        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
12644        code.caret = 5; // inside the fenced code
12645        code.insert_thematic_break();
12646        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n\n");
12647        assert_eq!(code.status, None, "no refusal to report any more");
12648
12649        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
12650        table.caret = 3; // in the header row
12651        table.insert_thematic_break();
12652        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n\n");
12653    }
12654
12655    #[test]
12656    fn insert_thematic_break_in_a_list_item_ends_the_list() {
12657        // The un-indented rule cannot continue the list, so it closes the list
12658        // and lands at the top level rather than nested inside it.
12659        let mut d = doc_with("hr_list", "- one\n- two\n");
12660        d.caret = "- one\n- tw".len(); // mid "two"
12661        d.insert_thematic_break();
12662        d.build_visual(80);
12663        let rule_at = d.source.find("---").unwrap();
12664        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12665        assert!(
12666            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
12667                && n.span.start <= rule_at
12668                && rule_at < n.span.end),
12669            "the rule must not be nested inside the list"
12670        );
12671    }
12672
12673    #[test]
12674    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
12675        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
12676        // which is the document the gesture was actually asked for — and the
12677        // line the caret goes on to under it wears the prefix too, as the line
12678        // Enter opens in a quote does.
12679        let mut d = doc_with("hr_quote", "> hello\n");
12680        d.caret = 4; // inside the quoted text
12681        d.insert_thematic_break();
12682        assert_eq!(d.source, "> hello\n>\n> ---\n>\n> \n");
12683        assert_eq!(d.caret, "> hello\n>\n> ---\n>\n> ".len());
12684        d.build_visual(80);
12685        let rule_at = d.source.find("---").unwrap();
12686        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12687        assert!(
12688            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
12689                && n.span.start <= rule_at
12690                && rule_at < n.span.end),
12691            "the rule belongs to the quote it was asked for"
12692        );
12693    }
12694
12695    // ── typing against a block picture ────────────────────────────────────────
12696
12697    /// A rendered-view document with the caret parked on one of the picture's two
12698    /// stops, and the map already built — the state a frontend is in between
12699    /// drawing a frame and the next keystroke.
12700    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
12701        let mut d = doc_in(View::Wysiwyg, name, src);
12702        d.build_visual_unwrapped();
12703        let start = src.find("![").unwrap();
12704        d.caret = match side {
12705            MediaStop::Before => start,
12706            MediaStop::After => start + "![](p.png)".len(),
12707        };
12708        d
12709    }
12710
12711    /// The block media the map publishes, after rebuilding it — "is this still a
12712    /// picture, or has it become a line of text with an image in it?"
12713    fn media_count(d: &mut Doc) -> usize {
12714        d.build_visual_unwrapped();
12715        d.vmap.media.len()
12716    }
12717
12718    #[test]
12719    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
12720        // The accident this prevents: tap the blank page under a photo (which
12721        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
12722        // paragraph with an *inline* image — the photo stops being drawn.
12723        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
12724        d.insert("xy");
12725        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
12726        assert_eq!(media_count(&mut d), 1, "still a picture");
12727    }
12728
12729    #[test]
12730    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
12731        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12732        d.insert("xy");
12733        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
12734        assert_eq!(media_count(&mut d), 1);
12735    }
12736
12737    #[test]
12738    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
12739        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
12740        d.insert("x");
12741        assert_eq!(d.source, "x\n\n![](p.png)\n");
12742        assert_eq!(media_count(&mut d), 1);
12743    }
12744
12745    #[test]
12746    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
12747        // The opened paragraph is part of the keystroke, not an edit the writer
12748        // made — so it undoes with the character, not a step later.
12749        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
12750        d.insert("x");
12751        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
12752        d.undo();
12753        assert_eq!(d.source, "hi\n\n![](p.png)\n");
12754    }
12755
12756    #[test]
12757    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
12758        // ⌘V dissolves the picture exactly as a keystroke does.
12759        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
12760        d.paste("pasted");
12761        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
12762        assert_eq!(media_count(&mut d), 1);
12763    }
12764
12765    #[test]
12766    fn typing_beside_an_inline_image_is_ordinary_editing() {
12767        // An inline image has no placeholder row and no stops of its own. Opening
12768        // a paragraph mid-sentence would be the bug, not the fix.
12769        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
12770        d.build_visual_unwrapped();
12771        d.caret = "see ![](p.png)".len();
12772        d.insert("!");
12773        assert_eq!(d.source, "see ![](p.png)! here\n");
12774    }
12775
12776    #[test]
12777    fn source_view_types_raw_markup_against_an_image_untouched() {
12778        // Source view is for writing the markup itself; a break inserted behind
12779        // the writer's back there would be the editor arguing with them.
12780        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
12781        d.caret = "![](p.png)".len();
12782        d.insert("x");
12783        assert_eq!(d.source, "![](p.png)x\n");
12784    }
12785
12786    #[test]
12787    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
12788        // A selection is replaced, not joined into, so there is nothing to
12789        // protect: the range takes the picture with it.
12790        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
12791        d.anchor = Some(d.caret);
12792        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
12793        d.insert("x");
12794        assert_eq!(d.source, "hi\n\nx\n");
12795    }
12796
12797    #[test]
12798    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
12799        // What this actually cost: a real vault's photo, to one stray Backspace.
12800        // The caret past `![](p.png)` was deleting the closing paren — invisible
12801        // in the rendered view — and the photo became the text `![](p.png`.
12802        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
12803        d.backspace();
12804        assert_eq!(d.source, "hi\n");
12805        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
12806        d.undo();
12807        assert_eq!(
12808            d.source, "hi\n\n![](p.png)\n",
12809            "and comes back in one piece"
12810        );
12811    }
12812
12813    #[test]
12814    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
12815        // Deleting the break here would join the picture to the paragraph above,
12816        // where it is an *inline* image and stops being drawn. Step over the
12817        // boundary; the next press deletes in the paragraph the caret reached.
12818        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12819        d.backspace();
12820        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
12821        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
12822        d.backspace();
12823        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
12824        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
12825    }
12826
12827    #[test]
12828    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
12829        // The mirror. A byte-step here eats the `!` and leaves a link.
12830        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
12831        d.delete_forward();
12832        assert_eq!(d.source, "hi\n\nbye\n");
12833        assert_eq!(media_count(&mut d), 0);
12834    }
12835
12836    #[test]
12837    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
12838        let mut d = doc_at_picture(
12839            "pic_del_after",
12840            "hi\n\n![](p.png)\n\nbye\n",
12841            MediaStop::After,
12842        );
12843        d.delete_forward();
12844        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
12845        assert_eq!(
12846            d.caret,
12847            d.source.find("bye").unwrap(),
12848            "the caret stepped down to `bye`"
12849        );
12850    }
12851
12852    #[test]
12853    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
12854        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
12855        d.backspace();
12856        assert_eq!(d.source, "\n");
12857        assert_eq!(media_count(&mut d), 0);
12858    }
12859
12860    #[test]
12861    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
12862        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
12863        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
12864        d.delete_word_back();
12865        assert_eq!(d.source, "hi there\n");
12866
12867        // And in front of one it runs *through* the paragraph break into the
12868        // prose above, which merges the picture inline — so it steps out first,
12869        // and the second press deletes the word it was aimed at.
12870        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
12871        d.delete_word_back();
12872        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
12873        d.delete_word_back();
12874        assert_eq!(
12875            d.source, "hi \n\n![](p.png)\n",
12876            "the word above went, the picture stayed"
12877        );
12878        assert_eq!(media_count(&mut d), 1);
12879    }
12880
12881    #[test]
12882    fn source_view_deletes_raw_markup_against_an_image_untouched() {
12883        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
12884        d.caret = "![](p.png)".len();
12885        d.backspace();
12886        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
12887    }
12888
12889    #[test]
12890    fn image_destination_at_caret_reads_the_image_under_the_caret() {
12891        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
12892        d.caret = 3; // inside the image markup
12893        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
12894        // Past the image, the caret is in no image.
12895        d.caret = "![a cat](cat.png)".len();
12896        assert_eq!(d.image_destination_at_caret(), None);
12897    }
12898
12899    #[test]
12900    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
12901        // The image is one placeholder row by default, and `set_media_rows` grows
12902        // it to the height the frontend measured: the label row plus blank
12903        // `decoration` fillers that hold the vertical space a raster is drawn into.
12904        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
12905        assert_eq!(d.vmap.media.len(), 1);
12906        let img_row = d.vmap.media[0].rows_span.start;
12907        assert_eq!(
12908            d.vmap.media[0].rows_span,
12909            img_row..img_row + 1,
12910            "default is one row"
12911        );
12912
12913        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
12914        d.build_visual(80);
12915        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
12916        let span = d.vmap.media[0].rows_span.clone();
12917        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
12918        // The label row carries the mark and its glyphs; the three below are blank
12919        // decoration — drawn, but no caret and no text.
12920        assert!(
12921            d.vmap.rows[span.start].media.is_some(),
12922            "mark rides the first row"
12923        );
12924        for r in (span.start + 1)..span.end {
12925            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
12926            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
12927            assert!(
12928                d.vmap.rows[r].media.is_none(),
12929                "only the first row is marked"
12930            );
12931        }
12932    }
12933
12934    #[test]
12935    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
12936        // The extra rows are pure spacers: the caret's only homes stay the stop in
12937        // front of the image and the one just past it, so walking the document top
12938        // to bottom visits the same offsets whether the image is 1 row or 5.
12939        let body = "ab\n\n![x](p.png)\n\ncd\n";
12940        let stops_at = |rows: usize| -> Vec<usize> {
12941            let mut d = wysiwyg_doc("img_stops", body);
12942            if rows > 1 {
12943                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
12944                d.build_visual(80);
12945            }
12946            d.caret = 0;
12947            let mut seen = vec![d.caret];
12948            loop {
12949                d.move_right(false);
12950                if *seen.last().unwrap() == d.caret {
12951                    break;
12952                }
12953                seen.push(d.caret);
12954            }
12955            seen
12956        };
12957        assert_eq!(
12958            stops_at(1),
12959            stops_at(5),
12960            "reserving rows must not add stops"
12961        );
12962    }
12963
12964    #[test]
12965    fn insert_link_repoints_the_link_at_a_bare_caret() {
12966        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
12967        d.caret = 3; // in the link's text, nothing selected
12968        d.insert_link("http://y.dev");
12969        assert_eq!(d.source, "[word](http://y.dev)\n");
12970        assert_eq!(d.selected_text(), Some("word"));
12971    }
12972
12973    #[test]
12974    fn insert_link_on_an_empty_range_autolinks_a_url() {
12975        // A link with no text of its own is an autolink, and twig spells it —
12976        // `<…>` is the canonical form and needs no text typed into it, so the
12977        // caret lands after it rather than selecting a finished link.
12978        let mut d = doc_with("link_empty", "\n");
12979        d.caret = 0;
12980        d.insert_link("http://x.dev");
12981        assert_eq!(d.source, "<http://x.dev>\n");
12982        assert_eq!(d.selection(), None);
12983        assert_eq!(d.caret, 14);
12984    }
12985
12986    #[test]
12987    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
12988        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
12989        // in Markdown, so a destination that can't autolink doubles as the text
12990        // instead — which is then selected, ready to be typed over.
12991        let mut d = doc_with("link_rel", "\n");
12992        d.caret = 0;
12993        d.insert_link("./notes.md");
12994        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
12995        assert_eq!(d.selection(), Some((1, 11)));
12996        d.insert("Notes");
12997        assert_eq!(d.source, "[Notes](./notes.md)\n");
12998    }
12999
13000    #[test]
13001    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
13002        // The autolink's text is its URL, so re-pointing replaces the whole
13003        // node — the caret must not splice a second link inside the first.
13004        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
13005        d.caret = 10;
13006        d.insert_link("https://y.dev");
13007        assert_eq!(d.source, "see <https://y.dev> ok\n");
13008    }
13009
13010    #[test]
13011    fn code_language_reads_and_edits_through_the_fence() {
13012        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
13013        d.caret = 10; // inside the code body
13014        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13015        assert!(d.caret_in_fenced_code());
13016
13017        d.set_code_language("python");
13018        assert!(
13019            d.source.starts_with("```python\n"),
13020            "source: {:?}",
13021            d.source
13022        );
13023        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13024
13025        // Clearing it leaves a bare fence and no label.
13026        d.set_code_language("");
13027        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
13028        assert_eq!(d.code_language_at_caret(), None);
13029
13030        // A caret outside any code block edits nothing.
13031        let mut p = doc_with("code_lang_none", "just prose\n");
13032        assert!(!p.caret_in_fenced_code());
13033        p.set_code_language("rust");
13034        assert_eq!(p.source, "just prose\n");
13035    }
13036
13037    #[test]
13038    fn code_language_reads_and_edits_through_a_quoted_fence() {
13039        let mut d = doc_with("code_lang_quote", "> ```rust\n> let x = 1;\n> ```\n");
13040        d.caret = d.source.find("let").unwrap();
13041        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13042        assert!(d.caret_in_fenced_code());
13043        d.set_code_language("python");
13044        assert!(
13045            d.source.starts_with("> ```python\n"),
13046            "source: {:?}",
13047            d.source
13048        );
13049        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13050    }
13051
13052    #[test]
13053    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
13054        // Markdown's info string ends at whitespace, so `two words` would write
13055        // a fence that reads back with a different language than the one asked
13056        // for. twig refuses it; leaf reports that and leaves the source alone.
13057        // The old splice trimmed the ends and wrote whatever was left.
13058        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
13059        d.caret = 10;
13060        d.set_code_language("two words");
13061        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
13062        assert!(d.status.is_some(), "the refusal should be reported");
13063        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13064    }
13065
13066    #[test]
13067    fn link_destination_at_caret_reads_both_spellings() {
13068        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
13069        d.caret = 5;
13070        assert_eq!(
13071            d.link_destination_at_caret().as_deref(),
13072            Some("https://x.dev")
13073        );
13074        d.caret = 0;
13075        assert_eq!(d.link_destination_at_caret(), None);
13076
13077        // An autolink has no `destination`; its text is the URL.
13078        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
13079        a.caret = 10;
13080        assert_eq!(
13081            a.link_destination_at_caret().as_deref(),
13082            Some("https://x.dev")
13083        );
13084        a.caret = 21;
13085        assert_eq!(a.link_destination_at_caret(), None);
13086    }
13087
13088    #[test]
13089    fn heading_at_caret_is_the_nearest_heading_above() {
13090        let src = "intro\n\n# Title\n\n## The *Second* Part\n\nbody here\n";
13091        let mut d = doc_with("heading_at", src);
13092        // Under no heading at all.
13093        d.caret = 2;
13094        assert_eq!(d.heading_at_caret(), None);
13095        // In a paragraph under a level-2 heading: that heading, its markup
13096        // stripped for the slug, and its own span.
13097        d.caret = src.find("body").unwrap() + 2;
13098        let h = d.heading_at_caret().expect("under `## The Second Part`");
13099        assert_eq!(h.text, "The Second Part");
13100        assert_eq!(h.level, 2);
13101        assert_eq!(&src[h.span.clone()].trim_end(), &"## The *Second* Part");
13102        // Standing in a heading answers with that heading.
13103        let h = d.heading_at(src.find("Title").unwrap()).unwrap();
13104        assert_eq!((h.text.as_str(), h.level), ("Title", 1));
13105        // And the text is what `locate` lands a slug of.
13106        let landing = d.locate("the-second-part").unwrap();
13107        assert_eq!(landing.start, d.heading_at_caret().unwrap().span.start);
13108    }
13109
13110    #[test]
13111    fn locate_finds_the_block_a_declared_id_names() {
13112        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
13113        // verse. The locator has to land on the *verse*, which is the whole
13114        // reason a link carries one.
13115        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
13116                   {#v2}\nYea, I make a record in the language of my father.\n";
13117        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13118        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
13119        assert_eq!(
13120            d.source[v2.start..v2.end].trim_end(),
13121            "Yea, I make a record in the language of my father."
13122        );
13123        // The attribute line is not part of it: `start` is a place to put a
13124        // caret, and `{#v2}` is markup the caret has no business landing in.
13125        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
13126        assert_eq!(d.locate("v99"), None);
13127    }
13128
13129    #[test]
13130    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
13131        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
13132        // Markdown heading is literal text. So `#the-second-part` can only be
13133        // the heading's own words, which is the rule every Markdown renderer
13134        // already follows and therefore the one a link was authored against.
13135        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
13136        let mut d = doc_with("locate_md", src);
13137        let hit = d.locate("the-second-part").expect("the heading's slug");
13138        assert!(d.source[hit.start..].starts_with("## The Second Part"));
13139        // Bounded by the next heading that isn't under it, so a peek shows the
13140        // section rather than only its title.
13141        assert_eq!(
13142            &d.source[hit.start..hit.end],
13143            "## The Second Part\n\nbody\n\n"
13144        );
13145
13146        // A subsection does not end its parent: `# Title` runs to `## Third`'s
13147        // sibling only because there is no other `#`, so it covers the lot.
13148        let title = d.locate("title").expect("the top heading");
13149        assert_eq!(title.end, d.source.len());
13150    }
13151
13152    #[test]
13153    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
13154        // djot mints `Some-Heading-Here`; a link to it is written
13155        // `#some-heading-here` by nearly everything that writes links. Both
13156        // spellings are one question.
13157        let src = "## Some Heading Here\n\nbody\n";
13158        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13159        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
13160        let slugged = d.locate("some-heading-here").expect("the link's spelling");
13161        assert_eq!(exact, slugged);
13162        // The section, not the heading line — there is more to show than a title.
13163        assert_eq!(&d.source[exact.start..exact.end], src);
13164    }
13165
13166    #[test]
13167    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
13168        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
13169        assert_eq!(d.locate(""), None);
13170        assert_eq!(d.locate("   "), None);
13171        // All punctuation: it names nothing, and must not be read as "match the
13172        // first heading whose slug is also empty".
13173        assert_eq!(d.locate("!!!"), None);
13174    }
13175
13176    #[test]
13177    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
13178        // The document's mistake, and the answer every other anchor
13179        // implementation gives — the alternative is for a link to mean whichever
13180        // of the two a walk happened to reach first.
13181        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
13182        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13183        let hit = d.locate("dup").expect("the first `{#dup}`");
13184        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
13185    }
13186
13187    #[test]
13188    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
13189        // The button's whole job: a reference where the caret was, a definition
13190        // to give it meaning, and the caret waiting in the empty note so the
13191        // next keystroke is the note's first word.
13192        let mut d = doc_with("fn_insert", "A claim and more.\n");
13193        d.caret = 7; // just past "A claim"
13194        d.insert_footnote();
13195        assert!(
13196            d.source.starts_with("A claim[^1] and more."),
13197            "{:?}",
13198            d.source
13199        );
13200        assert!(
13201            d.source.contains("[^1]:"),
13202            "the definition too: {:?}",
13203            d.source
13204        );
13205        assert_eq!(d.status, None);
13206
13207        let reference = d.source.find("[^1]").unwrap();
13208        let note = d
13209            .footnote_at(reference + 2)
13210            .expect("the reference just written");
13211        assert_eq!(note.label, "1");
13212        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
13213        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
13214        // …and typing there is typing into the note, not near it.
13215        d.insert("the note");
13216        assert_eq!(
13217            d.footnote_at(reference + 2).and_then(|f| f.text),
13218            Some("the note".to_string())
13219        );
13220    }
13221
13222    #[test]
13223    fn insert_footnote_numbers_past_the_notes_already_written() {
13224        // A second press must not hand back a label somebody else is using: twig
13225        // reuses a defined label rather than appending a rival definition, so a
13226        // repeat of `1` would quietly point the new reference at the old note.
13227        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
13228        d.caret = 7; // past `[^1]`, before " two."
13229        d.insert_footnote();
13230        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
13231        assert_eq!(d.source.matches("[^2]:").count(), 1);
13232    }
13233
13234    #[test]
13235    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
13236        // `[^2]` with no definition is still a 2 that means something to whoever
13237        // wrote it — stepping over it would mint a note for their reference. A
13238        // word label takes no number, so it blocks none.
13239        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
13240        d.caret = d.source.find(" c").unwrap();
13241        d.insert_footnote();
13242        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
13243        assert!(
13244            d.source.starts_with("a[^2] b[^why][^1] c"),
13245            "{:?}",
13246            d.source
13247        );
13248    }
13249
13250    #[test]
13251    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
13252        // A reference annotates the words before it. Consuming the selection —
13253        // which is what an insert normally does — would delete the very claim
13254        // the author selected in order to footnote.
13255        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
13256        d.anchor = Some(2);
13257        d.caret = 7; // "claim" selected
13258        d.insert_footnote();
13259        assert!(
13260            d.source.starts_with("A claim[^1] and more."),
13261            "{:?}",
13262            d.source
13263        );
13264    }
13265
13266    #[test]
13267    fn a_note_just_written_still_knows_where_its_reference_is() {
13268        // The authoring loop in one test: press the button, type the note, ask to
13269        // go back. The caret ends at the note's last byte — which is the *end* of
13270        // the definition's span, the one offset the query used to exclude — so
13271        // this is where the round trip either works or doesn't.
13272        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
13273        d.caret = 7;
13274        d.insert_footnote();
13275        d.insert("the note");
13276        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
13277        let back = d
13278            .footnote_definition_at_caret()
13279            .expect("still in the note we just typed");
13280        assert_eq!(back.label, "1");
13281        // …and following it lands on the reference's label, where a reader's
13282        // return leg lands.
13283        assert_eq!(back.offset, Some(9));
13284        assert_eq!(&d.source[9..10], "1");
13285    }
13286
13287    #[test]
13288    fn insert_footnote_takes_one_undo_for_both_halves() {
13289        // twig writes the pair as a single edit; the point of that is here.
13290        let before = "A claim and more.\n";
13291        let mut d = doc_with("fn_insert_undo", before);
13292        d.caret = 7;
13293        d.insert_footnote();
13294        assert_ne!(d.source, before);
13295        d.undo();
13296        assert_eq!(d.source, before, "one undo takes back both halves");
13297    }
13298
13299    #[test]
13300    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
13301        // HTML is authorable — it spells the inline marks — and has no footnote.
13302        // The refusal says so rather than writing brackets that would render as
13303        // brackets.
13304        let src = "<p>A claim.</p>\n";
13305        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
13306        assert!(!Capabilities::of(Format::Html).footnote);
13307        d.caret = 5;
13308        d.insert_footnote();
13309        assert_eq!(d.source, src, "nothing written");
13310        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
13311    }
13312
13313    #[test]
13314    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
13315        // The empty body is the one place this could go wrong: the definition
13316        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
13317        // byte early would draw up in the paragraph above the note it belongs to.
13318        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
13319        d.place_caret(7, false);
13320        d.insert_footnote();
13321        d.build_visual(80); // the frame a frontend draws after the edit
13322        assert_eq!(
13323            d.vmap.snap_to_stop(d.caret),
13324            d.caret,
13325            "the caret sits on a stop"
13326        );
13327        let (row, _) = d.caret_pos();
13328        assert!(
13329            drawn_rows(&d)[row].contains("[1]"),
13330            "the caret is on the note's row, not above it: {:?}",
13331            drawn_rows(&d)
13332        );
13333    }
13334
13335    #[test]
13336    fn footnote_at_caret_resolves_a_reference_to_its_note() {
13337        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
13338        // blank line, as one has to.
13339        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
13340        d.caret = 9;
13341        let f = d
13342            .footnote_at_caret()
13343            .expect("the caret stands in a reference");
13344        assert_eq!(f.label, "1");
13345        assert_eq!(f.text.as_deref(), Some("the note"));
13346        // The offset points at the note's first word, not at the definition's
13347        // `[` — the marker is decoration with no caret stop on it.
13348        assert_eq!(f.offset, Some(29));
13349        assert_eq!(&d.source[29..37], "the note");
13350        // …and `end` closes the range, so a frontend can ask which rendered rows
13351        // the note occupies rather than re-deriving them from the text.
13352        assert_eq!(f.end, Some(37));
13353        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
13354    }
13355
13356    /// Two definitions in a row: each is its own note, and neither reaches into
13357    /// the other.
13358    ///
13359    /// A djot definition's span used to run past the blank line into the first
13360    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
13361    /// offsets named the *next* note's rows too, showing a reader two footnotes
13362    /// when they had asked about one. twig 3.1 ends the span after the block's
13363    /// own last line; the test outlives the workaround leaf carried for it.
13364    #[test]
13365    fn footnote_at_stops_a_note_at_the_definition_after_it() {
13366        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
13367        for format in [Format::Markdown, Format::Djot] {
13368            let mut d = Doc::from_source(src.to_string(), format).unwrap();
13369            d.caret = 7;
13370            let f = d.footnote_at_caret().expect("a reference");
13371            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
13372            assert_eq!(
13373                &src[f.offset.unwrap()..f.end.unwrap()],
13374                "first note.",
13375                "in {format:?}"
13376            );
13377        }
13378    }
13379
13380    /// The other side of that boundary: a blank line *inside* a definition is
13381    /// interior to it, and the note keeps its second paragraph.
13382    ///
13383    /// This is what the old body scan cost. It stopped at the first line not
13384    /// indented under the note — a blank line is not — so a two-paragraph note
13385    /// came back as its first paragraph, and "go to note" framed half of it.
13386    /// Reading the span twig gives is both simpler and right.
13387    #[test]
13388    fn footnote_at_keeps_a_notes_second_paragraph() {
13389        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
13390        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13391        d.caret = 7;
13392        let f = d.footnote_at_caret().expect("a reference");
13393        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
13394        // And it stops there — `After.` is the next block, not more note.
13395        assert_eq!(
13396            &src[f.offset.unwrap()..f.end.unwrap()],
13397            f.text.as_deref().unwrap()
13398        );
13399        assert!(!f.text.as_deref().unwrap().contains("After"));
13400    }
13401
13402    #[test]
13403    fn footnote_at_bounds_a_note_whose_body_is_empty() {
13404        // `[^1]:` with nothing after it. The range is empty rather than
13405        // inverted, and still points inside the definition — which is what keeps
13406        // a frontend's row lookup from walking off into the block above.
13407        let src = "A claim[^1].\n\n[^1]:\n";
13408        let mut d = doc_with("fn_empty_body", src);
13409        d.caret = 9;
13410        let f = d.footnote_at_caret().expect("a reference");
13411        assert_eq!(f.text.as_deref(), Some(""));
13412        assert_eq!(f.offset, f.end, "an empty note is an empty range");
13413        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
13414    }
13415
13416    #[test]
13417    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
13418        let mut d = doc_with(
13419            "fn_at_caret_none",
13420            "A claim[^1] and more.\n\n[^1]: the note\n",
13421        );
13422        d.caret = 2; // in the prose
13423        assert_eq!(d.footnote_at_caret(), None);
13424    }
13425
13426    #[test]
13427    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
13428        // The two are deliberately separate: a reference names a note in this
13429        // document, a link names somewhere to leave for, and answering one with
13430        // the other is what made a reference click do nothing at all.
13431        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
13432        d.caret = 3; // the `1` of `[^1]`
13433        assert!(d.footnote_at_caret().is_some());
13434        assert_eq!(
13435            d.link_destination_at_caret(),
13436            None,
13437            "a reference is not a link"
13438        );
13439
13440        d.caret = 10; // inside the link's label
13441        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
13442        assert_eq!(
13443            d.link_destination_at_caret().as_deref(),
13444            Some("https://x.dev")
13445        );
13446    }
13447
13448    #[test]
13449    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
13450        // A `[^99]` the document never defines is a real state — a note deleted
13451        // out from under its reference — and the label is what lets a frontend
13452        // say so. `None` here would be indistinguishable from "not on a
13453        // reference", which is the wrong thing to tell a reader.
13454        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
13455        d.caret = 9;
13456        let f = d
13457            .footnote_at_caret()
13458            .expect("the reference is still a reference");
13459        assert_eq!(f.label, "99");
13460        assert_eq!(f.text, None);
13461        assert_eq!(f.offset, None);
13462    }
13463
13464    #[test]
13465    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
13466        // Labels are not always numbers, and a note's body runs past its first
13467        // line — the indented continuation belongs to the note, so it comes back
13468        // with it (source bytes, verbatim, as documented).
13469        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
13470        let mut d = doc_with("fn_word_label", src);
13471        d.caret = 6;
13472        let f = d
13473            .footnote_at_caret()
13474            .expect("the caret stands in a reference");
13475        assert_eq!(f.label, "note");
13476        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
13477    }
13478
13479    #[test]
13480    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
13481        // The point of the offset form: a pointer hovering a reference asks what
13482        // note it names, and must not drag the caret along to ask.
13483        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
13484        d.caret = 0;
13485        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
13486        assert_eq!(f.label, "1");
13487        assert_eq!(f.text.as_deref(), Some("the note"));
13488        assert_eq!(d.caret, 0, "asking must not move the caret");
13489        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
13490    }
13491
13492    #[test]
13493    fn footnote_definition_at_caret_points_back_at_the_reference() {
13494        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
13495        // the caret can rest on — is at 9.
13496        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
13497        d.caret = 30; // inside the note's body
13498        let f = d
13499            .footnote_definition_at_caret()
13500            .expect("the caret stands in a definition");
13501        assert_eq!(f.label, "1");
13502        assert_eq!(f.offset, Some(9));
13503        assert_eq!(&d.source[7..11], "[^1]");
13504    }
13505
13506    #[test]
13507    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
13508        // The two legs have to meet: wherever `footnote_at` sends the caret, the
13509        // definition query must answer for — otherwise arriving at a note leaves
13510        // the reader somewhere the way back isn't offered.
13511        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
13512        let mut d = doc_with("fn_def_marker", src);
13513        let landed = d.footnote_at(9).unwrap().offset.unwrap();
13514        assert_eq!(
13515            d.footnote_definition_at(landed).and_then(|f| f.offset),
13516            Some(9),
13517            "the note a reference sends you to offers the way back"
13518        );
13519    }
13520
13521    #[test]
13522    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
13523        // The two queries answer for disjoint places, which is what lets one
13524        // gesture mean "down to the note" in one and "back up" in the other
13525        // without either having to remember which way the reader is going.
13526        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
13527        d.caret = 2; // prose
13528        assert_eq!(d.footnote_definition_at_caret(), None);
13529        d.caret = 9; // the reference
13530        assert_eq!(d.footnote_definition_at_caret(), None);
13531        assert!(
13532            d.footnote_at_caret().is_some(),
13533            "which is the reference's own query"
13534        );
13535    }
13536
13537    #[test]
13538    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
13539        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
13540        // note", which is false and leaves a frontend unable to explain why the
13541        // way back is missing.
13542        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
13543        let mut d = doc_with("fn_def_orphan", src);
13544        d.caret = src.find("orphan").unwrap();
13545        let f = d
13546            .footnote_definition_at_caret()
13547            .expect("an orphan is still a definition");
13548        assert_eq!(f.label, "2");
13549        assert_eq!(f.offset, None);
13550    }
13551
13552    #[test]
13553    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
13554        // One label, cited twice. The first is where the reader most likely came
13555        // from, and the only answer that doesn't depend on how they got here.
13556        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
13557        let mut d = doc_with("fn_def_repeat", src);
13558        d.caret = src.find("the note").unwrap();
13559        let f = d.footnote_definition_at_caret().expect("a definition");
13560        assert_eq!(
13561            f.offset,
13562            Some(5),
13563            "the first `[^a]`'s label, not the second's"
13564        );
13565        assert_eq!(&src[3..7], "[^a]");
13566    }
13567
13568    #[test]
13569    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
13570        // Down and back up, each leg found from the document rather than from a
13571        // memory of the other — so it still works for a reader who scrolled to
13572        // the notes instead of jumping there.
13573        //
13574        // `place_caret` rather than assigning `caret`, because that is what a
13575        // frontend calls: it snaps to a real caret stop, and a jump that lands
13576        // on a byte the caret can't rest on would arrive somewhere the return
13577        // leg no longer answers for. `build_map` first, since snapping is a
13578        // no-op until the map exists — which is exactly how this went unnoticed
13579        // when the offsets pointed at the `[^` markers.
13580        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
13581        d.build_map(None);
13582        d.place_caret(9, false);
13583        let down = d
13584            .footnote_at_caret()
13585            .expect("a reference")
13586            .offset
13587            .expect("a note");
13588        d.place_caret(down, false);
13589        let up = d
13590            .footnote_definition_at_caret()
13591            .expect("a definition")
13592            .offset
13593            .expect("a reference");
13594        d.place_caret(up, false);
13595        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
13596        assert_eq!(
13597            d.footnote_at_caret().expect("back on the reference").label,
13598            "1"
13599        );
13600    }
13601
13602    #[test]
13603    fn insert_link_hands_the_destination_to_twig_raw() {
13604        // Escaping is twig's, and format-specific: Markdown ends a destination
13605        // at the first space and needs the `<…>` form, where djot would read
13606        // those angle brackets as part of the URL.
13607        let mut d = doc_with("link_space", "word\n");
13608        d.anchor = Some(0);
13609        d.caret = 4;
13610        d.insert_link("a b");
13611        assert_eq!(d.source, "[word](<a b>)\n");
13612    }
13613
13614    #[test]
13615    fn insert_link_reports_a_destination_no_format_can_carry() {
13616        let mut d = doc_with("link_bad", "word\n");
13617        d.anchor = Some(0);
13618        d.caret = 4;
13619        d.insert_link("a\nb");
13620        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
13621        assert!(
13622            d.status.is_some(),
13623            "InvalidArgument should reach the status line"
13624        );
13625        assert!(!d.dirty);
13626    }
13627
13628    #[test]
13629    fn insert_link_works_in_wysiwyg_view() {
13630        let mut d = wysiwyg_doc("link_wys", "word here\n");
13631        d.anchor = Some(0);
13632        d.caret = 4;
13633        d.insert_link("http://x.dev");
13634        assert_eq!(d.source, "[word](http://x.dev) here\n");
13635        assert_eq!(d.selected_text(), Some("word"));
13636        // The map the caret has to keep riding is rebuilt each frame; motion
13637        // over the fresh one must still land on a real stop (the debug_assert).
13638        d.build_visual(80);
13639        d.move_right(false);
13640        d.move_left(false);
13641    }
13642
13643    #[test]
13644    fn click_maps_a_row_col_to_a_byte_offset() {
13645        let mut d = doc_with("click", "ab\ncd\n");
13646        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
13647        assert_eq!(d.caret, 4);
13648    }
13649
13650    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
13651    // stop just as the `(row, col)` click path does, so the caret can never come
13652    // to rest in the blank gap between two paragraphs — where it would draw in one
13653    // place and type in another.
13654    #[test]
13655    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
13656        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
13657        // caret stop (stops are 0,1,3,4).
13658        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
13659        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
13660        d.place_caret(2, false);
13661        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13662        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
13663    }
13664
13665    #[test]
13666    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
13667        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
13668        d.place_caret(0, false); // anchor at the start of "A"
13669        d.place_caret(2, true); // drag into the gap
13670        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13671        let (s, e) = d.selection().expect("a selection");
13672        assert!(
13673            d.vmap.is_stop(s) && d.vmap.is_stop(e),
13674            "selection {s}..{e} off a stop"
13675        );
13676    }
13677
13678    #[test]
13679    fn place_caret_on_a_real_stop_is_left_untouched() {
13680        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
13681        d.place_caret(3, false); // the start of "B" — a genuine stop
13682        assert_eq!(d.caret, 3);
13683    }
13684
13685    // An *empty paragraph* (two blank lines, an intentional blank line the user
13686    // opened) is a real caret stop, unlike the gap — a click into it must stay.
13687    #[test]
13688    fn place_caret_rests_in_an_empty_paragraph() {
13689        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
13690        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
13691        assert!(d.vmap.is_stop(empty));
13692        d.place_caret(empty, false);
13693        assert_eq!(d.caret, empty);
13694    }
13695
13696    // The content end of a hidden mark is a home too (`VisualMap::mark_ends`):
13697    // a drag over the word `bold` ends there, and a caret placed there stays.
13698    #[test]
13699    fn place_caret_rests_at_the_end_of_a_hidden_marks_content() {
13700        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
13701        let mut d = wysiwyg_doc("place_mark_end", src);
13702        let start = src.find("bold").unwrap();
13703        d.place_caret(start, false);
13704        d.place_caret(start + 4, true);
13705        assert_eq!(d.selection(), Some((start, start + 4)), "the whole word");
13706        d.toggle(InlineKind::Strong);
13707        assert_eq!(d.source, src.replace("**bold**", "bold"));
13708    }
13709
13710    #[test]
13711    fn right_steps_onto_the_end_of_a_mark_and_then_past_its_delimiter() {
13712        let mut d = wysiwyg_doc("right_mark_end", "a **bold** b");
13713        d.caret = 7; // before the `d`
13714        d.move_right(false);
13715        assert_eq!(d.caret, 8, "onto the end of the bold");
13716        assert!(d.active_inline_marks().contains(InlineKind::Strong));
13717        d.move_right(false);
13718        assert_eq!(d.caret, 10, "past the closing `**`");
13719        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
13720        d.move_left(false);
13721        assert_eq!(d.caret, 8);
13722        d.move_left(false);
13723        assert_eq!(d.caret, 7);
13724        // Typing at the inner home extends the bold.
13725        d.caret = 8;
13726        d.insert("!");
13727        assert_eq!(d.source, "a **bold!** b");
13728    }
13729
13730    #[test]
13731    fn a_marks_end_home_follows_an_edit_through_the_incremental_map() {
13732        // The splice path shifts the home with the block it is in, and the
13733        // re-rendered block finds its own again.
13734        let mut d = wysiwyg_doc("mark_end_splice", "x\n\na **bold** b\n\ny\n");
13735        d.build_visual_unwrapped();
13736        d.edit(0, 0, "zz");
13737        d.build_visual_unwrapped();
13738        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a shift");
13739        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13740        let at = d.source.find("bold").unwrap();
13741        d.edit(at, at, "very ");
13742        d.build_visual_unwrapped();
13743        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a re-render");
13744        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13745    }
13746
13747    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
13748        doc_in(View::Wysiwyg, name, body)
13749    }
13750
13751    /// How many list items the source actually parses into — the check that a
13752    /// marker Leaf wrote is a marker the format agrees is one.
13753    fn list_items(doc: &mut Doc) -> usize {
13754        doc.editor
13755            .nodes()
13756            .unwrap()
13757            .iter()
13758            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
13759            .count()
13760    }
13761
13762    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
13763    /// incremental (`build_spliced` / `build_cached`) path must always match.
13764    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
13765        reference_map_revealing(source, None)
13766    }
13767
13768    /// [`reference_map`] with a reveal line — the ground truth for the
13769    /// `MarkupMode::Full` builds, where the map is a function of the caret's
13770    /// line as well as the text.
13771    fn reference_map_revealing(source: &str, reveal: Option<Reveal>) -> crate::wysiwyg::VisualMap {
13772        // The same parse `Doc` uses. With twig's plain defaults instead, the two
13773        // sides disagree on what the *document* is before the renderer is even
13774        // reached — a bare `:word` is a text directive to one and prose to the
13775        // other — and the mismatch reads as a splice bug that isn't one.
13776        let mut ed =
13777            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
13778        let nodes = ed.nodes().unwrap();
13779        crate::wysiwyg::build(
13780            &nodes,
13781            source,
13782            None,
13783            false,
13784            &wysiwyg::Surface::default(),
13785            reveal,
13786        )
13787    }
13788
13789    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
13790        if a.rows.len() != b.rows.len() {
13791            return true;
13792        }
13793        for (ra, rb) in a.rows.iter().zip(&b.rows) {
13794            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
13795                return true;
13796            }
13797            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
13798                if ga.ch != gb.ch || ga.src != gb.src {
13799                    return true;
13800                }
13801            }
13802        }
13803        false
13804    }
13805
13806    #[test]
13807    fn incremental_build_matches_a_fresh_build_across_edits() {
13808        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
13809        // fast path, gated on twig's `dirty_range`) or falls back to
13810        // `build_cached`. After each edit the map must be byte-identical to a
13811        // from-scratch build — this is the correctness net under the splice.
13812        let docs = [
13813            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
13814            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
13815            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
13816            // A footnote definition is a root beside `doc`, merged back into the
13817            // top-level list by `wysiwyg::top_blocks`. The random edits below
13818            // make and unmake definitions as they go (a deleted `:` turns one
13819            // back into a paragraph, and vice versa), which is exactly the
13820            // structural churn the splice path has to notice and bail out of.
13821            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
13822            // A comment is a top-level block that draws no rows — a layout entry
13823            // at zero rows either side of blocks that do. The edits below type
13824            // into the blocks around it (a splice past a hidden block), and
13825            // break the comment open into prose and back (a structural change).
13826            "intro\n\n<!-- exec -->\n```\ncode\n```\n\nafter the comment\n\n<!-- trail -->\n",
13827            // Link reference definitions: a hidden block that an edit can turn
13828            // into a paragraph (a deleted `:`) and back, and whose own bytes an
13829            // edit can land in.
13830            "see [a] and [b]\n\n[a]: /a\n\nmid text\n\n[b]: /b\n",
13831            // Blank lines above the first block draw as rows, counted as its
13832            // separator; above it past frontmatter and past a comment too.
13833            "\n\nfirst pushed down\n\nsecond\n",
13834            "---\ntitle: x\n---\n\n\nafter frontmatter\n\nmore\n",
13835            "<!-- lead -->\n\n\nafter a comment\n\nmore\n",
13836            // No `<div>` here yet: an edit that takes the blank line under
13837            // `</div>` leaves a map no fresh build draws. See
13838            // docs/tasks/text-glued-under-a-closing-div.md.
13839        ];
13840        // A deterministic mix: mostly single characters (which stay inside one
13841        // block → splice), plus edits that reshape structure (a paragraph break,
13842        // a heading marker, a code fence → fallback), so both paths are exercised.
13843        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
13844        for src in docs {
13845            let mut d = wysiwyg_doc("diff", src);
13846            d.build_visual_unwrapped();
13847            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
13848
13849            for step in 0..60usize {
13850                let len = d.source.len();
13851                let raw = (step * 13 + 5) % (len + 1);
13852                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
13853                let pre = d.source.clone();
13854                let action;
13855                if step % 3 == 0 && pos < len {
13856                    let end = (pos + 1..=len)
13857                        .find(|&i| d.source.is_char_boundary(i))
13858                        .unwrap();
13859                    action = format!("delete [{pos},{end})");
13860                    d.edit(pos, end, "");
13861                } else {
13862                    let ins = inserts[step % inserts.len()];
13863                    action = format!("insert {ins:?} @ {pos}");
13864                    d.edit(pos, pos, ins);
13865                }
13866                d.build_visual_unwrapped();
13867                if maps_differ(&d.vmap, &reference_map(&d.source)) {
13868                    panic!(
13869                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
13870                        d.source
13871                    );
13872                }
13873            }
13874        }
13875    }
13876
13877    /// A frontend is handed [`Doc::vmap`] and may present it differently:
13878    /// leaf-ratatui splices blank filler rows under an oversized heading so the
13879    /// raster it paints there has somewhere to stand, and leaves them in the map
13880    /// because the caret and the mouse both read it between frames. The splice
13881    /// path addresses that map by *row index*, against the block layout the last
13882    /// build recorded — so handed a map with rows in it that no block owns, it
13883    /// laid the re-rendered block over one of the fillers and carried the rows
13884    /// the block really occupied into the suffix. One stranded copy of the
13885    /// edited line, and everything below it a row further down, per keystroke.
13886    ///
13887    /// A map that isn't the one the layout describes is a map this path can't
13888    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
13889    #[test]
13890    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
13891        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
13892        d.build_visual_unwrapped();
13893
13894        // Stand in for the heading filler rows: two blank rows past the heading
13895        // that no block accounts for. Cloning a real row keeps every field
13896        // plausible — it is the row *count* the splice can't survive.
13897        let filler = d.vmap.rows[0].clone();
13898        d.vmap.rows.insert(1, filler.clone());
13899        d.vmap.rows.insert(1, filler);
13900
13901        // An edit inside the last block: the single-block case the splice path
13902        // is for, and the one the frontend hits on every keystroke.
13903        let at = d.source.len() - 1;
13904        d.edit(at, at, "!");
13905        d.build_visual_unwrapped();
13906
13907        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
13908    }
13909
13910    /// A glyph's [`FaceId`] has to mean the same thing however its row was
13911    /// built. A row comes three ways — a fresh walk, a [`BlockCache`] hit
13912    /// cloned at a shifted offset, and a previous map's rows a splice kept
13913    /// untouched — and only the first of those walks a `data-font` at all. An
13914    /// index into a per-build table would have had the same glyph naming two
13915    /// families the moment a second one appeared; the id is the name's own
13916    /// hash, so nothing is remapped and the table is merged rather than rebuilt.
13917    ///
13918    /// Two families, because one cannot tell a wrong id from a right one.
13919    ///
13920    /// [`FaceId`]: crate::style::FaceId
13921    /// [`BlockCache`]: crate::wysiwyg::BlockCache
13922    #[test]
13923    fn a_spliced_rebuild_still_says_which_family_each_glyph_is_set_in() {
13924        use crate::style::{FaceId, FaceRef};
13925        let garamond = FaceId::of("Garamond");
13926        let futura = FaceId::of("Futura");
13927        let mut d = wysiwyg_doc(
13928            "two_faces",
13929            "x <span data-font=\"Garamond\">alpha</span>\n\ny <span data-font=\"Futura\">beta</span>\n",
13930        );
13931        d.build_visual_unwrapped();
13932
13933        // What the map has to keep saying, whichever path built it.
13934        let check = |d: &Doc, ctx: &str| {
13935            let face_of = |ch: char| {
13936                d.vmap
13937                    .rows
13938                    .iter()
13939                    .flat_map(|r| r.glyphs.iter())
13940                    .find(|g| g.ch == ch)
13941                    .map(|g| g.style.font)
13942            };
13943            assert_eq!(face_of('a'), Some(Some(FaceRef::Named(garamond))), "{ctx}");
13944            assert_eq!(face_of('b'), Some(Some(FaceRef::Named(futura))), "{ctx}");
13945            assert_eq!(d.vmap.face_name(garamond), Some("Garamond"), "{ctx}");
13946            assert_eq!(d.vmap.face_name(futura), Some("Futura"), "{ctx}");
13947            assert_eq!(d.vmap.face_name(FaceId::of("Bodoni")), None, "{ctx}");
13948        };
13949        check(&d, "fresh");
13950
13951        // An edit inside the second block: the single-block case the splice
13952        // path is for. The first block's rows are carried over untouched, so
13953        // its glyphs' ids are the previous build's and the table has to be too.
13954        let at = d.source.find("beta").unwrap();
13955        d.edit(at, at, "z");
13956        d.build_visual_unwrapped();
13957        check(&d, "after an edit in the second block");
13958        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced");
13959
13960        // And the other way round, so the block that was kept is the one that
13961        // is now re-rendered.
13962        let at = d.source.find("alpha").unwrap();
13963        d.edit(at, at, "z");
13964        d.build_visual_unwrapped();
13965        check(&d, "after an edit in the first block");
13966        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced again");
13967
13968        // A structural edit is one the splice bails out of, so the map is
13969        // reassembled by `build_cached` — where an untouched block is a *cache
13970        // hit* and its rows are cloned without a `data-font` being walked
13971        // again. The names the entry stored are what keeps the table honest
13972        // there.
13973        let at = d.source.find("\n\ny ").unwrap();
13974        d.edit(at, at, "\n\nmiddle");
13975        d.build_visual_unwrapped();
13976        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached");
13977        // Twice, because that first `build_cached` is what stores the entries:
13978        // this one is the build where the Garamond block is a *hit*, its rows
13979        // cloned with their ids and no attribute walked to explain them.
13980        let at = d.source.len() - 1;
13981        d.edit(at, at, "\n\ntail");
13982        d.build_visual_unwrapped();
13983        check(&d, "after a structural edit, through the block cache");
13984        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached again");
13985
13986        // A family the edit took the last glyph of leaves the glyphs with no
13987        // face and the table with a name nothing asks for — harmless, and the
13988        // price of not walking the rows the splice exists to avoid walking.
13989        let span = d.source.find("<span data-font=\"Futura\">").unwrap();
13990        let end = d.source.rfind("</span>").unwrap() + "</span>".len();
13991        d.edit(span, end, "beta");
13992        d.build_visual_unwrapped();
13993        assert!(!d.source.contains("Futura"), "{:?}", d.source);
13994        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "the face removed");
13995    }
13996
13997    #[test]
13998    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
13999        // The same correctness net as `incremental_build_matches_a_fresh_build_
14000        // across_edits`, under `MarkupMode::Full` — where the map depends on
14001        // the caret's *line* as well as the text, so the two caches have a new
14002        // way to be wrong. Both are exercised: the block cache can hand back
14003        // rows built for a line that is no longer the revealed one, and the
14004        // splice path can reuse a suffix that still has yesterday's line raw.
14005        //
14006        // Caret motion is interleaved with the edits deliberately, because a
14007        // caret that only ever moved with the edit would never cross a line
14008        // without also dirtying it — the case where a stale reveal survives.
14009        let docs = [
14010            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
14011            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
14012        ];
14013        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
14014        for src in docs {
14015            let mut d = wysiwyg_doc("reveal_diff", src);
14016            d.set_markup_mode(MarkupMode::Full);
14017
14018            for step in 0..60usize {
14019                let len = d.source.len();
14020                let raw = (step * 13 + 5) % (len + 1);
14021                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
14022                let pre = d.source.clone();
14023                let action;
14024                if step % 3 == 0 && pos < len {
14025                    let end = (pos + 1..=len)
14026                        .find(|&i| d.source.is_char_boundary(i))
14027                        .unwrap();
14028                    action = format!("delete [{pos},{end})");
14029                    d.edit(pos, end, "");
14030                } else {
14031                    let ins = inserts[step % inserts.len()];
14032                    action = format!("insert {ins:?} @ {pos}");
14033                    d.edit(pos, pos, ins);
14034                }
14035                // Walk the caret somewhere else in the document, independently
14036                // of where the edit landed.
14037                let want = (step * 29 + 11) % (d.source.len() + 1);
14038                d.caret = (want..=d.source.len())
14039                    .find(|&i| d.source.is_char_boundary(i))
14040                    .unwrap();
14041                d.build_visual_unwrapped();
14042
14043                let want = reference_map_revealing(&d.source, d.reveal_line());
14044                if maps_differ(&d.vmap, &want) {
14045                    panic!(
14046                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
14047                        d.caret, d.source
14048                    );
14049                }
14050            }
14051        }
14052    }
14053
14054    #[test]
14055    fn caret_motion_across_lines_rebuilds_only_under_full() {
14056        // The cache-key change has to earn its keep in both directions: `Full`
14057        // must rebuild when the caret changes line (or the reveal would never
14058        // move), and the hidden modes must *not* (or every arrow key would pay
14059        // for a feature they don't use). The existing `cache_motion` test pins
14060        // the second for the default mode; this pins the pair against a mode
14061        // change alone.
14062        let body = "*one* here\n\n*two* there\n";
14063
14064        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
14065        full.set_markup_mode(MarkupMode::Full);
14066        caret_at(&mut full, "one");
14067        let before = full.revision();
14068        caret_at(&mut full, "two");
14069        assert_eq!(full.revision(), before, "motion is not an edit");
14070        assert!(
14071            drawn_rows(&full).iter().any(|r| r == "*two* there"),
14072            "the map followed the caret: {:?}",
14073            drawn_rows(&full)
14074        );
14075
14076        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
14077        caret_at(&mut hidden, "one");
14078        let key = hidden.vmap_key.clone();
14079        caret_at(&mut hidden, "two");
14080        assert_eq!(
14081            hidden.vmap_key, key,
14082            "a hidden mode rebuilds nothing on motion"
14083        );
14084    }
14085
14086    #[test]
14087    fn wysiwyg_down_crosses_a_paragraph_boundary() {
14088        // Regression: the blank separator row used to share the previous
14089        // paragraph's end offset, so Down got pinned at the boundary (while Up
14090        // still crossed). Both directions must step through it symmetrically.
14091        //
14092        // It's now stepped *over* rather than onto: the blank line between two
14093        // paragraphs is the boundary being drawn, not a line of the document, so
14094        // one press of Down crosses it. The goal column survives the crossing —
14095        // col 3 at the end of "abc" is col 3 at the end of "def".
14096        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
14097        d.caret = 3; // end of "abc" (row 0)
14098        d.move_down(false);
14099        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
14100        assert_eq!(d.caret, 8); // end of "def", col 3 kept
14101        d.move_up(false);
14102        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
14103        assert_eq!(d.caret, 3);
14104    }
14105
14106    #[test]
14107    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
14108        // The second Up and the second Down here run off the ends of the
14109        // document, which is no longer a place a press is swallowed: they carry
14110        // the caret to the start and the end of the text. The claim in the
14111        // middle — that a Down retraces the Up that crossed the paragraph gap —
14112        // is the one this test is for, and it is asserted where it is made.
14113        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
14114        d.caret = 5; // start of "def"
14115        let start = d.caret_pos();
14116        d.move_up(false);
14117        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
14118        d.move_up(false);
14119        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
14120        d.move_down(false);
14121        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
14122        d.move_down(false);
14123        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
14124    }
14125
14126    #[test]
14127    fn wysiwyg_new_paragraph_shows_before_typing() {
14128        // Regression: two Enters at the end of a paragraph produced trailing
14129        // newlines with no AST node, so the caret appeared stuck on the old line
14130        // until a character was typed. It must ride down onto the new line now.
14131        let mut d = doc_with("wys_newpara", "abc\n");
14132        d.view = View::Wysiwyg;
14133        d.caret = 3;
14134        d.insert("\n");
14135        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
14136        assert_eq!(d.source, "abc\n\n\n");
14137        d.build_visual(80);
14138        let (row, _) = d.caret_pos();
14139        assert!(
14140            row >= 2,
14141            "caret should have moved down to the new line, got row {row}"
14142        );
14143        assert!(
14144            d.vmap.num_rows() >= 3,
14145            "the blank lines should render as rows"
14146        );
14147    }
14148
14149    #[test]
14150    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
14151        // The reported bug: Enter at the end of a paragraph that has another
14152        // paragraph below put the caret at the *start of the next paragraph* —
14153        // the empty paragraph it opened had no row, so the caret snapped onto
14154        // "World". It must now sit on its own empty line, with a blank spacer
14155        // above it (the paragraph gap).
14156        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
14157        d.caret = 5; // end of "Hello"
14158        d.newline();
14159        d.build_visual(80);
14160        let (row, col) = d.caret_pos();
14161        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
14162        assert_eq!(
14163            d.vmap.row_width(row),
14164            0,
14165            "caret's row must be empty, not 'World'"
14166        );
14167        assert!(
14168            row >= 2,
14169            "a blank spacer row should sit above the caret, got row {row}"
14170        );
14171        // The row above the caret is a real (empty) gap, and "Hello" stays put.
14172        assert_eq!(
14173            d.vmap.row_width(row - 1),
14174            0,
14175            "the row above the caret is a gap"
14176        );
14177        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
14178        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
14179    }
14180
14181    #[test]
14182    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
14183        // At the document end a single Enter must also show the paragraph gap —
14184        // a blank spacer row above the caret — so the layout already matches how
14185        // it will look once the new paragraph has text.
14186        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
14187        d.caret = 5; // end of "Hello", no trailing newline
14188        d.newline(); // source becomes "Hello\n\n"
14189        d.build_visual(80);
14190        let (row, col) = d.caret_pos();
14191        assert_eq!(col, 0);
14192        assert!(
14193            row >= 2,
14194            "caret should sit below a blank spacer, got row {row}"
14195        );
14196        assert_eq!(
14197            d.vmap.row_width(row - 1),
14198            0,
14199            "the row above the caret is a gap"
14200        );
14201    }
14202
14203    #[test]
14204    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
14205        // The spacer is view-only: typing the new paragraph must not reflow the
14206        // caret onto a different row — the transient view already matched the
14207        // settled one.
14208        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
14209        d.caret = 5;
14210        d.newline();
14211        d.build_visual(80);
14212        let before = d.caret_pos();
14213        d.insert("New");
14214        d.build_visual(80);
14215        let after = d.caret_pos();
14216        assert_eq!(
14217            after.0, before.0,
14218            "typing must not move the caret to another row ({before:?} -> {after:?})"
14219        );
14220    }
14221
14222    #[test]
14223    fn wysiwyg_return_on_the_last_code_line_keeps_the_caret_in_the_block() {
14224        // Return at the end of the block's last line writes an empty line the
14225        // map used to drop, so the caret landed on `after` and the next
14226        // keystroke went into the paragraph below instead of into the code.
14227        let mut d = wysiwyg_doc("code_return", "prose\n\n```\nalpha\nbeta\n```\n\nafter\n");
14228        d.caret = d.source.find("beta").unwrap() + "beta".len();
14229        d.build_visual(80);
14230        let before = d.caret_pos().0;
14231
14232        d.newline();
14233        d.build_visual(80);
14234        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n");
14235
14236        let (row, col) = d.caret_pos();
14237        assert_eq!(row, before + 1, "the caret moves down one row");
14238        assert_eq!(col, 0, "onto the head of the empty line");
14239        let span = d.vmap.code_blocks[0].rows_span.clone();
14240        assert!(
14241            span.contains(&row),
14242            "caret row {row} is outside the block's rows {span:?}"
14243        );
14244
14245        // The whole point: what is typed next is code.
14246        d.insert("gamma");
14247        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\ngamma\n```\n\nafter\n");
14248    }
14249
14250    #[test]
14251    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
14252        let fm = "---\ntitle: hi\n---\n";
14253        let body = format!("{fm}# leaf\n\nbody\n");
14254        let mut d = wysiwyg_doc("wys_fm", &body);
14255        // Opening lifts the caret out of the now-hidden frontmatter.
14256        assert_eq!(
14257            d.caret,
14258            fm.len(),
14259            "caret should start at the first real block"
14260        );
14261        // Left at the content start can't step back into frontmatter.
14262        d.move_left(false);
14263        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
14264        // Doc-start lands on the content floor, not offset 0.
14265        d.move_doc_start(false);
14266        assert_eq!(d.caret, fm.len());
14267        // Select-all + copy never include the frontmatter bytes.
14268        d.select_all();
14269        let sel = d.selected_text().unwrap().to_string();
14270        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
14271        assert!(
14272            sel.starts_with("# leaf"),
14273            "selection should begin at content: {sel:?}"
14274        );
14275    }
14276
14277    #[test]
14278    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
14279        // A fresh note is frontmatter and nothing else. With no rendered block
14280        // to floor the caret it opened at offset 0 — before the opening `---` —
14281        // so the first keystroke wrote itself in front of the metadata and the
14282        // file came out as `This---\ntitle: …`.
14283        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
14284        let mut d = wysiwyg_doc("wys_fm_only", fm);
14285        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
14286        // Nothing is rendered, so the caret draws at the origin of an empty view
14287        // — the same place an empty document puts it.
14288        assert_eq!(d.caret_pos(), (0, 0));
14289        d.insert("This");
14290        assert_eq!(d.source, format!("{fm}This"));
14291    }
14292
14293    /// `select_range` is the verb for a range a host already knows the bytes of,
14294    /// so it must not snap — and must still hold every invariant `place_caret`
14295    /// holds, the frontmatter floor above all.
14296    #[test]
14297    fn select_range_takes_the_range_as_given_but_still_floors_it() {
14298        let fm = "---\ntitle: foo\n---\n\n";
14299        let body = format!("{fm}body foo here\n");
14300        let mut d = wysiwyg_doc("wys_select_range", &body);
14301
14302        // The `foo` in the body: taken exactly, not snapped to a caret stop.
14303        let at = body.rfind("foo").unwrap();
14304        d.select_range(at, at + 3);
14305        assert_eq!(d.selection(), Some((at, at + 3)));
14306        assert_eq!(d.selected_text(), Some("foo"));
14307
14308        // The `foo` in the hidden frontmatter: below the floor, so both ends
14309        // come up to it rather than parking the caret in the metadata, where a
14310        // later keystroke would rewrite `title:`.
14311        let hidden = body.find("foo").unwrap();
14312        assert!(hidden < d.vmap.content_start);
14313        d.select_range(hidden, hidden + 3);
14314        assert!(
14315            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
14316            "a range under the floor must not leave the caret in the frontmatter"
14317        );
14318
14319        // Past the end, and mid-character, are both brought back to something
14320        // sliceable rather than panicking the next reader of the range.
14321        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
14322        let mut d = multi;
14323        d.select_range(2, 9_999);
14324        assert_eq!(d.caret, d.source.len());
14325        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
14326        assert!(d.source.is_char_boundary(d.caret));
14327    }
14328
14329    /// The bug `select_range` exists for: a match butting up against a hidden
14330    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
14331    /// the one before the `**`.
14332    #[test]
14333    fn select_range_does_not_snap_off_a_hidden_delimiter() {
14334        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
14335        let at = d.source.find("needle").unwrap();
14336        d.select_range(at, at + 6);
14337        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
14338    }
14339
14340    #[test]
14341    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
14342        // Backspace deletes `prev_boundary..caret` directly; at the first real
14343        // block that boundary is inside the hidden frontmatter, so it must be a
14344        // no-op rather than eating the closing `---`.
14345        let fm = "---\ntitle: hi\n---\n";
14346        let body = format!("{fm}leaf\n");
14347        let mut d = wysiwyg_doc("wys_fm_bs", &body);
14348        assert_eq!(d.caret, fm.len());
14349        d.backspace();
14350        assert_eq!(d.source, body, "backspace must not touch frontmatter");
14351        d.delete_word_back();
14352        assert_eq!(
14353            d.source, body,
14354            "word-delete must not touch frontmatter either"
14355        );
14356    }
14357
14358    #[test]
14359    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
14360        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
14361        // fenced div, really, since core parses these on for every document
14362        // now (`parse_extensions`). The container is a `directive` node, an
14363        // `is_block_container` kind like `block_quote`, so the caret works
14364        // inside its child paragraph exactly as it would inside a quote: typing
14365        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
14366        // untouched.
14367        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
14368        let mut d = wysiwyg_doc("wys_vis", body);
14369        d.caret = body.find("hello").unwrap() + "hello".len();
14370        d.insert("!");
14371        assert_eq!(
14372            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
14373            "typing inside the block edits its content in place"
14374        );
14375        assert!(
14376            d.source.contains(":::vis{.public .family}"),
14377            "opening fence survives"
14378        );
14379        assert!(d.source.contains(":::\nafter"), "closing fence survives");
14380    }
14381
14382    #[test]
14383    fn source_view_still_reaches_frontmatter() {
14384        // The metadata is only *hidden*, never lost: the source view edits and
14385        // selects it in full, and it's always preserved on save.
14386        let fm = "---\ntitle: hi\n---\n";
14387        let body = format!("{fm}# leaf\n");
14388        let mut d = doc_with("src_fm", &body);
14389        d.select_all();
14390        let sel = d.selected_text().unwrap();
14391        assert!(
14392            sel.contains("title"),
14393            "source view should select everything"
14394        );
14395        d.move_doc_start(false);
14396        assert_eq!(d.caret, 0, "source view can reach offset 0");
14397    }
14398
14399    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
14400
14401    #[test]
14402    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
14403        // The border and padding between two cells all share one source offset,
14404        // so a column-stepping caret would sit on `│` and then stall there
14405        // forever. Right must step: end of "Name" -> start of "Qty".
14406        let mut d = wysiwyg_doc("tbl_right", TABLE);
14407        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
14408        d.move_right(false);
14409        assert_eq!(
14410            d.caret,
14411            TABLE.find("Qty").unwrap(),
14412            "should land in the next cell"
14413        );
14414        let (r, c) = d.caret_pos();
14415        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
14416    }
14417
14418    #[test]
14419    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
14420        let mut d = wysiwyg_doc("tbl_left", TABLE);
14421        d.caret = TABLE.find("Qty").unwrap();
14422        d.move_left(false);
14423        assert_eq!(
14424            d.caret,
14425            TABLE.find("Name").unwrap() + 4,
14426            "end of the previous cell"
14427        );
14428    }
14429
14430    #[test]
14431    fn wysiwyg_down_steps_over_a_table_rule() {
14432        // Between the header and the first body row sits a `├───┼───┤` rule.
14433        // It's drawn but holds no caret, so one Down must reach "Pear".
14434        let mut d = wysiwyg_doc("tbl_down", TABLE);
14435        d.caret = TABLE.find("Name").unwrap();
14436        d.move_down(false);
14437        assert_eq!(
14438            d.caret,
14439            TABLE.find("Pear").unwrap(),
14440            "one Down reaches the body row"
14441        );
14442        d.move_down(false);
14443        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
14444    }
14445
14446    #[test]
14447    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
14448        let mut d = wysiwyg_doc("tbl_tab", TABLE);
14449        d.caret = TABLE.find("Name").unwrap();
14450        // A hop lands with the destination cell's whole content selected, the
14451        // caret at its end — so typing replaces the cell like a form field.
14452        assert!(d.cell_hop(true));
14453        assert_eq!(
14454            d.selected_text(),
14455            Some("Qty"),
14456            "the target cell comes up selected"
14457        );
14458        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
14459        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
14460        assert_eq!(d.selected_text(), Some("Pear"));
14461        assert!(d.cell_hop(false));
14462        assert_eq!(d.selected_text(), Some("Qty"));
14463    }
14464
14465    #[test]
14466    fn tab_outside_a_table_is_not_a_cell_hop() {
14467        // `cell_hop` reports false so the frontend can indent as usual.
14468        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
14469        d.caret = 4;
14470        assert!(!d.cell_hop(true));
14471        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
14472    }
14473
14474    #[test]
14475    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
14476        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14477        d.caret = TABLE.rfind("12").unwrap(); // the final cell
14478        assert!(!d.cell_hop(true), "no cell after the last one");
14479        d.caret = TABLE.find("Name").unwrap();
14480        assert!(!d.cell_hop(false), "no cell before the first one");
14481    }
14482
14483    #[test]
14484    fn wysiwyg_vertical_cell_motion_holds_the_column() {
14485        // Down/Up step to the cell above/below in the *same column*, not back to
14486        // the top-left the way a naive row/col motion over the picture would.
14487        let mut d = wysiwyg_doc("tbl_vert", TABLE);
14488        d.caret = TABLE.find("Qty").unwrap();
14489        // Each vertical hop selects the destination cell, holding the column.
14490        assert!(d.cell_move_vertical(true));
14491        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
14492        assert!(d.cell_move_vertical(true));
14493        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
14494        assert!(!d.cell_move_vertical(true), "no row below the last");
14495        assert!(d.cell_move_vertical(false));
14496        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
14497        assert!(d.cell_move_vertical(false));
14498        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
14499        assert!(!d.cell_move_vertical(false), "no row above the header");
14500    }
14501
14502    #[test]
14503    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
14504        let mut d = wysiwyg_doc("tbl_grow", TABLE);
14505        d.caret = TABLE.rfind("12").unwrap();
14506        let rows_before = d.source.matches('\n').count();
14507        assert!(d.cell_tab(true), "acts as a table key");
14508        assert_eq!(
14509            d.source.matches('\n').count(),
14510            rows_before + 1,
14511            "a fresh row was appended"
14512        );
14513        assert!(d.caret_in_table(), "the caret entered the new row");
14514        // The caret sits in the new row's first cell — past the old last cell.
14515        assert!(d.caret > TABLE.rfind("12").unwrap());
14516    }
14517
14518    #[test]
14519    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
14520        let mut d = wysiwyg_doc("tbl_ret", TABLE);
14521        d.caret = TABLE.find("Name").unwrap();
14522        assert!(d.cell_return(), "acts as a table key");
14523        assert_eq!(
14524            d.selected_text(),
14525            Some("Pear"),
14526            "Return drops one cell, selecting it"
14527        );
14528        // From the last row, Return appends a row and enters it.
14529        d.caret = TABLE.rfind("Fig").unwrap();
14530        let rows_before = d.source.matches('\n').count();
14531        assert!(d.cell_return());
14532        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
14533        assert!(d.caret_in_table());
14534    }
14535
14536    #[test]
14537    fn return_and_tab_outside_a_table_decline() {
14538        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
14539        d.caret = 4;
14540        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
14541        assert!(!d.cell_tab(true), "no table: the frontend indents");
14542        assert!(
14543            !d.cell_line_break(),
14544            "no table: the frontend breaks the line"
14545        );
14546    }
14547
14548    #[test]
14549    fn a_click_under_a_trailing_table_lands_past_it_and_enter_opens_a_line() {
14550        // A document that ends in a table used to end *inside* it: nothing
14551        // past the last cell was a caret stop, so a click in the blank space
14552        // under the grid snapped back into the table and there was no way to
14553        // write a line after it. The bottom border's end is that stop now.
14554        let mut d = wysiwyg_doc("tbl_trail", TABLE);
14555        let rows = d.vmap.num_rows();
14556        d.click(rows + 3, 0, false);
14557        let end = TABLE.trim_end_matches('\n').len();
14558        assert_eq!(d.caret, end, "the caret stands just past the table");
14559        assert!(!d.caret_in_table(), "past the table is outside it");
14560        assert!(!d.cell_return(), "Return there is the frontend's newline");
14561        d.newline();
14562        d.insert("after");
14563        assert_eq!(
14564            d.source,
14565            format!("{TABLE}\nafter\n"),
14566            "Enter opens a paragraph under the table"
14567        );
14568    }
14569
14570    #[test]
14571    fn typing_at_a_table_s_trailing_stop_opens_a_paragraph_first() {
14572        // The stop sits at the end of the table's last source line, and a
14573        // line glued under a table is a row of it — `| Fig | 12 |x` would be a
14574        // three-cell row. So the text gets a paragraph of its own, as it does
14575        // beside a block picture.
14576        let mut d = wysiwyg_doc("tbl_type", TABLE);
14577        d.caret = TABLE.trim_end_matches('\n').len();
14578        d.insert("x");
14579        assert_eq!(d.source, format!("{TABLE}\nx\n"));
14580        assert_eq!(d.caret, TABLE.len() + 2, "the caret follows the text");
14581        // And a paste, which joins the block exactly as typing would.
14582        let mut d = wysiwyg_doc("tbl_paste", TABLE);
14583        d.caret = TABLE.trim_end_matches('\n').len();
14584        d.paste("pasted");
14585        assert_eq!(d.source, format!("{TABLE}\npasted\n"));
14586    }
14587
14588    #[test]
14589    fn right_leaves_a_table_by_its_trailing_stop_and_backspace_steps_back_in() {
14590        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14591        let last_cell_end = TABLE.rfind("12").unwrap() + 2;
14592        let end = TABLE.trim_end_matches('\n').len();
14593        d.caret = last_cell_end;
14594        d.move_right(false);
14595        assert_eq!(d.caret, end, "Right from the last cell leaves the table");
14596        // Backspace there takes no byte: the one behind the caret is the row's
14597        // closing `|`, which the rich view never drew. It steps back instead.
14598        d.backspace();
14599        assert_eq!(d.source, TABLE, "nothing deleted");
14600        assert_eq!(d.caret, last_cell_end, "back into the last cell");
14601        // Down from the last row lands on the same stop, and Up returns.
14602        d.move_down(false);
14603        assert_eq!(d.caret, end, "Down from the last row leaves the table");
14604        d.move_up(false);
14605        assert_eq!(d.caret, last_cell_end);
14606    }
14607
14608    #[test]
14609    fn a_table_s_trailing_stop_sits_between_it_and_the_text_below() {
14610        // With prose under the table, the stop is one hop between the last
14611        // cell and the paragraph — the shape a block picture's second stop has.
14612        let src = format!("{TABLE}\nafter\n");
14613        let mut d = wysiwyg_doc("tbl_mid", &src);
14614        d.caret = TABLE.rfind("12").unwrap() + 2;
14615        d.move_right(false);
14616        assert_eq!(d.caret, TABLE.trim_end_matches('\n').len());
14617        d.move_right(false);
14618        assert_eq!(d.caret, src.find("after").unwrap());
14619        // Typing at the stop still opens a paragraph, and the text below keeps
14620        // its own.
14621        d.move_left(false);
14622        d.insert("x");
14623        assert_eq!(d.source, format!("{TABLE}\nx\n\nafter\n"));
14624    }
14625
14626    #[test]
14627    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
14628        let mut d = wysiwyg_doc("tbl_break", TABLE);
14629        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
14630        assert!(d.cell_line_break(), "acts as a table key");
14631        assert!(
14632            d.source.contains("Pear<br>"),
14633            "spelled as an inline <br>: {}",
14634            d.source
14635        );
14636        assert!(d.caret_in_table(), "still in the cell, past the break");
14637        // The break renders as a real line: the "Pear" cell now draws two lines,
14638        // so the table's picture is one row taller than a single-line table.
14639        d.build_visual(80);
14640        let table = &d.vmap.tables[0];
14641        let cell = &table.grid[1].cells[0]; // first body row, first column
14642        assert!(
14643            cell.glyphs.iter().any(|g| g.ch == '\n'),
14644            "the cell carries the break as a newline glyph for the frontend to split"
14645        );
14646    }
14647
14648    #[test]
14649    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
14650        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
14651        // back as structure — the whole point of routing through insert_line_break
14652        // instead of splicing raw `<br>` bytes.
14653        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
14654        d.caret = TABLE.find("Pear").unwrap() + 4;
14655        assert!(d.cell_line_break());
14656        let kinds: Vec<Kind> = d
14657            .editor
14658            .nodes()
14659            .unwrap()
14660            .iter()
14661            .map(|n| n.kind.clone())
14662            .collect();
14663        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
14664        assert!(
14665            !kinds.contains(&Kind::RawInline),
14666            "still raw HTML: {kinds:?}"
14667        );
14668    }
14669
14670    #[test]
14671    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
14672        // The `<br>` draws as one newline glyph, so Backspace over it must take
14673        // all four bytes — a one-byte delete would strand a visible `<br` in the
14674        // cell (the reported bug).
14675        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
14676        d.caret = TABLE.find("Pear").unwrap() + 4;
14677        assert!(d.cell_line_break());
14678        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
14679        d.backspace(); // caret sits just past the break
14680        assert!(
14681            !d.source.contains("<br"),
14682            "no half-deleted <br left: {}",
14683            d.source
14684        );
14685        assert!(
14686            d.source.contains("| Pear |"),
14687            "the cell is back to one line: {}",
14688            d.source
14689        );
14690    }
14691
14692    #[test]
14693    fn backspace_at_a_cell_start_is_a_wall() {
14694        // The task's repro: two presses used to take the padding and then the
14695        // `|`, merging `d` into `c`'s cell and leaving the row a column short.
14696        let src = "| a | b |\n| - | - |\n| c | d |\n";
14697        let mut d = wysiwyg_doc("tbl_wall_bs", src);
14698        d.place_caret(src.find("d |").unwrap(), false);
14699        for _ in 0..3 {
14700            d.backspace();
14701        }
14702        assert_eq!(d.source, src);
14703        // Inside the padding too — right after the `|`, before the space. Set
14704        // directly: `place_caret` would snap it onto the stop past the space.
14705        d.caret = src.find("| d").unwrap() + 1;
14706        d.backspace();
14707        assert_eq!(d.source, src);
14708        // The row's first cell, and an empty one, are walls the same.
14709        d.place_caret(src.find("c |").unwrap(), false);
14710        d.backspace();
14711        assert_eq!(d.source, src);
14712        // A cell that opens on hidden markup: the wall is the first letter
14713        // drawn, not the `**` in front of it.
14714        let bold = "| a | b |\n| - | - |\n| c | **d** |\n";
14715        let mut d = wysiwyg_doc("tbl_wall_bs_bold", bold);
14716        d.place_caret(bold.find("d**").unwrap(), false);
14717        d.backspace();
14718        assert_eq!(d.source, bold);
14719        let empty = "| a | b |\n| - | - |\n| c |   |\n";
14720        let mut d = wysiwyg_doc("tbl_wall_bs_empty", empty);
14721        d.place_caret(empty.find("|   |").unwrap() + 2, false);
14722        d.backspace();
14723        assert_eq!(d.source, empty);
14724    }
14725
14726    #[test]
14727    fn backspace_inside_a_cell_still_deletes_a_character() {
14728        let src = "| a | b |\n| - | - |\n| c | de |\n";
14729        let mut d = wysiwyg_doc("tbl_wall_bs_mid", src);
14730        d.place_caret(src.find("e |").unwrap(), false);
14731        d.backspace();
14732        assert_eq!(d.source, "| a | b |\n| - | - |\n| c | e |\n");
14733    }
14734
14735    #[test]
14736    fn delete_at_a_cell_end_is_a_wall() {
14737        // The mirror: Delete at `c`'s end would take the padding, then the `|`.
14738        let src = "| a | b |\n| - | - |\n| c | d |\n";
14739        let mut d = wysiwyg_doc("tbl_wall_del", src);
14740        d.place_caret(src.find("c |").unwrap() + 1, false);
14741        for _ in 0..3 {
14742            d.delete_forward();
14743        }
14744        assert_eq!(d.source, src);
14745        // And inside the trailing padding, set directly past the snap.
14746        d.caret = src.find("c |").unwrap() + 2;
14747        d.delete_forward();
14748        assert_eq!(d.source, src);
14749        // The row's last cell is a wall on its closing `|` as well.
14750        d.place_caret(src.find("d |").unwrap() + 1, false);
14751        d.delete_forward();
14752        assert_eq!(d.source, src);
14753        // Mid-cell Delete is untouched.
14754        d.place_caret(src.find("c |").unwrap(), false);
14755        d.delete_forward();
14756        assert_eq!(d.source, "| a | b |\n| - | - |\n|  | d |\n");
14757    }
14758
14759    #[test]
14760    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
14761        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
14762        d.caret = TABLE.find("Pear").unwrap() + 4;
14763        assert!(d.cell_line_break());
14764        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
14765        d.delete_forward();
14766        assert!(
14767            !d.source.contains("<br"),
14768            "no half-deleted <br: {}",
14769            d.source
14770        );
14771        assert!(
14772            d.source.contains("| Pear |"),
14773            "cell back to one line: {}",
14774            d.source
14775        );
14776    }
14777
14778    #[test]
14779    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
14780        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
14781        // still consumed (a real newline would split the one-line row), but the
14782        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
14783        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
14784        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
14785        d.caret = src.find("Pear").unwrap() + 4;
14786        assert!(d.caret_in_table(), "caret should be inside the djot table");
14787        assert!(
14788            d.cell_line_break(),
14789            "the key is consumed, not passed to the frontend"
14790        );
14791        assert_eq!(d.source, src, "the djot cell is left untouched");
14792        assert!(
14793            !d.source.contains("<br>"),
14794            "no non-idiomatic <br> spliced into djot"
14795        );
14796        assert!(
14797            d.status.is_some(),
14798            "the refusal is surfaced on the status line"
14799        );
14800    }
14801
14802    #[test]
14803    fn typing_in_a_cell_edits_that_cell() {
14804        // Editing comes free once offsets map correctly: the caret is a source
14805        // offset, so a normal splice lands inside the pipe table.
14806        let mut d = wysiwyg_doc("tbl_type", TABLE);
14807        d.caret = TABLE.find("Pear").unwrap() + 4;
14808        d.insert("s");
14809        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
14810    }
14811
14812    #[test]
14813    fn motion_and_delete_treat_an_emoji_as_one_character() {
14814        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
14815        // bytes, several codepoints. Right-arrow must clear it in one step, and
14816        // backspace must remove the whole cluster, not a stray joiner.
14817        let family = "👨‍👩‍👧";
14818        let mut d = doc_with("emoji", &format!("a{family}b\n"));
14819        d.caret = 1; // just after 'a', before the emoji
14820        d.move_right(false);
14821        assert_eq!(
14822            d.caret,
14823            1 + family.len(),
14824            "one step clears the whole cluster"
14825        );
14826        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
14827
14828        d.backspace(); // delete the emoji as a unit
14829        assert_eq!(d.source, "ab\n");
14830        assert_eq!(d.caret, 1);
14831    }
14832
14833    #[test]
14834    fn motion_handles_a_combining_accent_as_one_character() {
14835        // "e" + U+0301 (combining acute) renders as one é.
14836        let mut d = doc_with("combining", "e\u{0301}x\n");
14837        d.caret = 0;
14838        d.move_right(false);
14839        assert_eq!(
14840            d.caret,
14841            "e\u{0301}".len(),
14842            "steps past base + combining mark"
14843        );
14844    }
14845
14846    #[test]
14847    fn undo_then_redo_round_trips_an_edit() {
14848        let mut d = doc_with("undo", "hello\n");
14849        d.caret = 5;
14850        d.insert("!");
14851        assert_eq!(d.source, "hello!\n");
14852        d.undo();
14853        assert_eq!(d.source, "hello\n");
14854        assert_eq!(d.caret, 5, "undo restores the caret");
14855        d.redo();
14856        assert_eq!(d.source, "hello!\n");
14857    }
14858
14859    #[test]
14860    fn a_run_of_typing_undoes_as_one_step() {
14861        let mut d = doc_with("coalesce", "\n");
14862        d.caret = 0;
14863        d.insert("a");
14864        d.insert("b");
14865        d.insert("c");
14866        assert_eq!(d.source, "abc\n");
14867        d.undo(); // the whole typed run, not just "c"
14868        assert_eq!(d.source, "\n");
14869        d.undo(); // nothing left — the run was one step
14870        assert_eq!(d.source, "\n");
14871        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
14872    }
14873
14874    // ── IME composition ──────────────────────────────────────────────────────
14875
14876    #[test]
14877    fn a_composition_run_undoes_as_one_step() {
14878        let mut d = doc_with("compose", "\n");
14879        d.caret = 0;
14880        // What an IME does: each step replaces the last one's provisional bytes.
14881        d.edit_composing(0, 0, "k");
14882        d.edit_composing(0, 1, "か");
14883        d.edit_composing(0, 3, "かん");
14884        d.edit_composing(0, 6, "感"); // the commit
14885        d.end_composition();
14886        assert_eq!(d.source, "感\n");
14887        d.undo(); // the whole composition, not its last keystroke
14888        assert_eq!(d.source, "\n");
14889        assert_eq!(d.status.as_deref(), None, "the run was a single step");
14890    }
14891
14892    /// A Replace All the way a host does one: every match, last to first so
14893    /// the offsets still to go stay put, each a selection replaced by an
14894    /// insert, inside one undo group. `select_range` rather than the host's
14895    /// snapping `place_caret`, which would snap against a map these tests do
14896    /// not rebuild between edits.
14897    fn replace_all_in(d: &mut Doc, needle: &str, with: &str) {
14898        let hits: Vec<usize> = d.source.match_indices(needle).map(|(i, _)| i).collect();
14899        d.begin_undo_group();
14900        for at in hits.into_iter().rev() {
14901            d.select_range(at, at + needle.len());
14902            d.insert(with);
14903        }
14904        d.end_undo_group();
14905    }
14906
14907    #[test]
14908    fn a_replace_all_undoes_and_redoes_as_one_step() {
14909        let mut d = wysiwyg_doc("group", "a cat, a **cat**, a cat\n");
14910        d.caret = 0;
14911        d.insert("x");
14912        replace_all_in(&mut d, "cat", "dog");
14913        assert_eq!(d.source, "xa dog, a **dog**, a dog\n");
14914        assert!(d.undo(), "one undo");
14915        assert_eq!(
14916            d.source, "xa cat, a **cat**, a cat\n",
14917            "puts back every match"
14918        );
14919        assert!(d.redo(), "one redo");
14920        assert_eq!(
14921            d.source, "xa dog, a **dog**, a dog\n",
14922            "replaces them all again"
14923        );
14924        assert!(d.undo());
14925        assert!(d.undo(), "the typing before is its own step");
14926        assert_eq!(d.source, "a cat, a **cat**, a cat\n");
14927        assert!(!d.can_undo());
14928    }
14929
14930    #[test]
14931    fn typing_after_a_group_is_a_step_of_its_own() {
14932        // A one-character replacement is an insert like a keystroke, and a
14933        // keystroke after it would coalesce with it outside a group.
14934        let mut d = wysiwyg_doc("group", "a b a\n");
14935        replace_all_in(&mut d, "a", "c");
14936        d.caret = d.source.len() - 1;
14937        d.insert("d");
14938        assert_eq!(d.source, "c b cd\n");
14939        assert!(d.undo());
14940        assert_eq!(d.source, "c b c\n", "the typing alone");
14941        assert!(d.undo());
14942        assert_eq!(d.source, "a b a\n", "then the replacement, whole");
14943    }
14944
14945    #[test]
14946    fn a_group_of_more_edits_than_the_history_holds_is_still_one_step() {
14947        // twig keeps 200 steps; a group folds as it goes, so it never holds
14948        // more than one of them.
14949        let src = format!("start\n{}\n", "x ".repeat(300));
14950        let mut d = wysiwyg_doc("group", &src);
14951        d.caret = 5;
14952        d.insert("!");
14953        replace_all_in(&mut d, "x", "yy");
14954        assert_eq!(d.undo_steps, 2);
14955        assert!(d.undo());
14956        assert_eq!(d.source, src.replacen("start", "start!", 1));
14957        assert!(d.undo());
14958        assert_eq!(d.source, src);
14959        assert!(!d.can_undo());
14960    }
14961
14962    #[test]
14963    fn an_undo_closes_an_open_group() {
14964        let mut d = wysiwyg_doc("group", "one\n");
14965        d.caret = 3;
14966        d.begin_undo_group();
14967        d.begin_undo_group();
14968        d.insert("x");
14969        assert!(d.in_undo_group());
14970        assert!(d.undo());
14971        assert!(
14972            !d.in_undo_group(),
14973            "the history moved, so the group is over"
14974        );
14975        d.end_undo_group();
14976        d.end_undo_group();
14977        assert_eq!(d.source, "one\n");
14978        assert!(d.redo());
14979        assert_eq!(d.source, "onex\n");
14980    }
14981
14982    #[test]
14983    fn a_substitution_behind_the_caret_leaves_the_caret_and_is_its_own_step() {
14984        let mut d = wysiwyg_doc("substitute", "\n");
14985        d.caret = 0;
14986        for c in ["I", " ", "s", "a", "w", " ", "t", "e", "h", " "] {
14987            d.insert(c);
14988        }
14989        assert_eq!(d.source, "I saw teh \n");
14990        let at = d.source.find("teh").unwrap();
14991        assert!(d.substitute(at, at + 3, "the"));
14992        assert_eq!(d.source, "I saw the \n");
14993        assert_eq!(d.caret, 10, "still after the space");
14994        assert!(d.selection().is_none());
14995        d.insert("c");
14996        assert_eq!(d.source, "I saw the c\n");
14997        assert!(d.undo(), "the typing after it is a step of its own");
14998        assert_eq!(d.source, "I saw the \n");
14999        assert!(d.undo(), "the correction is one step");
15000        assert_eq!(d.source, "I saw teh \n", "what was typed");
15001        assert_eq!(d.caret, 10, "with the caret where it stood");
15002        assert!(d.redo());
15003        assert_eq!(d.source, "I saw the \n");
15004        assert!(d.undo());
15005        assert!(d.undo(), "and the typing before it is its own");
15006        assert_eq!(d.source, "\n");
15007        assert!(!d.can_undo());
15008    }
15009
15010    #[test]
15011    fn a_substitution_keeps_the_markup_it_stands_beside() {
15012        // A quote typed just past a bold run: only its own byte changes.
15013        let mut d = wysiwyg_doc("substitute", "A **bold** word\n");
15014        let at = d.source.find(" word").unwrap();
15015        d.caret = at;
15016        d.insert("\"");
15017        assert_eq!(d.source, "A **bold**\" word\n");
15018        assert!(d.substitute(at, at + 1, "\u{201d}"));
15019        assert_eq!(d.source, "A **bold**\u{201d} word\n");
15020        assert_eq!(d.caret, at + "\u{201d}".len());
15021        assert!(
15022            d.marks_at(d.source.find("bold").unwrap())
15023                .iter()
15024                .any(|(k, _)| *k == InlineKind::Strong)
15025        );
15026        // A range that is not one is refused, and changes nothing.
15027        let src = d.source.clone();
15028        assert!(!d.substitute(3, 2, "x"));
15029        assert!(!d.substitute(0, src.len() + 1, "x"));
15030        assert!(!d.substitute(d.source.find('\u{201d}').unwrap() + 1, d.source.len(), "x"));
15031        assert_eq!(d.source, src);
15032    }
15033
15034    #[test]
15035    fn a_substitution_that_half_lands_takes_back_only_its_own_deletion() {
15036        // The deletion lands and twig refuses the literal text: the deleted
15037        // bytes go back, and nothing else moves — not an earlier substitution
15038        // of the same keystroke, not the group it is in, and no redo is left
15039        // to delete them again.
15040        let mut d = wysiwyg_doc("substitute", "\n");
15041        d.set_markup_mode(MarkupMode::None);
15042        d.caret = 0;
15043        for c in ["a", "\"", "b", " ", "\""] {
15044            d.insert(c);
15045        }
15046        assert_eq!(d.source, "a\"b \"\n");
15047
15048        d.refuse_next_literal = true;
15049        assert!(!d.substitute(1, 2, "\u{201c}"));
15050        assert_eq!(d.source, "a\"b \"\n");
15051        assert_eq!(d.caret, 5, "the caret where it stood");
15052        assert!(!d.can_redo(), "no redo step left behind");
15053
15054        d.begin_undo_group();
15055        assert!(d.substitute(4, 5, "\u{201d}"));
15056        d.refuse_next_literal = true;
15057        assert!(!d.substitute(1, 2, "\u{201c}"));
15058        assert!(d.in_undo_group(), "the group is still open");
15059        assert_eq!(d.source, "a\"b \u{201d}\n", "the first substitution stands");
15060        d.end_undo_group();
15061        assert!(!d.can_redo());
15062        assert!(d.undo());
15063        assert_eq!(d.source, "a\"b \"\n", "one step takes the group back");
15064        assert!(d.undo());
15065        assert_eq!(d.source, "\n", "and the typing is still one step");
15066        assert!(!d.can_undo());
15067
15068        // A group whose first edit is the one that half lands has no step.
15069        let mut d = wysiwyg_doc("substitute", "\n");
15070        d.set_markup_mode(MarkupMode::None);
15071        d.caret = 0;
15072        d.insert("\"");
15073        d.begin_undo_group();
15074        d.refuse_next_literal = true;
15075        assert!(!d.substitute(0, 1, "\u{201c}"));
15076        assert!(d.substitute(0, 1, "\u{201c}"));
15077        d.end_undo_group();
15078        assert!(d.undo());
15079        assert_eq!(
15080            d.source, "\"\n",
15081            "the substitution that landed is the group's step"
15082        );
15083        assert!(d.undo());
15084        assert_eq!(d.source, "\n");
15085    }
15086
15087    #[test]
15088    fn a_substitution_is_written_the_way_typing_writes() {
15089        // Where typing is literal, so is a replacement's text.
15090        let mut d = wysiwyg_doc("substitute", "say hi\n");
15091        d.set_markup_mode(MarkupMode::None);
15092        assert!(d.substitute(4, 6, "*hi*"));
15093        assert_eq!(d.source, "say \\*hi\\*\n");
15094        assert!(d.undo());
15095        assert_eq!(d.source, "say hi\n", "one step, escapes and all");
15096    }
15097
15098    #[test]
15099    fn can_undo_is_false_once_a_coalesced_run_is_undone() {
15100        // The task's repro: five characters typed are one twig step, and the
15101        // counter used to say five.
15102        let mut d = wysiwyg_doc("undo_truth", "\n");
15103        d.caret = 0;
15104        for c in ["h", "e", "l", "l", "o"] {
15105            d.insert(c);
15106        }
15107        assert!(d.can_undo());
15108        assert!(d.undo(), "the run undoes");
15109        assert_eq!(d.source, "\n");
15110        assert!(!d.can_undo(), "and nothing is left behind it");
15111        let rev = d.revision();
15112        assert!(!d.undo(), "an undo that does not move says so");
15113        assert_eq!(d.revision(), rev);
15114        assert!(d.can_redo());
15115        assert!(d.redo());
15116        assert_eq!(d.source, "hello\n");
15117        assert!(!d.can_redo());
15118        assert!(!d.redo());
15119    }
15120
15121    #[test]
15122    fn can_undo_is_exact_across_the_gestures_that_coalesce() {
15123        // Each gesture below folds, or may fold, one twig step into another.
15124        // After it, the mirror must name exactly the number of undos twig
15125        // takes — and the same number of redos back.
15126        type Gesture = fn(&mut Doc);
15127        let cases: &[(&str, &str, Gesture)] = &[
15128            ("typing", "\n", |d| {
15129                d.caret = 0;
15130                d.insert("ab");
15131                d.insert("c");
15132                d.move_left(false);
15133                d.insert("x");
15134            }),
15135            ("backspaces", "abcdef\n", |d| {
15136                d.caret = 6;
15137                d.backspace();
15138                d.backspace();
15139                d.insert("z");
15140                d.backspace();
15141            }),
15142            ("ordered list item", "1. one\n2. two\n", |d| {
15143                d.caret = 6;
15144                d.newline();
15145                d.insert("x");
15146            }),
15147            ("list indent", "- one\n- two\n", |d| {
15148                d.caret = d.source.find("two").unwrap();
15149                d.indent();
15150                d.outdent();
15151            }),
15152            ("bold then type", "one two\n", |d| {
15153                d.select_range(0, 3);
15154                d.toggle(InlineKind::Strong);
15155                d.caret = d.source.len() - 1;
15156                d.insert("!");
15157            }),
15158            ("highlight", "one two\n", |d| {
15159                d.select_range(0, 3);
15160                d.highlight(None);
15161                d.highlight(Some(MarkColor::Green));
15162            }),
15163            ("heading and quote", "one\n", |d| {
15164                d.caret = 1;
15165                d.toggle_heading(2);
15166                d.toggle_blockquote();
15167            }),
15168            ("footnote", "one\n", |d| {
15169                d.caret = 3;
15170                d.insert_footnote();
15171                d.insert("note");
15172            }),
15173            ("blocks", "one\n\ntwo\n\nthree\n", |d| {
15174                d.caret = 1;
15175                d.move_block_down();
15176                d.toggle_list(true);
15177                d.set_alignment(Some(Align::Center));
15178                d.insert_page_break();
15179                d.insert_table(2, 2);
15180            }),
15181            ("paste and compose", "\n", |d| {
15182                d.caret = 0;
15183                d.paste("one two");
15184                d.delete_word_back();
15185                d.edit_composing(d.caret, d.caret, "か");
15186                d.edit_composing(d.caret - 3, d.caret, "蚊");
15187                d.end_composition();
15188                d.insert("z");
15189            }),
15190            ("table", "| a | b |\n| - | - |\n| c | d |\n", |d| {
15191                d.place_caret(d.source.find("d |").unwrap(), false);
15192                d.cell_tab(true);
15193                d.insert("e");
15194                d.cell_return();
15195            }),
15196            ("replace all", "cat cat cat\n", |d| {
15197                d.caret = 0;
15198                d.insert("a ");
15199                replace_all_in(d, "cat", "dog");
15200                d.insert("!");
15201            }),
15202            ("nested group", "one\n\ntwo\n", |d| {
15203                d.begin_undo_group();
15204                d.caret = 3;
15205                d.insert("x");
15206                d.begin_undo_group();
15207                d.toggle_heading(1);
15208                d.end_undo_group();
15209                d.insert("y");
15210                d.end_undo_group();
15211                d.backspace();
15212            }),
15213            ("group around a list", "1. one\n2. two\n", |d| {
15214                d.begin_undo_group();
15215                d.caret = 6;
15216                d.newline();
15217                d.insert("x");
15218                d.end_undo_group();
15219            }),
15220            ("substitution", "\n", |d| {
15221                d.caret = 0;
15222                d.insert("t");
15223                d.insert("e");
15224                d.insert("h");
15225                d.insert(" ");
15226                d.substitute(0, 3, "the");
15227                d.insert("c");
15228            }),
15229            ("empty group", "one\n", |d| {
15230                d.caret = 3;
15231                d.insert("x");
15232                d.begin_undo_group();
15233                d.end_undo_group();
15234                d.insert("y");
15235            }),
15236            ("undo inside a group", "one\n", |d| {
15237                d.caret = 3;
15238                d.begin_undo_group();
15239                d.insert("x");
15240                d.undo();
15241                d.insert("y");
15242                d.insert("z");
15243                d.end_undo_group();
15244            }),
15245        ];
15246        for (name, src, gesture) in cases {
15247            let mut d = wysiwyg_doc("undo_exact", src);
15248            gesture(&mut d);
15249            let (steps, after) = (d.undo_steps, d.source.clone());
15250            let mut undone = 0;
15251            while d.can_undo() {
15252                assert!(d.undo(), "{name}: can_undo said yes, undo moved nothing");
15253                undone += 1;
15254            }
15255            assert!(!d.undo(), "{name}: can_undo said no, undo moved");
15256            assert_eq!(undone, steps, "{name}");
15257            assert_eq!(d.source, *src, "{name}: back to the start");
15258            let mut redone = 0;
15259            while d.can_redo() {
15260                assert!(d.redo(), "{name}: can_redo said yes, redo moved nothing");
15261                redone += 1;
15262            }
15263            assert!(!d.redo(), "{name}: can_redo said no, redo moved");
15264            assert_eq!(redone, steps, "{name}");
15265            assert_eq!(d.source, after, "{name}: forward to the end");
15266        }
15267    }
15268
15269    #[test]
15270    fn two_compositions_are_two_undo_steps() {
15271        let mut d = doc_with("compose_two", "\n");
15272        d.caret = 0;
15273        d.edit_composing(0, 0, "か");
15274        d.edit_composing(0, 3, "蚊");
15275        d.end_composition();
15276        d.edit_composing(3, 3, "き");
15277        d.edit_composing(3, 6, "木");
15278        d.end_composition();
15279        assert_eq!(d.source, "蚊木\n");
15280        d.undo();
15281        assert_eq!(d.source, "蚊\n", "only the second composition");
15282        d.undo();
15283        assert_eq!(d.source, "\n");
15284    }
15285
15286    #[test]
15287    fn a_composition_does_not_fold_into_the_typing_around_it() {
15288        let mut d = doc_with("compose_typing", "\n");
15289        d.caret = 0;
15290        d.insert("a");
15291        d.insert("b");
15292        d.edit_composing(2, 2, "か");
15293        d.edit_composing(2, 5, "蚊");
15294        d.end_composition();
15295        d.insert("c");
15296        assert_eq!(d.source, "ab蚊c\n");
15297        d.undo();
15298        assert_eq!(d.source, "ab蚊\n");
15299        d.undo();
15300        assert_eq!(d.source, "ab\n");
15301        d.undo();
15302        assert_eq!(d.source, "\n");
15303    }
15304
15305    #[test]
15306    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
15307        let mut d = doc_with("compose_spurious", "\n");
15308        d.caret = 0;
15309        d.insert("a");
15310        d.end_composition(); // an IME unmarking unprompted
15311        d.insert("b");
15312        assert_eq!(d.source, "ab\n");
15313        d.undo();
15314        assert_eq!(d.source, "\n", "still one typed run");
15315    }
15316
15317    // ── the clipboard's rich flavor ──────────────────────────────────────────
15318
15319    #[test]
15320    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
15321        let mut d = doc_with("sel_inline", "a **bold** c\n");
15322        d.anchor = Some(2);
15323        d.caret = 10; // `**bold**`, inside the paragraph
15324        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
15325    }
15326
15327    #[test]
15328    fn a_whole_block_selection_keeps_its_paragraph() {
15329        let mut d = doc_with("sel_block", "a **bold** c\n");
15330        d.anchor = Some(0);
15331        d.caret = 12; // the entire paragraph
15332        assert_eq!(
15333            d.selection_html().as_deref(),
15334            Some("<p>a <strong>bold</strong> c</p>")
15335        );
15336    }
15337
15338    #[test]
15339    fn a_multi_block_selection_keeps_its_structure() {
15340        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
15341        d.select_all();
15342        let html = d.selection_html().expect("renders");
15343        assert!(html.contains("<p>para</p>"), "{html:?}");
15344        assert!(html.contains("<li>one</li>"), "{html:?}");
15345    }
15346
15347    #[test]
15348    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
15349        // The fragment `Head` is a paragraph standalone; the *document* says it
15350        // sits inside one block, so the wrapper is an artifact either way.
15351        let mut d = doc_with("sel_heading", "# Head line\n");
15352        d.anchor = Some(2);
15353        d.caret = 6;
15354        assert_eq!(d.selection_html().as_deref(), Some("Head"));
15355    }
15356
15357    #[test]
15358    fn no_selection_publishes_no_html() {
15359        let mut d = doc_with("sel_none", "a b\n");
15360        d.caret = 1;
15361        assert_eq!(d.selection_html(), None);
15362    }
15363
15364    #[test]
15365    fn pasting_html_converts_it_and_is_one_undo_step() {
15366        let mut d = doc_with("paste_html", "x\n");
15367        d.caret = 1;
15368        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
15369        assert_eq!(d.source, "xa **b** c\n");
15370        d.undo();
15371        assert_eq!(d.source, "x\n", "the whole paste, in one step");
15372    }
15373
15374    #[test]
15375    fn pasting_html_replaces_the_selection() {
15376        let mut d = doc_with("paste_html_sel", "keep drop\n");
15377        d.anchor = Some(5);
15378        d.caret = 9;
15379        assert!(d.paste_html("<em>new</em>"));
15380        assert_eq!(d.source, "keep *new*\n");
15381    }
15382
15383    #[test]
15384    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
15385        let mut d = doc_with("paste_html_bad", "x\n");
15386        d.caret = 1;
15387        // twig builds no table from HTML; raw `<table>` in prose is worse than
15388        // the plain flavor the caller still holds.
15389        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
15390        assert_eq!(d.source, "x\n", "declined edits nothing");
15391    }
15392
15393    #[test]
15394    fn copy_then_paste_round_trips_through_the_html_flavor() {
15395        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
15396        d.select_all();
15397        let html = d.selection_html().expect("renders");
15398        let mut into = doc_with("clip_round_dst", "\n");
15399        into.caret = 0;
15400        assert!(into.paste_html(&html));
15401        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
15402    }
15403
15404    #[test]
15405    fn moving_the_caret_starts_a_new_undo_group() {
15406        let mut d = doc_with("break", "\n");
15407        d.caret = 0;
15408        d.insert("a");
15409        d.insert("b"); // "ab\n", caret at 2
15410        d.move_left(false); // breaks the run
15411        d.insert("X"); // "aXb\n"
15412        assert_eq!(d.source, "aXb\n");
15413        d.undo();
15414        assert_eq!(
15415            d.source, "ab\n",
15416            "first undo removes only the post-move insert"
15417        );
15418        d.undo();
15419        assert_eq!(d.source, "\n", "second undo removes the earlier run");
15420    }
15421
15422    #[test]
15423    fn undo_reverses_a_format_toggle() {
15424        let mut d = doc_with("fmt_undo", "a word b\n");
15425        d.anchor = Some(2);
15426        d.caret = 6;
15427        d.toggle(InlineKind::Strong);
15428        assert_eq!(d.source, "a **word** b\n");
15429        d.undo();
15430        assert_eq!(d.source, "a word b\n");
15431    }
15432
15433    #[test]
15434    fn undo_back_to_the_saved_state_clears_dirty() {
15435        let mut d = doc_with("dirty_undo", "hello\n");
15436        assert!(!d.dirty);
15437        d.caret = 5;
15438        d.insert("!");
15439        assert!(d.dirty);
15440        d.undo();
15441        assert!(
15442            !d.dirty,
15443            "undoing to the saved source is not a modification"
15444        );
15445    }
15446
15447    #[test]
15448    fn a_new_edit_invalidates_redo() {
15449        let mut d = doc_with("redo_inv", "\n");
15450        d.caret = 0;
15451        d.insert("a");
15452        d.undo();
15453        d.insert("b"); // diverges — the redo of "a" is now gone
15454        d.redo();
15455        assert_eq!(d.source, "b\n");
15456    }
15457
15458    #[test]
15459    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
15460        let mut d = doc_with("can_undo", "hello\n");
15461        assert!(
15462            !d.can_undo() && !d.can_redo(),
15463            "a fresh document has no history"
15464        );
15465        d.caret = 5;
15466        d.insert("!");
15467        assert!(
15468            d.can_undo() && !d.can_redo(),
15469            "an edit is a step to take back"
15470        );
15471        d.undo();
15472        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
15473        d.redo();
15474        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
15475        d.undo();
15476        d.insert("?");
15477        assert!(
15478            d.can_undo() && !d.can_redo(),
15479            "a fresh edit ends the redo chain"
15480        );
15481        // A coalesced run over-counts steps — the bound is what a menu needs,
15482        // and it reconciles the moment twig reports the history empty.
15483        d.insert("a");
15484        d.insert("b");
15485        while d.can_undo() {
15486            d.undo();
15487        }
15488        assert_eq!(d.source, "hello\n");
15489        assert!(!d.can_undo());
15490        // A reading surface has nothing to undo, whatever the history holds.
15491        d.redo();
15492        d.set_read_only(true);
15493        assert!(!d.can_undo() && !d.can_redo());
15494    }
15495
15496    #[test]
15497    fn undo_on_empty_history_is_a_no_op() {
15498        let mut d = doc_with("undo_empty", "hi\n");
15499        d.undo();
15500        assert_eq!(d.source, "hi\n");
15501        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
15502    }
15503
15504    #[test]
15505    fn a_one_character_paste_is_its_own_undo_step() {
15506        for view in [View::Source, View::Wysiwyg] {
15507            let mut d = doc_in(view, "paste_step", "ab\n");
15508            d.caret = 0;
15509            d.insert("x");
15510            d.insert("y"); // a run of typing
15511            d.paste("z"); // one character, but pasted — not part of that run
15512            assert_eq!(d.source, "xyzab\n");
15513            d.undo();
15514            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
15515            assert_eq!(d.caret, 2, "and hands back the caret it found");
15516            d.undo();
15517            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
15518        }
15519    }
15520
15521    #[test]
15522    fn the_same_character_typed_still_joins_the_run() {
15523        // The other half of the pair: `z` is a keystroke here and a paste above,
15524        // and the two undo differently. Nothing about the *string* says which —
15525        // which is why provenance has to come from the door the caller uses.
15526        for view in [View::Source, View::Wysiwyg] {
15527            let mut d = doc_in(view, "typed_run", "ab\n");
15528            d.caret = 0;
15529            d.insert("x");
15530            d.insert("y");
15531            d.insert("z");
15532            d.undo();
15533            assert_eq!(d.source, "ab\n", "one run, one step");
15534        }
15535    }
15536
15537    #[test]
15538    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
15539        for view in [View::Source, View::Wysiwyg] {
15540            let mut d = doc_in(view, "undo_caret", "hello world\n");
15541            d.caret = 11; // standing at the end of "world", away from the edit
15542            d.edit(0, 5, "goodbye");
15543            assert_eq!(d.source, "goodbye world\n");
15544            d.undo();
15545            assert_eq!(d.source, "hello world\n");
15546            // The undone edit ends at offset 5; the user was at 11.
15547            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
15548        }
15549    }
15550
15551    #[test]
15552    fn undo_restores_the_selection_the_edit_replaced() {
15553        for view in [View::Source, View::Wysiwyg] {
15554            let mut d = doc_in(view, "undo_sel", "a word b\n");
15555            d.anchor = Some(2);
15556            d.caret = 6; // "word" selected
15557            d.insert("X");
15558            assert_eq!(d.source, "a X b\n");
15559            d.undo();
15560            assert_eq!(d.source, "a word b\n");
15561            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
15562        }
15563    }
15564
15565    #[test]
15566    fn redo_restores_the_caret_the_edit_left_behind() {
15567        for view in [View::Source, View::Wysiwyg] {
15568            let mut d = doc_in(view, "redo_caret", "hello world\n");
15569            d.caret = 11;
15570            d.edit(0, 5, "goodbye");
15571            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
15572            d.undo();
15573            d.redo();
15574            assert_eq!(d.source, "goodbye world\n");
15575            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
15576        }
15577    }
15578
15579    #[test]
15580    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
15581        for view in [View::Source, View::Wysiwyg] {
15582            let mut d = doc_in(view, "run_caret", "hi\n");
15583            d.caret = 2;
15584            d.insert("a");
15585            d.insert("b");
15586            d.insert("c");
15587            assert_eq!(d.source, "hiabc\n");
15588            d.undo();
15589            assert_eq!(d.source, "hi\n");
15590            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
15591            d.redo();
15592            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
15593        }
15594    }
15595
15596    #[test]
15597    fn undo_restores_the_caret_across_a_format_toggle() {
15598        // A toggle reaches twig without going through `splice`, so it has to
15599        // record its own step — miss it and every stack depth below it is off by
15600        // one, and undo starts handing back another edit's caret.
15601        for view in [View::Source, View::Wysiwyg] {
15602            let mut d = doc_in(view, "fmt_caret", "a word b\n");
15603            d.caret = 8;
15604            d.anchor = Some(2);
15605            d.caret = 6;
15606            d.toggle(InlineKind::Strong);
15607            assert_eq!(d.source, "a **word** b\n");
15608            d.undo();
15609            assert_eq!(d.source, "a word b\n");
15610            assert_eq!(
15611                d.selection(),
15612                Some((2, 6)),
15613                "the toggled selection comes back"
15614            );
15615        }
15616    }
15617
15618    #[test]
15619    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
15620        // The drift that would never announce itself: twig drops its redo stack
15621        // on any fresh edit, so a leaf redo entry that outlives it would restore
15622        // a caret from the timeline that edit abandoned.
15623        for view in [View::Source, View::Wysiwyg] {
15624            let mut d = doc_in(view, "redo_trunc", "hello world\n");
15625            d.caret = 11;
15626            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
15627            d.undo();
15628            assert_eq!(d.caret, 11);
15629            d.caret = 0;
15630            d.insert("X"); // diverges: A's redo is gone from twig
15631            assert_eq!(d.source, "Xhello world\n");
15632
15633            d.redo();
15634            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
15635            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
15636            d.undo();
15637            assert_eq!(d.source, "hello world\n");
15638            assert_eq!(
15639                d.caret, 0,
15640                "the surviving step's caret, not the dropped one"
15641            );
15642        }
15643    }
15644
15645    #[test]
15646    fn indent_and_outdent_move_the_caret_line_with_its_text() {
15647        for view in [View::Source, View::Wysiwyg] {
15648            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
15649            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
15650            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
15651            // Indentation the caret is standing *in* collapses to the line start
15652            // rather than dragging the caret into the text.
15653            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
15654            // A line with none to give back is left exactly as it was.
15655            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
15656            // Less than a full level gives back what it has.
15657            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
15658            // A tab is one level however many spaces it isn't.
15659            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
15660        }
15661    }
15662
15663    #[test]
15664    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
15665        // Why the level is two spaces and not the four both frontends type
15666        // today. Four is markdown's indented-code-block marker, so a Tab on a
15667        // paragraph would silently restyle it as code — a width that changes
15668        // what the document *means* isn't an indent. Pinned because the number
15669        // is the kind of thing a later list-aware pass would reach for.
15670        let mut d = doc_with("indent_kind", "hello\n");
15671        d.caret = 2;
15672        d.indent();
15673        assert_eq!(d.source, "  hello\n");
15674        assert!(
15675            d.nodes().iter().any(|n| n.kind == Kind::Para),
15676            "still prose after a Tab"
15677        );
15678        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
15679
15680        // The four-space level this replaces, for contrast: same text, and twig
15681        // reparses the paragraph into a code block.
15682        let mut wide = doc_with("indent_kind_4", "    hello\n");
15683        wide.build_visual(80);
15684        assert!(
15685            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
15686            "four spaces is a code block, not an indented paragraph"
15687        );
15688    }
15689
15690    #[test]
15691    fn indent_nests_a_list_item_under_its_parent() {
15692        // Tab indents a list item by its own marker width, landing its marker at
15693        // the parent's content column so twig reparses it as a nested list.
15694        for view in [View::Source, View::Wysiwyg] {
15695            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
15696            d.caret = 6; // on the second item
15697            d.indent();
15698            assert_eq!(d.source, "- a\n  - b\n");
15699            let lists = d
15700                .nodes()
15701                .iter()
15702                .filter(|n| n.kind == Kind::BulletList)
15703                .count();
15704            assert_eq!(lists, 2, "the indented item is a nested list");
15705        }
15706    }
15707
15708    #[test]
15709    fn indent_nests_an_ordered_item_at_its_marker_width() {
15710        // An ordered marker `1. ` is three columns wide, so a two-space step
15711        // (which nests a bullet) leaves it flat. Regression: Tab must use the
15712        // marker width, three, so the item actually nests — and the source
15713        // renumbers so the sub-list restarts at 1 and the outer list resumes.
15714        for view in [View::Source, View::Wysiwyg] {
15715            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
15716            d.caret = d.source.find('b').unwrap();
15717            d.indent();
15718            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
15719            let lists = d
15720                .nodes()
15721                .iter()
15722                .filter(|n| n.kind == Kind::OrderedList)
15723                .count();
15724            assert_eq!(lists, 2, "the indented item is a nested ordered list");
15725        }
15726    }
15727
15728    #[test]
15729    fn indent_leaves_a_lists_first_item_put() {
15730        // The first item of a list has no sibling above it to nest under, so Tab
15731        // is a no-op there — the marker stays at column zero rather than being
15732        // shoved into indentation twig can't read as a sub-list.
15733        for view in [View::Source, View::Wysiwyg] {
15734            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
15735            d.caret = 1; // on the FIRST item
15736            d.indent();
15737            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
15738            // The sibling below still nests, proving the guard is per-item.
15739            d.caret = d.source.find('b').unwrap();
15740            d.indent();
15741            assert_eq!(d.source, "- a\n  - b\n");
15742        }
15743    }
15744
15745    #[test]
15746    fn hidden_mode_keeps_typed_markup_literal() {
15747        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
15748        // twig escapes what would open markup, so the source is `\*hi\*` and the
15749        // AST is a plain string. Formatting is the commands' job in this mode.
15750        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
15751        d.insert("*hi*");
15752        assert_eq!(d.source, "\\*hi\\*");
15753        assert!(
15754            d.nodes()
15755                .iter()
15756                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
15757        );
15758    }
15759
15760    #[test]
15761    fn hidden_mode_escapes_a_line_start_block_marker() {
15762        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
15763        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
15764        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
15765        d.insert("# hi");
15766        assert_eq!(d.source, "\\# hi");
15767        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
15768    }
15769
15770    #[test]
15771    fn authoring_modes_keep_typed_markup_live() {
15772        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
15773        // (no escape), the same as source view — escaping is `None`'s alone, and
15774        // it's the axis, not the reveal, that decides.
15775        for (view, mode) in [
15776            (View::Wysiwyg, MarkupMode::Shortcuts),
15777            (View::Wysiwyg, MarkupMode::Full),
15778            (View::Source, MarkupMode::None),
15779        ] {
15780            let mut d = doc_in(view, "live_markup", "");
15781            d.set_markup_mode(mode);
15782            d.insert("*hi*");
15783            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
15784        }
15785    }
15786
15787    #[test]
15788    fn hidden_mode_overwrite_undoes_in_one_step() {
15789        // Typing over a selection escapes the replacement *and* stays a single
15790        // undo — the selection-delete and the literal insert fold together, so
15791        // one undo brings the whole selection back, like a plain overwrite.
15792        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
15793        d.anchor = Some(2);
15794        d.caret = 6; // "word"
15795        d.insert("*");
15796        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
15797        d.undo();
15798        assert_eq!(d.source, "a word b\n");
15799        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
15800    }
15801
15802    #[test]
15803    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
15804        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
15805        // the whole visual character, never stranding the hidden `\`.
15806        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
15807        d.insert("*");
15808        assert_eq!(d.source, "\\*");
15809        d.backspace();
15810        assert_eq!(d.source, "", "the escape backslash went with the *");
15811        // A *literal* backslash (source view, no escape) is an ordinary char.
15812        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
15813        s.caret = 3; // after `b`
15814        s.backspace();
15815        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
15816    }
15817
15818    #[test]
15819    fn hidden_mode_leaves_structural_markup_alone() {
15820        // Enter continues a bullet list by writing a real `- ` marker (an
15821        // `insert_raw`, not the typing path), so Hidden mode's escaping never
15822        // touches it — the list keeps working.
15823        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
15824        d.caret = 6;
15825        d.newline();
15826        d.insert("two");
15827        assert_eq!(d.source, "- item\n- two\n");
15828    }
15829
15830    #[test]
15831    fn markup_mode_defaults_to_none_and_round_trips() {
15832        // Diaryx's default is the clean `None` surface; a markup-fluent
15833        // frontend can climb the ladder, and the choice sticks.
15834        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
15835        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
15836        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
15837            d.set_markup_mode(mode);
15838            assert_eq!(d.markup_mode(), mode);
15839        }
15840    }
15841
15842    #[test]
15843    fn full_mode_reveals_only_the_caret_line() {
15844        // The mode's whole claim: the caret's line shows its raw delimiters and
15845        // every other line stays resolved. Two paragraphs with identical markup
15846        // so the only difference between the rows is where the caret is.
15847        let mut d = doc_in(
15848            View::Wysiwyg,
15849            "reveal_caret_line",
15850            "*one* here\n\n*two* there\n",
15851        );
15852        d.set_markup_mode(MarkupMode::Full);
15853
15854        caret_at(&mut d, "one");
15855        let rows = drawn_rows(&d);
15856        assert!(
15857            rows.iter().any(|r| r == "*one* here"),
15858            "caret's line raw: {rows:?}"
15859        );
15860        assert!(
15861            rows.iter().any(|r| r == "two there"),
15862            "other line resolved: {rows:?}"
15863        );
15864
15865        // Move to the other paragraph: the reveal follows, and the line just
15866        // left goes back to being resolved.
15867        caret_at(&mut d, "two");
15868        let rows = drawn_rows(&d);
15869        assert!(
15870            rows.iter().any(|r| r == "*two* there"),
15871            "caret's line raw: {rows:?}"
15872        );
15873        assert!(
15874            rows.iter().any(|r| r == "one here"),
15875            "left line resolved: {rows:?}"
15876        );
15877    }
15878
15879    #[test]
15880    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
15881        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
15882        // the same treatment as an emphasis's `*`: hidden while the caret is
15883        // elsewhere, shown in full where the caret lands. That falls out of
15884        // `delims` reading the bytes between the mark's span and its content
15885        // span, which is exactly `==🔴 ` and `==`, rather than from a table
15886        // of spellings — so the no-space form `==🟢green==` reveals right too.
15887        let mut d = doc_in(
15888            View::Wysiwyg,
15889            "reveal_coloured_mark",
15890            "a ==🔴 red== one\n\nb ==plain== two\n",
15891        );
15892        d.set_markup_mode(MarkupMode::Full);
15893
15894        caret_at(&mut d, "red");
15895        let rows = drawn_rows(&d);
15896        assert!(
15897            rows.iter().any(|r| r == "a ==🔴 red== one"),
15898            "the caret's line shows the colour it was written with: {rows:?}"
15899        );
15900        assert!(
15901            rows.iter().any(|r| r == "b plain two"),
15902            "and every other line stays resolved: {rows:?}"
15903        );
15904
15905        // Away from it, the emoji goes back to being markup — the reader sees
15906        // the words and the wash.
15907        caret_at(&mut d, "two");
15908        let rows = drawn_rows(&d);
15909        assert!(
15910            rows.iter().any(|r| r == "a red one"),
15911            "resolved again: {rows:?}"
15912        );
15913    }
15914
15915    #[test]
15916    fn hidden_modes_never_reveal_wherever_the_caret_is() {
15917        // The two rungs below `Full` share a rendering: delimiters stay hidden
15918        // even under the caret. `Shortcuts` differing from `None` only in what
15919        // typing does is exactly the point of splitting the axes.
15920        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
15921            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
15922            d.set_markup_mode(mode);
15923            caret_at(&mut d, "one");
15924            let rows = drawn_rows(&d);
15925            assert!(
15926                rows.iter().any(|r| r == "one here"),
15927                "{mode:?} hides: {rows:?}"
15928            );
15929            assert!(
15930                !rows.iter().any(|r| r.contains('*')),
15931                "{mode:?} shows no `*`: {rows:?}"
15932            );
15933        }
15934    }
15935
15936    #[test]
15937    fn revealed_delimiters_are_the_authors_own_spelling() {
15938        // Delimiters are re-read from the source rather than synthesized per
15939        // kind, so a line comes back spelled the way it was written: `_em_` does
15940        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
15941        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
15942        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
15943        d.set_markup_mode(MarkupMode::Full);
15944        caret_at(&mut d, "em");
15945        let rows = drawn_rows(&d);
15946        assert!(
15947            rows.iter().any(|r| r == body.trim_end()),
15948            "the revealed line is its own source: {rows:?}"
15949        );
15950    }
15951
15952    #[test]
15953    fn revealed_heading_shows_its_hashes() {
15954        // The `# ` marker is a block-level prefix, not an inline delimiter, so
15955        // it takes its own path — but it reveals on the same rule.
15956        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
15957        d.set_markup_mode(MarkupMode::Full);
15958
15959        caret_at(&mut d, "Title");
15960        assert!(
15961            drawn_rows(&d).iter().any(|r| r == "# Title"),
15962            "{:?}",
15963            drawn_rows(&d)
15964        );
15965
15966        caret_at(&mut d, "body");
15967        let rows = drawn_rows(&d);
15968        assert!(
15969            rows.iter().any(|r| r == "Title"),
15970            "hashes hidden again: {rows:?}"
15971        );
15972    }
15973
15974    #[test]
15975    fn revealed_delimiters_are_caret_stops() {
15976        // A delimiter that is drawn but can't be reached is worse than one
15977        // that's hidden: the mode exists so the markup can be *edited*. Every
15978        // revealed byte must be somewhere the caret can stand.
15979        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
15980        d.set_markup_mode(MarkupMode::Full);
15981        caret_at(&mut d, "em");
15982        let opener = d.source.find('*').unwrap();
15983        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
15984        assert!(
15985            d.vmap.is_stop(opener + 3),
15986            "the closing `*` is a caret stop"
15987        );
15988    }
15989
15990    #[test]
15991    fn setext_heading_reveals_nothing_across_its_newline() {
15992        // A setext heading's underline is on another line, so it is not the
15993        // caret line's to reveal — and emitting it would inject a `\n` glyph
15994        // that splits the row where the author wrote no break.
15995        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
15996        d.set_markup_mode(MarkupMode::Full);
15997        caret_at(&mut d, "Title");
15998        let rows = drawn_rows(&d);
15999        assert!(
16000            rows.iter().any(|r| r == "Title"),
16001            "title renders alone: {rows:?}"
16002        );
16003        assert!(
16004            !rows.iter().any(|r| r.contains('=')),
16005            "no underline leaks in: {rows:?}"
16006        );
16007    }
16008
16009    #[test]
16010    fn markup_mode_axes_split_the_ladder() {
16011        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
16012        // that authors markup but still hides it, and it's the only rung where
16013        // the two axes disagree.
16014        assert!(!MarkupMode::None.authors());
16015        assert!(!MarkupMode::None.reveals_caret_line());
16016        assert!(MarkupMode::Shortcuts.authors());
16017        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
16018        assert!(MarkupMode::Full.authors());
16019        assert!(MarkupMode::Full.reveals_caret_line());
16020    }
16021
16022    #[test]
16023    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
16024        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
16025        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
16026        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
16027        // nested bullet and `hello` stays prose: the file round-trips instead of
16028        // hiding a heading the user never asked for.
16029        for view in [View::Source, View::Wysiwyg] {
16030            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
16031            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
16032            d.indent();
16033            assert_eq!(d.source, "- hello\n  * \n");
16034            assert!(
16035                d.nodes().iter().all(|n| n.kind != Kind::Heading),
16036                "no heading"
16037            );
16038            // And it's genuinely a nested list, not a flat one.
16039            assert_eq!(
16040                d.nodes()
16041                    .iter()
16042                    .filter(|n| n.kind == Kind::BulletList)
16043                    .count(),
16044                2
16045            );
16046        }
16047    }
16048
16049    #[test]
16050    fn indenting_a_dash_item_with_content_keeps_its_dash() {
16051        // With content, `- x` can't be a setext underline, so there's nothing to
16052        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
16053        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
16054        d.caret = d.source.find('x').unwrap();
16055        d.indent();
16056        assert_eq!(d.source, "- hello\n  - x\n");
16057    }
16058
16059    #[test]
16060    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
16061        // The dash→`*` repair coalesces into the Tab, so a single undo restores
16062        // the whole pre-Tab state rather than stranding a half-collapsed doc.
16063        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
16064        d.caret = d.source.find("- \n").unwrap() + 2;
16065        d.indent();
16066        assert_eq!(d.source, "- hello\n  * \n");
16067        d.undo();
16068        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
16069    }
16070
16071    #[test]
16072    fn indent_leaves_a_nested_lists_first_item_put_too() {
16073        // The guard is about siblings, not depth: the first item of an *inner*
16074        // list (already nested under `a`) still has nothing before it at its own
16075        // level, so Tab can't take it deeper.
16076        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
16077        d.caret = d.source.find('b').unwrap();
16078        d.indent();
16079        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
16080        // But `c` (a sibling of `b`) nests under `b`.
16081        d.caret = d.source.find('c').unwrap();
16082        d.indent();
16083        assert_eq!(d.source, "- a\n  - b\n    - c\n");
16084    }
16085
16086    #[test]
16087    fn backspace_at_a_nested_item_start_outdents_it() {
16088        // Backspace with the caret right after a nested item's marker gives back
16089        // one level of nesting, the mirror of Tab — and renumbers the flattened
16090        // ordered list back to a clean run.
16091        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
16092        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
16093        d.backspace();
16094        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16095    }
16096
16097    #[test]
16098    fn backspace_at_a_top_level_item_start_strips_the_marker() {
16099        // At the outermost level there's no nesting left to give back, so the same
16100        // keystroke drops the bullet and leaves a plain paragraph.
16101        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
16102        d.caret = d.source.find('b').unwrap(); // right after `- `
16103        d.backspace();
16104        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
16105    }
16106
16107    #[test]
16108    fn backspace_mid_item_still_deletes_a_character() {
16109        // The list behaviour is armed only at the item's content start; anywhere
16110        // else Backspace is the ordinary character delete.
16111        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
16112        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
16113        d.backspace();
16114        assert_eq!(d.source, "- b\n");
16115    }
16116
16117    #[test]
16118    fn backspace_at_a_heading_start_strips_the_marker() {
16119        // The `# ` is markup the rich view hides, so Backspace over it takes the
16120        // whole marker and leaves a paragraph. Deleting a byte of it instead left
16121        // `#Title` — no longer a heading, with the hash now literal text the user
16122        // never typed and has to delete again.
16123        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
16124        d.caret = d.source.find('T').unwrap(); // right after `## `
16125        d.backspace();
16126        assert_eq!(d.source, "Title\n");
16127        assert_eq!(
16128            d.caret, 0,
16129            "the caret stays with the text it was in front of"
16130        );
16131    }
16132
16133    #[test]
16134    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
16135        // Only the heading's own marker goes — the quote (or list) it sits in is
16136        // untouched, exactly as un-heading it should be.
16137        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
16138        d.caret = d.source.find('T').unwrap();
16139        d.backspace();
16140        assert_eq!(d.source, "> Title\n");
16141    }
16142
16143    #[test]
16144    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
16145        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
16146        // behind would surface the same stray hash the marker delete just avoided.
16147        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
16148        d.caret = d.source.find('T').unwrap();
16149        d.backspace();
16150        assert_eq!(d.source, "Title\n");
16151        // And it's one edit: a single undo puts the whole heading back.
16152        d.undo();
16153        assert_eq!(d.source, "# Title #\n");
16154    }
16155
16156    #[test]
16157    fn backspace_mid_heading_still_deletes_a_character() {
16158        // The heading behaviour is armed only at the content's start; anywhere
16159        // else Backspace is the ordinary character delete.
16160        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
16161        d.caret = d.source.find('b').unwrap();
16162        d.backspace();
16163        assert_eq!(d.source, "# b\n");
16164    }
16165
16166    #[test]
16167    fn source_view_backspace_still_edits_the_heading_marker_literally() {
16168        // In source view the `# ` is text on the screen the user is deleting a
16169        // byte of, so it keeps its literal meaning — the same split the list
16170        // ladder and Enter draw between the two views.
16171        let mut d = doc_with("bsp_head_src", "# Title\n");
16172        d.caret = d.source.find('T').unwrap();
16173        d.backspace();
16174        assert_eq!(d.source, "#Title\n");
16175    }
16176
16177    #[test]
16178    fn outdent_unnests_an_ordered_item_in_one_press() {
16179        // Shift+Tab gives back exactly the marker width the indent added, so a
16180        // nested ordered item unnests in a single press, and the flattened list
16181        // renumbers back to a clean 1, 2, 3.
16182        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
16183        d.caret = d.source.find('b').unwrap();
16184        d.outdent();
16185        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16186        let lists = d
16187            .nodes()
16188            .iter()
16189            .filter(|n| n.kind == Kind::OrderedList)
16190            .count();
16191        assert_eq!(lists, 1, "back to one flat list");
16192    }
16193
16194    #[test]
16195    fn table_insert_row_adds_a_row_below_the_caret() {
16196        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16197        d.caret = d.source.find('1').unwrap(); // in the body row
16198        d.table_insert_row(true);
16199        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
16200    }
16201
16202    #[test]
16203    fn table_insert_and_delete_column_at_the_caret() {
16204        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16205        d.caret = d.source.find('a').unwrap(); // column 0
16206        d.table_insert_column(true); // add a column to the right of `a`
16207        assert_eq!(
16208            d.source,
16209            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
16210        );
16211        d.caret = d.source.find('b').unwrap(); // now the third column
16212        d.table_delete_column();
16213        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
16214    }
16215
16216    // ── ragged formats ───────────────────────────────────────────────────────
16217    // No format spells every gesture. HTML writes the inline marks as a tag pair
16218    // and no heading, list, quote or link; Markdown spells five of the eight
16219    // marks — the highlight only because leaf parses with `highlight`, which is
16220    // why the question is asked with the extensions; djot spells all eight and
16221    // no in-cell break. leaf asks twig per
16222    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
16223    // op discover the fact on its own — one of them didn't.
16224
16225    /// An HTML document in the rich view, ready for a gesture.
16226    fn html_doc(body: &str) -> Doc {
16227        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
16228        d.view = View::Wysiwyg;
16229        d.build_visual(80);
16230        d
16231    }
16232
16233    #[test]
16234    fn a_table_gesture_leaves_an_html_table_alone() {
16235        // The regression this guard exists for. twig's table editor consults no
16236        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
16237        // HTML `<table>` as a *pipe table* and reported success: the whole
16238        // element replaced by `| a | b |`, silently, on one press of a toolbar
16239        // button. Every grid op went the same way.
16240        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
16241        // A table of named operations, which is what it looks like.
16242        #[allow(clippy::type_complexity)]
16243        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
16244            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
16245            ("delete row", &|d: &mut Doc| d.table_delete_row()),
16246            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
16247            ("delete column", &|d: &mut Doc| d.table_delete_column()),
16248            ("align", &|d: &mut Doc| {
16249                d.table_set_alignment(Alignment::Right)
16250            }),
16251            ("move row", &|d: &mut Doc| d.table_move_row(true)),
16252            ("move column", &|d: &mut Doc| d.table_move_column(true)),
16253        ];
16254        for (name, op) in ops {
16255            let mut d = html_doc(src);
16256            d.caret = d.source.find('a').unwrap();
16257            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
16258            op(&mut d);
16259            assert_eq!(d.source, src, "{name} rewrote an HTML table");
16260            assert!(
16261                !d.dirty,
16262                "{name} marked the document dirty without editing it"
16263            );
16264            assert!(d.status.is_some(), "{name} refused without saying why");
16265        }
16266    }
16267
16268    #[test]
16269    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
16270        // A task box is a form control in HTML and a footnote has no native
16271        // spelling at all — the two gestures twig 3.5 still spells nothing
16272        // for, now that a quote, a list, a link and an image print through
16273        // its renderer (see the test below).
16274        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16275        // A table of named operations, which is what it looks like.
16276        #[allow(clippy::type_complexity)]
16277        let ops: [(&str, &dyn Fn(&mut Doc)); 3] = [
16278            ("task item", &|d: &mut Doc| d.toggle_task_item()),
16279            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
16280            ("footnote", &|d: &mut Doc| d.insert_footnote()),
16281        ];
16282        for (name, op) in ops {
16283            let mut d = html_doc(src);
16284            let at = d.source.find("Hello").unwrap();
16285            d.caret = at;
16286            d.anchor = Some(at + 5); // a selection, for the ops that want one
16287            op(&mut d);
16288            assert_eq!(d.source, src, "{name} edited an HTML document");
16289            assert!(
16290                !d.dirty,
16291                "{name} marked the document dirty without editing it"
16292            );
16293            let status = d.status.as_deref().unwrap_or("");
16294            assert!(
16295                status.contains("html"),
16296                "{name}: the refusal should name the format, got {status:?}"
16297            );
16298        }
16299    }
16300
16301    #[test]
16302    fn html_spells_a_quote_a_list_a_link_and_an_image_through_the_renderer() {
16303        // twig 3.5: where HTML has no marker alphabet it prints the fresh
16304        // node — a `<blockquote>` around the paragraph, a `<ul>`/`<ol>` with
16305        // the paragraph as its item, an `<a>` or `<img>` over the selection.
16306        // Until then every one of these was a refusal; now each is a real
16307        // edit, which is what the toolbar's capability flags say too.
16308        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16309        #[allow(clippy::type_complexity)]
16310        let ops: [(&str, &dyn Fn(&mut Doc), &str); 5] = [
16311            (
16312                "quote",
16313                &|d: &mut Doc| d.toggle_blockquote(),
16314                "<blockquote>",
16315            ),
16316            ("list", &|d: &mut Doc| d.toggle_list(false), "<ul>\n<li>"),
16317            (
16318                "ordered list",
16319                &|d: &mut Doc| d.toggle_list(true),
16320                "<ol>\n<li>",
16321            ),
16322            (
16323                "link",
16324                &|d: &mut Doc| d.insert_link("https://example.dev"),
16325                "<a href=\"https://example.dev\">Hello</a>",
16326            ),
16327            (
16328                "image",
16329                &|d: &mut Doc| d.insert_image("pic.png", "alt"),
16330                "<img alt=\"Hello\" src=\"pic.png\">",
16331            ),
16332        ];
16333        for (name, op, expect) in ops {
16334            let mut d = html_doc(src);
16335            let at = d.source.find("Hello").unwrap();
16336            d.caret = at;
16337            d.anchor = Some(at + 5);
16338            op(&mut d);
16339            assert!(d.source.contains(expect), "{name}: got {:?}", d.source);
16340            assert!(d.dirty, "{name}: a real edit");
16341            assert_eq!(
16342                d.status, None,
16343                "{name}: a supported gesture reports nothing"
16344            );
16345        }
16346    }
16347
16348    #[test]
16349    fn html_spells_a_heading_as_its_tag_pair() {
16350        // twig 3.4 rebuilds a heading or paragraph as its tag pair, attributes
16351        // along — the one block gesture whose HTML shape it can write. So ⌘2
16352        // in an HTML document is a real edit, and ⌘0 takes it back.
16353        let src = "<h1>Title</h1>\n<p>Hello world</p>\n";
16354        let mut d = html_doc(src);
16355        d.caret = d.source.find("Hello").unwrap();
16356        d.toggle_heading(2);
16357        assert_eq!(d.source, "<h1>Title</h1>\n<h2>Hello world</h2>\n");
16358        assert!(d.dirty);
16359        assert_eq!(d.status, None, "a supported gesture reports nothing");
16360        d.toggle_heading(2);
16361        assert_eq!(d.source, src, "the same level again is back to a paragraph");
16362    }
16363
16364    #[test]
16365    fn html_spells_the_inline_marks_and_the_rule() {
16366        // The other half, and why one per-document flag stopped being enough:
16367        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
16368        // already emits and the parser reads straight back as the same mark —
16369        // and the rule button writes an `<hr>`. Refusing these on the old
16370        // "HTML is parse-only" reading would now be leaf's own limitation.
16371        let mut d = html_doc("<p>Hello world</p>\n");
16372        let at = d.source.find("world").unwrap();
16373        d.caret = at;
16374        d.anchor = Some(at + 5);
16375        d.toggle(InlineKind::Strong);
16376        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
16377        assert!(d.dirty);
16378        assert_eq!(d.status, None, "a supported gesture reports nothing");
16379
16380        // And off again — the toggle reverses, which is the property that makes
16381        // authoring in HTML worth offering rather than a one-way trip.
16382        d.toggle(InlineKind::Strong);
16383        assert_eq!(d.source, "<p>Hello world</p>\n");
16384
16385        let mut d = html_doc("<p>Hello world</p>\n");
16386        d.caret = d.source.find("world").unwrap();
16387        d.insert_thematic_break();
16388        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
16389    }
16390
16391    #[test]
16392    fn a_mark_the_format_cannot_spell_arms_nothing() {
16393        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
16394        // sticky mark for the next text typed. Guarding only the twig call
16395        // leaves that path live, promising a mark the gesture will not write and
16396        // then swallowing the error inside `insert`.
16397        //
16398        // Markdown carries this, on the superscript now rather than on the
16399        // highlight: `^x^` is text there in any configuration, whereas twig
16400        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
16401        // which every leaf document does.
16402        let mut d = doc_with("mark", "Hello world\n");
16403        d.view = View::Wysiwyg;
16404        d.build_visual(80);
16405        d.caret = d.source.find("world").unwrap();
16406        d.toggle(InlineKind::Superscript);
16407        assert!(d.pending_marks.is_empty(), "no mark should be armed");
16408        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
16409        d.insert("X");
16410        assert_eq!(d.source, "Hello Xworld\n");
16411    }
16412
16413    #[test]
16414    fn markdown_authors_a_highlight_and_a_strikethrough() {
16415        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
16416        // write. `==x==` is authorable because leaf's own `parse_extensions`
16417        // turns `highlight` on — twig will only mint bytes this editor's reparse
16418        // reads back — and `~~x~~` because GFM strikethrough is parsed by
16419        // default, so the refusal there was never right for any leaf document.
16420        // twig 3.10 adds the underline, spelled `<u>x</u>` and paired back into
16421        // an `insert` under the `html_elements` leaf parses with.
16422        for (kind, marked) in [
16423            (InlineKind::Mark, "a ==word== b\n"),
16424            (InlineKind::Delete, "a ~~word~~ b\n"),
16425            (InlineKind::Insert, "a <u>word</u> b\n"),
16426        ] {
16427            let mut d = doc_with("author_mark", "a word b\n");
16428            d.anchor = Some(2);
16429            d.caret = 6;
16430            d.toggle(kind);
16431            assert_eq!(d.source, marked, "{kind:?}");
16432            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
16433            assert!(d.dirty, "{kind:?}");
16434            // The region stays selected, so the second press reverses it — the
16435            // property that separates authoring from a one-way trip.
16436            d.toggle(kind);
16437            assert_eq!(d.source, "a word b\n", "{kind:?}");
16438        }
16439    }
16440
16441    #[test]
16442    fn an_authored_highlight_reads_back_as_a_mark() {
16443        // The round trip the extension gate exists to protect: what the toggle
16444        // writes, the reparse must read back as a `mark` rather than as two
16445        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
16446        // rebuilt map rather than from the source text.
16447        let mut d = doc_with("mark_roundtrip", "a word b\n");
16448        d.view = View::Wysiwyg;
16449        d.build_visual(80);
16450        d.anchor = Some(2);
16451        d.caret = 6;
16452        d.toggle(InlineKind::Mark);
16453        assert_eq!(d.source, "a ==word== b\n");
16454        d.build_visual(80);
16455        let w = d
16456            .vmap
16457            .rows
16458            .iter()
16459            .flat_map(|r| r.glyphs.iter())
16460            .find(|g| g.ch == 'w')
16461            .expect("the highlighted word");
16462        assert_eq!(w.style.role, crate::Role::Mark(None));
16463    }
16464
16465    #[test]
16466    fn an_authored_underline_reads_back_as_an_insert() {
16467        // The same round trip for `<u>…</u>`: under `html_elements` the tag pair
16468        // is one `insert`, so the word is underlined and the tags are markup the
16469        // caret-off line hides — not two `raw_inline` runs drawn as literal
16470        // HTML around plain text.
16471        let mut d = doc_with("underline_roundtrip", "a word b\nnext\n");
16472        d.view = View::Wysiwyg;
16473        d.build_visual(80);
16474        d.anchor = Some(2);
16475        d.caret = 6;
16476        d.toggle(InlineKind::Insert);
16477        assert_eq!(d.source, "a <u>word</u> b\nnext\n");
16478        d.anchor = None;
16479        d.caret = d.source.find("next").unwrap();
16480        d.build_visual(80);
16481        let glyphs: Vec<_> = d.vmap.rows.iter().flat_map(|r| r.glyphs.iter()).collect();
16482        let w = glyphs
16483            .iter()
16484            .find(|g| g.ch == 'w')
16485            .expect("the underlined word");
16486        assert!(w.style.underline);
16487        assert!(!glyphs.iter().any(|g| g.ch == '<'), "the tags are hidden");
16488    }
16489
16490    #[test]
16491    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
16492        // The three states of one gesture, in the order a palette is pressed:
16493        // an uncoloured highlight takes the prefix, a coloured one has it
16494        // replaced, and `None` takes it away with the space that was part of the
16495        // spelling.
16496        let mut d = doc_with("mark_colour", "a ==word== b\n");
16497        d.caret = d.source.find("word").unwrap();
16498        d.set_mark_color(Some(MarkColor::Red));
16499        assert_eq!(d.source, "a ==🔴 word== b\n");
16500        assert_eq!(d.status, None);
16501        assert!(d.dirty);
16502
16503        d.set_mark_color(Some(MarkColor::Blue));
16504        assert_eq!(d.source, "a ==🔵 word== b\n");
16505
16506        d.set_mark_color(None);
16507        assert_eq!(d.source, "a ==word== b\n");
16508    }
16509
16510    #[test]
16511    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
16512        // The prefix is written *before* the word, so an offset in the word has
16513        // to ride its width — a caret that stayed put would be a caret that
16514        // walked backwards through the text it was standing in.
16515        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
16516        let word = d.source.find("word").unwrap();
16517        d.caret = word + 2; // between `wo` and `rd`
16518        d.set_mark_color(Some(MarkColor::Red));
16519        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
16520
16521        // And back the other way when the prefix goes.
16522        d.set_mark_color(None);
16523        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
16524    }
16525
16526    #[test]
16527    fn the_colour_at_the_caret_is_what_the_palette_lights() {
16528        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
16529        d.caret = d.source.find("red").unwrap();
16530        assert!(d.caret_in_mark());
16531        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
16532
16533        d.caret = d.source.find("plain").unwrap();
16534        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
16535        assert_eq!(d.mark_color_at_caret(), None);
16536
16537        d.caret = d.source.find(" and ").unwrap() + 2;
16538        assert!(!d.caret_in_mark());
16539        assert_eq!(d.mark_color_at_caret(), None);
16540    }
16541
16542    #[test]
16543    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
16544        // The gesture colours a highlight that exists; it does not make one.
16545        // Two presses is the price of a coloured highlight from bare text, and
16546        // the reason is undo — one press that spliced twice would take two
16547        // presses to take back.
16548        let mut d = doc_with("mark_colour_none", "a word b\n");
16549        d.caret = d.source.find("word").unwrap();
16550        d.set_mark_color(Some(MarkColor::Red));
16551        assert_eq!(d.source, "a word b\n");
16552        assert!(d.status.is_some(), "it should say why");
16553        assert!(!d.dirty);
16554
16555        // Clearing where there is nothing to clear is the same refusal, not a
16556        // quiet success — the caret is in no highlight either way.
16557        d.status = None;
16558        d.set_mark_color(None);
16559        assert_eq!(d.source, "a word b\n");
16560        assert!(d.status.is_some());
16561    }
16562
16563    #[test]
16564    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
16565        // twig answers this one *successfully* with a `Change` describing some
16566        // earlier edit, so a caller that trusted the change would jump the caret
16567        // to wherever that was. Core answers it before asking.
16568        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
16569        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
16570        d.caret = d.source.find("word").unwrap();
16571        let (source, caret) = (d.source.clone(), d.caret);
16572        d.set_mark_color(None);
16573        assert_eq!(d.source, source);
16574        assert_eq!(
16575            d.caret, caret,
16576            "the caret must not ride a change that isn't one"
16577        );
16578        assert_eq!(d.status, None, "and it is not an error either");
16579    }
16580
16581    #[test]
16582    fn djot_spells_the_highlight_and_not_its_colour() {
16583        // The reason the palette is its own capability rather than the Highlight
16584        // button's: `{=word=}` is a highlight djot writes happily, and there is
16585        // no djot spelling for a colour on it.
16586        assert!(Capabilities::of(Format::Djot).mark);
16587        assert!(!Capabilities::of(Format::Djot).mark_color);
16588        assert!(Capabilities::of(Format::Markdown).mark_color);
16589
16590        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
16591        d.caret = d.source.find("word").unwrap();
16592        assert!(
16593            d.caret_in_mark(),
16594            "the caret is in a highlight all the same"
16595        );
16596        d.set_mark_color(Some(MarkColor::Red));
16597        assert_eq!(d.source, "a {=word=} b\n");
16598        assert!(
16599            d.status.as_deref().unwrap_or("").contains("djot"),
16600            "and the refusal names the document's format: {:?}",
16601            d.status
16602        );
16603    }
16604
16605    #[test]
16606    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
16607        // The round trip that matters for a palette: the bytes twig writes are
16608        // bytes its own reparse reads back as a colour, so the swatch that was
16609        // pressed is the swatch that lights afterwards.
16610        let mut d = doc_with("mark_colour_undo", "a word b\n");
16611        d.anchor = Some(2);
16612        d.caret = 6;
16613        d.toggle(InlineKind::Mark);
16614        d.caret = d.source.find("word").unwrap();
16615        d.set_mark_color(Some(MarkColor::Green));
16616        assert_eq!(d.source, "a ==🟢 word== b\n");
16617        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
16618
16619        // One splice, one step: the colour comes off and the highlight stays.
16620        d.undo();
16621        assert_eq!(d.source, "a ==word== b\n");
16622        d.undo();
16623        assert_eq!(d.source, "a word b\n");
16624    }
16625
16626    #[test]
16627    fn every_colour_leaf_names_is_one_twig_writes() {
16628        // The two enums are one vocabulary, and this is what says so: each of
16629        // leaf's colours writes an emoji twig's reparse reads back as *that*
16630        // colour, so `twig_mark_color`'s table cannot quietly pair red with
16631        // orange.
16632        for color in MarkColor::ALL {
16633            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
16634            d.caret = d.source.find("word").unwrap();
16635            d.set_mark_color(Some(color));
16636            assert_eq!(d.status, None, "{color:?}");
16637            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
16638        }
16639    }
16640
16641    #[test]
16642    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
16643        // The two presses a coloured highlight is made of, in the state the
16644        // first one leaves: `toggle` selects the whole `==word==` and puts the
16645        // caret one past the closing `==`, which is *not* in the mark. Asking at
16646        // the caret alone would refuse to colour the highlight just written —
16647        // the selection's start is what answers.
16648        let mut d = doc_with("mark_colour_fresh", "a word b\n");
16649        d.anchor = Some(2);
16650        d.caret = 6;
16651        d.toggle(InlineKind::Mark);
16652        assert_eq!(d.source, "a ==word== b\n");
16653        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
16654
16655        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
16656        d.set_mark_color(Some(MarkColor::Yellow));
16657        assert_eq!(d.source, "a ==🟡 word== b\n");
16658        assert_eq!(d.status, None);
16659    }
16660
16661    #[test]
16662    fn one_press_highlights_a_selection_and_colours_it() {
16663        // What a toolbar swatch means over a plain selection, and the undo it
16664        // has to have: one press, one step. Two steps would leave an uncoloured
16665        // highlight behind on the way back, which is a state the author never
16666        // asked for and never saw.
16667        let mut d = doc_with("highlight_one", "a word b\n");
16668        d.anchor = Some(2);
16669        d.caret = 6;
16670        d.highlight(Some(MarkColor::Purple));
16671        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
16672        assert_eq!(d.status, None);
16673
16674        d.undo();
16675        assert_eq!(d.source, "a word b\n", "one press, one undo");
16676    }
16677
16678    #[test]
16679    fn one_press_on_an_existing_highlight_only_recolours_it() {
16680        // The other half: inside a highlight there is nothing to make, so the
16681        // compound is the plain gesture and the text is untouched.
16682        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
16683        d.caret = d.source.find("word").unwrap();
16684        d.highlight(Some(MarkColor::Blue));
16685        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
16686        d.undo();
16687        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
16688    }
16689
16690    #[test]
16691    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
16692        // `None` means "no colour", and over bare text that is the Highlight
16693        // button's own job. The fold must not happen here — there is no second
16694        // splice, and folding would take the *previous* edit into this one.
16695        let mut d = doc_with("highlight_none", "a word b and more\n");
16696        d.caret = d.source.find("more").unwrap() + 4; // after "more"
16697        d.insert("!"); // an earlier edit for a wrong fold to swallow
16698        d.anchor = Some(2);
16699        d.caret = 6;
16700        d.highlight(None);
16701        assert_eq!(d.source, "a ==word== b and more!\n");
16702
16703        d.undo();
16704        assert_eq!(
16705            d.source, "a word b and more!\n",
16706            "only the highlight came off"
16707        );
16708        d.undo();
16709        assert_eq!(
16710            d.source, "a word b and more\n",
16711            "and the edit before it survived"
16712        );
16713    }
16714
16715    #[test]
16716    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
16717        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
16718        // a colour cannot be armed with it — so the compound declines rather
16719        // than leaving half a promise.
16720        let mut d = doc_with("highlight_bare", "a word b\n");
16721        d.caret = 4;
16722        d.highlight(Some(MarkColor::Red));
16723        assert_eq!(d.source, "a word b\n");
16724        assert!(d.pending_marks.is_empty(), "and nothing armed");
16725        assert!(d.status.is_some());
16726    }
16727
16728    #[test]
16729    fn a_read_only_document_takes_no_colour() {
16730        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
16731        d.caret = d.source.find("word").unwrap();
16732        d.set_read_only(true);
16733        d.set_mark_color(Some(MarkColor::Red));
16734        assert_eq!(d.source, "a ==word== b\n");
16735    }
16736
16737    #[test]
16738    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
16739        // The other door into `toggle`: no selection, so nothing reaches twig
16740        // until `insert` realises the armed mark. It is armed now — the guard
16741        // above asks `Doc::supports`, which asks with the extensions — and what
16742        // it writes is the same `==…==`.
16743        let mut d = doc_with("sticky_mark", "xy\n");
16744        d.caret = 1;
16745        d.toggle(InlineKind::Mark);
16746        assert!(d.pending_marks.contains(InlineKind::Mark));
16747        d.insert("Z");
16748        assert_eq!(d.source, "x==Z==y\n");
16749    }
16750
16751    #[test]
16752    fn html_documents_still_take_typed_text() {
16753        // The guard covers *markup* gestures and must not touch plain editing:
16754        // twig's splicer is language-neutral, and typing into an HTML document
16755        // is the thing that does work today.
16756        let mut d = html_doc("<p>Hello world</p>\n");
16757        d.caret = d.source.find("world").unwrap();
16758        d.insert("big ");
16759        assert_eq!(d.source, "<p>Hello big world</p>\n");
16760        assert!(d.dirty);
16761        d.backspace();
16762        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
16763        d.undo();
16764        d.undo();
16765        assert_eq!(d.source, "<p>Hello world</p>\n");
16766    }
16767
16768    #[test]
16769    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
16770        // `authorable` only separates "there is a door in" from "there is not",
16771        // and HTML is on the near side of that line — which is exactly why a
16772        // toolbar must not be built from it.
16773        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
16774        assert!(html.authorable());
16775        assert!(
16776            !Doc::from_source("<r>x</r>".into(), Format::Xml)
16777                .unwrap()
16778                .authorable()
16779        );
16780
16781        let caps = html.capabilities();
16782        assert!(caps.bold && caps.italic && caps.code && caps.mark);
16783        assert!(caps.thematic_break && caps.cell_line_break);
16784        // A heading is a tag pair twig rebuilds (3.4), and since 3.5 so are a
16785        // quote, a list, a code block's language, a link and an image — each
16786        // printed as a fresh node where HTML has no marker to rewrite. A task
16787        // box is a form control and a footnote has no spelling, so those two
16788        // are what keeps the record ragged.
16789        assert!(caps.heading && caps.blockquote && caps.bullet_list);
16790        assert!(caps.link && caps.image && caps.code_language);
16791        assert!(!caps.task && !caps.footnote);
16792        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
16793        // twig's table editor would happily re-emit as `| a | b |`.
16794        assert!(!caps.table);
16795
16796        // The two lightweight formats spell everything leaf offers — and still
16797        // differ from each other, which is the other half of why one boolean
16798        // can't serve.
16799        for fmt in [Format::Markdown, Format::Djot] {
16800            let caps = Capabilities::of(fmt);
16801            assert!(
16802                caps.heading && caps.blockquote && caps.ordered_list,
16803                "{fmt:?}"
16804            );
16805            assert!(
16806                caps.task && caps.link && caps.image && caps.table,
16807                "{fmt:?}"
16808            );
16809        }
16810        // Both spell the highlight, the strikethrough and the underline: djot
16811        // natively, and Markdown because `Capabilities` asks with
16812        // `parse_extensions` rather than with twig's defaults — `==x==` is text
16813        // under those, and a mark under the `highlight` leaf always parses
16814        // with; `<u>x</u>` likewise pairs into an `insert` only under
16815        // `html_elements`.
16816        for fmt in [Format::Markdown, Format::Djot] {
16817            let caps = Capabilities::of(fmt);
16818            assert!(caps.mark && caps.strike && caps.underline, "{fmt:?}");
16819        }
16820        // What still separates them, now that the highlight doesn't: djot has
16821        // no in-cell break, and Markdown spells neither of the scripts.
16822        assert!(Capabilities::of(Format::Djot).superscript);
16823        assert!(!Capabilities::of(Format::Markdown).superscript);
16824        assert!(Capabilities::of(Format::Markdown).cell_line_break);
16825        assert!(!Capabilities::of(Format::Djot).cell_line_break);
16826
16827        // A parse-only format answers no to every one of them, so the coarse
16828        // predicate and the record agree there.
16829        let caps = Capabilities::of(Format::Xml);
16830        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
16831    }
16832
16833    #[test]
16834    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
16835        // The guard exists to name the *document's* format rather than twig's
16836        // internals, so the message has to survive being one leaf writes itself.
16837        // Checked against a gesture twig also refuses, since that is the pair
16838        // most at risk of drifting apart — the task box, once the code
16839        // language stopped being one (twig 3.5).
16840        let mut d = html_doc("<p>Hello</p>\n");
16841        d.caret = d.source.find("Hello").unwrap();
16842        d.toggle_task_item();
16843        assert_eq!(d.status.as_deref(), Some("task: not supported in html"));
16844        assert!(!d.dirty);
16845    }
16846
16847    #[test]
16848    fn table_set_alignment_respells_the_delimiter() {
16849        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16850        d.caret = d.source.find('b').unwrap();
16851        d.table_set_alignment(Alignment::Right);
16852        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
16853    }
16854
16855    #[test]
16856    fn each_empty_table_cell_has_its_own_editable_home() {
16857        // Regression: an empty cell has no twig content_span, so both cells of a
16858        // `|  |  |` row collapsed onto the row's start (before the first `│`).
16859        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
16860        // tell the cells apart. Each empty cell must now have a distinct home
16861        // inside it.
16862        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
16863        let (c0, c1) = {
16864            let cells = &d.vmap.tables[0].grid[1].cells;
16865            (cells[0].start, cells[1].start)
16866        };
16867        assert!(
16868            c0 < c1,
16869            "the two empty cells have distinct homes: {c0} < {c1}"
16870        );
16871        d.caret = c0;
16872        d.insert("x");
16873        assert_eq!(
16874            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
16875            "typed inside the cell"
16876        );
16877    }
16878
16879    #[test]
16880    fn arrows_step_into_each_empty_table_cell() {
16881        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
16882        let (c0, c1) = {
16883            let cells = &d.vmap.tables[0].grid[1].cells;
16884            (cells[0].start, cells[1].start)
16885        };
16886        d.caret = d.source.find('b').unwrap(); // in the header's second cell
16887        let mut seen = std::collections::HashSet::new();
16888        for _ in 0..6 {
16889            d.move_right(false);
16890            seen.insert(d.caret);
16891        }
16892        assert!(
16893            seen.contains(&c0),
16894            "right arrow reaches the first empty cell"
16895        );
16896        assert!(
16897            seen.contains(&c1),
16898            "right arrow reaches the second empty cell"
16899        );
16900    }
16901
16902    #[test]
16903    fn table_op_off_a_table_is_a_no_op_with_a_status() {
16904        let mut d = doc_with("tbl_none", "just text\n");
16905        d.caret = 3;
16906        d.table_insert_row(true);
16907        assert_eq!(d.source, "just text\n", "nothing changed");
16908        assert!(d.status.is_some(), "a status explains why");
16909        assert!(!d.caret_in_table());
16910    }
16911
16912    #[test]
16913    fn enter_in_an_ordered_list_renumbers_the_following_items() {
16914        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
16915        // the renumber pass keeps them sequential, matching what the view draws.
16916        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
16917        d.caret = d.source.find('a').unwrap() + 1; // end of item a
16918        d.newline();
16919        d.insert("x");
16920        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
16921    }
16922
16923    #[test]
16924    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
16925        for view in [View::Source, View::Wysiwyg] {
16926            let mut d = doc_in(view, "outdent_noop", "hello\n");
16927            d.caret = 2;
16928            d.outdent();
16929            assert_eq!(d.source, "hello\n");
16930            assert!(!d.dirty, "a no-op is not a modification");
16931            d.undo();
16932            assert_eq!(
16933                d.status.as_deref(),
16934                Some("nothing to undo"),
16935                "spends no undo step"
16936            );
16937            assert_eq!(d.source, "hello\n");
16938        }
16939    }
16940
16941    #[test]
16942    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
16943        for view in [View::Source, View::Wysiwyg] {
16944            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
16945            d.anchor = Some(0);
16946            d.caret = 7; // through "two"
16947            d.indent();
16948            assert_eq!(
16949                d.source, "  one\n\n  two\n",
16950                "the blank line keeps no trailing pad"
16951            );
16952            // Selected, so a second Tab lands on the same lines rather than on
16953            // whatever the shifted offsets now cover.
16954            assert_eq!(d.selection(), Some((0, 12)));
16955            d.indent();
16956            assert_eq!(d.source, "    one\n\n    two\n");
16957        }
16958    }
16959
16960    #[test]
16961    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
16962        for view in [View::Source, View::Wysiwyg] {
16963            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
16964            d.anchor = Some(0);
16965            d.caret = 15;
16966            d.outdent();
16967            assert_eq!(d.source, "two\none\nnone\n");
16968        }
16969    }
16970
16971    #[test]
16972    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
16973        for view in [View::Source, View::Wysiwyg] {
16974            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
16975            d.anchor = Some(0);
16976            d.caret = 7;
16977            d.indent();
16978            assert_eq!(d.source, "  one\n\n  two\n");
16979            d.undo();
16980            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
16981            assert_eq!(
16982                d.selection(),
16983                Some((0, 7)),
16984                "with the selection it was aimed at"
16985            );
16986            d.redo();
16987            assert_eq!(d.source, "  one\n\n  two\n");
16988            assert_eq!(
16989                d.selection(),
16990                Some((0, 12)),
16991                "redo replays the caret the indent placed, not the one splice left"
16992            );
16993        }
16994    }
16995
16996    #[test]
16997    fn vertical_motion_keeps_the_column() {
16998        let mut d = doc_with("move", "abcd\nef\n");
16999        d.caret = 3; // "abc|d" on row 0, col 3
17000        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
17001        assert_eq!(d.caret, 7); // just after "ef"
17002    }
17003
17004    // ── goal column ──────────────────────────────────────────────────────────
17005
17006    #[test]
17007    fn vertical_motion_goal_column_survives_a_short_line() {
17008        // Regression: re-deriving the column from the clamped position on
17009        // every step permanently forgets it once a short line clamps it.
17010        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
17011        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
17012        assert_eq!(
17013            g("abcd|ef\nxy\nghijkl\n", |d| {
17014                d.move_down(false); // clamps to end of "xy"
17015                d.move_down(false); // restores col 4 on the long line
17016            }),
17017            "abcdef\nxy\nghij|kl\n"
17018        );
17019    }
17020
17021    #[test]
17022    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
17023        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
17024        assert_eq!(d.goal_col, None);
17025        d.caret = 4; // row 0, col 4
17026        d.move_down(false); // clamps into "xy"; goal stays the original col
17027        assert_eq!(d.goal_col, Some(4));
17028        assert_eq!(d.caret_pos(), (1, 2));
17029
17030        // A horizontal motion drops the goal column...
17031        d.move_left(false);
17032        assert_eq!(d.goal_col, None);
17033
17034        // ...so the next vertical motion picks up the *new* column (1), not
17035        // the stale one (4).
17036        d.move_down(false);
17037        assert_eq!(d.goal_col, Some(1));
17038        assert_eq!(d.caret_pos(), (2, 1));
17039    }
17040
17041    #[test]
17042    fn editing_clears_the_goal_column() {
17043        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
17044        d.caret = 4;
17045        d.move_down(false);
17046        assert_eq!(d.goal_col, Some(4));
17047        d.insert("Z");
17048        assert_eq!(d.goal_col, None);
17049    }
17050
17051    #[test]
17052    fn vertical_motion_on_an_empty_document_is_a_no_op() {
17053        let mut d = doc_with("empty_vert", "");
17054        d.move_down(false);
17055        assert_eq!(d.caret, 0);
17056        d.move_up(false);
17057        assert_eq!(d.caret, 0);
17058    }
17059
17060    // ── the document's edges ─────────────────────────────────────────────────
17061
17062    #[test]
17063    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
17064        // The reproduction, and the disagreement: Down on the last line ran to
17065        // the end of the document in the source view — by accident, an
17066        // out-of-range row clamping to the end of the string — and did nothing
17067        // whatever in the view leaf opens in. One rule now, in both.
17068        for (view, tag) in VIEWS {
17069            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
17070            d.caret = 1;
17071            d.move_down(false);
17072            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
17073            d.move_up(false);
17074            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
17075        }
17076    }
17077
17078    #[test]
17079    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
17080        // Down off the bottom is a motion like any other, so it latches a goal
17081        // column — and Up comes back to the column the caret left, not to the
17082        // one the document's end happened to be in.
17083        for (view, tag) in VIEWS {
17084            let gap = if view == View::Source { "\n" } else { "\n\n" };
17085            let src = format!("abcdef{gap}ghijkl");
17086            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
17087            d.caret = 2; // row 0, col 2
17088            d.move_down(false);
17089            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
17090            d.move_down(false);
17091            assert_eq!(
17092                d.caret,
17093                src.len(),
17094                "{tag}: Down off the bottom reaches the end"
17095            );
17096            d.move_up(false);
17097            assert_eq!(
17098                d.caret_pos().1,
17099                2,
17100                "{tag}: Up returns to the column Down left"
17101            );
17102        }
17103    }
17104
17105    #[test]
17106    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
17107        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
17108        // Up that did nothing still armed a goal column, and the next Down aimed
17109        // at a column the caret had never been in.
17110        for (view, tag) in VIEWS {
17111            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
17112            d.caret = 0;
17113            d.move_up(false);
17114            assert_eq!(d.caret, 0, "{tag}: already at the start");
17115            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
17116
17117            d.caret = d.source.len();
17118            d.move_down(false);
17119            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
17120            assert_eq!(
17121                d.goal_col, None,
17122                "{tag}: a no-op Down latched a goal column"
17123            );
17124        }
17125    }
17126
17127    // ── soft wrap ────────────────────────────────────────────────────────────
17128    // Every other test here builds the map at 80 columns, where no fixture is
17129    // long enough to fold. A wrap is where one offset belongs to two rows at
17130    // once, and it broke everything that asks the caret what row it is on.
17131
17132    /// The wrapped fixture these cases share, folded at 12 columns into
17133    /// `one two ` / `three four ` / `five six ` / `seven eight`.
17134    fn wrapped_doc(name: &str) -> Doc {
17135        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
17136        d.build_visual(12);
17137        d
17138    }
17139
17140    #[test]
17141    fn home_and_end_work_from_a_wrapped_row() {
17142        // The reproduction: offset 19 is the `f` of "five", the first character
17143        // of the third row — and also the offset the second row ends at. It
17144        // resolved to the *second* row, so End aimed at a place the caret was
17145        // already in and did nothing, while Home walked backwards onto a row the
17146        // caret had left.
17147        let mut d = wrapped_doc("wrap_home_end");
17148        d.caret = 19;
17149        assert_eq!(
17150            d.caret_pos(),
17151            (2, 0),
17152            "the wrap boundary opens the third row"
17153        );
17154        d.move_end(false);
17155        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
17156        d.move_home(false);
17157        assert_eq!(d.caret, 19, "Home left the row the caret was on");
17158    }
17159
17160    #[test]
17161    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
17162        // The row's end is the last offset that is only ever its own: the offset
17163        // past it opens the row below, and aiming there would send a second
17164        // press on to *that* row's end, and a third to the next — End walking
17165        // down the paragraph rather than sitting where it landed.
17166        let mut d = wrapped_doc("wrap_end_twice");
17167        d.caret = 12; // inside "three", on the second row
17168        d.move_end(false);
17169        assert_eq!(
17170            d.caret, 18,
17171            "the end of `three four`, before the space the wrap ate"
17172        );
17173        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
17174        d.move_end(false);
17175        assert_eq!(d.caret, 18, "a second End moved the caret");
17176        d.move_home(false);
17177        assert_eq!(d.caret, 8, "Home takes the row's own start");
17178    }
17179
17180    #[test]
17181    fn vertical_motion_crosses_a_soft_wrap() {
17182        // Down aimed at the row below's column 0, an offset that resolved *up*
17183        // to the row above's end — so it landed on the offset it already had and
17184        // the caret could never leave a paragraph's first row.
17185        let mut d = wrapped_doc("wrap_down");
17186        d.caret = 0;
17187        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
17188            d.move_down(false);
17189            assert_eq!(d.caret, want, "Down stalled");
17190            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
17191        }
17192        d.move_down(false);
17193        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
17194
17195        // ...and back up, one row per press. The goal column is the end of the
17196        // last row, past every other row's width, so each press clamps to the
17197        // row's own last offset rather than to the one that opens the next.
17198        let mut d = wrapped_doc("wrap_up");
17199        d.caret = 39;
17200        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
17201            d.move_up(false);
17202            assert_eq!(d.caret, want, "Up stalled");
17203            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
17204        }
17205    }
17206
17207    #[test]
17208    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
17209        // The kills take the same line Home and End do, so in WYSIWYG they take
17210        // the visual row — and a soft wrap has no newline in it to delete, so
17211        // nothing is joined by reaching the end of one.
17212        let mut d = wrapped_doc("wrap_kill");
17213        d.caret = 19; // the `f` of "five", opening the third row
17214        d.delete_to_line_end();
17215        // The space the wrap ate goes with the row it was drawn on: sparing it
17216        // would leave "four  seven", two spaces where the row had been.
17217        assert_eq!(d.source, "one two three four seven eight");
17218
17219        // Backwards from the row's last caret position — which is *before* that
17220        // space, so this one survives, being on the far side of the caret.
17221        let mut d = wrapped_doc("wrap_kill_back");
17222        d.caret = 27;
17223        d.delete_to_line_start();
17224        assert_eq!(d.source, "one two three four  seven eight");
17225    }
17226
17227    // ── document start / end ────────────────────────────────────────────────
17228
17229    #[test]
17230    fn move_doc_start_and_end_jump_to_the_edges() {
17231        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
17232        assert_eq!(
17233            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
17234            "|hello\nworld\n"
17235        );
17236        assert_eq!(
17237            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
17238            "hello\nworld\n|"
17239        );
17240        // Already at the edge: a no-op.
17241        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
17242        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
17243    }
17244
17245    #[test]
17246    fn move_doc_start_and_end_extend_the_selection() {
17247        assert_eq!(
17248            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
17249                .move_doc_end(true)),
17250            "hello wor[ld\n|]"
17251        );
17252        assert_eq!(
17253            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
17254                .move_doc_start(true)),
17255            "[|hello wor]ld\n"
17256        );
17257    }
17258
17259    #[test]
17260    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
17261        let mut d = doc_with("empty_edges", "");
17262        d.move_doc_end(false);
17263        assert_eq!(d.caret, 0);
17264        d.move_doc_start(false);
17265        assert_eq!(d.caret, 0);
17266    }
17267
17268    // ── arrow collapses an active selection ─────────────────────────────────
17269
17270    #[test]
17271    fn arrow_collapses_selection_to_its_near_edge() {
17272        let mut d = doc_with("collapse", "hello world\n");
17273
17274        // Forward selection (anchor before caret): Right -> end, Left -> start.
17275        d.anchor = Some(2);
17276        d.caret = 7;
17277        d.move_right(false);
17278        assert_eq!((d.caret, d.anchor), (7, None));
17279
17280        d.anchor = Some(2);
17281        d.caret = 7;
17282        d.move_left(false);
17283        assert_eq!((d.caret, d.anchor), (2, None));
17284
17285        // Backward selection (anchor after caret): edges are the same
17286        // regardless of which end the caret started on.
17287        d.anchor = Some(7);
17288        d.caret = 2;
17289        d.move_right(false);
17290        assert_eq!((d.caret, d.anchor), (7, None));
17291
17292        d.anchor = Some(7);
17293        d.caret = 2;
17294        d.move_left(false);
17295        assert_eq!((d.caret, d.anchor), (2, None));
17296    }
17297
17298    #[test]
17299    fn arrow_with_extend_keeps_growing_the_selection() {
17300        let mut d = doc_with("collapse_extend", "hello world\n");
17301        d.anchor = Some(2);
17302        d.caret = 7;
17303        d.move_right(true); // extend: no collapse, caret steps one further
17304        assert_eq!((d.caret, d.anchor), (8, Some(2)));
17305    }
17306
17307    #[test]
17308    fn arrow_without_a_selection_moves_one_character_as_before() {
17309        let mut d = doc_with("no_collapse", "hello\n");
17310        d.caret = 2;
17311        d.move_right(false);
17312        assert_eq!(d.caret, 3);
17313        d.move_left(false);
17314        assert_eq!(d.caret, 2);
17315    }
17316
17317    /// Press Right until it stops, collecting the offsets walked through. Every
17318    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
17319    /// two stops sharing one source offset can't be moved between, so the caret
17320    /// stalls on the first of them and the walk never reaches the rest.
17321    fn walk_right(d: &mut Doc) -> Vec<usize> {
17322        let mut seen = vec![d.caret];
17323        for _ in 0..2000 {
17324            let before = d.caret;
17325            d.move_right(false);
17326            if d.caret == before {
17327                break;
17328            }
17329            seen.push(d.caret);
17330        }
17331        seen
17332    }
17333
17334    #[test]
17335    fn the_caret_crosses_a_soft_break() {
17336        // A newline inside a paragraph is a `soft_break`, which twig gives no
17337        // span of its own — the space it renders as used to borrow the offset of
17338        // the character before it, and a caret can't move without changing
17339        // offset. Right must walk clean off the end of the first line.
17340        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
17341        d.caret = 0;
17342        let seen = walk_right(&mut d);
17343        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17344    }
17345
17346    #[test]
17347    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
17348        // The paragraph holds one soft break. Folded (the default) it lays out as
17349        // a single reflowed row; Preserve re-lays it as a row per source line.
17350        // The setter must invalidate the cached map for the change to show, and
17351        // again on the way back — so a round trip returns to the folded layout.
17352        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
17353        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
17354        d.build_visual(80);
17355        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
17356
17357        d.set_line_flow(LineFlow::Preserve);
17358        d.build_visual(80);
17359        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
17360
17361        d.set_line_flow(LineFlow::Fold);
17362        d.build_visual(80);
17363        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
17364    }
17365
17366    #[test]
17367    fn the_caret_still_crosses_a_preserved_soft_break() {
17368        // Preserve renders the soft break as a row boundary rather than a space,
17369        // but the caret must still reach every offset — the break's own offset is
17370        // the first row's end stop, so Right walks clean off the end of line one
17371        // onto line two, exactly as it does when the break is folded.
17372        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
17373        d.set_line_flow(LineFlow::Preserve);
17374        d.build_visual(80);
17375        d.caret = 0;
17376        let seen = walk_right(&mut d);
17377        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17378    }
17379
17380    #[test]
17381    fn the_caret_walks_a_code_block() {
17382        // Every glyph of a code block used to map to the block's start, so the
17383        // whole block was a single offset and the caret couldn't move inside it.
17384        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
17385        let mut d = wysiwyg_doc("code_walk", src);
17386        d.caret = 0;
17387        let seen = walk_right(&mut d);
17388        // The fences are markup: hidden, and no caret stop. The code between
17389        // them is reached a character at a time.
17390        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
17391        for off in code.clone() {
17392            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
17393        }
17394        assert!(seen.contains(&code.end), "no stop after the last line");
17395    }
17396
17397    #[test]
17398    fn the_caret_walks_an_indented_code_block() {
17399        // An indented block's text has the four-space indent stripped, so it
17400        // isn't a verbatim slice and its lines have to be re-found. The caret
17401        // lands on the code, never in the indent.
17402        let src = "    indented\n    code\n";
17403        let mut d = wysiwyg_doc("indent_code_walk", src);
17404        d.caret = 0;
17405        let seen = walk_right(&mut d);
17406        assert!(seen.contains(&src.find("indented").unwrap()));
17407        assert!(seen.contains(&src.find("code").unwrap()));
17408        assert!(
17409            !seen.contains(&0) || seen[0] == 0,
17410            "the caret starts where it was put"
17411        );
17412        // Nothing in the stripped indent is a stop.
17413        for off in [1, 2, 3] {
17414            assert!(!seen.contains(&off), "landed in the indent at {off}");
17415        }
17416    }
17417
17418    #[test]
17419    fn the_caret_leaves_a_tight_heading() {
17420        // "# H" with text directly under it: the heading row's end and the
17421        // separator row's end are the same offset. Right used to find the
17422        // separator's copy, set the caret to where it already was, and stop.
17423        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
17424        d.caret = 2; // the "H"
17425        let seen = walk_right(&mut d);
17426        assert!(
17427            seen.len() > 2,
17428            "Right stalled at the heading's end: {seen:?}"
17429        );
17430        assert!(
17431            seen.contains(&8),
17432            "never reached the end of \"text\": {seen:?}"
17433        );
17434    }
17435
17436    #[test]
17437    fn the_caret_skips_the_gap_between_two_paragraphs() {
17438        // The blank line between two paragraphs is the boundary itself. The
17439        // caret used to be able to sit on it, and typing there landed in the
17440        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
17441        // soft break, so the text visibly snapped back up.
17442        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
17443        d.caret = 1; // the end of "A"
17444        d.move_right(false);
17445        assert_eq!(d.caret, 3, "Right stopped in the gap");
17446        d.insert("x");
17447        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
17448    }
17449
17450    #[test]
17451    fn down_from_a_paragraph_lands_on_the_next_one() {
17452        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
17453        d.caret = 0;
17454        d.move_down(false);
17455        assert_eq!(d.caret, 3, "Down stopped in the gap");
17456    }
17457
17458    #[test]
17459    fn clicking_the_gap_lands_on_real_text() {
17460        // A click can still *reach* the gap — it's drawn, so it's clickable.
17461        // It has to resolve to somewhere the caret can be.
17462        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
17463        d.click(1, 0, false); // the gap row
17464        assert!(
17465            d.caret == 1 || d.caret == 3,
17466            "click left the caret in the gap at {}",
17467            d.caret
17468        );
17469        d.insert("x");
17470        // Either edge of the boundary is a fair place to land; inside it isn't.
17471        assert!(
17472            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
17473            "click in the gap typed into the boundary: {:?}",
17474            d.source
17475        );
17476    }
17477
17478    #[test]
17479    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
17480        // Enter inserts a paragraph break, which leaves a blank line spare on
17481        // either side of a new one. That middle line is a real empty paragraph:
17482        // the caret lands there, and typing makes a paragraph rather than
17483        // extending a neighbour.
17484        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
17485        d.caret = 1;
17486        d.newline();
17487        assert_eq!(d.source, "A\n\n\n\nB\n");
17488        d.build_visual(80);
17489        let (row, _) = d.caret_pos();
17490        assert!(
17491            d.vmap.row_is_navigable(row),
17492            "the caret landed on a gap row"
17493        );
17494        d.insert("x");
17495        assert_eq!(
17496            d.source, "A\n\nx\n\nB\n",
17497            "the new paragraph merged into a neighbour"
17498        );
17499    }
17500
17501    #[test]
17502    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
17503        let mut d = wysiwyg_doc("gap_eof", "A\n");
17504        d.caret = 1;
17505        d.newline();
17506        d.build_visual(80);
17507        let (row, _) = d.caret_pos();
17508        assert!(
17509            d.vmap.row_is_navigable(row),
17510            "the caret landed on a gap row"
17511        );
17512        d.insert("x");
17513        assert!(
17514            d.source.starts_with("A\n\n") && d.source.contains('x'),
17515            "typing at the end merged into A: {:?}",
17516            d.source
17517        );
17518    }
17519
17520    // ── click_past_end ───────────────────────────────────────────────────────
17521
17522    /// [`Doc::click_past_end`] on `body`, and the source it left, with the caret
17523    /// rendered as `|`.
17524    fn past_end(name: &str, body: &str) -> (Doc, String) {
17525        let mut d = wysiwyg_doc(name, body);
17526        d.click_past_end();
17527        let out = render_caret(&d);
17528        (d, out)
17529    }
17530
17531    #[test]
17532    fn click_past_end_opens_an_empty_paragraph_under_the_last_block() {
17533        let (mut d, out) = past_end("pe_para", "A\n");
17534        assert_eq!(out, "A\n\n|");
17535        d.build_visual(80);
17536        let (row, _) = d.caret_pos();
17537        assert!(
17538            d.vmap.row_is_navigable(row),
17539            "the caret landed on a gap row"
17540        );
17541        d.insert("x");
17542        assert_eq!(d.source, "A\n\nx", "typing merged into A");
17543    }
17544
17545    #[test]
17546    fn click_past_end_writes_both_newlines_when_the_file_has_none() {
17547        assert_eq!(past_end("pe_bare", "A").1, "A\n\n|");
17548    }
17549
17550    #[test]
17551    fn click_past_end_is_only_a_caret_move_when_the_paragraph_is_already_there() {
17552        let (d, out) = past_end("pe_there", "A\n\n");
17553        assert_eq!(out, "A\n\n|");
17554        assert!(!d.dirty, "a click wrote to a document it did not need to");
17555        assert!(
17556            !d.can_undo(),
17557            "a click that changed nothing left an undo step"
17558        );
17559    }
17560
17561    #[test]
17562    fn click_past_end_leaves_a_closed_fence() {
17563        let (mut d, out) = past_end("pe_fence", "```\ncode\n```\n");
17564        assert_eq!(out, "```\ncode\n```\n\n|");
17565        d.build_visual(80);
17566        let (row, _) = d.caret_pos();
17567        assert!(!d.vmap.rows[row].code, "the caret is still on a code row");
17568        d.insert("x");
17569        assert_eq!(d.source, "```\ncode\n```\n\nx");
17570    }
17571
17572    #[test]
17573    fn click_past_end_closes_an_unclosed_fence_first() {
17574        assert_eq!(past_end("pe_open", "```\ncode\n").1, "```\ncode\n```\n\n|");
17575        assert_eq!(
17576            past_end("pe_open2", "````\ncode").1,
17577            "````\ncode\n````\n\n|"
17578        );
17579        assert_eq!(past_end("pe_tilde", "~~~\ncode\n").1, "~~~\ncode\n~~~\n\n|");
17580        assert_eq!(
17581            past_end("pe_quoted", "> ```\n> code\n").1,
17582            "> ```\n> code\n> ```\n\n|"
17583        );
17584    }
17585
17586    #[test]
17587    fn click_past_end_does_not_close_an_indented_block() {
17588        assert_eq!(past_end("pe_indent", "    code\n").1, "    code\n\n|");
17589    }
17590
17591    #[test]
17592    fn click_past_end_under_a_list_and_a_table_leaves_them() {
17593        let (mut d, out) = past_end("pe_list", "- a\n- b\n");
17594        assert_eq!(out, "- a\n- b\n\n|");
17595        d.insert("x");
17596        assert_eq!(d.source, "- a\n- b\n\nx", "typed into the list");
17597        assert_eq!(
17598            past_end("pe_table", "| a |\n|---|\n| b |\n").1,
17599            "| a |\n|---|\n| b |\n\n|"
17600        );
17601    }
17602
17603    #[test]
17604    fn click_past_end_on_an_empty_document_writes_nothing() {
17605        let (d, out) = past_end("pe_empty", "");
17606        assert_eq!(out, "|");
17607        assert!(!d.dirty);
17608    }
17609
17610    #[test]
17611    fn click_past_end_is_one_undo_step() {
17612        let (mut d, _) = past_end("pe_undo", "A\n");
17613        d.undo();
17614        assert_eq!(d.source, "A\n");
17615    }
17616
17617    #[test]
17618    fn click_past_end_in_the_source_view_only_moves_the_caret() {
17619        let mut d = doc_with("pe_source", "A\n");
17620        d.click_past_end();
17621        assert_eq!(render_caret(&d), "A\n|");
17622        assert!(!d.dirty);
17623    }
17624
17625    #[test]
17626    fn click_past_end_on_a_read_only_document_only_moves_the_caret() {
17627        let mut d = wysiwyg_doc("pe_ro", "A\n");
17628        d.set_read_only(true);
17629        d.click_past_end();
17630        assert_eq!(render_caret(&d), "A\n|");
17631    }
17632
17633    // ── toggle_code_block ────────────────────────────────────────────────────
17634
17635    #[test]
17636    fn toggle_code_block_fences_the_paragraph_at_the_caret_and_reverses() {
17637        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17638        assert_eq!(g("cb_on", "hel|lo\n"), "```\nhel|lo\n```\n");
17639        assert_eq!(g("cb_off", "```\nhel|lo\n```\n"), "hel|lo\n");
17640        assert_eq!(g("cb_end", "hello|\n"), "```\nhello|\n```\n");
17641        assert_eq!(
17642            g("cb_wrap", "aaa\nb|bb\nccc\n"),
17643            "```\naaa\nb|bb\nccc\n```\n"
17644        );
17645        assert_eq!(
17646            g("cb_unwrap", "```\naaa\nb|bb\nccc\n```\n"),
17647            "aaa\nb|bb\nccc\n"
17648        );
17649        // An indented block dedents, and the lines stay one-to-one.
17650        assert_eq!(g("cb_indent", "    co|de\n"), "co|de\n");
17651        // A quote's marker is kept on every line, the fence's included.
17652        assert_eq!(g("cb_quote", "> hel|lo\n"), "> ```\n> hel|lo\n> ```\n");
17653    }
17654
17655    #[test]
17656    fn toggle_code_block_on_a_blank_line_opens_an_empty_fence() {
17657        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17658        assert_eq!(g("cb_blank", "A\n\n|"), "A\n\n```\n|\n```");
17659        assert_eq!(
17660            g("cb_blank_mid", "A\n\n|\n\nB\n"),
17661            "A\n\n```\n|\n```\n\nB\n"
17662        );
17663        // Tight against a neighbour, a blank line goes in on that side.
17664        assert_eq!(g("cb_blank_tight", "A\n|\nB\n"), "A\n\n```\n|\n```\n\nB\n");
17665        // Inside a quote, on a quoted blank line.
17666        assert_eq!(
17667            g("cb_blank_quote", "> A\n>\n> |\n"),
17668            "> A\n>\n> ```\n> |\n> ```\n"
17669        );
17670    }
17671
17672    #[test]
17673    fn toggle_code_block_from_a_blank_line_is_a_block_the_caret_can_type_into() {
17674        let mut d = wysiwyg_doc("cb_type", "A\n\n");
17675        d.click_past_end();
17676        d.toggle_code_block();
17677        assert!(
17678            d.caret_in_code_block(),
17679            "the caret is not in the block it opened"
17680        );
17681        d.insert("let x = 1;");
17682        d.newline();
17683        d.insert("x");
17684        assert_eq!(d.source, "A\n\n```\nlet x = 1;\nx\n```");
17685        d.build_visual(80);
17686        let (row, _) = d.caret_pos();
17687        assert!(d.vmap.rows[row].code, "typed text is not on a code row");
17688        // And back out: the button reverses what it did, text kept.
17689        d.toggle_code_block();
17690        assert_eq!(d.source, "A\n\nlet x = 1;\nx\n");
17691        assert!(!d.caret_in_code_block());
17692    }
17693
17694    #[test]
17695    fn toggle_code_block_over_a_selection_fences_it_whole_and_keeps_it_selected() {
17696        let mut d = wysiwyg_doc("cb_sel", "one\n\ntwo\n\nthree\n");
17697        d.anchor = Some(1);
17698        d.caret = 7;
17699        d.toggle_code_block();
17700        assert_eq!(d.source, "```\none\n\ntwo\n```\n\nthree\n");
17701        assert!(d.selection().is_some(), "the block came back unselected");
17702        d.toggle_code_block();
17703        assert_eq!(
17704            d.source, "one\n\ntwo\n\nthree\n",
17705            "a second press did not reverse the first"
17706        );
17707    }
17708
17709    #[test]
17710    fn toggle_code_block_inside_a_list_item_is_refused_and_reported() {
17711        let mut d = wysiwyg_doc("cb_list", "- it|em\n".replace('|', "").as_str());
17712        d.caret = 3;
17713        d.toggle_code_block();
17714        assert_eq!(d.source, "- item\n");
17715        assert!(
17716            d.status
17717                .as_deref()
17718                .is_some_and(|s| s.starts_with("code block:"))
17719        );
17720    }
17721
17722    #[test]
17723    fn caret_in_code_block_reads_fenced_and_indented_blocks() {
17724        let mut d = wysiwyg_doc("cb_in", "para\n\n```\ncode\n```\n\n    more\n");
17725        d.caret = 2;
17726        assert!(!d.caret_in_code_block());
17727        d.caret = 11;
17728        assert!(d.caret_in_code_block());
17729        d.caret = 25;
17730        assert!(d.caret_in_code_block(), "an indented block is a code block");
17731    }
17732
17733    #[test]
17734    fn toggle_code_block_is_one_undo_step() {
17735        let mut d = wysiwyg_doc("cb_undo", "hello\n");
17736        d.caret = 2;
17737        d.toggle_code_block();
17738        d.undo();
17739        assert_eq!(render_caret(&d), "he|llo\n");
17740    }
17741
17742    #[test]
17743    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
17744        // A paragraph broken over two source lines is one paragraph. Selecting
17745        // it must not stop at the newline inside it — that newline is markup the
17746        // rich-text view exists to hide.
17747        let src = "one two\nthree four\n\nnext\n";
17748        let mut d = wysiwyg_doc("triple_para", src);
17749        d.select_block_at(2);
17750        assert_eq!(
17751            d.selected_text(),
17752            Some("one two\nthree four"),
17753            "stopped at the soft break"
17754        );
17755    }
17756
17757    #[test]
17758    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
17759        // The reader scrolls down past the caret's row. Nothing moved the
17760        // caret, so the view must stay where it was put — the old code revealed
17761        // the caret every frame, which dragged the view straight back and made
17762        // the document unscrollable past the caret.
17763        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
17764        d.caret = 0;
17765        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
17766        d.scroll = 4; // the wheel
17767        d.follow_caret(0, 3, 9);
17768        assert_eq!(
17769            d.scroll, 4,
17770            "the wheel was overruled by a caret that never moved"
17771        );
17772    }
17773
17774    #[test]
17775    fn moving_the_caret_brings_the_view_back_to_it() {
17776        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
17777        d.caret = 0;
17778        d.follow_caret(0, 3, 9);
17779        d.scroll = 6; // scrolled away
17780        d.move_right(false); // ...and now the caret moves
17781        let (row, _) = d.caret_pos();
17782        d.follow_caret(row, 3, 9);
17783        assert!(
17784            d.scroll <= row && row < d.scroll + 3,
17785            "caret row {row} off screen at scroll {}",
17786            d.scroll
17787        );
17788    }
17789
17790    #[test]
17791    fn scrolling_stops_at_the_last_row() {
17792        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
17793        d.caret = 0;
17794        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
17795        d.scroll = 999; // the wheel, spun hard
17796        d.follow_caret(0, 3, 3);
17797        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
17798    }
17799
17800    #[test]
17801    fn every_cell_of_a_wide_table_is_reachable() {
17802        // A table whose cells are far wider than the surface: the columns are
17803        // cut to fit and the text wraps inside them, so no cell hangs off the
17804        // right edge where the caret can never go.
17805        let src = "| Ingredient | Notes |\n|---|---|\n\
17806                   | flour milled coarse | sift it twice before folding it in |\n";
17807        let mut d = wysiwyg_doc("wide_table_walk", src);
17808        d.build_visual(30);
17809        d.caret = 0;
17810        let seen = walk_right(&mut d);
17811        for word in ["Ingredient", "Notes", "coarse", "folding"] {
17812            let at = src.find(word).unwrap();
17813            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
17814        }
17815    }
17816
17817    // ── view parity ──────────────────────────────────────────────────────────
17818    // `doc_with` pins the source view, so everything above tests a view users
17819    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
17820    // deletion golden cases through *both*, plus the WYSIWYG cases the two
17821    // can't share: where the source carries markup the rendered text is a
17822    // different string, and the views agreeing would itself be the bug.
17823
17824    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
17825
17826    /// Run `action` in both views on one `|`-marked fixture and assert they
17827    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
17828    /// source verbatim, so the two views are looking at the same text and any
17829    /// disagreement is one of them having lost the plot.
17830    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
17831        let (src, caret) = parse_caret(marked);
17832        let run = |view: View, tag: &str| {
17833            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
17834            d.caret = caret;
17835            action(&mut d);
17836            render_caret(&d)
17837        };
17838        let source = run(VIEWS[0].0, VIEWS[0].1);
17839        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
17840        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
17841        source
17842    }
17843
17844    #[test]
17845    fn word_motion_agrees_across_the_views_on_plain_prose() {
17846        let g = both_views;
17847        assert_eq!(
17848            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
17849            "hello |world"
17850        );
17851        assert_eq!(
17852            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
17853            "|hello world"
17854        );
17855        assert_eq!(
17856            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
17857            "hello| world"
17858        );
17859        assert_eq!(
17860            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
17861            "hello world|"
17862        );
17863        assert_eq!(
17864            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
17865            "foo|.bar"
17866        );
17867        assert_eq!(
17868            g("par_ext", "hello |world", |d| d.move_word_right(true)),
17869            "hello [world|]"
17870        );
17871    }
17872
17873    #[test]
17874    fn word_deletion_agrees_across_the_views_on_plain_prose() {
17875        let g = both_views;
17876        assert_eq!(
17877            g("par_db", "hello world|", |d| d.delete_word_back()),
17878            "hello |"
17879        );
17880        assert_eq!(
17881            g("par_df", "hello |world", |d| d.delete_word_forward()),
17882            "hello |"
17883        );
17884        assert_eq!(
17885            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
17886            "|bar baz"
17887        );
17888        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
17889    }
17890
17891    #[test]
17892    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
17893        let g = both_views;
17894        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
17895        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
17896        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
17897        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
17898    }
17899
17900    #[test]
17901    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
17902        // The reproduction: the stop table was built one stop per `char`, so
17903        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
17904        // source view, which steps by grapheme, can't reach and backspace can't
17905        // survive. The two views must land on the same offset.
17906        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
17907        for (view, tag) in VIEWS {
17908            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
17909            d.caret = 1;
17910            d.move_right(false);
17911            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
17912
17913            // ...and the edit that used to sever a joiner off the front of it.
17914            d.backspace();
17915            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
17916            assert_eq!(d.caret, 1);
17917        }
17918    }
17919
17920    #[test]
17921    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
17922        for (view, tag) in VIEWS {
17923            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
17924            d.caret = 0;
17925            d.move_right(false);
17926            assert_eq!(
17927                d.caret,
17928                "e\u{0301}".len(),
17929                "{tag} stopped on the combining mark"
17930            );
17931        }
17932    }
17933
17934    #[test]
17935    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
17936        // The general form: whatever route the caret takes through a document
17937        // full of clusters, it never lands between the codepoints of one — so no
17938        // motion-then-backspace sequence can leave a dangling joiner behind.
17939        use unicode_segmentation::UnicodeSegmentation;
17940
17941        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
17942        let mut d = wysiwyg_doc("cluster_walk", src);
17943        d.caret = 0;
17944        let boundaries: Vec<usize> = src
17945            .grapheme_indices(true)
17946            .map(|(i, _)| i)
17947            .chain(std::iter::once(src.len()))
17948            .collect();
17949        for off in walk_right(&mut d) {
17950            assert!(
17951                boundaries.contains(&off),
17952                "Right stopped at {off}, inside a grapheme cluster"
17953            );
17954        }
17955    }
17956
17957    #[test]
17958    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
17959        // The reproduction: ⌥→ from inside the opening `**` computed its
17960        // boundary over the raw source and landed on byte 8 — inside the
17961        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
17962        // "bold". The caret drew past the bold word and sat inside it.
17963        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
17964        d.caret = 2;
17965        d.move_word_right(false);
17966        assert!(
17967            d.vmap.is_stop(d.caret),
17968            "landed at {}, not a caret stop",
17969            d.caret
17970        );
17971        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
17972        // The rendered row is "a bold c": column 6 is the space just past "bold",
17973        // and now the caret is really there rather than only drawn there.
17974        assert_eq!(d.caret_pos(), (0, 6));
17975
17976        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
17977        d.move_word_left(false);
17978        assert_eq!(d.caret, 4);
17979        assert_eq!(d.caret_pos(), (0, 2));
17980    }
17981
17982    #[test]
17983    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
17984        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
17985        // inside the closing `**`, and left "a ** c\n" — delimiters with no
17986        // opener. Glyph space covers the word alone, which would leave
17987        // "a **** c": markup wrapped around nothing. The word and the styling
17988        // that was only ever the word's go together.
17989        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
17990        d.caret = 10;
17991        d.delete_word_back();
17992        assert_eq!(d.source, "a  c\n");
17993        assert_eq!(d.caret, 2);
17994
17995        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
17996        d.caret = 4; // the "b"
17997        d.delete_word_forward();
17998        assert_eq!(d.source, "a  c\n");
17999    }
18000
18001    #[test]
18002    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
18003        let src = "a ***bold*** c\n";
18004        let mut d = wysiwyg_doc("wys_word_del_nest", src);
18005        d.caret = src.find(" c").unwrap();
18006        d.delete_word_back();
18007        assert_eq!(
18008            d.source, "a  c\n",
18009            "the emph inside the strong empties it too"
18010        );
18011
18012        let src = "a `code` c\n";
18013        let mut d = wysiwyg_doc("wys_word_del_code", src);
18014        d.caret = src.find(" c").unwrap();
18015        d.delete_word_back();
18016        assert_eq!(d.source, "a  c\n");
18017    }
18018
18019    #[test]
18020    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
18021        // Only an *emptied* node goes. Take one word of two and the `**` still
18022        // has a job to do — over the word that's left, with the space the delete
18023        // pushed against the opening delimiter moved out in front of it, or the
18024        // run would be no run at all (`** words**` is literal asterisks — see
18025        // the mark-edge rule on `splice`).
18026        let src = "a **two words** c\n";
18027        let mut d = wysiwyg_doc("wys_word_del_partial", src);
18028        d.caret = src.find(" words").unwrap();
18029        d.delete_word_back();
18030        assert_eq!(d.source, "a  **words** c\n");
18031    }
18032
18033    #[test]
18034    fn source_view_word_motion_still_walks_the_markup() {
18035        // The other half of the decision: in the source view the `**` are
18036        // characters like any other — they're on the screen, so word motion has
18037        // to stop at them and a word-delete has to leave them behind. Only
18038        // WYSIWYG hides them, so only WYSIWYG steps over them.
18039        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
18040        assert_eq!(
18041            g("src_word_motion", "a |**bold** c\n", |d| d
18042                .move_word_right(false)),
18043            "a **bold|** c\n"
18044        );
18045        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
18046        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
18047        assert_eq!(
18048            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
18049            "a **| c\n"
18050        );
18051    }
18052
18053    #[test]
18054    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
18055        // The single invariant both bugs violated: the caret draws and edits at
18056        // the same place only when it's on a stop. `debug_assert_on_a_stop`
18057        // makes the same claim in-place; this pins it from the outside, over a
18058        // document with every kind of thing the map has to be careful about.
18059        // At two widths: the wide one every other test builds at, where no
18060        // fixture folds, and one narrow enough that they all do. A soft wrap is
18061        // where an offset stops being on exactly one row, and testing only the
18062        // width that never wraps is how the caret came to be pinned at the first
18063        // one Down reached.
18064        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
18065                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
18066        // A table of named operations, which is what it looks like.
18067        #[allow(clippy::type_complexity)]
18068        let motions: [(&str, fn(&mut Doc)); 8] = [
18069            ("right", |d| d.move_right(false)),
18070            ("left", |d| d.move_left(false)),
18071            ("word_right", |d| d.move_word_right(false)),
18072            ("word_left", |d| d.move_word_left(false)),
18073            ("down", |d| d.move_down(false)),
18074            ("up", |d| d.move_up(false)),
18075            ("home", |d| d.move_home(false)),
18076            ("end", |d| d.move_end(false)),
18077        ];
18078        for width in [80, 12] {
18079            let mut d = wysiwyg_doc("stop_invariant", src);
18080            d.build_visual(width);
18081            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18082            assert!(stops.len() > 20, "fixture should have plenty of stops");
18083            for start in stops {
18084                for (name, motion) in &motions {
18085                    d.caret = start;
18086                    d.anchor = None;
18087                    motion(&mut d);
18088                    assert!(
18089                        d.vmap.is_stop(d.caret),
18090                        "{name} from {start} at width {width} landed at {} — not a caret stop",
18091                        d.caret
18092                    );
18093                }
18094            }
18095        }
18096    }
18097
18098    #[test]
18099    fn no_wysiwyg_motion_is_a_dead_end() {
18100        // Down held to the bottom of a document reaches the bottom, and Up held
18101        // to the top reaches the top — from anywhere, at a width that wraps. The
18102        // invariant above says a motion lands somewhere legal; this one says it
18103        // gets somewhere at all, which is what a caret pinned at a wrap boundary
18104        // was quietly failing to do while every assertion around it held.
18105        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
18106                   - item one two three four five\n\nlast\n";
18107        for width in [80, 12] {
18108            let mut d = wysiwyg_doc("no_dead_end", src);
18109            d.build_visual(width);
18110            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18111            let (first, last) = (stops[0], stops[stops.len() - 1]);
18112            for &start in &stops {
18113                for (name, motion, want) in [
18114                    (
18115                        "down",
18116                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
18117                        last,
18118                    ),
18119                    ("up", |d: &mut Doc| d.move_up(false), first),
18120                ] {
18121                    d.caret = start;
18122                    d.anchor = None;
18123                    d.goal_col = None;
18124                    // Every row, plus the presses the edges take, plus slack.
18125                    for _ in 0..d.vmap.num_rows() + 4 {
18126                        motion(&mut d);
18127                    }
18128                    assert_eq!(
18129                        d.caret, want,
18130                        "{name} held from {start} at width {width} never arrived"
18131                    );
18132                }
18133            }
18134        }
18135    }
18136    // ── display columns ──────────────────────────────────────────────────────
18137    // A `col` is a terminal cell, not a character. The two are the same number
18138    // for the ASCII the fixtures above are written in, which is how they came
18139    // apart in the first place: `你` is one character drawn in two cells, so a
18140    // column counted in characters names a cell the text isn't in — one earlier
18141    // for every wide character to its left.
18142
18143    #[test]
18144    fn a_wide_character_is_two_columns_wide() {
18145        // The reproduction: `你` is one char and two cells, so the caret just
18146        // past it drew at column 1 — inside the character it had already left.
18147        for (view, tag) in VIEWS {
18148            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
18149            d.caret = "你".len();
18150            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
18151            d.caret = "你好".len();
18152            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
18153        }
18154    }
18155
18156    #[test]
18157    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
18158        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
18159        // two-cell — measuring six cells one at a time, but the character they
18160        // spell is drawn in two. Width belongs to the cluster, not the glyph,
18161        // and the frontends measure it the same way.
18162        let family = "👨‍👩‍👧";
18163        for (view, tag) in VIEWS {
18164            let src = format!("a{family}b\n");
18165            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
18166            d.caret = 1 + family.len();
18167            assert_eq!(
18168                d.caret_pos(),
18169                (0, 3),
18170                "{tag}: 'a' is one cell, the family two"
18171            );
18172        }
18173    }
18174
18175    #[test]
18176    fn both_cells_of_a_wide_character_mean_the_character() {
18177        // Clicking the far half of `好` is still clicking `好`: half a character
18178        // is not a place the caret can be, so it comes to rest at the
18179        // character's start — the column it would have been drawn at anyway.
18180        for (view, tag) in VIEWS {
18181            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
18182            for col in [2, 3] {
18183                d.caret = 0;
18184                d.click(0, col, false);
18185                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
18186                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
18187            }
18188            // Past the last cell is the line's end, as it is for ASCII.
18189            d.click(0, 9, false);
18190            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
18191        }
18192    }
18193
18194    #[test]
18195    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
18196        // The mapping is only a mapping if it inverts: the cell the caret is
18197        // drawn in has to be the cell that brings it back to the same offset.
18198        // Over a fixture where a character may be one cell or two, and one
18199        // codepoint or five.
18200        use unicode_segmentation::UnicodeSegmentation;
18201
18202        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
18203
18204        let mut d = doc_in(View::Source, "roundtrip_source", src);
18205        // Every offset the source view's caret can occupy: it steps by grapheme
18206        // cluster, so those are its boundaries.
18207        for (off, _) in src
18208            .grapheme_indices(true)
18209            .chain(std::iter::once((src.len(), "")))
18210        {
18211            d.caret = off;
18212            let (row, col) = d.caret_pos();
18213            d.click(row, col, false);
18214            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
18215        }
18216
18217        // And in WYSIWYG, where the offsets the caret can occupy are the map's
18218        // stops rather than every boundary.
18219        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
18220        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18221        assert!(stops.len() > 20, "fixture should have plenty of stops");
18222        for off in stops {
18223            d.caret = off;
18224            let (row, col) = d.caret_pos();
18225            d.click(row, col, false);
18226            assert_eq!(
18227                d.caret, off,
18228                "wysiwyg: {off} → ({row}, {col}) → {}",
18229                d.caret
18230            );
18231        }
18232    }
18233
18234    #[test]
18235    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
18236        // Down from under `世` lands under the glyph in that cell, not two
18237        // characters further along the line. The goal is a column, so a line of
18238        // wide characters and a line of ASCII line up the way they're drawn.
18239        //
18240        // The gap differs by view: a bare newline inside a paragraph is a soft
18241        // break, which WYSIWYG draws as a space on a single row. The views share
18242        // a grid only where the source's lines are the renderer's rows too.
18243        for (view, tag) in VIEWS {
18244            let gap = if view == View::Source { "\n" } else { "\n\n" };
18245            let src = format!("你好世{gap}abcdef\n");
18246            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
18247            d.caret = "你好".len();
18248            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
18249            d.move_down(false);
18250            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
18251            assert!(
18252                d.source[d.caret..].starts_with('e'),
18253                "{tag}: landed on the wrong glyph"
18254            );
18255        }
18256    }
18257
18258    #[test]
18259    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
18260        // Down from column 3 onto `你好`, whose characters start at columns 0
18261        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
18262        // between the cells of one character, so the caret rests on it — and on
18263        // its start, which is the only offset there that is a caret stop.
18264        for (view, tag) in VIEWS {
18265            let gap = if view == View::Source { "\n" } else { "\n\n" };
18266            let src = format!("abcdef{gap}你好\n");
18267            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
18268            let line = src.find('你').unwrap();
18269            d.caret = 3;
18270            d.move_down(false);
18271            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
18272            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
18273        }
18274    }
18275
18276    #[test]
18277    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
18278        // The column the cell's text is laid out in is measured in cells, so the
18279        // caret walking that text has to be too — the two agreeing is the whole
18280        // point of the grid staying square.
18281        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
18282        let at = d.source.find("你").unwrap();
18283        d.caret = at;
18284        let (row, col) = d.caret_pos();
18285        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
18286        // cells further along.
18287        assert_eq!(col, 2, "the cell's first character");
18288        d.move_right(false);
18289        assert_eq!(
18290            d.caret_pos(),
18291            (row, 4),
18292            "`好` is drawn past `你`'s two cells"
18293        );
18294        assert_eq!(d.caret, at + "你".len());
18295    }
18296
18297    // ── active inline marks ───────────────────────────────────────────────────
18298
18299    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
18300    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
18301        let (src, caret) = parse_caret(marked);
18302        let mut d = doc_in(view, name, &src);
18303        d.caret = caret;
18304        d.active_inline_marks().iter().collect()
18305    }
18306
18307    /// The marks over the selection `[start, end)`.
18308    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
18309        let mut d = doc_in(view, name, src);
18310        d.anchor = Some(start);
18311        d.caret = end;
18312        d.active_inline_marks().iter().collect()
18313    }
18314
18315    #[test]
18316    fn a_caret_in_a_mark_reports_it() {
18317        for (view, tag) in VIEWS {
18318            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
18319            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
18320            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
18321            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
18322            // Plain text under no mark lights nothing — the toolbar's resting state.
18323            assert_eq!(m("a| **bold** b"), [], "{tag}");
18324            assert!(m("plain t|ext").is_empty(), "{tag}");
18325        }
18326    }
18327
18328    #[test]
18329    fn nested_marks_all_report() {
18330        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
18331        // the ancestor chain is a chain, and every mark on it is in force.
18332        for (view, tag) in VIEWS {
18333            assert_eq!(
18334                marks(
18335                    view,
18336                    &format!("marks_nested_{tag}"),
18337                    "**bold and *bo|th*** end"
18338                ),
18339                [InlineKind::Strong, InlineKind::Emph],
18340                "{tag}"
18341            );
18342        }
18343    }
18344
18345    #[test]
18346    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
18347        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
18348        // the first byte of its text and the byte after its last — both inside
18349        // the mark's span, both places typing lands inside the bold. The offset
18350        // past the closing delimiter is the next text, and reports nothing.
18351        let src = "a **bold** b";
18352        let inner_start = src.find("bold").unwrap(); // 4
18353        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
18354        for (view, tag) in VIEWS {
18355            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
18356            for off in [2, 3, inner_start, inner_end, 9] {
18357                d.caret = off;
18358                assert!(
18359                    d.active_inline_marks().contains(InlineKind::Strong),
18360                    "{tag}: offset {off} is inside the strong span"
18361                );
18362            }
18363            for off in [0, 1, 10, 11, 12] {
18364                d.caret = off;
18365                assert!(
18366                    !d.active_inline_marks().contains(InlineKind::Strong),
18367                    "{tag}: offset {off} is outside the strong run"
18368                );
18369            }
18370        }
18371    }
18372
18373    #[test]
18374    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
18375        // Regression: twig resolves an offset that is one node's end and the
18376        // next one's start to the node that *starts* there, so `**bold**|\n`
18377        // isn't bold. With nothing following there's no tie to break and the
18378        // chain still ended at the mark, which made a trailing `\n` — not the
18379        // text — decide whether the caret after a bold word reported bold. It's
18380        // the offset past the mark either way, and typing there is plain either
18381        // way. A blank document typed into is exactly this shape.
18382        for (view, tag) in VIEWS {
18383            let m = |name: String, marked| marks(view, &name, marked);
18384            assert_eq!(
18385                m(format!("marks_eob_{tag}"), "**bold**|"),
18386                [],
18387                "{tag}: no trailing newline"
18388            );
18389            assert_eq!(
18390                m(format!("marks_eol_{tag}"), "**bold**|\n"),
18391                [],
18392                "{tag}: with one"
18393            );
18394            // And the last offset that *is* in the mark still is.
18395            assert_eq!(
18396                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
18397                [InlineKind::Strong],
18398                "{tag}"
18399            );
18400        }
18401    }
18402
18403    #[test]
18404    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
18405        let src = "a **bold** b";
18406        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
18407        for (view, tag) in VIEWS {
18408            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
18409            // The whole bold word, and a slice of it.
18410            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
18411            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
18412            // Ending exactly at the closing delimiter's start is still all-bold:
18413            // an exclusive end sits *past* the last selected character, so the
18414            // question is asked of the character, not the boundary.
18415            assert_eq!(
18416                m(b, d_ + 2),
18417                [InlineKind::Strong],
18418                "{tag}: through the close"
18419            );
18420            // Half in, half out: Bold lit here would claim a press turns it off.
18421            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
18422            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
18423        }
18424    }
18425
18426    #[test]
18427    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
18428        // Both ends are bold, but the space between them isn't — two runs are two
18429        // nodes, which is exactly what the node id catches and a kind-only
18430        // comparison would not.
18431        let src = "**one** **two**";
18432        for (view, tag) in VIEWS {
18433            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
18434            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
18435        }
18436    }
18437
18438    #[test]
18439    fn marks_read_the_document_as_it_is_edited() {
18440        // The point of asking twig every frame instead of caching: the answer has
18441        // to follow the toggle that changed it.
18442        let mut d = wysiwyg_doc("marks_live", "one two\n");
18443        d.anchor = Some(0);
18444        d.caret = 3;
18445        assert!(d.active_inline_marks().is_empty(), "plain to start");
18446        d.toggle(InlineKind::Strong);
18447        assert_eq!(d.source, "**one** two\n");
18448        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
18449        assert!(d.active_inline_marks().contains(InlineKind::Strong));
18450        d.toggle(InlineKind::Strong);
18451        assert!(d.active_inline_marks().is_empty(), "and off again");
18452    }
18453
18454    #[test]
18455    fn a_link_is_not_an_inline_mark() {
18456        // `link`/`str` are inline nodes, but nothing on the inline toolbar
18457        // toggles them — a set with a "link mark" in it would have no button.
18458        for (view, tag) in VIEWS {
18459            assert_eq!(
18460                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
18461                [],
18462                "{tag}"
18463            );
18464        }
18465    }
18466
18467    // ── blank documents ───────────────────────────────────────────────────────
18468
18469    #[test]
18470    fn a_blank_document_is_untitled_empty_and_markdown() {
18471        let mut d = Doc::blank().unwrap();
18472        assert!(d.is_untitled());
18473        assert_eq!(d.path, PathBuf::new());
18474        assert_eq!(
18475            d.file_name(),
18476            "untitled",
18477            "the header has to show something"
18478        );
18479        assert_eq!(d.format_name(), "markdown");
18480        assert_eq!(d.source, "");
18481        assert!(!d.dirty, "nothing typed yet is nothing to lose");
18482        assert_eq!(d.disk_state(), DiskState::Untitled);
18483        // And it's a document you can be in: the default view renders it.
18484        d.build_visual(80);
18485        assert_eq!(d.caret, 0);
18486    }
18487
18488    #[test]
18489    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
18490        let mut d = Doc::blank().unwrap();
18491        d.insert("hello");
18492        assert!(d.dirty);
18493        d.save();
18494        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
18495        assert!(d.dirty, "it must not come away believing it saved");
18496        assert!(d.is_untitled(), "and it still has no file");
18497    }
18498
18499    #[test]
18500    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
18501        let p = temp_path("blank_save_as");
18502        let mut d = Doc::blank().unwrap();
18503        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
18504        // be kept literal (`\#`); this test is about save-as, not escaping (which
18505        // has its own test), so it types nothing that escaping would touch.
18506        d.insert("hi");
18507        d.save_as(p.clone());
18508        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
18509        assert!(!d.is_untitled());
18510        assert!(!d.dirty);
18511        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
18512        assert_eq!(
18513            d.disk_state(),
18514            DiskState::Unchanged,
18515            "the watermark is stamped"
18516        );
18517        // And ⌘S is a plain save from here on.
18518        d.insert("!");
18519        d.save();
18520        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
18521        let _ = std::fs::remove_file(&p);
18522    }
18523
18524    // ── a file that isn't there yet ───────────────────────────────────────────
18525
18526    /// A unique path in the temp dir with the given extension, guaranteed not to
18527    /// exist — what `leaf notes.md` is handed when the file has never been made.
18528    fn missing_path(name: &str, ext: &str) -> PathBuf {
18529        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18530        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18531        let mut p = std::env::temp_dir();
18532        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
18533        let _ = std::fs::remove_file(&p);
18534        p
18535    }
18536
18537    #[test]
18538    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
18539        let p = missing_path("named", "md");
18540        let mut d = Doc::open_or_create(p.clone()).unwrap();
18541
18542        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
18543        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
18544        assert!(
18545            !d.is_untitled(),
18546            "it has the name the user asked for — ^S must not detour to Save As"
18547        );
18548        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
18549        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
18550        assert!(!p.exists(), "and opening it wrote nothing");
18551        // And it's a document you can be in.
18552        d.build_visual(80);
18553        assert_eq!(d.caret, 0);
18554    }
18555
18556    #[test]
18557    fn a_new_file_is_created_by_its_first_save() {
18558        let p = missing_path("first_save", "md");
18559        let mut d = Doc::open_or_create(p.clone()).unwrap();
18560        d.insert("hello\n");
18561        assert!(d.dirty);
18562        d.save();
18563
18564        assert_eq!(
18565            std::fs::read_to_string(&p).unwrap(),
18566            "hello\n",
18567            "a plain ^S wrote it — no Save As, no name to invent"
18568        );
18569        assert!(!d.dirty);
18570        assert_eq!(d.disk_state(), DiskState::Unchanged);
18571        let _ = std::fs::remove_file(&p);
18572    }
18573
18574    #[test]
18575    fn a_new_file_takes_its_format_from_the_extension() {
18576        // The one thing `blank` can't do: with no name it has to assume Markdown,
18577        // and typing djot into a Markdown parse is the wrong buffer.
18578        let dj = missing_path("format", "dj");
18579        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
18580        let md = missing_path("format", "md");
18581        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
18582    }
18583
18584    #[test]
18585    fn a_new_file_reports_itself_missing_until_it_is_saved() {
18586        // Not `Untitled` — that's the answer for a document with no path, and it
18587        // would tell a frontend there is nothing a save could collide with. Here
18588        // there is a path, and the file simply isn't at it yet.
18589        let p = missing_path("disk_state", "md");
18590        let mut d = Doc::open_or_create(p.clone()).unwrap();
18591        assert_eq!(d.disk_state(), DiskState::Missing);
18592
18593        // Somebody else creates it while the buffer is open: that's an overwrite
18594        // the frontend has to be able to prompt about, exactly as for an opened
18595        // file. Their bytes, not ours, so `Changed`.
18596        std::fs::write(&p, "theirs\n").unwrap();
18597        assert_eq!(d.disk_state(), DiskState::Changed);
18598
18599        // Saving makes the file ours and re-stamps the watermark.
18600        d.insert("ours\n");
18601        d.save();
18602        assert_eq!(d.disk_state(), DiskState::Unchanged);
18603        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
18604        let _ = std::fs::remove_file(&p);
18605    }
18606
18607    #[test]
18608    fn open_or_create_still_opens_a_file_that_is_there() {
18609        let d = doc_with("open_or_create_existing", "body\n");
18610        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
18611        assert_eq!(reopened.source, "body\n");
18612        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
18613    }
18614
18615    #[test]
18616    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
18617        // A mistyped flag or a stray argument must not become a buffer promising
18618        // to save somewhere — the same refusal `open` gives a real file.
18619        let mut p = std::env::temp_dir();
18620        p.push("leaf_test_new_bad_ext.wat");
18621        assert!(Doc::open_or_create(p).is_err());
18622        let mut none = std::env::temp_dir();
18623        none.push("leaf_test_new_no_ext");
18624        assert!(Doc::open_or_create(none).is_err());
18625    }
18626
18627    #[test]
18628    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
18629        // Opening reads nothing, so there is nothing to fail on yet; the write is
18630        // where it fails, and it says so rather than claiming a save.
18631        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
18632        let mut d = Doc::open_or_create(p).unwrap();
18633        d.insert("x");
18634        d.save();
18635        assert!(
18636            d.status.as_deref().unwrap().starts_with("save failed:"),
18637            "got {:?}",
18638            d.status
18639        );
18640        assert!(d.dirty, "it must not come away believing it saved");
18641    }
18642
18643    // ── save as ───────────────────────────────────────────────────────────────
18644
18645    /// A unique path in the temp dir that no fixture wrote — a Save As target.
18646    fn temp_path(name: &str) -> PathBuf {
18647        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18648        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18649        let mut p = std::env::temp_dir();
18650        p.push(format!("leaf_test_target_{name}_{seq}.md"));
18651        let _ = std::fs::remove_file(&p);
18652        p
18653    }
18654
18655    #[test]
18656    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
18657        let mut d = doc_with("save_as_move", "original\n");
18658        let old = d.path.clone();
18659        let new = temp_path("save_as_move");
18660        d.insert("edited: ");
18661        d.save_as(new.clone());
18662
18663        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
18664        assert_eq!(
18665            std::fs::read_to_string(&old).unwrap(),
18666            "original\n",
18667            "Save As doesn't touch the file it came from"
18668        );
18669        assert_eq!(d.path, new, "the document moved");
18670        assert!(!d.dirty);
18671        assert_eq!(
18672            d.status.as_deref(),
18673            Some(&*format!("saved {}", d.file_name()))
18674        );
18675
18676        // Every later save follows it, which is the whole difference from a copy.
18677        d.caret = 0;
18678        d.insert("re-");
18679        d.save();
18680        assert_eq!(
18681            std::fs::read_to_string(&new).unwrap(),
18682            "re-edited: original\n"
18683        );
18684        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
18685        let _ = std::fs::remove_file(&new);
18686    }
18687
18688    #[test]
18689    fn save_as_overwrites_an_existing_target() {
18690        // The picker already asked; asking again down here is the same question
18691        // twice, and the second one has no way to be answered.
18692        let new = temp_path("save_as_over");
18693        std::fs::write(&new, "theirs\n").unwrap();
18694        let mut d = doc_with("save_as_over", "ours\n");
18695        d.save_as(new.clone());
18696        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
18697        let _ = std::fs::remove_file(&new);
18698    }
18699
18700    #[test]
18701    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
18702        let mut d = doc_with("save_as_fail", "body\n");
18703        let old = d.path.clone();
18704        d.insert("x");
18705        // A directory that doesn't exist: the write can't land.
18706        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
18707        d.save_as(bad);
18708
18709        assert_eq!(
18710            d.path, old,
18711            "the document must not move to a file that isn't there"
18712        );
18713        assert!(d.dirty, "and must not believe it saved");
18714        assert!(
18715            d.status.as_deref().unwrap().starts_with("save failed:"),
18716            "the same failure a plain save reports, got {:?}",
18717            d.status
18718        );
18719        // The original is still the document's file, and still saveable.
18720        d.save();
18721        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
18722        assert!(!d.dirty);
18723    }
18724
18725    #[test]
18726    fn save_as_renames_without_reparsing_the_format() {
18727        // `.dj` on the name doesn't make the buffer djot: it was parsed as
18728        // Markdown and still is, and saying otherwise would be a conversion the
18729        // user never asked for (and an undo history thrown away to do it).
18730        let mut d = doc_with("save_as_format", "**b**\n");
18731        let mut new = temp_path("save_as_format");
18732        new.set_extension("dj");
18733        d.save_as(new.clone());
18734        assert_eq!(d.format_name(), "markdown");
18735        let _ = std::fs::remove_file(&new);
18736    }
18737
18738    // ── external change / reload ──────────────────────────────────────────────
18739
18740    #[test]
18741    fn an_untouched_file_reports_unchanged() {
18742        let mut d = doc_with("disk_clean", "body\n");
18743        assert_eq!(d.disk_state(), DiskState::Unchanged);
18744        // Editing the buffer is not editing the file.
18745        d.insert("x");
18746        assert_eq!(d.disk_state(), DiskState::Unchanged);
18747        assert!(d.dirty);
18748        // Saving re-stamps the watermark rather than reporting our own bytes back.
18749        d.save();
18750        assert_eq!(d.disk_state(), DiskState::Unchanged);
18751    }
18752
18753    #[test]
18754    fn a_file_written_underneath_reports_changed() {
18755        let mut d = doc_with("disk_changed", "body\n");
18756        std::fs::write(&d.path, "someone else\n").unwrap();
18757        assert_eq!(d.disk_state(), DiskState::Changed);
18758        // Dirty *and* changed is the clobber: both halves are readable, and
18759        // leaf-core takes neither side.
18760        d.insert("x");
18761        assert!(d.dirty && d.disk_state() == DiskState::Changed);
18762        // Saving anyway is allowed — the frontend asked, or chose not to.
18763        d.save();
18764        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
18765        assert_eq!(d.disk_state(), DiskState::Unchanged);
18766    }
18767
18768    #[test]
18769    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
18770        // The hash is what makes this honest: the file was written (a fresh
18771        // mtime), and nothing about the document is stale.
18772        let d = doc_with("disk_same_bytes", "body\n");
18773        std::fs::write(&d.path, "body\n").unwrap();
18774        assert_eq!(d.disk_state(), DiskState::Unchanged);
18775    }
18776
18777    #[test]
18778    fn a_deleted_file_reports_missing() {
18779        let mut d = doc_with("disk_missing", "body\n");
18780        std::fs::remove_file(&d.path).unwrap();
18781        assert_eq!(d.disk_state(), DiskState::Missing);
18782        // A save recreates it, and the document is whole again.
18783        d.save();
18784        assert_eq!(d.disk_state(), DiskState::Unchanged);
18785        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
18786    }
18787
18788    #[test]
18789    fn reload_replaces_the_document_with_the_file() {
18790        for (view, tag) in VIEWS {
18791            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
18792            d.insert("edited ");
18793            assert!(d.dirty);
18794            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
18795            d.reload();
18796
18797            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
18798            assert!(!d.dirty, "{tag}: the file is what we have");
18799            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
18800            assert_eq!(
18801                d.status.as_deref(),
18802                Some(&*format!("reloaded {}", d.file_name()))
18803            );
18804            // The reloaded tree is live, not the old parse.
18805            d.caret = d.source.find("three").unwrap();
18806            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
18807        }
18808    }
18809
18810    #[test]
18811    fn reload_clamps_the_caret_and_drops_the_selection() {
18812        let mut d = doc_with("reload_caret", "a long first line\n");
18813        d.caret = 12;
18814        d.anchor = Some(4);
18815        std::fs::write(&d.path, "short\n").unwrap();
18816        d.reload();
18817        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
18818        assert_eq!(
18819            d.anchor, None,
18820            "a selection over bytes that changed is a lie"
18821        );
18822        assert!(d.selection().is_none());
18823
18824        // A caret the file still has room for stays put.
18825        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
18826        d.caret = 2;
18827        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
18828        d.reload();
18829        assert_eq!(d.caret, 2);
18830    }
18831
18832    /// A silent reload is something that happened *to* a reader — a formatter,
18833    /// a `git checkout` — so it has to be undoable like anything else that
18834    /// changes the document, and undoable as one step rather than as however
18835    /// many the file happens to differ by.
18836    #[test]
18837    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
18838        let mut d = doc_with("reload_undo", "body\n");
18839        d.insert("x");
18840        assert_eq!(d.source, "xbody\n");
18841        std::fs::write(&d.path, "replaced\n").unwrap();
18842        d.reload();
18843        assert_eq!(d.source, "replaced\n");
18844        assert!(!d.dirty, "a reload lands clean");
18845
18846        // One ^Z takes the whole swap off, and hands back the unsaved work it
18847        // replaced — which is unsaved again, because the file no longer says it.
18848        d.undo();
18849        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
18850        assert!(d.dirty, "and what it comes back to is unsaved");
18851        // …and the history under it is still there.
18852        d.undo();
18853        assert_eq!(
18854            d.source, "body\n",
18855            "the typing before the reload undoes too"
18856        );
18857        // Redo walks back up through the reload.
18858        d.redo();
18859        d.redo();
18860        assert_eq!(d.source, "replaced\n");
18861    }
18862
18863    /// A file rewritten with the bytes it already had is not an edit, so it
18864    /// must not leave an undo step behind for something nobody did.
18865    #[test]
18866    fn reloading_identical_bytes_pushes_no_undo_step() {
18867        let mut d = doc_with("reload_same", "body\n");
18868        d.insert("x");
18869        std::fs::write(&d.path, "xbody\n").unwrap();
18870        d.reload();
18871        assert_eq!(d.source, "xbody\n");
18872        assert!(!d.dirty, "the file now says what the buffer does");
18873        d.undo();
18874        assert_eq!(
18875            d.source, "body\n",
18876            "one step back is the typing, not a no-op"
18877        );
18878    }
18879
18880    #[test]
18881    fn a_reload_that_cant_read_leaves_the_document_alone() {
18882        let mut d = doc_with("reload_gone", "body\n");
18883        d.insert("x");
18884        std::fs::remove_file(&d.path).unwrap();
18885        d.reload();
18886        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
18887        assert!(d.dirty);
18888        assert!(
18889            d.status.as_deref().unwrap().starts_with("reload failed:"),
18890            "{:?}",
18891            d.status
18892        );
18893
18894        // And an untitled document has nothing to reload from.
18895        let mut d = Doc::blank().unwrap();
18896        d.insert("typed");
18897        d.reload();
18898        assert_eq!(d.source, "typed");
18899        assert_eq!(d.status.as_deref(), Some("no file to reload"));
18900    }
18901
18902    #[test]
18903    fn a_read_only_document_refuses_every_door() {
18904        let mut d = doc_with("readonly", "one two three\n");
18905        d.insert("x");
18906        assert!(d.dirty, "writable first, so the undo step exists");
18907        d.set_read_only(true);
18908        let before = d.source.clone();
18909        d.insert("y");
18910        d.backspace();
18911        d.undo();
18912        d.redo();
18913        assert_eq!(d.source, before, "no door moved a byte");
18914        d.set_read_only(false);
18915        d.undo();
18916        assert_ne!(d.source, before, "off again, the same doors work");
18917    }
18918
18919    /// The doors that go to twig's own verbs rather than through the splice.
18920    /// Typed text in the rendered view under the default markup mode is the
18921    /// everyday one — it is what a keystroke in leaf-web or the Apple views
18922    /// becomes — and it walked straight past the gate.
18923    #[test]
18924    fn a_read_only_document_refuses_the_doors_around_the_splice() {
18925        let mut d = wysiwyg_doc(
18926            "readonly-doors",
18927            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
18928        );
18929        d.set_markup_mode(MarkupMode::None);
18930        d.set_read_only(true);
18931        let before = d.source.clone();
18932        d.place_caret(3, false);
18933        d.insert("y");
18934        d.insert_link("https://example.com");
18935        d.insert_image("a.png", "alt");
18936        d.insert_thematic_break();
18937        d.insert_footnote();
18938        d.place_caret(0, false);
18939        d.place_caret(3, true);
18940        d.toggle(InlineKind::Strong);
18941        d.toggle_heading(2);
18942        d.set_block(BlockKind::Paragraph);
18943        d.toggle_list(false);
18944        d.toggle_blockquote();
18945        d.toggle_task_item();
18946        d.newline();
18947        d.indent();
18948        d.set_code_language("rust");
18949        let in_cell = d.source.find("| c").unwrap() + 2;
18950        d.place_caret(in_cell, false);
18951        assert!(d.caret_in_table(), "the caret is in the grid");
18952        assert!(!d.cell_line_break(), "the cell break reports the refusal");
18953        assert_eq!(d.source, before, "no door moved a byte");
18954        assert!(!d.dirty, "nothing to save");
18955        d.set_read_only(false);
18956        d.place_caret(3, false);
18957        d.insert("y");
18958        assert_ne!(d.source, before, "off again, the same doors work");
18959    }
18960
18961    #[test]
18962    fn a_selection_quote_carries_its_context_on_char_boundaries() {
18963        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
18964        let start = d.source.find("exact").unwrap();
18965        d.place_caret(start, false);
18966        d.place_caret(start + "exact".len(), true);
18967        let q = d.selection_quote(3).unwrap();
18968        assert_eq!(q.exact, "exact");
18969        assert_eq!(
18970            q.prefix, "你好 ",
18971            "chars, not bytes — the multibyte pair counts as two"
18972        );
18973        assert_eq!(q.suffix, " 世界");
18974        assert_eq!(&d.source[q.start..q.end], "exact");
18975        // At the edges the context clips rather than erring.
18976        d.place_caret(0, false);
18977        d.place_caret(6, true);
18978        let q = d.selection_quote(40).unwrap();
18979        assert_eq!(q.prefix, "");
18980        assert_eq!(q.exact, "before");
18981        // No selection is no quote.
18982        d.place_caret(0, false);
18983        assert!(d.selection_quote(3).is_none());
18984    }
18985
18986    #[test]
18987    fn highlights_are_kept_sorted_and_answer_point_queries() {
18988        let mut d = doc_with("hl", "one two three\n");
18989        d.set_highlights(vec![
18990            Highlight {
18991                start: 8,
18992                end: 13,
18993                id: "b".into(),
18994                color: None,
18995                marker: None,
18996            },
18997            Highlight {
18998                start: 0,
18999                end: 3,
19000                id: "a".into(),
19001                color: Some("#ffe066".into()),
19002                marker: None,
19003            },
19004            Highlight {
19005                start: 5,
19006                end: 5,
19007                id: "empty".into(),
19008                color: None,
19009                marker: None,
19010            },
19011        ]);
19012        assert_eq!(
19013            d.highlights()
19014                .iter()
19015                .map(|h| h.id.as_str())
19016                .collect::<Vec<_>>(),
19017            ["a", "b"],
19018            "sorted by start, the empty range dropped"
19019        );
19020        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
19021        assert_eq!(d.highlight_at(3), None, "end is exclusive");
19022        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
19023        d.set_highlights(Vec::new());
19024        assert!(d.highlights().is_empty(), "a replace is a replace");
19025    }
19026
19027    /// `Highlight::covering` and the cursor over it are what both painters ask
19028    /// per glyph, so they have to answer the same as the scan they replaced —
19029    /// including in the gaps, which is where most glyphs are.
19030    #[test]
19031    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
19032        let hl = |start: usize, end: usize, id: &str| Highlight {
19033            start,
19034            end,
19035            id: id.into(),
19036            color: None,
19037            marker: None,
19038        };
19039        // Disjoint, as search hits are: in a range, in a gap, and past the end.
19040        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
19041        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
19042        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
19043        assert_eq!(
19044            Highlight::covering(&hits, 105),
19045            None,
19046            "a gap covers nothing"
19047        );
19048        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
19049        assert_eq!(Highlight::covering(&hits, 9_999), None);
19050        assert_eq!(Highlight::covering(&[], 0), None);
19051
19052        // Nested: first by start, so a hit inside an annotation still resolves
19053        // to the annotation — and the range that stops short doesn't mask it.
19054        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
19055        assert_eq!(
19056            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
19057            Some("outer")
19058        );
19059        assert_eq!(
19060            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
19061            Some("outer")
19062        );
19063    }
19064
19065    /// The cursor is an optimisation, so the only thing worth asserting is that
19066    /// it is not also a change of answer — at every offset, over a list with a
19067    /// nest in it, walked forwards and then backwards.
19068    #[test]
19069    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
19070        let hl = |start: usize, end: usize, id: &str| Highlight {
19071            start,
19072            end,
19073            id: id.into(),
19074            color: None,
19075            marker: None,
19076        };
19077        let mut list = vec![
19078            hl(0, 20, "outer"),
19079            hl(5, 10, "inner"),
19080            hl(30, 33, "hit"),
19081            hl(40, 43, "hit"),
19082        ];
19083        list.sort_by_key(|h| (h.start, h.end));
19084
19085        let mut cursor = HighlightCursor::new(&list);
19086        for offset in 0..50 {
19087            assert_eq!(
19088                cursor.at(offset).map(|h| h.id.as_str()),
19089                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19090                "cursor disagrees at {offset}"
19091            );
19092        }
19093        // Backwards: the cursor re-seats rather than answering from where it
19094        // had got to, so a painter that revisits a row is still told the truth.
19095        for offset in (0..50).rev() {
19096            assert_eq!(
19097                cursor.at(offset).map(|h| h.id.as_str()),
19098                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19099                "cursor disagrees walking back at {offset}"
19100            );
19101        }
19102    }
19103
19104    // ── the presentation vocabulary ─────────────────────────────────────────
19105
19106    /// A document in `format`, for the gesture tests that want more than the
19107    /// Markdown `doc_with` writes.
19108    fn fmt_doc(body: &str, format: Format) -> Doc {
19109        Doc::from_source(body.to_string(), format).unwrap()
19110    }
19111
19112    /// Alignment is a block property, so the gesture is `set_block_attrs` on
19113    /// the caret's block whatever is selected — and each format spells it its
19114    /// own way: djot's `{…}` line above the block, a `<div>` around it in
19115    /// Markdown (the format has nowhere else to put it), the tag in HTML.
19116    #[test]
19117    fn set_alignment_spells_the_class_the_format_s_own_way() {
19118        let mut dj = fmt_doc("hello\n", Format::Djot);
19119        dj.caret = 1;
19120        dj.set_alignment(Some(Align::Center));
19121        assert_eq!(dj.source, "{.center}\nhello\n");
19122        assert!(dj.dirty);
19123        assert_eq!(dj.status, None);
19124
19125        let mut md = fmt_doc("hello\n", Format::Markdown);
19126        md.caret = 1;
19127        md.set_alignment(Some(Align::Right));
19128        assert_eq!(md.source, "<div class=\"right\">\n\nhello\n\n</div>\n");
19129
19130        let mut html = fmt_doc("<p>hello</p>\n", Format::Html);
19131        html.caret = html.source.find("hello").unwrap();
19132        html.set_alignment(Some(Align::Justify));
19133        assert_eq!(html.source, "<p class=\"justify\">hello</p>\n");
19134    }
19135
19136    /// Each gesture edits **one key and keeps the rest** — twig's contract is
19137    /// replace-not-merge, so leaf reads the node's attributes, edits its own
19138    /// key out of them, and passes the list back whole. A document from
19139    /// elsewhere passes through the editor unharmed.
19140    #[test]
19141    fn a_presentation_gesture_keeps_every_attribute_it_did_not_write() {
19142        let mut d = fmt_doc(
19143            "{.lead .center #intro data-line-height=\"1.5\"}\nhello\n",
19144            Format::Djot,
19145        );
19146        d.caret = d.source.find("hello").unwrap();
19147        d.set_alignment(Some(Align::Right));
19148        // `center` goes, `lead` stays, and neither the id nor the spacing is
19149        // touched.
19150        // The serializer picks the order; what matters is which keys survive.
19151        assert!(d.source.contains(".lead"), "{:?}", d.source);
19152        assert!(d.source.contains(".right"), "{:?}", d.source);
19153        assert!(!d.source.contains(".center"), "{:?}", d.source);
19154        assert!(d.source.contains("#intro"), "{:?}", d.source);
19155        assert!(
19156            d.source.contains("data-line-height=\"1.5\""),
19157            "{:?}",
19158            d.source
19159        );
19160        assert_eq!(d.alignment_at_caret(), Some(Align::Right));
19161        assert_eq!(
19162            d.line_spacing_at_caret(),
19163            Some(LineHeight::Step(LineSpacing::OneHalf))
19164        );
19165
19166        // And the other way round: the spacing gesture leaves the classes be.
19167        d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19168        assert!(d.source.contains(".lead"), "{:?}", d.source);
19169        assert!(d.source.contains(".right"), "{:?}", d.source);
19170        assert_eq!(
19171            d.line_spacing_at_caret(),
19172            Some(LineHeight::Step(LineSpacing::Double))
19173        );
19174    }
19175
19176    /// Clearing is the same gesture with `None`: the key goes, the tokens leaf
19177    /// owns go out of `class`, and a block left with nothing at all is spelled
19178    /// bare again — in Markdown by unwrapping the div twig wrapped it in.
19179    #[test]
19180    fn none_clears_a_key_and_an_empty_set_unwraps_the_block() {
19181        let mut dj = fmt_doc("{.lead .center}\nhello\n", Format::Djot);
19182        dj.caret = dj.source.find("hello").unwrap();
19183        dj.set_alignment(None);
19184        assert_eq!(dj.source, "{.lead}\nhello\n", "the foreign class stays");
19185        assert_eq!(dj.alignment_at_caret(), None);
19186
19187        let mut bare = fmt_doc("{.center}\nhello\n", Format::Djot);
19188        bare.caret = bare.source.find("hello").unwrap();
19189        bare.set_alignment(None);
19190        assert_eq!(
19191            bare.source, "hello\n",
19192            "the last key takes the line with it"
19193        );
19194
19195        let mut md = fmt_doc("hello\n", Format::Markdown);
19196        md.caret = 1;
19197        md.set_alignment(Some(Align::Center));
19198        assert_eq!(md.source, "<div class=\"center\">\n\nhello\n\n</div>\n");
19199        md.caret = md.source.find("hello").unwrap();
19200        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::OneFifteen)));
19201        assert_eq!(
19202            md.source, "<div class=\"center\" data-line-height=\"1.15\">\n\nhello\n\n</div>\n",
19203            "the second key rewrites the div rather than nesting a second"
19204        );
19205        md.caret = md.source.find("hello").unwrap();
19206        md.set_alignment(None);
19207        md.caret = md.source.find("hello").unwrap();
19208        md.set_line_spacing(None);
19209        assert_eq!(md.source, "hello\n", "an empty set unwraps the div");
19210    }
19211
19212    /// Size, face and colour are the run's over a selection and the block's
19213    /// with none — so "make this paragraph larger" is a click with the caret in
19214    /// it rather than a select-all first.
19215    #[test]
19216    fn a_run_gesture_wraps_a_selection_and_sets_the_block_without_one() {
19217        // With a selection: a span, in each format's own spelling.
19218        let mut dj = fmt_doc("a big b\n", Format::Djot);
19219        dj.anchor = Some(2);
19220        dj.caret = 5;
19221        dj.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19222        assert_eq!(dj.source, "a [big]{data-size=\"large\"} b\n");
19223        assert_eq!(
19224            dj.font_size_at_caret(),
19225            Some(FontSize::Step(SizeStep::Large))
19226        );
19227
19228        let mut md = fmt_doc("a big b\n", Format::Markdown);
19229        md.anchor = Some(2);
19230        md.caret = 5;
19231        md.set_text_color(Some(TextColor::Named(MarkColor::Blue)));
19232        assert_eq!(md.source, "a <span data-color=\"blue\">big</span> b\n");
19233        assert_eq!(
19234            md.text_color_at_caret(),
19235            Some(TextColor::Named(MarkColor::Blue))
19236        );
19237
19238        // Without one: the caret's block, through the block gesture.
19239        let mut block = fmt_doc("a big b\n", Format::Djot);
19240        block.caret = 3;
19241        block.set_font_family(Some(FontFace::Generic(FontFamily::Monospace)));
19242        assert_eq!(block.source, "{data-font=\"monospace\"}\na big b\n");
19243        assert_eq!(
19244            block.font_family_at_caret(),
19245            Some(FontFace::Generic(FontFamily::Monospace))
19246        );
19247    }
19248
19249    /// The *Other…* row of each of the four menus: a value goes into the
19250    /// document in its canonical spelling and comes back out of the query as
19251    /// the same value. One round trip per property, because the four go out
19252    /// through different doors — two block gestures, and the run three through
19253    /// the span that `wrap_range_attrs` mints.
19254    #[test]
19255    fn an_exact_value_round_trips_through_the_gesture_and_the_query() {
19256        // Size: the run three, over a selection.
19257        let mut d = fmt_doc("a big b\n", Format::Djot);
19258        d.anchor = Some(2);
19259        d.caret = 5;
19260        d.set_font_size(FontSize::points(14.0));
19261        assert_eq!(d.source, "a [big]{data-size=\"14pt\"} b\n");
19262        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19263
19264        // Colour, onto the same span — the gesture keeps the size it finds.
19265        d.set_text_color(Some(TextColor::Rgb {
19266            r: 0xc0,
19267            g: 0x30,
19268            b: 0x30,
19269        }));
19270        assert_eq!(
19271            d.source,
19272            "a [big]{data-size=\"14pt\" data-color=\"#c03030\"} b\n"
19273        );
19274        assert_eq!(
19275            d.text_color_at_caret(),
19276            Some(TextColor::Rgb {
19277                r: 0xc0,
19278                g: 0x30,
19279                b: 0x30
19280            })
19281        );
19282
19283        // Face: a family name, as given.
19284        d.set_font_family(Some(FontFace::Named("Garamond".into())));
19285        assert!(
19286            d.source.contains("data-font=\"Garamond\""),
19287            "{:?}",
19288            d.source
19289        );
19290        assert_eq!(
19291            d.font_family_at_caret(),
19292            Some(FontFace::Named("Garamond".into()))
19293        );
19294
19295        // Line spacing: a block gesture, and an exact ratio.
19296        let mut block = fmt_doc("hello\n", Format::Djot);
19297        block.caret = 1;
19298        block.set_line_spacing(LineHeight::ratio(1.3));
19299        assert_eq!(block.source, "{data-line-height=\"1.3\"}\nhello\n");
19300        assert_eq!(block.line_spacing_at_caret(), LineHeight::ratio(1.3));
19301
19302        // And a value spelled long is written back short, so the same press
19303        // twice writes the same bytes: `14.0pt` in, `14pt` out.
19304        let mut long = fmt_doc("{data-size=\"14.0pt\"}\nhello\n", Format::Djot);
19305        long.caret = long.source.find("hello").unwrap();
19306        assert_eq!(long.font_size_at_caret(), FontSize::points(14.0));
19307        let in_force = long.font_size_at_caret();
19308        long.set_font_size(in_force);
19309        assert_eq!(long.source, "{data-size=\"14pt\"}\nhello\n");
19310    }
19311
19312    /// A value the grammar does not cover is what it was before the vocabulary
19313    /// opened: carried untouched by the document, answered `None` by the query
19314    /// so the menu ticks *Default*, and rewritten only by a gesture on its own
19315    /// key. leaf is not going to grow a CSS parser to guess at `1.3em`.
19316    #[test]
19317    fn a_value_outside_the_grammar_is_carried_and_the_menu_ticks_the_default() {
19318        let src =
19319            "{data-size=\"huge\" data-color=\"rgb(1,2,3)\" data-line-height=\"1.3em\"}\nhello\n";
19320        let mut d = fmt_doc(src, Format::Djot);
19321        d.caret = d.source.find("hello").unwrap();
19322        assert_eq!(d.font_size_at_caret(), None);
19323        assert_eq!(d.text_color_at_caret(), None);
19324        assert_eq!(d.line_spacing_at_caret(), None);
19325
19326        // The keys are still there, untouched, after a gesture on a *different*
19327        // key — "edit one key and keep the rest" holds for a value it cannot
19328        // read as readily as for one it can.
19329        d.set_alignment(Some(Align::Center));
19330        assert!(d.source.contains("data-size=\"huge\""), "{:?}", d.source);
19331        assert!(
19332            d.source.contains("data-color=\"rgb(1,2,3)\""),
19333            "{:?}",
19334            d.source
19335        );
19336        assert!(
19337            d.source.contains("data-line-height=\"1.3em\""),
19338            "{:?}",
19339            d.source
19340        );
19341        // And the gesture on its *own* key replaces it, which is the one way a
19342        // carried value ever changes.
19343        d.caret = d.source.find("hello").unwrap();
19344        d.set_font_size(FontSize::points(12.0));
19345        assert!(d.source.contains("data-size=\"12pt\""), "{:?}", d.source);
19346        assert!(!d.source.contains("huge"), "{:?}", d.source);
19347    }
19348
19349    /// The nearest node wins whichever *form* either node wrote: a value inside
19350    /// a name, a name inside a value. The fold has one rule and does not learn
19351    /// a second one for exact values.
19352    #[test]
19353    fn the_nearest_node_wins_whether_it_named_a_size_or_measured_one() {
19354        // A value inside a name: the block says `small`, the span says `14pt`.
19355        let mut d = fmt_doc(
19356            "{data-size=\"small\"}\nx [y]{data-size=\"14pt\"} z\n",
19357            Format::Djot,
19358        );
19359        d.caret = d.source.find('y').unwrap();
19360        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19361        d.caret = d.source.find('x').unwrap();
19362        assert_eq!(
19363            d.font_size_at_caret(),
19364            Some(FontSize::Step(SizeStep::Small))
19365        );
19366
19367        // And a name inside a value, which is the same rule read the other way.
19368        let mut e = fmt_doc(
19369            "{data-size=\"14pt\" data-color=\"#c03030\"}\nx [y]{data-size=\"small\"} z\n",
19370            Format::Djot,
19371        );
19372        e.caret = e.source.find('y').unwrap();
19373        assert_eq!(
19374            e.font_size_at_caret(),
19375            Some(FontSize::Step(SizeStep::Small))
19376        );
19377        assert_eq!(
19378            e.text_color_at_caret(),
19379            Some(TextColor::Rgb {
19380                r: 0xc0,
19381                g: 0x30,
19382                b: 0x30
19383            }),
19384            "the block's colour still reaches the span"
19385        );
19386        e.caret = e.source.find('x').unwrap();
19387        assert_eq!(e.font_size_at_caret(), FontSize::points(14.0));
19388    }
19389
19390    /// twig re-styles the span a range already lies in rather than nesting a
19391    /// second, and an empty set unwraps it — so a second press of the menu
19392    /// fixes the size instead of building `[[big]{.a}]{.b}`, and the entry that
19393    /// means "the theme's own" takes the span away.
19394    #[test]
19395    fn a_second_run_gesture_re_styles_the_span_and_none_unwraps_it() {
19396        let mut d = fmt_doc("a big b\n", Format::Djot);
19397        d.anchor = Some(2);
19398        d.caret = 5;
19399        d.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19400        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19401
19402        // The selection `wrap_range_attrs` left behind covers the whole span;
19403        // colouring it now keeps the size, because the gesture reads the span's
19404        // attributes before it edits its own key.
19405        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19406        assert_eq!(
19407            d.source, "a [big]{data-size=\"large\" data-color=\"red\"} b\n",
19408            "one span, both keys"
19409        );
19410        assert_eq!(
19411            d.font_size_at_caret(),
19412            Some(FontSize::Step(SizeStep::Large))
19413        );
19414        assert_eq!(
19415            d.text_color_at_caret(),
19416            Some(TextColor::Named(MarkColor::Red))
19417        );
19418
19419        d.set_text_color(None);
19420        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19421        d.set_font_size(None);
19422        assert_eq!(d.source, "a big b\n", "the last key unwraps the span");
19423        assert_eq!(d.font_size_at_caret(), None);
19424    }
19425
19426    /// The queries read the nearest node that names the property: the span the
19427    /// caret is in, then its block, then the `div`s around it.
19428    #[test]
19429    fn a_presentation_query_reads_the_nearest_node_that_names_it() {
19430        let mut d = fmt_doc(
19431            "{.center data-size=\"small\" data-font=\"serif\"}\nx [y]{data-size=\"xx-large\"} z\n",
19432            Format::Djot,
19433        );
19434        // In the span: its own size, the block's face and alignment.
19435        d.caret = d.source.find('y').unwrap();
19436        assert_eq!(
19437            d.font_size_at_caret(),
19438            Some(FontSize::Step(SizeStep::XxLarge))
19439        );
19440        assert_eq!(
19441            d.font_family_at_caret(),
19442            Some(FontFace::Generic(FontFamily::Serif))
19443        );
19444        assert_eq!(d.alignment_at_caret(), Some(Align::Center));
19445        assert_eq!(d.line_spacing_at_caret(), None);
19446        assert_eq!(d.text_color_at_caret(), None);
19447
19448        // Outside it: the block's size.
19449        d.caret = d.source.find('x').unwrap();
19450        assert_eq!(
19451            d.font_size_at_caret(),
19452            Some(FontSize::Step(SizeStep::Small))
19453        );
19454
19455        // And through a Markdown div, which is where a Markdown block's
19456        // attributes live.
19457        let mut md = fmt_doc(
19458            "<div class=\"center\" data-size=\"large\">\n\nhello\n\n</div>\n",
19459            Format::Markdown,
19460        );
19461        md.caret = md.source.find("hello").unwrap();
19462        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19463        assert_eq!(
19464            md.font_size_at_caret(),
19465            Some(FontSize::Step(SizeStep::Large))
19466        );
19467
19468        // A document that names none of it answers `None` everywhere, which is
19469        // "the theme's own" and what every toolbar draws unlit.
19470        let mut plain = doc_with("plain_presentation", "hello\n");
19471        plain.caret = 1;
19472        assert_eq!(plain.alignment_at_caret(), None);
19473        assert_eq!(plain.line_spacing_at_caret(), None);
19474        assert_eq!(plain.font_size_at_caret(), None);
19475        assert_eq!(plain.font_family_at_caret(), None);
19476        assert_eq!(plain.text_color_at_caret(), None);
19477    }
19478
19479    /// A djot fenced div is anonymous the way an attributed span is, and is a
19480    /// block all the same — the *form* is the whole of what tells them apart.
19481    /// Read as a span it poisoned both halves: the run gesture copied the div's
19482    /// entire attribute set onto the span it minted, duplicating the `id`, and
19483    /// the run and block queries answered off a node the walker draws nothing
19484    /// for.
19485    #[test]
19486    fn a_djot_fenced_div_is_not_an_attributed_span() {
19487        let src = "{.center data-size=\"small\" #box}\n:::\nhello world\n:::\n";
19488        let mut d = fmt_doc(src, Format::Djot);
19489        let at = d.source.find("world").unwrap();
19490        d.anchor = Some(at);
19491        d.caret = at + "world".len();
19492        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19493        assert_eq!(
19494            d.source,
19495            "{.center data-size=\"small\" #box}\n:::\nhello [world]{data-color=\"red\"}\n:::\n",
19496            "the span carries its own key and nothing of the div's"
19497        );
19498
19499        // And the queries stop at the block: a djot div is not a `<div>`, the
19500        // walker lends its keys to nothing inside it, and a query that said
19501        // otherwise would tick a menu entry no glyph on screen obeys.
19502        assert_eq!(
19503            d.text_color_at_caret(),
19504            Some(TextColor::Named(MarkColor::Red))
19505        );
19506        assert_eq!(d.font_size_at_caret(), None);
19507        assert_eq!(d.alignment_at_caret(), None);
19508    }
19509
19510    /// Clearing a property the block does not name and a `div` around it does
19511    /// would write nothing and change nothing — twig's `set_block_attrs`
19512    /// reaches one node, and the div is not it. The gesture says so instead of
19513    /// leaving the author pressing an entry that never ticks.
19514    #[test]
19515    fn clearing_a_property_an_enclosing_div_names_says_so_and_writes_nothing() {
19516        // Markdown, two paragraphs in one div: not the sole-child shape twig
19517        // writes, so `block_attrs_at_caret` reads the paragraph and the
19518        // paragraph names none of it.
19519        let src = "<div class=\"center\" data-line-height=\"1.5\" data-size=\"large\">\n\nhello\n\nworld\n\n</div>\n";
19520        let mut md = fmt_doc(src, Format::Markdown);
19521        md.caret = md.source.find("hello").unwrap();
19522        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19523
19524        md.set_alignment(None);
19525        assert_eq!(md.source, src, "nothing written");
19526        assert!(!md.dirty);
19527        assert_eq!(
19528            md.status.as_deref(),
19529            Some("alignment: set on the div around the block")
19530        );
19531        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19532
19533        // The same for a `data-` key, at both levels — the block pair and the
19534        // run three, the run three at a bare caret being the block gesture.
19535        md.set_line_spacing(None);
19536        assert_eq!(md.source, src);
19537        assert_eq!(
19538            md.status.as_deref(),
19539            Some("line spacing: set on the div around the block")
19540        );
19541        md.set_font_size(None);
19542        assert_eq!(md.source, src);
19543        assert_eq!(
19544            md.status.as_deref(),
19545            Some("size: set on the div around the block")
19546        );
19547
19548        // HTML has no sole-child fold at all: a block's attributes go on the
19549        // block, so the div around one is always out of reach.
19550        let html_src = "<div class=\"center\"><p>hi</p></div>\n";
19551        let mut html = fmt_doc(html_src, Format::Html);
19552        html.caret = html.source.find("hi").unwrap();
19553        assert_eq!(html.alignment_at_caret(), Some(Align::Center));
19554        html.set_alignment(None);
19555        assert_eq!(html.source, html_src);
19556        assert!(!html.dirty);
19557        assert_eq!(
19558            html.status.as_deref(),
19559            Some("alignment: set on the div around the block")
19560        );
19561
19562        // And it is a refusal, not a rule against clearing: a block that names
19563        // the property itself still loses it, div or no div.
19564        let mut own = fmt_doc(
19565            "<div class=\"center\"><p class=\"right\">hi</p></div>\n",
19566            Format::Html,
19567        );
19568        own.caret = own.source.find("hi").unwrap();
19569        own.set_alignment(None);
19570        assert_eq!(own.source, "<div class=\"center\"><p>hi</p></div>\n");
19571        assert_eq!(own.status, None);
19572    }
19573
19574    /// An edited key is rewritten **where it stands**. The proposal's worked
19575    /// example is the test: a paragraph that came in as `id="intro"
19576    /// class="lead center" data-line-height="1.5"` and is right-aligned goes
19577    /// out as the same list with one token changed. Removing the key and
19578    /// pushing it back shuffled a document's attributes on every press.
19579    #[test]
19580    fn an_edited_key_keeps_its_place_among_the_attributes() {
19581        let mut html = fmt_doc(
19582            "<p id=\"intro\" class=\"lead center\" data-line-height=\"1.5\">hello</p>\n",
19583            Format::Html,
19584        );
19585        html.caret = html.source.find("hello").unwrap();
19586        html.set_alignment(Some(Align::Right));
19587        assert_eq!(
19588            html.source,
19589            "<p id=\"intro\" class=\"lead right\" data-line-height=\"1.5\">hello</p>\n"
19590        );
19591
19592        // A `data-` key the same way, and a key the block did not have still
19593        // goes on the end.
19594        html.caret = html.source.find("hello").unwrap();
19595        html.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19596        assert_eq!(
19597            html.source,
19598            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\">hello</p>\n"
19599        );
19600        html.caret = html.source.find("hello").unwrap();
19601        html.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19602        assert_eq!(
19603            html.source,
19604            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\" data-size=\"large\">hello</p>\n"
19605        );
19606
19607        // Djot writes the same list in its own spelling, and the order is the
19608        // author's there too.
19609        let mut dj = fmt_doc(
19610            "{#intro .lead .center data-line-height=\"1.5\"}\nhello\n",
19611            Format::Djot,
19612        );
19613        dj.caret = dj.source.find("hello").unwrap();
19614        dj.set_alignment(Some(Align::Right));
19615        assert_eq!(
19616            dj.source,
19617            "{#intro .lead .right data-line-height=\"1.5\"}\nhello\n"
19618        );
19619    }
19620
19621    /// A page break is a block, so twig alone lands one after the caret's whole
19622    /// block; the paragraph is parted at the caret first, exactly as
19623    /// `insert_thematic_break` parts it, and each format spells the directive
19624    /// its own way.
19625    #[test]
19626    fn insert_page_break_parts_the_paragraph_and_spells_the_directive() {
19627        let mut md = doc_with("page_break_md", "hello world\n");
19628        md.caret = 5;
19629        md.insert_page_break();
19630        assert_eq!(md.source, "hello\n\n::page-break\n\nworld\n");
19631        assert!(md.dirty);
19632        assert_eq!(md.status, None);
19633
19634        let mut dj = fmt_doc("hello world\n", Format::Djot);
19635        dj.caret = 5;
19636        dj.insert_page_break();
19637        assert_eq!(dj.source, "hello\n\n::: page-break\n:::\n\nworld\n");
19638
19639        // At a block's end there is no second half to mint, so the break simply
19640        // follows the block — the rule the rule button already has.
19641        let mut end = doc_with("page_break_end", "hello\n");
19642        end.caret = 5;
19643        end.insert_page_break();
19644        assert_eq!(end.source, "hello\n\n::page-break\n\n");
19645        assert_eq!(end.caret, end.source.len(), "on the line under the break");
19646
19647        // And it reaches the map as the placeholder row a frontend paginates on.
19648        end.view = View::Wysiwyg;
19649        end.build_visual(80);
19650        assert_eq!(
19651            end.vmap
19652                .rows
19653                .iter()
19654                .find_map(|r| r.leaf_directive.as_ref())
19655                .map(|m| m.name.as_str()),
19656            Some(PAGE_BREAK)
19657        );
19658
19659        // HTML and AsciiDoc spell it their own way, and draw it the same.
19660        for (fmt, src, spelled) in [
19661            (Format::Html, "<p>hello</p>\n", "<page-break></page-break>"),
19662            (Format::Asciidoc, "hello\n", "<<<"),
19663        ] {
19664            let mut d = fmt_doc(src, fmt);
19665            d.caret = d.source.find("hello").unwrap() + 5;
19666            d.insert_page_break();
19667            assert!(d.source.contains(spelled), "{fmt:?}: {:?}", d.source);
19668            d.view = View::Wysiwyg;
19669            d.build_visual(80);
19670            let marks = d
19671                .vmap
19672                .rows
19673                .iter()
19674                .filter_map(|r| r.leaf_directive.as_ref())
19675                .map(|m| m.name.as_str())
19676                .collect::<Vec<_>>();
19677            assert_eq!(marks, [PAGE_BREAK], "{fmt:?}");
19678        }
19679    }
19680
19681    /// The vocabulary's capabilities, per format. The two block properties are
19682    /// `SetBlockAttrs` and the three run ones `WrapRangeAttrs`, which is why
19683    /// AsciiDoc can align a paragraph and not size a run: its `[#id.role]#text#`
19684    /// keeps an id and a role and has no slot for a `data-` key.
19685    #[test]
19686    fn the_presentation_capabilities_are_ragged_per_format() {
19687        for fmt in [Format::Markdown, Format::Djot, Format::Html] {
19688            let c = Capabilities::of(fmt);
19689            assert!(c.alignment, "{fmt:?} alignment");
19690            assert!(c.line_spacing, "{fmt:?} line spacing");
19691            assert!(c.font_size, "{fmt:?} size");
19692            assert!(c.font_family, "{fmt:?} face");
19693            assert!(c.text_color, "{fmt:?} colour");
19694        }
19695        // Markdown spells both only under the extensions leaf parses with — a
19696        // `<div>` and a `<span>` read back as containers under `html_elements`,
19697        // and `::page-break` as a directive under `directives`. Ask twig's own
19698        // defaults and the answer is no, which is why `Capabilities` is built
19699        // with `supports_with`.
19700        assert!(!Format::Markdown.supports(Gesture::SetBlockAttrs));
19701        assert!(!Format::Markdown.supports(Gesture::WrapRangeAttrs));
19702        assert!(!Format::Markdown.supports(Gesture::InsertDirective));
19703
19704        let adoc = Capabilities::of(Format::Asciidoc);
19705        assert!(adoc.alignment && adoc.line_spacing, "AsciiDoc's `[…]` line");
19706        assert!(
19707            !adoc.font_size && !adoc.font_family && !adoc.text_color,
19708            "AsciiDoc has no inline spelling that keeps a data- key"
19709        );
19710
19711        // XML spells none of it, and neither page break — nor has it blocks a
19712        // caret could name for a move.
19713        let xml = Capabilities::of(Format::Xml);
19714        assert!(!xml.alignment && !xml.font_size && !xml.page_break && !xml.move_block);
19715        for f in [Format::Markdown, Format::Djot, Format::Html] {
19716            assert!(Capabilities::of(f).move_block, "{f:?} moves blocks");
19717        }
19718        for f in [
19719            Format::Markdown,
19720            Format::Djot,
19721            Format::Html,
19722            Format::Asciidoc,
19723        ] {
19724            assert!(Capabilities::of(f).page_break, "{f:?} breaks pages");
19725        }
19726    }
19727
19728    /// A format that cannot spell a property refuses in its own words and
19729    /// writes nothing — the guard every other gesture has.
19730    #[test]
19731    fn a_presentation_gesture_a_format_cannot_spell_is_refused_with_a_reason() {
19732        let src = "<doc><p>hello</p></doc>\n";
19733        #[allow(clippy::type_complexity)]
19734        let ops: [(&str, &dyn Fn(&mut Doc)); 6] = [
19735            ("alignment", &|d: &mut Doc| {
19736                d.set_alignment(Some(Align::Center))
19737            }),
19738            ("line spacing", &|d: &mut Doc| {
19739                d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)))
19740            }),
19741            ("size", &|d: &mut Doc| {
19742                d.set_font_size(Some(FontSize::Step(SizeStep::Large)))
19743            }),
19744            ("face", &|d: &mut Doc| {
19745                d.set_font_family(Some(FontFace::Generic(FontFamily::Serif)))
19746            }),
19747            ("colour", &|d: &mut Doc| {
19748                d.set_text_color(Some(TextColor::Named(MarkColor::Red)))
19749            }),
19750            ("page break", &|d: &mut Doc| d.insert_page_break()),
19751        ];
19752        for (name, op) in ops {
19753            let mut d = fmt_doc(src, Format::Xml);
19754            let at = d.source.find("hello").unwrap();
19755            d.caret = at;
19756            d.anchor = Some(at + 5);
19757            op(&mut d);
19758            assert_eq!(d.source, src, "{name} edited an XML document");
19759            assert!(!d.dirty, "{name} marked the document dirty");
19760            let status = d.status.as_deref().unwrap_or("");
19761            assert!(
19762                status.contains("xml"),
19763                "{name}: the refusal should name the format, got {status:?}"
19764            );
19765        }
19766
19767        // AsciiDoc is the ragged one: the block gesture works where the run
19768        // gesture does not, and a *selection* is what tells the two apart.
19769        let mut adoc = fmt_doc("hello world\n", Format::Asciidoc);
19770        adoc.anchor = Some(0);
19771        adoc.caret = 5;
19772        adoc.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19773        assert_eq!(adoc.source, "hello world\n", "no inline spelling");
19774        assert!(adoc.status.is_some());
19775    }
19776
19777    /// A read-only document takes none of it, and a caret on a blank line has
19778    /// no block to carry an attribute — both say so rather than writing.
19779    #[test]
19780    fn a_presentation_gesture_respects_read_only_and_a_blank_line() {
19781        let mut ro = fmt_doc("hello\n", Format::Djot);
19782        ro.read_only = true;
19783        ro.caret = 1;
19784        ro.set_alignment(Some(Align::Center));
19785        assert_eq!(ro.source, "hello\n");
19786
19787        let mut blank = fmt_doc("a\n\n\nb\n", Format::Djot);
19788        blank.caret = 2; // the empty line between the two paragraphs
19789        blank.set_alignment(Some(Align::Center));
19790        assert_eq!(blank.source, "a\n\n\nb\n");
19791        assert!(
19792            blank.status.as_deref().unwrap_or("").contains("no block"),
19793            "got {:?}",
19794            blank.status
19795        );
19796    }
19797
19798    /// A block attribute gesture keeps the caret on the **text** it was on, not
19799    /// on the byte offset it had. Markdown has nowhere to put a paragraph's
19800    /// attributes but a `<div>` around it, and twig splices the div and the
19801    /// block it wraps as one region — so a caret that kept its offset landed in
19802    /// the markup, and every press after the first answered "no block at the
19803    /// caret" with the toolbar's queries reading nothing.
19804    #[test]
19805    fn a_markdown_block_gesture_keeps_the_caret_on_its_text() {
19806        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
19807        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
19808        md.caret = md.source.find("brown").unwrap() + 2; // "br|own"
19809
19810        // Wrapping: the div and two blank lines open above the block.
19811        md.set_alignment(Some(Align::Center));
19812        assert_eq!(
19813            md.source,
19814            "<div class=\"center\">\n\nthe quick brown fox\n\n</div>\n"
19815        );
19816        assert_eq!(word(&md), 2, "the caret left its word: {}", md.caret);
19817        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19818
19819        // Re-styling: the attribute line changes length under the same caret,
19820        // and the second press reaches the same block rather than nothing.
19821        md.set_alignment(Some(Align::Right));
19822        assert_eq!(
19823            md.source, "<div class=\"right\">\n\nthe quick brown fox\n\n</div>\n",
19824            "a second press re-styles the div"
19825        );
19826        assert_eq!(md.status, None);
19827        assert_eq!(word(&md), 2);
19828
19829        // A second key on the same div — the line grows, the caret rides it.
19830        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19831        assert_eq!(
19832            md.source,
19833            "<div class=\"right\" data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
19834        );
19835        assert_eq!(word(&md), 2);
19836        assert_eq!(
19837            md.line_spacing_at_caret(),
19838            Some(LineHeight::Step(LineSpacing::Double))
19839        );
19840
19841        // Unwrapping: the line shrinks, and then the div goes altogether.
19842        md.set_alignment(None);
19843        assert_eq!(
19844            md.source,
19845            "<div data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
19846        );
19847        assert_eq!(word(&md), 2);
19848        md.set_line_spacing(None);
19849        assert_eq!(md.source, "the quick brown fox\n", "the last key unwraps");
19850        assert_eq!(word(&md), 2, "the caret came back down with the block");
19851        assert_eq!(md.alignment_at_caret(), None);
19852        assert_eq!(md.status, None);
19853    }
19854
19855    /// The same rule in djot, where the spelling is a `{…}` line *above* the
19856    /// block rather than a wrapper around it: inserting it pushes the block
19857    /// down, re-styling it changes the line's length, and clearing the last key
19858    /// takes the line away again. The caret rides all three.
19859    #[test]
19860    fn a_djot_attribute_line_keeps_the_caret_on_its_text() {
19861        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
19862        let mut dj = fmt_doc("the quick brown fox\n", Format::Djot);
19863        dj.caret = dj.source.find("brown").unwrap() + 2;
19864
19865        dj.set_alignment(Some(Align::Center));
19866        assert_eq!(dj.source, "{.center}\nthe quick brown fox\n");
19867        assert_eq!(word(&dj), 2);
19868        assert_eq!(dj.alignment_at_caret(), Some(Align::Center));
19869
19870        dj.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19871        assert_eq!(
19872            dj.source, "{.center data-line-height=\"2\"}\nthe quick brown fox\n",
19873            "a second press edits the line the first wrote"
19874        );
19875        assert_eq!(word(&dj), 2);
19876
19877        dj.set_alignment(None);
19878        assert_eq!(dj.source, "{data-line-height=\"2\"}\nthe quick brown fox\n");
19879        assert_eq!(word(&dj), 2);
19880
19881        dj.set_line_spacing(None);
19882        assert_eq!(dj.source, "the quick brown fox\n");
19883        assert_eq!(word(&dj), 2);
19884        assert_eq!(dj.status, None);
19885    }
19886
19887    /// The run gestures with no selection are the block gesture, so they keep
19888    /// the caret the same way — and a heading keeps it inside the heading's own
19889    /// text, past the `# ` its content span starts after. A selection rides
19890    /// along whole: a block gesture is not a run gesture, and what was selected
19891    /// before the press is still selected after it.
19892    #[test]
19893    fn a_block_gesture_carries_a_selection_and_a_heading_caret_too() {
19894        // No selection: the run gesture goes through the block door.
19895        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
19896        md.caret = md.source.find("brown").unwrap() + 2;
19897        md.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19898        assert_eq!(
19899            md.source,
19900            "<div data-size=\"large\">\n\nthe quick brown fox\n\n</div>\n"
19901        );
19902        assert_eq!(md.caret - md.source.find("brown").unwrap(), 2);
19903        assert_eq!(
19904            md.font_size_at_caret(),
19905            Some(FontSize::Step(SizeStep::Large))
19906        );
19907        md.set_font_size(Some(FontSize::Step(SizeStep::Small)));
19908        assert_eq!(
19909            md.font_size_at_caret(),
19910            Some(FontSize::Step(SizeStep::Small)),
19911            "the second press reached the same block"
19912        );
19913
19914        // A selection: alignment is the block's whatever is selected, and the
19915        // words stay selected.
19916        let mut sel = fmt_doc("the quick brown fox\n", Format::Markdown);
19917        let at = sel.source.find("brown").unwrap();
19918        sel.anchor = Some(at);
19919        sel.caret = at + 5;
19920        sel.set_alignment(Some(Align::Center));
19921        let now = sel.source.find("brown").unwrap();
19922        assert_eq!(sel.selection(), Some((now, now + 5)), "the words moved out");
19923
19924        // A heading: the content span starts past the `# `.
19925        let mut h = fmt_doc("# hi there\n\nbody\n", Format::Markdown);
19926        h.caret = h.source.find("there").unwrap() + 1;
19927        h.set_alignment(Some(Align::Right));
19928        assert_eq!(
19929            h.source,
19930            "<div class=\"right\">\n\n# hi there\n\n</div>\n\nbody\n"
19931        );
19932        assert_eq!(h.caret, h.source.find("there").unwrap() + 1);
19933        assert_eq!(h.alignment_at_caret(), Some(Align::Right));
19934    }
19935
19936    /// A djot document open in the rich view, with its map built as
19937    /// [`wysiwyg_doc`] builds a Markdown one's.
19938    fn wysiwyg_djot(body: &str) -> Doc {
19939        let mut d = fmt_doc(body, Format::Djot);
19940        d.view = View::Wysiwyg;
19941        d.build_visual(80);
19942        d
19943    }
19944
19945    /// Backspace at the start of a block whose presentation is spelled as
19946    /// hidden markup before it strips that presentation, the way Backspace at
19947    /// a heading's start strips its `#`. The ordinary delete fused djot's
19948    /// `{.center}` line onto the text and took the blank line a Markdown div
19949    /// needs between its tag and its paragraph.
19950    #[test]
19951    fn backspace_at_the_start_of_a_centred_paragraph_strips_its_attributes() {
19952        let mut md = wysiwyg_doc(
19953            "wys_attr_bksp",
19954            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
19955        );
19956        md.caret = md.source.find("hello").unwrap();
19957        md.backspace();
19958        assert_eq!(
19959            md.source, "above\n\nhello\n\nbelow\n",
19960            "the div is unwrapped"
19961        );
19962        assert_eq!(md.caret, 7, "the caret stays at the start of its text");
19963        md.backspace();
19964        assert_eq!(
19965            md.source, "above\nhello\n\nbelow\n",
19966            "the next press joins the paragraphs, as it always did"
19967        );
19968
19969        let mut dj = wysiwyg_djot("above\n\n{.center}\nhello\n\nbelow\n");
19970        dj.caret = dj.source.find("hello").unwrap();
19971        dj.backspace();
19972        assert_eq!(
19973            dj.source, "above\n\nhello\n\nbelow\n",
19974            "the attribute line goes"
19975        );
19976        assert_eq!(dj.caret, 7);
19977
19978        // A heading's own marker is the nearer hidden markup, and goes first;
19979        // the attributes are the next press's.
19980        let mut dj = wysiwyg_djot("{.center}\n# Title\n");
19981        dj.caret = dj.source.find("Title").unwrap();
19982        dj.backspace();
19983        assert_eq!(dj.source, "{.center}\nTitle\n", "the `#` first");
19984        dj.build_visual(80);
19985        dj.backspace();
19986        assert_eq!(dj.source, "Title\n", "then the attributes");
19987        assert_eq!(dj.caret, 0);
19988    }
19989
19990    /// A div around several blocks has no sole child for twig to unwrap, so
19991    /// at its first block the caret steps back to the stop before rather than
19992    /// taking the div apart; a later block has an ordinary paragraph above it
19993    /// and joins as any paragraph does.
19994    #[test]
19995    fn backspace_at_the_first_of_a_div_s_blocks_steps_back_and_a_later_one_joins() {
19996        let src = "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n";
19997        let mut d = wysiwyg_doc("wys_div_first", src);
19998        d.caret = d.source.find("hello").unwrap();
19999        d.backspace();
20000        assert_eq!(d.source, src, "nothing is deleted");
20001        assert_eq!(d.caret, 5, "the caret steps back to the end of `above`");
20002
20003        let mut d = wysiwyg_doc("wys_div_later", src);
20004        d.caret = d.source.find("world").unwrap();
20005        d.backspace();
20006        assert_eq!(
20007            d.source, "above\n\n<div class=\"center\">\n\nhello\nworld\n\n</div>\n",
20008            "a later block joins the one above it"
20009        );
20010    }
20011
20012    /// Backspace at the start of the paragraph after a Markdown div joins it
20013    /// into the div's last paragraph — the join any two paragraphs make, with
20014    /// the hidden `</div>` carried past the joined text. The ordinary delete
20015    /// took the newline under the tag, which drew nothing different, and the
20016    /// next press took the `>` and left the div unclosed.
20017    #[test]
20018    fn backspace_after_a_div_joins_the_paragraph_into_it() {
20019        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20020        let mut d = wysiwyg_doc("wys_div_join", src);
20021        d.caret = d.source.find("below").unwrap();
20022        d.backspace();
20023        assert_eq!(
20024            d.source,
20025            "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n"
20026        );
20027        assert_eq!(
20028            d.caret,
20029            d.source.find("below").unwrap(),
20030            "the caret stays at the start of the joined text"
20031        );
20032        d.build_visual(80);
20033        assert_eq!(
20034            d.alignment_at_caret(),
20035            Some(Align::Center),
20036            "and is centred now"
20037        );
20038        d.undo();
20039        assert_eq!(d.source, src, "one undo step");
20040
20041        // A list closes the div: the paragraph joins the last item's text,
20042        // under the item's continuation indent, inside the div.
20043        let src = "<div class=\"center\">\n\n- item\n\n</div>\n\nbelow\n";
20044        let mut d = wysiwyg_doc("wys_div_list", src);
20045        d.caret = d.source.find("below").unwrap();
20046        d.backspace();
20047        assert_eq!(
20048            d.source, "<div class=\"center\">\n\n- item\n  below\n\n</div>\n",
20049            "the paragraph joins the item"
20050        );
20051        assert_eq!(d.caret, d.source.find("below").unwrap());
20052
20053        // And where twig has nothing to join into — a code block above — the
20054        // caret steps back to the stop before, and nothing is deleted.
20055        let src = "```\ncode\n```\n\nbelow\n";
20056        let mut d = wysiwyg_doc("wys_code_then_para", src);
20057        d.caret = d.source.find("below").unwrap();
20058        d.backspace();
20059        assert_eq!(d.source, src, "nothing is deleted");
20060        assert!(
20061            d.caret < d.source.find("below").unwrap(),
20062            "the caret stepped back"
20063        );
20064    }
20065
20066    /// Backspace on a blank line collapses to the stop before it — but not
20067    /// across hidden markup, which that collapse deleted whole: a `</div>`,
20068    /// or a comment between two blocks. There the blank line goes alone, and
20069    /// the caret lands where the collapse would have put it.
20070    #[test]
20071    fn backspace_on_a_blank_line_after_hidden_markup_keeps_the_markup() {
20072        let mut d = wysiwyg_doc(
20073            "wys_div_blank",
20074            "<div class=\"center\">\n\nhello\n\n</div>\n\n\n\nbelow\n",
20075        );
20076        d.caret = d.source.find("below").unwrap() - 2; // the empty paragraph
20077        assert!(
20078            d.vmap.is_stop(d.caret),
20079            "the empty paragraph is a caret home"
20080        );
20081        d.backspace();
20082        assert_eq!(
20083            d.source, "<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
20084            "the blank line goes and the div stays closed"
20085        );
20086        assert_eq!(
20087            d.caret,
20088            d.source.find("hello").unwrap() + 5,
20089            "onto the end of `hello`"
20090        );
20091
20092        let mut d = wysiwyg_doc("wys_comment_blank", "above\n\n<!-- note -->\n\n\n\nbelow\n");
20093        d.caret = d.source.find("below").unwrap() - 2;
20094        assert!(d.vmap.is_stop(d.caret));
20095        d.backspace();
20096        assert_eq!(
20097            d.source, "above\n\n<!-- note -->\n\nbelow\n",
20098            "the comment stays"
20099        );
20100        assert_eq!(d.caret, 5);
20101    }
20102
20103    /// Backspace at the end of an attributed span steps inside its hidden
20104    /// closing tag the way it steps inside a `**`, and takes the span with
20105    /// its last letter. Before, the byte-step took the `>` of `</span>`,
20106    /// which left the paragraph unparseable: it vanished from the rich view,
20107    /// and the Backspace after that joined the next block into the wreck.
20108    #[test]
20109    fn backspace_walks_into_a_sized_span_and_takes_the_emptied_span_with_its_space() {
20110        let src = "above\n\nThis <span data-size=\"x-large\">is</span> a test\n\nTest 2\n";
20111        let mut d = wysiwyg_doc("wys_span_bs", src);
20112        d.caret = d.source.find("a test").unwrap() + 6;
20113        for _ in 0..7 {
20114            d.backspace();
20115        }
20116        assert_eq!(
20117            d.source,
20118            "above\n\nThis <span data-size=\"x-large\">is</span>\n\nTest 2\n"
20119        );
20120        d.backspace();
20121        assert_eq!(
20122            d.source, "above\n\nThis <span data-size=\"x-large\">i</span>\n\nTest 2\n",
20123            "the first Backspace after the tag takes the letter, not the `>`"
20124        );
20125        d.backspace();
20126        assert_eq!(
20127            d.source, "above\n\nThis \n\nTest 2\n",
20128            "the last letter takes the span with it"
20129        );
20130        assert_eq!(d.caret, 12, "the caret is where the letter was");
20131        d.backspace();
20132        assert_eq!(d.source, "above\n\nThis\n\nTest 2\n");
20133        assert_eq!(d.caret, 11);
20134        d.build_visual(80);
20135        assert!(
20136            d.vmap
20137                .rows
20138                .iter()
20139                .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "This"),
20140            "the paragraph is still drawn"
20141        );
20142    }
20143
20144    #[test]
20145    fn backspace_walks_into_a_djot_sized_span_too() {
20146        let mut d = wysiwyg_djot("This [is]{data-size=\"x-large\"}\n\nTest 2\n");
20147        d.caret = d.source.find("\n\nTest 2").unwrap();
20148        // The caret home at the paragraph's end is inside the span, before
20149        // its `]`: the map offers no stop after `]{…}`.
20150        d.build_visual(80);
20151        assert_eq!(d.vmap.stop_before(31), Some(8));
20152        d.caret = 8;
20153        d.backspace();
20154        assert_eq!(d.source, "This [i]{data-size=\"x-large\"}\n\nTest 2\n");
20155        d.backspace();
20156        assert_eq!(
20157            d.source, "This \n\nTest 2\n",
20158            "the attribute block outside the span goes with it"
20159        );
20160        d.backspace();
20161        assert_eq!(d.source, "This\n\nTest 2\n");
20162        assert_eq!(d.caret, 4);
20163    }
20164
20165    /// A span that is empty as the file was written has no stop of its own;
20166    /// Backspace reaching it from behind takes it with the character before
20167    /// it, the character the key looked aimed at.
20168    #[test]
20169    fn backspace_over_an_already_empty_span_takes_it_with_the_character_before() {
20170        let src = "This <span data-size=\"x-large\"></span> a test\n";
20171        let mut d = wysiwyg_doc("wys_span_empty", src);
20172        d.caret = d.source.find(" a test").unwrap();
20173        d.backspace();
20174        assert_eq!(d.source, "This a test\n");
20175        assert_eq!(d.caret, 4);
20176    }
20177
20178    /// The mirror: Delete in front of a span's opening tag takes its first
20179    /// letter, and the span with its last.
20180    #[test]
20181    fn delete_walks_into_a_sized_span_and_takes_the_span_with_its_last_letter() {
20182        let src = "This <span data-size=\"x-large\">is</span> a test\n";
20183        let mut d = wysiwyg_doc("wys_span_del", src);
20184        d.caret = 5;
20185        d.delete_forward();
20186        assert_eq!(
20187            d.source,
20188            "This <span data-size=\"x-large\">s</span> a test\n"
20189        );
20190        d.delete_forward();
20191        assert_eq!(d.source, "This  a test\n");
20192        assert_eq!(d.caret, 5);
20193        d.delete_forward();
20194        assert_eq!(d.source, "This a test\n");
20195        assert_eq!(d.caret, 5);
20196    }
20197
20198    /// The block version of the span's emptying rule. Centre a one-letter
20199    /// paragraph — Markdown spells that as a `<div>` around it — and
20200    /// Backspace the letter: the div goes with it, leaving a plain blank line
20201    /// the caret is at home on, in the incremental map and the from-scratch
20202    /// one alike. Before, the letter went alone; the emptied div drew a
20203    /// caret home only the stale map had, and the next Backspace collapsed
20204    /// the line and left `<div class="center">\n\n</div>` standing invisibly
20205    /// in the file.
20206    #[test]
20207    fn backspace_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20208        let mut d = wysiwyg_doc("wys_div_empty", "Try the toolbar.\n\nT\n");
20209        d.caret = d.source.len() - 1;
20210        d.set_alignment(Some(Align::Center));
20211        assert_eq!(
20212            d.source,
20213            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n"
20214        );
20215        d.backspace();
20216        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20217        assert_eq!(d.caret, 18, "on the blank line where the letter was");
20218        // The host rebuilds the map after every key; the spliced map and a
20219        // fresh one both give the line a caret home.
20220        d.build_visual_unwrapped();
20221        assert!(d.vmap.is_stop(18));
20222        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20223        d.backspace();
20224        assert_eq!(
20225            d.source, "Try the toolbar.\n",
20226            "then the blank line collapses"
20227        );
20228        assert_eq!(d.caret, 16);
20229
20230        // With a block after the div the blank line keeps a gap each side.
20231        let mut d = wysiwyg_doc(
20232            "wys_div_empty_mid",
20233            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n\nbelow\n",
20234        );
20235        d.caret = d.source.find("T\n").unwrap() + 1;
20236        d.backspace();
20237        assert_eq!(d.source, "Try the toolbar.\n\n\n\nbelow\n");
20238        assert_eq!(d.caret, 18);
20239        d.build_visual_unwrapped();
20240        assert!(d.vmap.is_stop(18));
20241        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20242    }
20243
20244    /// djot spells the same paragraph as a `{.center}` line above it, and
20245    /// twig has no node at all for that line once the paragraph is gone —
20246    /// so the line goes with the letter too.
20247    #[test]
20248    fn backspace_that_empties_a_centred_paragraph_takes_its_djot_attrs_line_too() {
20249        let mut d = fmt_doc("Try the toolbar.\n\nT\n", Format::Djot);
20250        d.build_visual(80);
20251        d.caret = d.source.len() - 1;
20252        d.set_alignment(Some(Align::Center));
20253        assert_eq!(d.source, "Try the toolbar.\n\n{.center}\nT\n");
20254        d.backspace();
20255        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20256        assert_eq!(d.caret, 18);
20257        d.build_visual(80);
20258        assert!(d.vmap.is_stop(18));
20259    }
20260
20261    /// The rule is for a block that would be no block: a div holding more
20262    /// keeps its tags, and an emptied heading is still a heading.
20263    #[test]
20264    fn emptying_a_paragraph_keeps_a_div_that_holds_more_and_a_heading_its_marker() {
20265        let mut d = wysiwyg_doc(
20266            "wys_div_more",
20267            "<div class=\"center\">\n\nText\n\nT\n\n</div>\n",
20268        );
20269        d.caret = d.source.find("T\n").unwrap() + 1;
20270        d.backspace();
20271        assert_eq!(d.source, "<div class=\"center\">\n\nText\n\n\n\n</div>\n");
20272        assert_eq!(d.caret, 28, "the blank line inside the div, as after Enter");
20273
20274        let mut d = wysiwyg_doc(
20275            "wys_div_heading",
20276            "<div class=\"center\">\n\n# T\n\n</div>\n",
20277        );
20278        d.caret = d.source.find("T\n").unwrap() + 1;
20279        d.backspace();
20280        assert_eq!(d.source, "<div class=\"center\">\n\n# \n\n</div>\n");
20281        assert_eq!(d.caret, 24);
20282        d.build_visual(80);
20283        assert!(
20284            d.vmap.is_stop(24),
20285            "the empty heading is still a caret home"
20286        );
20287    }
20288
20289    /// The mirror: Delete in front of the letter takes the div with it.
20290    #[test]
20291    fn delete_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20292        let mut d = wysiwyg_doc(
20293            "wys_div_empty_del",
20294            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n",
20295        );
20296        d.caret = d.source.find("T\n").unwrap();
20297        d.delete_forward();
20298        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20299        assert_eq!(d.caret, 18);
20300        d.build_visual(80);
20301        assert!(d.vmap.is_stop(18));
20302
20303        let mut d = fmt_doc("Try the toolbar.\n\n{.center}\nT\n", Format::Djot);
20304        d.build_visual(80);
20305        d.caret = d.source.find("T\n").unwrap();
20306        d.delete_forward();
20307        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20308        assert_eq!(d.caret, 18);
20309    }
20310
20311    /// Backspace at a block's start is twig's join, spelled per format — so
20312    /// the cases the one-newline delete got wrong come out right: a
20313    /// paragraph joins onto a heading's line, HTML's `</p><p>` goes as one,
20314    /// and a quote's prefix is written on the joined line.
20315    #[test]
20316    fn backspace_at_a_block_start_joins_it_the_format_s_way() {
20317        let mut d = wysiwyg_doc("wys_join_heading", "# Title\n\nbelow\n");
20318        d.caret = d.source.find("below").unwrap();
20319        d.backspace();
20320        assert_eq!(d.source, "# Title below\n", "onto the heading's line");
20321        assert_eq!(d.caret, d.source.find("below").unwrap());
20322        d.undo();
20323        assert_eq!(d.source, "# Title\n\nbelow\n", "one undo step");
20324
20325        let mut d = wysiwyg_doc("wys_join_quote", "> a\n\nb\n");
20326        d.caret = d.source.find('b').unwrap();
20327        d.backspace();
20328        assert_eq!(d.source, "> a\n> b\n", "into the quote, with its prefix");
20329        assert_eq!(d.caret, d.source.find('b').unwrap());
20330
20331        let mut h = fmt_doc("<p>above</p>\n<p class=\"x\">below</p>\n", Format::Html);
20332        h.view = View::Wysiwyg;
20333        h.build_visual(80);
20334        h.caret = h.source.find("below").unwrap();
20335        h.backspace();
20336        assert_eq!(
20337            h.source, "<p>above\nbelow</p>\n",
20338            "one paragraph, the tag gone whole"
20339        );
20340        assert_eq!(h.caret, h.source.find("below").unwrap());
20341    }
20342
20343    /// Delete at the end of a block's content is the same join aimed at the
20344    /// block after it, and the caret stays where the joined text now begins.
20345    #[test]
20346    fn delete_at_a_block_end_joins_the_next_block_into_it() {
20347        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20348        let mut d = wysiwyg_doc("wys_del_join", src);
20349        d.caret = d.source.find("hello").unwrap() + 5;
20350        d.delete_forward();
20351        assert_eq!(
20352            d.source, "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n",
20353            "below joins hello inside the div"
20354        );
20355        assert_eq!(
20356            d.caret,
20357            d.source.find("hello").unwrap() + 5,
20358            "the caret stays"
20359        );
20360
20361        let mut d = wysiwyg_doc("wys_del_join_head", "above\n\n# Title\n");
20362        d.caret = 5;
20363        d.delete_forward();
20364        assert_eq!(
20365            d.source, "above\nTitle\n",
20366            "the heading's marker goes with the join"
20367        );
20368        assert_eq!(d.caret, 5);
20369
20370        // A code block after the paragraph: nothing to join, the caret steps
20371        // forward onto the next stop and nothing is deleted.
20372        let src = "above\n\n```\ncode\n```\n";
20373        let mut d = wysiwyg_doc("wys_del_code", src);
20374        d.caret = 5;
20375        d.delete_forward();
20376        assert_eq!(d.source, src);
20377        assert!(d.caret > 5, "the caret stepped forward");
20378    }
20379
20380    // ── Text statistics ──────────────────────────────────────────────────────
20381
20382    /// The counts of `body`, from a document open in the WYSIWYG view — the
20383    /// shape every case below starts from.
20384    fn counts_of(name: &str, body: &str) -> TextCounts {
20385        doc_in(View::Wysiwyg, name, body).counts()
20386    }
20387
20388    #[test]
20389    fn counts_tally_plain_prose() {
20390        let c = counts_of(
20391            "counts_prose",
20392            "The quick brown fox jumps over the lazy dog.\n",
20393        );
20394        assert_eq!(
20395            c,
20396            TextCounts {
20397                words: 9,
20398                characters: 44,
20399                characters_without_spaces: 36,
20400                paragraphs: 1,
20401            }
20402        );
20403    }
20404
20405    #[test]
20406    fn counts_read_the_text_and_not_the_markup() {
20407        // The `**` are four bytes of source and no part of the word.
20408        assert_eq!(
20409            counts_of("counts_marks", "a **bold** word\n"),
20410            TextCounts {
20411                words: 3,
20412                characters: 11,
20413                characters_without_spaces: 9,
20414                paragraphs: 1,
20415            }
20416        );
20417        // A link is its label; the destination is plumbing, however long.
20418        assert_eq!(
20419            counts_of(
20420                "counts_link",
20421                "see [the label](https://example.com/a/b/c) here\n"
20422            ),
20423            TextCounts {
20424                words: 4,
20425                characters: 18,
20426                characters_without_spaces: 15,
20427                paragraphs: 1,
20428            }
20429        );
20430    }
20431
20432    #[test]
20433    fn counts_spend_nothing_on_a_picture() {
20434        // A block image renders as a `🖼 alt` placeholder — a picture, not a
20435        // sentence, and not a paragraph either.
20436        assert_eq!(
20437            counts_of("counts_image", "![a long caption](pic.png)\n"),
20438            TextCounts::default()
20439        );
20440        // And it adds nothing to the prose around it.
20441        assert_eq!(
20442            counts_of("counts_image_prose", "text\n\n![a long caption](pic.png)\n"),
20443            TextCounts {
20444                words: 1,
20445                characters: 4,
20446                characters_without_spaces: 4,
20447                paragraphs: 1,
20448            }
20449        );
20450    }
20451
20452    #[test]
20453    fn counts_spend_nothing_on_drawn_furniture() {
20454        // A thematic break is drawn, not written, and an empty paragraph has
20455        // nothing in it — neither is a paragraph of the document.
20456        assert_eq!(
20457            counts_of("counts_rule", "one\n\n---\n\ntwo\n"),
20458            TextCounts {
20459                words: 2,
20460                characters: 6,
20461                characters_without_spaces: 6,
20462                paragraphs: 2,
20463            }
20464        );
20465    }
20466
20467    #[test]
20468    fn counts_measure_characters_as_a_reader_does() {
20469        // Four Han characters (each its own word under UAX#29), one ZWJ emoji
20470        // family that is a single grapheme cluster, and two letters.
20471        let c = counts_of(
20472            "counts_graphemes",
20473            "你好世界 👩\u{200d}👩\u{200d}👧\u{200d}👦 ok\n",
20474        );
20475        assert_eq!(
20476            c,
20477            TextCounts {
20478                words: 5,
20479                characters: 9,
20480                characters_without_spaces: 7,
20481                paragraphs: 1,
20482            }
20483        );
20484    }
20485
20486    #[test]
20487    fn counts_take_a_code_block_as_one_paragraph() {
20488        let c = counts_of("counts_code", "```rust\nlet x = 1;\n\nlet y = 2;\n```\n");
20489        assert_eq!(
20490            c,
20491            TextCounts {
20492                words: 6,
20493                characters: 20,
20494                characters_without_spaces: 14,
20495                paragraphs: 1,
20496            }
20497        );
20498    }
20499
20500    #[test]
20501    fn counts_take_a_table_as_one_paragraph() {
20502        // The box-drawn borders and the column padding are the renderer's, not
20503        // the author's; the cells are what was written.
20504        let c = counts_of("counts_table", "| a b | c |\n| - | - |\n| d | e |\n");
20505        assert_eq!(
20506            c,
20507            TextCounts {
20508                words: 5,
20509                characters: 6,
20510                characters_without_spaces: 5,
20511                paragraphs: 1,
20512            }
20513        );
20514    }
20515
20516    #[test]
20517    fn counts_give_every_item_and_every_quoted_paragraph_its_own_paragraph() {
20518        let c = counts_of(
20519            "counts_blocks",
20520            "- one\n- two\n- three\n\n> first quoted\n>\n> second quoted\n",
20521        );
20522        assert_eq!(
20523            c,
20524            TextCounts {
20525                words: 7,
20526                characters: 36,
20527                characters_without_spaces: 34,
20528                paragraphs: 5,
20529            }
20530        );
20531    }
20532
20533    #[test]
20534    fn counts_leave_the_frontmatter_out() {
20535        // The WYSIWYG view doesn't render it and a writer didn't write it.
20536        let c = counts_of(
20537            "counts_frontmatter",
20538            "---\ntitle: Hidden\n---\n\nvisible words here\n",
20539        );
20540        assert_eq!(
20541            c,
20542            TextCounts {
20543                words: 3,
20544                characters: 18,
20545                characters_without_spaces: 16,
20546                paragraphs: 1,
20547            }
20548        );
20549    }
20550
20551    #[test]
20552    fn counts_of_an_empty_document_are_all_zero() {
20553        assert_eq!(counts_of("counts_empty", ""), TextCounts::default());
20554    }
20555
20556    /// UAX#29 puts a boundary at the hyphen, so a hyphenated compound is two
20557    /// words. Recorded rather than corrected: it is what the algorithm says,
20558    /// and what every other UAX#29 counter reports.
20559    #[test]
20560    fn counts_split_a_hyphenated_compound_in_two() {
20561        let c = counts_of("counts_hyphen", "well-known example\n");
20562        assert_eq!(c.words, 3);
20563        assert_eq!(c.characters, 18);
20564        // Punctuation on its own is no word, and an apostrophe doesn't split one.
20565        assert_eq!(counts_of("counts_punct", "don't ... stop\n").words, 2);
20566    }
20567
20568    #[test]
20569    fn selection_counts_measure_the_selection_and_nothing_without_one() {
20570        let src = "alpha beta\n\ngamma delta\n";
20571        let mut d = doc_in(View::Wysiwyg, "counts_sel", src);
20572        assert_eq!(d.selection_counts(), None, "no selection, no counts");
20573
20574        // From the `b` of `beta` to the end of `gamma`: two blocks clipped.
20575        d.select_range(6, 17);
20576        assert_eq!(
20577            d.selection_counts(),
20578            Some(TextCounts {
20579                words: 2,
20580                characters: 9,
20581                characters_without_spaces: 9,
20582                paragraphs: 2,
20583            })
20584        );
20585    }
20586
20587    /// The count is of the document, not of the window it is shown in — so
20588    /// ⌘E must not move it, and neither must a resize or an edit made with no
20589    /// map built at all.
20590    #[test]
20591    fn counts_agree_across_the_views() {
20592        let src =
20593            "# Head\n\nA **bold** word, a [label](http://x), and more.\n\n- item one\n- item two\n";
20594        let mut d = doc_in(View::Wysiwyg, "counts_views", src);
20595        let wysiwyg = d.counts();
20596        assert!(wysiwyg.words > 0 && wysiwyg.paragraphs == 4);
20597
20598        d.toggle_view();
20599        assert_eq!(d.view, View::Source);
20600        d.build_source();
20601        assert_eq!(d.counts(), wysiwyg, "the source view counts the same text");
20602
20603        // A narrower measure is a narrower window, not a shorter document.
20604        d.toggle_view();
20605        d.build_visual(24);
20606        assert_eq!(d.counts(), wysiwyg, "wrapping is not an input");
20607
20608        // And an edit made in the source view, with the visual map left stale,
20609        // still counts the document as it now stands.
20610        d.toggle_view();
20611        d.caret = d.source.len();
20612        d.insert("\n\ntail words\n");
20613        let after = d.counts();
20614        assert_eq!(after.paragraphs, wysiwyg.paragraphs + 1);
20615        assert_eq!(after.words, wysiwyg.words + 2);
20616    }
20617
20618    // ── math ─────────────────────────────────────────────────────────────────
20619
20620    #[test]
20621    fn a_formula_reveals_on_the_caret_line_in_the_hidden_modes() {
20622        // The rule the proposal states: a formula's content is its TeX, not
20623        // its picture, so it reveals on the caret's line in *every* mode —
20624        // and nothing else on that line does outside `Full`.
20625        let mut d = doc_in(
20626            View::Wysiwyg,
20627            "math_reveal",
20628            "*one* $x+y$ here\n\ntwo there\n",
20629        );
20630        d.set_inline_pictures(true);
20631        assert_eq!(d.markup_mode(), MarkupMode::None);
20632
20633        // Away from the formula's line: the atom, and no reveal at all.
20634        caret_at(&mut d, "two");
20635        assert!(
20636            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20637            "{:?}",
20638            drawn_rows(&d)
20639        );
20640        assert_eq!(d.vmap.math.len(), 1);
20641        assert_eq!(d.reveal_line(), None, "a line with no math keys nothing");
20642
20643        // On it: the formula is its source, the emphasis is still resolved.
20644        caret_at(&mut d, "here");
20645        assert!(
20646            drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"),
20647            "{:?}",
20648            drawn_rows(&d)
20649        );
20650        assert!(d.vmap.math.is_empty());
20651        assert_eq!(d.reveal_line(), Some(Reveal::math(0..16)));
20652
20653        // Off again, and the picture is back.
20654        caret_at(&mut d, "two");
20655        assert!(drawn_rows(&d).iter().any(|r| r == "one ∑ here"));
20656
20657        // The same in Shortcuts; and Full reveals the emphasis too.
20658        d.set_markup_mode(MarkupMode::Shortcuts);
20659        caret_at(&mut d, "here");
20660        assert!(drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"));
20661        d.set_markup_mode(MarkupMode::Full);
20662        caret_at(&mut d, "here");
20663        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20664    }
20665
20666    #[test]
20667    fn an_unrevealed_map_shows_the_carets_line_as_a_page_does() {
20668        let mut d = doc_in(
20669            View::Wysiwyg,
20670            "math_unrevealed",
20671            "*one* $x+y$ here\n\ntwo there\n",
20672        );
20673        d.set_inline_pictures(true);
20674        d.set_markup_mode(MarkupMode::Full);
20675        caret_at(&mut d, "here");
20676        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20677        let (screen, caret) = (d.visual_key(), d.caret);
20678
20679        // On paper: the delimiters hidden and the formula a picture, though
20680        // the caret has not moved off the line.
20681        d.set_unrevealed(true);
20682        d.build_visual(80);
20683        assert!(
20684            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20685            "{:?}",
20686            drawn_rows(&d)
20687        );
20688        assert_eq!(d.vmap.math.len(), 1);
20689        assert_eq!(d.caret, caret);
20690
20691        // Off again: the screen's map is back as it was, and the next build
20692        // reuses it rather than building it over.
20693        d.set_unrevealed(false);
20694        assert_eq!(d.visual_key(), screen);
20695        d.build_visual(80);
20696        assert_eq!(d.visual_key(), screen);
20697        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20698        assert_eq!(d.caret, caret);
20699    }
20700
20701    #[test]
20702    fn a_formula_closed_by_typing_reveals_at_once() {
20703        // The reveal line is decided from the last build's layout, which
20704        // across an edit is stale: the keystroke that closes a `$…$` asks a
20705        // layout that knew no math. `build_map` asks again once the new
20706        // layout is in, so the formula does not snap to its picture under
20707        // the caret.
20708        let mut d = doc_in(View::Wysiwyg, "math_typed", "say \n");
20709        d.set_inline_pictures(true);
20710        d.set_markup_mode(MarkupMode::Shortcuts);
20711        d.caret = 4;
20712        for ch in ["$", "x", "$"] {
20713            d.insert(ch);
20714            d.build_visual(80);
20715        }
20716        assert_eq!(d.source, "say $x$\n");
20717        assert_eq!(
20718            drawn_rows(&d)[0],
20719            "say $x$",
20720            "source, not a picture, under the caret"
20721        );
20722        assert!(d.vmap.math.is_empty());
20723        // Leaving the line folds it — there is only one line, so add one.
20724        d.newline();
20725        d.insert("more");
20726        d.build_visual(80);
20727        assert_eq!(drawn_rows(&d)[0], "say ∑");
20728        assert_eq!(d.vmap.math.len(), 1);
20729        // And deleting the formula while revealed drops the reveal with it.
20730        d.caret = 7;
20731        d.build_visual(80);
20732        assert_eq!(drawn_rows(&d)[0], "say $x$");
20733        for _ in 0..3 {
20734            d.backspace();
20735        }
20736        d.build_visual(80);
20737        assert_eq!(d.source, "say \n\nmore\n");
20738        assert_eq!(d.reveal_line(), None);
20739    }
20740
20741    #[test]
20742    fn a_display_block_is_edited_where_it_stands() {
20743        let mut d = doc_in(
20744            View::Wysiwyg,
20745            "math_block",
20746            "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n",
20747        );
20748        caret_at(&mut d, "end");
20749        assert_eq!(
20750            drawn_rows(&d),
20751            vec!["intro", "", "∑ \\int_0^1 x", "", "end"]
20752        );
20753        // Up from `end` lands on the placeholder, whose glyphs all carry the
20754        // block's start — which is on its `$$` line, so the block reveals.
20755        d.move_up(false);
20756        d.build_visual(80);
20757        assert_eq!(d.caret, 7);
20758        assert_eq!(
20759            drawn_rows(&d),
20760            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
20761        );
20762        // Down walks the source lines, still revealed; typing edits the TeX.
20763        d.move_down(false);
20764        d.build_visual(80);
20765        assert_eq!(d.caret, 10);
20766        d.move_end(false);
20767        d.insert("^2");
20768        d.build_visual(80);
20769        assert_eq!(d.source, "intro\n\n$$\n\\int_0^1 x^2\n$$\n\nend\n");
20770        assert_eq!(drawn_rows(&d)[3], "\\int_0^1 x^2");
20771        // Out below, and it folds to the placeholder with the new TeX.
20772        d.move_down(false);
20773        d.move_down(false);
20774        d.move_down(false);
20775        d.build_visual(80);
20776        assert_eq!(drawn_rows(&d)[2], "∑ \\int_0^1 x^2");
20777        assert_eq!(d.vmap.math[0].tex, "\n\\int_0^1 x^2\n");
20778    }
20779
20780    #[test]
20781    fn set_math_rows_reserves_filler_rows_by_tex() {
20782        let mut d = doc_in(View::Wysiwyg, "math_rows", "$$\nx\n$$\n\nend\n");
20783        caret_at(&mut d, "end");
20784        assert_eq!(d.vmap.math[0].rows_span, 0..1);
20785        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
20786        d.build_visual(80);
20787        assert_eq!(d.vmap.math[0].rows_span, 0..3);
20788        assert_eq!(drawn_rows(&d)[..3], ["∑ x", "", ""]);
20789        // Cheap when nothing changed.
20790        let key = d.visual_key();
20791        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
20792        d.build_visual(80);
20793        assert_eq!(d.visual_key(), key);
20794    }
20795
20796    #[test]
20797    fn a_dollar_typed_in_shortcuts_authors_math() {
20798        let mut d = doc_in(View::Wysiwyg, "math_dollar_sc", "\n");
20799        d.set_markup_mode(MarkupMode::Shortcuts);
20800        d.caret = 0;
20801        d.insert("$x$");
20802        assert_eq!(d.source, "$x$\n");
20803        d.caret = 1;
20804        assert_eq!(d.breadcrumb(), "doc › para › inline_math");
20805
20806        // `None` keeps typed syntax literal, and under the math extension a
20807        // `$` is syntax: twig escapes it, and the paragraph stays text.
20808        let mut d = doc_in(View::Wysiwyg, "math_dollar_none", "\n");
20809        assert_eq!(d.markup_mode(), MarkupMode::None);
20810        d.caret = 0;
20811        d.insert("$x$");
20812        assert_eq!(d.source, "\\$x\\$\n");
20813        d.caret = 2;
20814        assert_eq!(d.breadcrumb(), "doc › para › str");
20815    }
20816
20817    #[test]
20818    fn counts_see_a_formula_as_a_picture_however_it_is_written() {
20819        let c = counts_of(
20820            "counts_math",
20821            "the sum $\\sum_i x_i$ and\n\n$$\ny = mx + c\n$$\n",
20822        );
20823        // `the sum … and` is three words; neither formula counts, and the
20824        // display block is not a paragraph of text.
20825        assert_eq!(c.words, 3);
20826        assert_eq!(c.paragraphs, 1);
20827    }
20828}