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 fences at the item's content column and keeps
6059    /// the marker (a task item's box too) on the opening fence's line, so the
6060    /// block stays the item's; unfencing puts the marker back on the text.
6061    /// What twig still refuses — an AsciiDoc item's own first line — is
6062    /// reported rather than worked around.
6063    pub fn toggle_code_block(&mut self) {
6064        // The read-only gate — this door reaches twig without the splice.
6065        if self.read_only {
6066            return;
6067        }
6068        if self.refuse_unsupported("code block", Gesture::ToggleCodeBlock) {
6069            return;
6070        }
6071        let selected = self.selection();
6072        // The caret at a code block's rows resolves to its *content*, and twig
6073        // finds the block from any offset inside its span — but a caret parked
6074        // on the closing fence's own line end is past it, so the block's start
6075        // is handed over whenever the caret is in one at all.
6076        let (start, end) = match selected {
6077            Some(range) => range,
6078            None => match self.code_block_start_at_caret() {
6079                Some(start) => (start, start),
6080                None => match self.block_offset_for_caret() {
6081                    Some(off) => (off, off),
6082                    None => return self.open_empty_code_block(),
6083                },
6084            },
6085        };
6086        self.record_caret();
6087        match self.editor.toggle_code_block(start, end, None) {
6088            Ok(change) => {
6089                // Read the caret's place out of the *pre-edit* source, before
6090                // `refresh` swaps it out — and how many lines the region held,
6091                // which is what says whether a fence line went in above the
6092                // caret's line or came off it.
6093                let place = selected
6094                    .is_none()
6095                    .then(|| self.caret_line_tail(&change.old));
6096                let old_lines = self.source[change.old.clone()].matches('\n').count();
6097                self.last_edit_kind = None; // structural edit is its own undo step
6098                self.refresh();
6099                match place {
6100                    // From a selection: keep the block selected, so a second
6101                    // press reverses the first (twig unfences from any offset in
6102                    // the fence's span, the region's start included).
6103                    None => {
6104                        self.anchor = Some(change.new.start);
6105                        self.caret = change.new.end;
6106                    }
6107                    // From a caret: the same line, the same distance from its
6108                    // end, shifted by the opening fence that was written above
6109                    // it (or peeled off). Dedenting an indented block keeps the
6110                    // lines one-to-one, and shifts nothing.
6111                    Some((line, tail)) => {
6112                        let new_lines = self.source[change.new.start.min(self.source.len())
6113                            ..change.new.end.min(self.source.len())]
6114                            .matches('\n')
6115                            .count();
6116                        let line = match new_lines.cmp(&old_lines) {
6117                            std::cmp::Ordering::Greater => line + 1,
6118                            std::cmp::Ordering::Less => line.saturating_sub(1),
6119                            std::cmp::Ordering::Equal => line,
6120                        };
6121                        self.anchor = None;
6122                        self.caret = self.line_tail_offset(&change.new, (line, tail));
6123                    }
6124                }
6125                self.dirty = self.source != self.clean_source;
6126                self.status = None;
6127                self.clamp_caret();
6128                self.record_caret();
6129            }
6130            Err(e) => self.status = Some(format!("code block: {e}")),
6131        }
6132    }
6133
6134    /// Write an empty fenced block on the blank line the caret stands on, and
6135    /// put the caret on the empty line inside it — the half of
6136    /// [`toggle_code_block`](Self::toggle_code_block) that is leaf's, because
6137    /// twig reports `NotFound` for a range no block covers.
6138    ///
6139    /// Inside a quote the fence lines and the empty line keep the quote's
6140    /// prefix, as twig's own fencing does. A blank line goes in on whichever
6141    /// side has text against it, since a fence may interrupt a paragraph in
6142    /// Markdown but a block standing tight against its neighbours is not the
6143    /// document any editor writes.
6144    fn open_empty_code_block(&mut self) {
6145        let caret = self.caret.min(self.source.len());
6146        let prefix = self.quote_prefix_at(caret);
6147        let line_start = self.source[..caret].rfind('\n').map_or(0, |i| i + 1);
6148        let line_end = self.source[caret..]
6149            .find('\n')
6150            .map_or(self.source.len(), |i| caret + i);
6151        let prev_blank = line_start == 0
6152            || self.source[..line_start - 1]
6153                .rsplit('\n')
6154                .next()
6155                .is_some_and(|l| l.trim_start_matches(['>', ' ']).is_empty());
6156        let next_blank = line_end >= self.source.len()
6157            || self.source[line_end + 1..]
6158                .split('\n')
6159                .next()
6160                .is_some_and(|l| l.trim_start_matches(['>', ' ']).is_empty());
6161        // A blank line inside a quote is a bare `>`: the space after it is
6162        // the content's, and there is none.
6163        let blank = prefix.trim_end();
6164        let mut text = String::new();
6165        if !prev_blank {
6166            text.push_str(blank);
6167            text.push('\n');
6168        }
6169        text.push_str(&prefix);
6170        text.push_str("```\n");
6171        text.push_str(&prefix);
6172        let inside = text.len();
6173        text.push('\n');
6174        text.push_str(&prefix);
6175        text.push_str("```");
6176        if !next_blank {
6177            text.push('\n');
6178            text.push_str(blank);
6179        }
6180        // Over whatever the blank line held (its quote prefix, trailing
6181        // spaces), so the block's own prefix is the one twig will read back.
6182        let at = line_start;
6183        if !self.splice(at, line_end, &text, EditKind::Other) {
6184            return;
6185        }
6186        self.caret = at + inside;
6187        self.anchor = None;
6188        self.clamp_caret();
6189        self.record_caret();
6190    }
6191
6192    /// Whether the caret stands in a code block, fenced or indented — what
6193    /// lights the Code Block button. Wider than
6194    /// [`caret_in_fenced_code`](Self::caret_in_fenced_code), which asks the
6195    /// narrower question a language prompt needs.
6196    pub fn caret_in_code_block(&mut self) -> bool {
6197        self.code_block_start_at_caret().is_some()
6198    }
6199
6200    /// Whether the caret stands anywhere inside a block quote, however deep —
6201    /// what lights the Block Quote button. A quote is a container rather than
6202    /// a block kind, so this is true alongside a heading or a code block, not
6203    /// instead of one.
6204    pub fn caret_in_blockquote(&mut self) -> bool {
6205        let off = self.caret.min(self.source.len());
6206        // A quote's span stops short of its closing newline, so the end of its
6207        // last line is `span.end` itself, and has to count.
6208        self.nodes()
6209            .into_iter()
6210            .any(|n| n.kind == Kind::BlockQuote && n.span.start <= off && off <= n.span.end)
6211    }
6212
6213    // ── Task list items ──────────────────────────────────────────────────────
6214    // The checkbox in `- [x] done`. twig owns all three gestures: the box is
6215    // inline content of the item's first paragraph rather than part of its
6216    // marker, so adding or removing one must leave the item's continuation
6217    // indentation alone, and an item inside a quote is found past the quote
6218    // markers. leaf names the gesture and the offset; the spelling is twig's.
6219
6220    /// Whether the list item at the caret carries a checkbox, and which way it
6221    /// faces — `Some(true)` ticked, `Some(false)` empty, `None` for a plain list
6222    /// item or no item at all. What a toolbar reads to light its checkbox button.
6223    pub fn task_checked_at_caret(&mut self) -> Option<bool> {
6224        self.task_checked_at(self.caret)
6225    }
6226
6227    /// [`task_checked_at_caret`](Self::task_checked_at_caret) for an arbitrary
6228    /// offset — what a frontend asks before deciding a click landed on a box.
6229    pub fn task_checked_at(&mut self, offset: usize) -> Option<bool> {
6230        self.innermost_list_item(offset.min(self.source.len()))?
6231            .checked
6232    }
6233
6234    /// Tick or untick the task item at the caret (the checkbox's keyboard half).
6235    /// A no-op with a reported reason when the caret is in no task item — minting
6236    /// a box here is [`toggle_task_item`](Self::toggle_task_item)'s job.
6237    pub fn toggle_task_checked(&mut self) {
6238        self.toggle_task_at(self.caret);
6239    }
6240
6241    /// Tick or untick the task item covering `offset` — what a *click* on a
6242    /// rendered checkbox is. Separate from the caret form because a click carries
6243    /// its own offset and must not first move the caret there: ticking a box
6244    /// three paragraphs away should not take the cursor with it.
6245    pub fn toggle_task_at(&mut self, offset: usize) {
6246        // The read-only gate — this door reaches twig without the splice.
6247        if self.read_only {
6248            return;
6249        }
6250        if self.refuse_unsupported("task", Gesture::ToggleTaskChecked) {
6251            return;
6252        }
6253        let offset = offset.min(self.source.len());
6254        self.record_caret();
6255        match self.editor.toggle_task_checked(offset) {
6256            Ok(_) => self.after_task_edit(),
6257            Err(e) => self.status = Some(format!("task: {e}")),
6258        }
6259    }
6260
6261    /// Give the list item at the caret a checkbox, or take its checkbox away —
6262    /// the gesture that converts between a plain bullet and a task. A new box
6263    /// arrives unticked.
6264    ///
6265    /// Outside a list the caret's block becomes a bullet first, and the box
6266    /// goes on the new item — one undo step. twig's gesture only converts an
6267    /// item that is already there, and a Checklist button that did nothing on
6268    /// a paragraph read as broken.
6269    pub fn toggle_task_item(&mut self) {
6270        // The read-only gate — this door reaches twig without the splice.
6271        if self.read_only {
6272            return;
6273        }
6274        if self.refuse_unsupported("task", Gesture::ToggleTaskItem) {
6275            return;
6276        }
6277        if self
6278            .innermost_list_item(self.caret.min(self.source.len()))
6279            .is_none()
6280        {
6281            if self.refuse_unsupported(
6282                "task",
6283                Gesture::ToggleBlockContainer(BlockContainerKind::BulletList),
6284            ) {
6285                return;
6286            }
6287            self.begin_undo_group();
6288            self.toggle_list(false);
6289            if self
6290                .innermost_list_item(self.caret.min(self.source.len()))
6291                .is_some()
6292            {
6293                self.box_item_at_caret();
6294            }
6295            self.end_undo_group();
6296            return;
6297        }
6298        self.box_item_at_caret();
6299    }
6300
6301    /// twig's half of [`toggle_task_item`](Self::toggle_task_item): the box on
6302    /// the item the caret is already in.
6303    fn box_item_at_caret(&mut self) {
6304        let caret = self.caret.min(self.source.len());
6305        self.record_caret();
6306        match self.editor.toggle_task_item(caret) {
6307            Ok(_) => self.after_task_edit(),
6308            Err(e) => self.status = Some(format!("task: {e}")),
6309        }
6310    }
6311
6312    /// Settle after a task gesture. The caret rides its old byte offset and is
6313    /// clamped back in: a box is three or four bytes on the item's first line, so
6314    /// text after it shifts by that much at most, and `clamp_caret` lands it on a
6315    /// real stop either way.
6316    fn after_task_edit(&mut self) {
6317        self.last_edit_kind = None;
6318        self.refresh();
6319        self.anchor = None;
6320        self.dirty = self.source != self.clean_source;
6321        self.status = None;
6322        self.clamp_caret();
6323        self.record_caret();
6324    }
6325
6326    // ── Tables ───────────────────────────────────────────────────────────────
6327    // A table is a grid, and twig edits it as one — add/remove/move a row or
6328    // column, set a column's alignment — re-spelling the whole table in a single
6329    // splice. Every gesture is anchored at the caret's cell. leaf just names the
6330    // gesture and re-reads the result; the whole table's numbering, borders, and
6331    // delimiter are twig's to keep straight.
6332
6333    /// Whether the caret is inside a table — what a frontend asks to enable or
6334    /// disable its table controls.
6335    ///
6336    /// An HTML `<table>` still answers `true`: the caret really is in a table,
6337    /// and the reason the grid controls stay dark there is
6338    /// [`Capabilities::table`], which is a fact about the document's format
6339    /// rather than about the caret. A frontend needs both.
6340    pub fn caret_in_table(&mut self) -> bool {
6341        let caret = self.caret.min(self.source.len());
6342        self.editor
6343            .ancestors_at(caret)
6344            .map(|c| c.into_iter().any(|m| m.kind == Kind::Table))
6345            .unwrap_or(false)
6346    }
6347
6348    /// One grid op, guarded and settled — the shared body of the seven below.
6349    ///
6350    /// The guard is why this exists rather than seven copies of the same three
6351    /// lines, and it is the one guard leaf cannot delegate to twig. The table
6352    /// editor is the gesture family that consults no `Syntax` table (it spells a
6353    /// grid, not a delimiter) and therefore the one twig's `Format::supports`
6354    /// deliberately has no variant for: handed an HTML `<table>` it rebuilds the
6355    /// grid as a *pipe table* and reports success, swapping the element out for
6356    /// `| a | b |` and taking the rest of the document's markup with it. Nothing
6357    /// downstream could tell that from a successful edit — the splice is real,
6358    /// the reparse succeeds, `dirty` is honest — which is what makes it worth
6359    /// stopping at the door rather than detecting after the fact. See
6360    /// [`spells_pipe_tables`].
6361    fn table_op(
6362        &mut self,
6363        what: &str,
6364        op: impl FnOnce(&mut Editor, usize) -> Result<(), twig::Error>,
6365    ) {
6366        if self.refuse_unless(what, spells_pipe_tables(self.format)) {
6367            return;
6368        }
6369        self.record_caret();
6370        let at = self.caret;
6371        let r = op(&mut self.editor, at);
6372        self.apply_table(r, what);
6373    }
6374
6375    /// Insert an empty row below (`below`) or above the caret's row.
6376    pub fn table_insert_row(&mut self, below: bool) {
6377        self.table_op("table row", |e, at| e.table_insert_row(at, below));
6378    }
6379
6380    /// Delete the caret's row (not the header, not the last body row).
6381    pub fn table_delete_row(&mut self) {
6382        self.table_op("table row", |e, at| e.table_delete_row(at));
6383    }
6384
6385    /// Insert an empty column right (`right`) or left of the caret's column.
6386    pub fn table_insert_column(&mut self, right: bool) {
6387        self.table_op("table column", |e, at| e.table_insert_column(at, right));
6388    }
6389
6390    /// Delete the caret's column (unless it is the only one).
6391    pub fn table_delete_column(&mut self) {
6392        self.table_op("table column", |e, at| e.table_delete_column(at));
6393    }
6394
6395    /// Set the caret's column to `alignment`.
6396    pub fn table_set_alignment(&mut self, alignment: Alignment) {
6397        self.table_op("table alignment", |e, at| {
6398            e.table_set_alignment(at, alignment)
6399        });
6400    }
6401
6402    /// Move the caret's row one place down (`down`) or up, within the body rows.
6403    pub fn table_move_row(&mut self, down: bool) {
6404        self.table_op("table row", |e, at| e.table_move_row(at, down));
6405    }
6406
6407    /// Move the caret's column one place right (`right`) or left.
6408    pub fn table_move_column(&mut self, right: bool) {
6409        self.table_op("table column", |e, at| e.table_move_column(at, right));
6410    }
6411
6412    /// Settle the caret and document flags after a table op (or report its
6413    /// error). twig re-spells the whole table, so the caret rides its old byte
6414    /// offset and is clamped back into the rebuilt bytes — near enough to where
6415    /// it was, since the op preserves the cells' content and order around it.
6416    fn apply_table(&mut self, result: Result<(), twig::Error>, what: &str) {
6417        match result {
6418            Ok(()) => {
6419                self.last_edit_kind = None;
6420                self.refresh();
6421                self.anchor = None;
6422                self.clamp_caret();
6423                self.dirty = self.source != self.clean_source;
6424                self.status = None;
6425                self.record_caret();
6426            }
6427            Err(e) => self.status = Some(format!("{what}: {e}")),
6428        }
6429    }
6430
6431    /// One `toggle_block_container` over the block-level target.
6432    ///
6433    /// leaf says *where*; twig decides everything else — which blocks the range
6434    /// covers, whether that means wrapping, unwrapping, nesting or converting,
6435    /// and how this document's format spells the prefix. The rule that a
6436    /// container only comes off when the range covers every block it holds is
6437    /// what the re-anchoring below is built around.
6438    fn toggle_container(&mut self, kind: BlockContainerKind) {
6439        // The read-only gate — this door reaches twig without the splice.
6440        if self.read_only {
6441            return;
6442        }
6443        if self.refuse_unsupported(&format!("{kind:?}"), Gesture::ToggleBlockContainer(kind)) {
6444            return;
6445        }
6446        let selected = self.selection();
6447        // A blank line holds no block, and twig opens an *empty* container on one
6448        // — since 3.2.0; it used to decline the range with `NotFound`, which is
6449        // why this used to lend it a scratch paragraph to wrap. Worth knowing
6450        // here because the line-for-line caret mapping below cannot describe it:
6451        // opening one under a paragraph writes the blank line the format needs
6452        // above the marker too, so the rewritten region has a line the old one
6453        // didn't, and "the same line, the same distance from its end" lands on
6454        // that new blank instead of in the container.
6455        let opened_empty = selected.is_none() && self.block_offset_for_caret().is_none();
6456        // Without a selection the target is the caret's own block, resolved the
6457        // way `set_block` resolves it — a caret at a line end sits at the doc
6458        // level and has to be nudged back onto the block it looks like it's in.
6459        // An empty range is enough: twig widens to the whole lines it touches.
6460        let (start, end) = match selected {
6461            Some(range) => range,
6462            None => {
6463                let off = self.block_offset_for_caret().unwrap_or(self.caret);
6464                (off, off)
6465            }
6466        };
6467        self.record_caret();
6468        match self.editor.toggle_block_container(start, end, kind) {
6469            Ok(change) => {
6470                // Read the caret's place out of the *pre-edit* source, before
6471                // `refresh` swaps that source out from under it.
6472                let place = (selected.is_none() && !opened_empty)
6473                    .then(|| self.caret_line_tail(&change.old));
6474                self.last_edit_kind = None; // structural edit is its own undo step
6475                self.refresh();
6476                match place {
6477                    // Both land the caret at the far end of what twig wrote, and
6478                    // differ only in what they leave selected.
6479                    //
6480                    // From a selection: select what the container now holds, the
6481                    // way `toggle` keeps its marked region selected — and for a
6482                    // stronger reason than symmetry: a container comes *off* only
6483                    // a range covering every block it holds, so a selection left
6484                    // on its old bytes (now short by a prefix per line) would nest
6485                    // on the second press instead of reversing the first.
6486                    //
6487                    // From a blank line: nothing to select, and the end of the
6488                    // region is exactly past the bare `> ` / `- ` twig wrote —
6489                    // the caret standing inside the container that was asked for.
6490                    None => {
6491                        self.anchor = (!opened_empty).then_some(change.new.start);
6492                        self.caret = change.new.end;
6493                    }
6494                    Some(place) => {
6495                        self.anchor = None;
6496                        self.caret = self.line_tail_offset(&change.new, place);
6497                    }
6498                }
6499                self.dirty = self.source != self.clean_source;
6500                self.status = None;
6501                self.clamp_caret();
6502                self.record_caret();
6503            }
6504            Err(e) => self.status = Some(format!("{kind:?}: {e}")),
6505        }
6506    }
6507
6508    /// The caret's place inside the region a container toggle is rewriting, in
6509    /// the only terms the rewrite preserves: which of the region's lines it sits
6510    /// on, and how many bytes of that line lie ahead of it.
6511    ///
6512    /// A container's markup goes in at column 0 and never touches what follows
6513    /// on the line, so that pair survives the edit exactly where a byte offset
6514    /// does not — a caret left on its old offset slides back by one prefix per
6515    /// line above it, which on a hard-wrapped paragraph parks it *inside* the
6516    /// `> ` it just asked for.
6517    fn caret_line_tail(&self, old: &std::ops::Range<usize>) -> (usize, usize) {
6518        let caret = self.caret.clamp(old.start, old.end);
6519        let line = self.source[old.start..caret].matches('\n').count();
6520        let end = self.source[caret..old.end]
6521            .find('\n')
6522            .map_or(old.end, |i| caret + i);
6523        (line, end - caret)
6524    }
6525
6526    /// [`caret_line_tail`](Self::caret_line_tail) undone against the rewritten
6527    /// region: the offset `tail` bytes back from the end of the region's `line`.
6528    ///
6529    /// Both walks are clamped rather than trusted, because the one op that does
6530    /// *not* keep a region's lines one-to-one is stripping a list — twig blows
6531    /// the items back apart with blank lines between them — and a caret landing
6532    /// on the nearest line of the right item beats one landing out of the region
6533    /// entirely.
6534    fn line_tail_offset(
6535        &self,
6536        new: &std::ops::Range<usize>,
6537        (line, tail): (usize, usize),
6538    ) -> usize {
6539        let region = &self.source[new.start.min(self.source.len())..new.end.min(self.source.len())];
6540        let mut start = 0;
6541        for _ in 0..line {
6542            match region[start..].find('\n') {
6543                Some(i) => start += i + 1,
6544                None => break,
6545            }
6546        }
6547        let end = region[start..]
6548            .find('\n')
6549            .map_or(region.len(), |i| start + i);
6550        new.start + end.saturating_sub(tail).max(start)
6551    }
6552
6553    /// Link the selection to `destination` — the toolbar's Link button. With no
6554    /// selection it acts at the caret, which re-points a link the caret is
6555    /// already standing in (twig replaces an existing link's destination and
6556    /// keeps its text) and otherwise spells a link that has no text of its own:
6557    /// an autolink (`<https://x.dev>`) where the destination is one, and
6558    /// `[destination](destination)` where it isn't.
6559    ///
6560    /// `destination` reaches twig raw. Escaping it is format knowledge and the
6561    /// two formats genuinely disagree — Markdown ends a destination at the first
6562    /// space and moves it into `<…>`, djot reads that `<…>` as part of the URL
6563    /// itself — so the side holding the document is the side that gets to spell
6564    /// it. A destination twig can't carry at all (one with a newline) comes back
6565    /// as an error rather than a quietly rewritten URL.
6566    pub fn insert_link(&mut self, destination: &str) {
6567        if self.read_only || self.refuse_unsupported("link", Gesture::InsertLink) {
6568            return;
6569        }
6570        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6571        self.record_caret();
6572        match self.editor.insert_link(start, end, destination) {
6573            Ok(change) => {
6574                self.last_edit_kind = None;
6575                self.refresh();
6576                match self.link_text_span(change.new.start) {
6577                    // A link with text of its own: select it, so typing replaces
6578                    // a `[dest](dest)`'s stand-in label and a second press
6579                    // re-points what the first one linked.
6580                    Some(text) => {
6581                        self.anchor = (text.start != text.end).then_some(text.start);
6582                        self.caret = text.end;
6583                    }
6584                    // An autolink is finished the moment it's written — its text
6585                    // *is* the URL. Leaving it selected would aim the next press
6586                    // at the one shape twig still wraps instead of re-points.
6587                    None => {
6588                        self.anchor = None;
6589                        self.caret = change.new.end;
6590                    }
6591                }
6592                self.dirty = self.source != self.clean_source;
6593                self.status = None;
6594                self.clamp_caret();
6595                self.record_caret();
6596            }
6597            Err(e) => self.status = Some(format!("link: {e}")),
6598        }
6599    }
6600
6601    /// Insert a block-level image at the caret: `![alt](destination)`. Any
6602    /// selection becomes the alt text (so "select a caption, insert image" labels
6603    /// it); with no selection, `alt` is used — empty for none. The caret lands
6604    /// just past the inserted image.
6605    ///
6606    /// Both halves go through twig (`insert_literal` for the alt text,
6607    /// `insert_image` for the image), so neither is spelled here. That used to be a
6608    /// `format!`, and it was wrong the first time an app inserted a real filename:
6609    /// Markdown ends a destination at the first space, so `![](my photo.png)` is
6610    /// not an image at all — and the fix is per-format, since moving into the
6611    /// `<…>` form is exactly wrong for Djot, where `<…>` becomes the URL itself.
6612    pub fn insert_image(&mut self, destination: &str, alt: &str) {
6613        if self.read_only || self.refuse_unsupported("image", Gesture::InsertImage) {
6614            return;
6615        }
6616        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6617        self.record_caret();
6618        // With no selection and an explicit `alt`, the alt text has to exist in the
6619        // document before it can be the image's — and it is raw caller input, so
6620        // it goes in through `insert_literal`, which escapes it for the format
6621        // rather than letting a `]` in someone's caption close the image early.
6622        let (start, end) = if start == end && !alt.is_empty() {
6623            match self.editor.insert_literal(start, alt) {
6624                Ok(change) => (change.new.start, change.new.end),
6625                Err(e) => {
6626                    self.status = Some(format!("image: {e}"));
6627                    return;
6628                }
6629            }
6630        } else {
6631            (start, end)
6632        };
6633        match self.editor.insert_image(start, end, destination) {
6634            Ok(change) => {
6635                self.last_edit_kind = None;
6636                self.refresh();
6637                // Just past the image, nothing selected — where a caret belongs
6638                // after inserting one.
6639                self.anchor = None;
6640                self.caret = change.new.end;
6641                self.dirty = self.source != self.clean_source;
6642                self.status = None;
6643                self.clamp_caret();
6644                self.record_caret();
6645            }
6646            Err(e) => self.status = Some(format!("image: {e}")),
6647        }
6648    }
6649
6650    /// Insert a block-level image, video, or audio at the caret. The image case
6651    /// is [`insert_image`](Self::insert_image); video and audio are spelled as
6652    /// HTML elements, which is the only spelling Markdown and Djot have for them:
6653    ///
6654    /// ```text
6655    /// <video src="clip.mp4" controls>alt</video>
6656    /// <audio src="take.mp3" controls>alt</audio>
6657    /// ```
6658    ///
6659    /// HTML rather than a `::video{…}` directive deliberately. A directive means
6660    /// something only to an app that knows the vocabulary, so the document would
6661    /// read as literal punctuation everywhere else; `<video>` is what every other
6662    /// renderer already understands, and what leaf's own reader picks back up
6663    /// through `html_elements` promotion (see [`parse_extensions`]).
6664    ///
6665    /// The one-line spelling needs twig ≥ 2.5.1, which widened CommonMark's
6666    /// HTML-block tag list to cover `<video>`/`<audio>`/`<picture>` under
6667    /// `html_elements`. Before that only the multi-line form parsed as a block at
6668    /// all, and this wrote three lines to work around it.
6669    ///
6670    /// `controls` is always written: a player with no transport is a still frame
6671    /// the reader can't do anything with. Any selection becomes the element's
6672    /// fallback text, exactly as it becomes an image's alt.
6673    ///
6674    /// The same verbatim-insertion caveat as [`insert_image`](Self::insert_image)
6675    /// applies, and bites harder here: a `"` in `destination` closes the
6676    /// attribute. A frontend taking these from a file picker is fine; one taking
6677    /// them from free text should keep them tame.
6678    ///
6679    /// [`MediaInfo`]: crate::MediaInfo
6680    pub fn insert_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
6681        if kind == MediaKind::Image {
6682            return self.insert_image(destination, alt);
6683        }
6684        // Gated on the *image* gesture, not on one of its own — there isn't one,
6685        // since the bytes below are spelled here rather than by twig, and an HTML
6686        // document would in fact parse them. The button is one control with three
6687        // kinds behind it, and two of them working in a format where the third
6688        // cannot is a worse surface than three that agree — especially as
6689        // `insert_image` is the kind anyone reaches for first.
6690        if self.refuse_unsupported("media", Gesture::InsertImage) {
6691            return;
6692        }
6693        let (start, end) = self.selection().unwrap_or((self.caret, self.caret));
6694        let alt_text = self
6695            .selected_text()
6696            .map(str::to_string)
6697            .unwrap_or_else(|| alt.to_string());
6698        let tag = match kind {
6699            MediaKind::Audio => "audio",
6700            _ => "video",
6701        };
6702        let markup = format!("<{tag} src=\"{destination}\" controls>{alt_text}</{tag}>");
6703        self.edit(start, end, &markup);
6704    }
6705
6706    /// Append media at the **end** of the document, as a block of its own —
6707    /// the verb for a picture that *arrives* rather than one the writer
6708    /// places: an attachment imported while the caret was wherever it last
6709    /// was, a drawing placed from a tray under the body. At the caret it
6710    /// would land inline in front of whatever word the caret happened to be
6711    /// beside, which for an editor nobody has tapped yet is the first word
6712    /// of the document.
6713    ///
6714    /// The document is ended with a blank line first, where it does not
6715    /// already end with one, so the media is a paragraph of its own rather
6716    /// than a lazy continuation of the last one; an empty document needs no
6717    /// separator. Then [`insert_media`](Self::insert_media) at the new end,
6718    /// with everything that means: the same markup per kind, the same
6719    /// refusal on a format without images. The selection is dropped — the
6720    /// verb is about the end of the document, not about what was selected —
6721    /// and the caret is left past the media, as `insert_media` leaves it.
6722    pub fn append_media(&mut self, kind: MediaKind, destination: &str, alt: &str) {
6723        if self.read_only || self.refuse_unsupported("media", Gesture::InsertImage) {
6724            return;
6725        }
6726        let separator = if self.source.is_empty() || self.source.ends_with("\n\n") {
6727            ""
6728        } else if self.source.ends_with('\n') {
6729            "\n"
6730        } else {
6731            "\n\n"
6732        };
6733        let end = self.source.len();
6734        self.anchor = None;
6735        self.caret = end;
6736        if !separator.is_empty() {
6737            self.edit(end, end, separator);
6738        }
6739        self.anchor = None;
6740        self.caret = self.source.len();
6741        self.insert_media(kind, destination, alt);
6742    }
6743
6744    /// Insert a thematic break at the caret — the toolbar's Horizontal Rule
6745    /// button. Spelling and placement are both twig's; leaf used to write `---`
6746    /// itself, which was the Markdown spelling in a djot document too.
6747    ///
6748    /// A rule is a block, so `insert_thematic_break` alone has nowhere to put one
6749    /// mid-paragraph and lands it after the caret's whole block. To get a rule
6750    /// *at* the caret — the paragraph parted in two around it, which is what a
6751    /// rule button is understood to do — the paragraph is first divided with
6752    /// `split_block` and the rule then aimed at the **first** half. Aiming it at
6753    /// the offset `split_block` returns puts the rule after the *second* half
6754    /// instead, which is a rule in the right document and the wrong place.
6755    ///
6756    /// Only a plain paragraph is split, and only where there is something to
6757    /// part: at the paragraph's end the split has no second half to mint and
6758    /// would write the separator anyway — a blank line and the empty slot Enter
6759    /// leaves for the next paragraph, which the rule then lands above and
6760    /// nothing fills — so there the rule goes straight after the paragraph,
6761    /// which is where the split-and-aim was sending it regardless. At the
6762    /// paragraph's *start* the split is kept, though it parts nothing either:
6763    /// `|para` becomes `\npara` with the caret on the new blank line, and a
6764    /// rule aimed at a blank line is written on it (twig ≥ 3.5.2), which is how
6765    /// "before the paragraph" is said through a gesture that only knows
6766    /// "after" — `---\n\npara`, and `prev\n\n---\n\npara` mid-document. Everywhere
6767    /// else the rule simply lands after the block, which is both twig's own
6768    /// answer and the better one: splitting a fenced code block would leave two
6769    /// fences with a rule between them, and splitting a list item would mint an
6770    /// item nobody asked for on the way to a rule that lands after the list
6771    /// regardless. A table and a setext heading refuse the split outright, so
6772    /// they take the same path by themselves.
6773    ///
6774    /// The caret ends on the line under the rule, which is where the writer
6775    /// goes on: at the start of the paragraph's second half when the rule
6776    /// parted one, and otherwise on an empty line opened under the rule — see
6777    /// [`stand_under_block`](Self::stand_under_block). It used to be left at
6778    /// the end of what twig wrote, which is the rule's own row: the caret was
6779    /// drawn beside the rule, and mid-document the next keystroke joined the
6780    /// block below.
6781    pub fn insert_thematic_break(&mut self) {
6782        if self.read_only || self.refuse_unsupported("thematic break", Gesture::InsertThematicBreak)
6783        {
6784            return;
6785        }
6786        self.caret = self.skip_trailing_close_delims(self.caret);
6787        // A selection is replaced by the rule, so collapse it first and let the
6788        // split-and-rule below run from the caret it leaves behind.
6789        if let Some((s, e)) = self.selection() {
6790            self.splice(s, e, "", EditKind::Other);
6791        }
6792        self.anchor = None;
6793        self.record_caret();
6794        let at = self.caret;
6795        // A failure here is not fatal: the rule still lands after the block,
6796        // which is exactly what this call was trying to improve on.
6797        let parted = self.part_for_block(at);
6798        match self.editor.insert_thematic_break(at) {
6799            Ok(change) => {
6800                self.last_edit_kind = None;
6801                self.refresh();
6802                if parted {
6803                    self.coalesce_last_undo();
6804                }
6805                self.anchor = None;
6806                self.caret = change.new.end;
6807                self.dirty = self.source != self.clean_source;
6808                self.status = None;
6809                self.clamp_caret();
6810                self.record_caret();
6811                self.caret_under_written_block(change.new, parted);
6812            }
6813            Err(e) => self.status = Some(format!("thematic break: {e}")),
6814        }
6815    }
6816
6817    /// Part the bare paragraph at `at` for a block gesture, where
6818    /// [`caret_parts_bare_paragraph`](Self::caret_parts_bare_paragraph) says
6819    /// to, and say whether it was parted.
6820    ///
6821    /// The split is counted as a step of its own, so the gesture can fold the
6822    /// block it writes next into it. It used to go to twig uncounted: twig
6823    /// kept it as a step and leaf's count did not, so one Undo took back the
6824    /// block and left the paragraph parted, with Undo then reporting nothing
6825    /// left to undo.
6826    fn part_for_block(&mut self, at: usize) -> bool {
6827        if !self.caret_parts_bare_paragraph() || self.editor.split_block(at).is_err() {
6828            return false;
6829        }
6830        self.refresh();
6831        true
6832    }
6833
6834    /// Where a block gesture leaves the caret once twig has written the block
6835    /// `new` spans — a rule, a page break: on the line under it. That is the
6836    /// start of the paragraph's second half when the gesture `parted` one,
6837    /// and otherwise the line [`stand_under_block`](Self::stand_under_block)
6838    /// finds or writes, folded into the gesture's step.
6839    ///
6840    /// The block is the outermost node twig's change opens, whatever its
6841    /// kind, since the kind a leaf directive comes back as is the format's.
6842    fn caret_under_written_block(&mut self, new: Range<usize>, parted: bool) {
6843        let block = self
6844            .nodes()
6845            .into_iter()
6846            .filter(|n| n.kind != Kind::Doc && new.contains(&n.span.start))
6847            .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)));
6848        let Some(block) = block else {
6849            return;
6850        };
6851        let (end, _) = wysiwyg::block_line(&self.source, block.span.end);
6852        if parted {
6853            // The second half starts at the first text under the block; the
6854            // split left it no leading whitespace.
6855            let rest = &self.source[end..];
6856            self.caret = end + (rest.len() - rest.trim_start().len());
6857            self.record_caret();
6858        } else if self.stand_under_block(end) {
6859            self.coalesce_last_undo();
6860        }
6861    }
6862
6863    /// Stand the caret on the line under the block whose last line's text ends
6864    /// at `end` — a thematic break, a page break — first writing that line if
6865    /// the block has none: where the rule and page-break buttons leave the
6866    /// caret, and where Enter on a rule takes it. Whether anything was
6867    /// written, so a caller can fold it into its own step.
6868    ///
6869    /// The caret's line is the first under the block that the view gives a
6870    /// home: the second blank line in [`LineFlow::Fold`], which draws the
6871    /// first as the gap closing the block, and the first in
6872    /// [`LineFlow::Preserve`], where every blank line is somewhere to type.
6873    /// When anything follows, one more blank line has to stand between the
6874    /// caret's line and it, or what is typed there runs on into the next
6875    /// block. Only what that shape is missing is written. A block twig wrote on
6876    /// a blank line still has the blank lines that were under the caret and
6877    /// needs one line more, or none, where a rule written under a paragraph
6878    /// needs two.
6879    ///
6880    /// Blank means blank inside the block's container: a quote's blank lines
6881    /// keep their `>`, and the caret's line wears the quote's whole prefix, as
6882    /// the line Enter opens in a quote does. The document's last line, when no
6883    /// newline ends it, counts only once a blank line stands above it, since
6884    /// only then does the view draw it as a row. Fold always writes the gap
6885    /// above it if it isn't there, so there a block ending the document takes
6886    /// one newline more and the caret its end.
6887    fn stand_under_block(&mut self, end: usize) -> bool {
6888        let prefix = self.continuation_prefix_at(end);
6889        let blank = prefix.trim_end();
6890        let gap = usize::from(self.line_flow == LineFlow::Fold);
6891        // The blank lines directly under the block's own, by where each starts,
6892        // and whether the line that ends the run has anything on it.
6893        let mut blanks = Vec::new();
6894        let mut follows = false;
6895        let mut at = end;
6896        while let Some(nl) = self.source[at..].find('\n') {
6897            let start = at + nl + 1;
6898            let len = self.source[start..].find('\n');
6899            let line = &self.source[start..len.map_or(self.source.len(), |len| start + len)];
6900            let line = line.trim_end();
6901            if line != blank {
6902                follows = !line.trim().is_empty();
6903                break;
6904            }
6905            let Some(len) = len else {
6906                if gap > 0 || !blanks.is_empty() {
6907                    blanks.push(start);
6908                }
6909                break;
6910            };
6911            blanks.push(start);
6912            at = start + len;
6913        }
6914        let missing = (gap + 1 + usize::from(follows)).saturating_sub(blanks.len());
6915        // What is missing goes in at the rule's end, above the blank lines
6916        // already there, so the caret's line is the same one counted from
6917        // the rule either way: written here, or one of those, moved down.
6918        let mut text = String::new();
6919        let mut caret = None;
6920        for line in 1..=missing {
6921            text.push('\n');
6922            if line == gap + 1 {
6923                text.push_str(&prefix);
6924                caret = Some(end + text.len());
6925            } else {
6926                text.push_str(blank);
6927            }
6928        }
6929        let caret = caret.unwrap_or_else(|| {
6930            let start = blanks[gap - missing];
6931            let line = self.source[start..].split('\n').next().unwrap_or("");
6932            start + text.len() + line.trim_end_matches('\r').len().min(prefix.len())
6933        });
6934        if !text.is_empty() && !self.splice(end, end, &text, EditKind::Other) {
6935            return false;
6936        }
6937        self.caret = caret.min(self.source.len());
6938        self.anchor = None;
6939        self.goal_col = None;
6940        self.record_caret();
6941        !text.is_empty()
6942    }
6943
6944    /// The thematic break the caret stands under, as its text's end, when
6945    /// Enter there belongs to the rule: the caret at the rule's home past it
6946    /// (the start of the line under it), that line blank, and the caret drawn
6947    /// on the rule's own row.
6948    ///
6949    /// Drawn on the rule's row, because the home past a rule is also the start
6950    /// of the line under it, and which of the two the view draws it on is the
6951    /// flow's. [`LineFlow::Fold`] draws that line as the gap under the rule,
6952    /// no caret's home, so the caret is beside the rule. [`LineFlow::Preserve`]
6953    /// makes every blank line a home, so it draws the caret there and Enter is
6954    /// an ordinary blank line's — unless it is the document's unterminated
6955    /// last line, which is no row in either flow.
6956    fn rule_above_caret(&mut self) -> Option<usize> {
6957        let caret = self.caret.min(self.source.len());
6958        let above = self.source[..caret].strip_suffix('\n')?;
6959        let above_start = above.rfind('\n').map_or(0, |i| i + 1);
6960        let text = above[above_start..].trim_end();
6961        let (last, _) = text.char_indices().next_back()?;
6962        let rule = self
6963            .editor
6964            .ancestors_at(above_start + last)
6965            .ok()?
6966            .into_iter()
6967            .find(|m| m.kind == Kind::ThematicBreak)?;
6968        let (end, home) = wysiwyg::block_line(&self.source, rule.span.end);
6969        if home != caret {
6970            return None;
6971        }
6972        let blank = self.continuation_prefix_at(end);
6973        let line_end = self.source[caret..].find('\n').map(|i| caret + i);
6974        let line = &self.source[caret..line_end.unwrap_or(self.source.len())];
6975        if line.trim_end() != blank.trim_end() && !line.trim().is_empty() {
6976            return None;
6977        }
6978        (self.line_flow == LineFlow::Fold || line_end.is_none()).then_some(end)
6979    }
6980
6981    /// Insert a fresh table at the caret — the toolbar's Table button. One
6982    /// header row, `rows` empty body rows, `cols` columns, spelled by twig in
6983    /// the document's own dialect and placed the way its thematic break is:
6984    /// after the caret's block, blank-separated. A bare paragraph is parted
6985    /// around the caret first, exactly as
6986    /// [`insert_thematic_break`](Self::insert_thematic_break) parts it, so the
6987    /// table lands *at* the caret rather than after everything the caret's
6988    /// paragraph says.
6989    ///
6990    /// The caret ends in the first header cell, selected the way Tab selects
6991    /// a cell — the natural next act is to type the heading, and Tab then
6992    /// walks the grid. That cell is read back from the rebuilt table map
6993    /// rather than computed from the splice, because twig's blank line and
6994    /// quote prefix put the first bar at an offset only the reparse knows.
6995    ///
6996    /// The shape is the caller's: a menu offers a few, a dialog asks. Zero
6997    /// rows or columns is twig's refusal (a header with nothing under it is
6998    /// what its row delete refuses to leave), reported through `status` —
6999    /// and refused here before the paragraph is parted, which would otherwise
7000    /// be left parted around a table never written.
7001    pub fn insert_table(&mut self, rows: usize, cols: usize) {
7002        if self.read_only || self.refuse_unsupported("table", Gesture::InsertTable) {
7003            return;
7004        }
7005        // twig's one refusal of a shape, asked before the paragraph is parted
7006        // for a table that would never be written into it.
7007        if rows == 0 || cols == 0 {
7008            self.status = Some("table: needs at least one row and one column".into());
7009            return;
7010        }
7011        self.caret = self.skip_trailing_close_delims(self.caret);
7012        if let Some((s, e)) = self.selection() {
7013            self.splice(s, e, "", EditKind::Other);
7014        }
7015        self.anchor = None;
7016        self.record_caret();
7017        let at = self.caret;
7018        let parted = self.part_for_block(at);
7019        match self.editor.insert_table(at, rows, cols) {
7020            Ok(change) => {
7021                self.last_edit_kind = None;
7022                self.refresh();
7023                if parted {
7024                    self.coalesce_last_undo();
7025                }
7026                self.anchor = None;
7027                self.caret = change.new.end;
7028                self.dirty = self.source != self.clean_source;
7029                self.status = None;
7030                self.clamp_caret();
7031                // Into the first header cell of the table just written: the
7032                // first table whose grid begins inside the splice.
7033                self.rebuild_map();
7034                let first_cell = self
7035                    .vmap
7036                    .tables
7037                    .iter()
7038                    .filter_map(|t| t.grid.first().and_then(|row| row.cells.first()))
7039                    .find(|cell| cell.start >= change.new.start && cell.start < change.new.end)
7040                    .map(|cell| (cell.start, cell.end));
7041                if let Some((start, end)) = first_cell {
7042                    self.select_cell(start, end);
7043                }
7044                self.record_caret();
7045            }
7046            Err(e) => self.status = Some(format!("table: {e}")),
7047        }
7048    }
7049
7050    /// Whether the caret sits in a paragraph and nothing else — no list item, no
7051    /// quote, no fence, no table — with paragraph text still ahead of it. The
7052    /// one shape where parting the block around the caret is unambiguously what
7053    /// a rule button means; see
7054    /// [`insert_thematic_break`](Self::insert_thematic_break) for why every other
7055    /// container is left to take the rule after itself.
7056    ///
7057    /// The "text ahead" half is what keeps `split_block` from running at the
7058    /// one edge where its output composes badly. At a paragraph's end twig
7059    /// cannot mint the empty second half (no format spells an empty
7060    /// paragraph), so it writes only the separator — a blank line and the
7061    /// slot Enter leaves for the paragraph to come — and a block then aimed at
7062    /// the first half lands above a slot that nothing fills: `para\n` with the
7063    /// caret at 4 came out as `para\n\n* * *\n\n\n`. Trailing whitespace counts
7064    /// as nothing ahead, since the split would shed it as the second half's
7065    /// leading indent and leave the same slot. Which end of the newline a
7066    /// paragraph's span stops at differs between the formats (Markdown before
7067    /// it, djot after), which is why this reads the remaining bytes rather
7068    /// than comparing offsets. The paragraph's
7069    /// start is deliberately not the same case — see
7070    /// [`insert_thematic_break`](Self::insert_thematic_break) for why that
7071    /// split is kept.
7072    fn caret_parts_bare_paragraph(&mut self) -> bool {
7073        let caret = self.caret.min(self.source.len());
7074        let Ok(chain) = self.editor.ancestors_at(caret) else {
7075            return false;
7076        };
7077        let mut para_end = None;
7078        for m in chain {
7079            match m.kind {
7080                Kind::Para => para_end = Some(m.span.end.min(self.source.len())),
7081                Kind::ListItem
7082                | Kind::TaskListItem
7083                | Kind::BlockQuote
7084                | Kind::CodeBlock
7085                | Kind::Table => return false,
7086                _ => {}
7087            }
7088        }
7089        match para_end {
7090            Some(end) if end > caret => !self.source[caret..end].trim().is_empty(),
7091            _ => false,
7092        }
7093    }
7094
7095    /// The destination of the link under the caret — what a Link prompt shows so
7096    /// ⌘K on an existing link edits its URL instead of asking for it again.
7097    /// `None` when the caret stands in no link.
7098    ///
7099    /// An autolink carries no separate destination: its text *is* the URL, so
7100    /// that's what comes back for one.
7101    pub fn link_destination_at_caret(&mut self) -> Option<String> {
7102        self.link_destination_at(self.caret)
7103    }
7104
7105    /// The destination of the link at `off`.
7106    /// [`link_destination_at_caret`](Self::link_destination_at_caret) for a place
7107    /// the caret isn't.
7108    ///
7109    /// The offset form exists for the same reason
7110    /// [`footnote_at`](Self::footnote_at)'s does: a frontend drawing a *piece* of
7111    /// the document somewhere else — a footnote's text in a popover, say — has
7112    /// rows and runs but no caret in them, and still needs to know which of those
7113    /// runs a reader can follow.
7114    pub fn link_destination_at(&mut self, off: usize) -> Option<String> {
7115        self.nodes()
7116            .into_iter()
7117            .filter(|n| matches!(n.kind.as_str(), "link" | "url" | "email"))
7118            .filter(|n| n.span.start <= off && off < n.span.end)
7119            .max_by_key(|n| n.span.start)
7120            .and_then(|n| n.destination.or(n.text))
7121    }
7122
7123    /// The heading the caret is under — the nearest heading at or above it,
7124    /// whatever its level. See [`heading_at`](Self::heading_at).
7125    pub fn heading_at_caret(&mut self) -> Option<Heading> {
7126        self.heading_at(self.caret)
7127    }
7128
7129    /// The heading `off` is under: the last heading that starts at or before
7130    /// it, or the one `off` stands in. `None` above the first heading.
7131    ///
7132    /// The question between [`link_destination_at`](Self::link_destination_at)
7133    /// ("which link is this") and [`locate`](Self::locate) ("where does this
7134    /// fragment land"): a host writing a link *to* a place needs the heading
7135    /// that place is under, to name it by `#slug`. Nearest, not enclosing —
7136    /// a level-3 heading under a level-2 is the answer for the text below the
7137    /// level-3, because it is the finer place to land.
7138    pub fn heading_at(&mut self, off: usize) -> Option<Heading> {
7139        let nodes = self.nodes();
7140        let h = nodes
7141            .iter()
7142            .filter(|n| n.kind == Kind::Heading && n.span.start <= off)
7143            .max_by_key(|n| n.span.start)?;
7144        let mut text = String::new();
7145        inline_text(&nodes, h.first_child, &mut text);
7146        Some(Heading {
7147            text: text.trim().to_string(),
7148            level: h.level.unwrap_or(1),
7149            span: h.span.clone(),
7150        })
7151    }
7152
7153    /// Where the locator `id` lands in this document — the `#v2` half of a
7154    /// `chapter.dj#v2`, resolved to the block it names. `None` when nothing here
7155    /// answers to it.
7156    ///
7157    /// The other end of a link, and the reason this exists: without it a
7158    /// destination has only file granularity, so following a citation into a
7159    /// chapter drops the reader at the top of it to hunt for the verse. Which is
7160    /// also why it is a *document* query rather than a caret one — the document
7161    /// being asked is usually not the one the reader is in.
7162    ///
7163    /// Three readings, tried in order, because the same `#some-heading` is
7164    /// written three ways across the formats leaf opens:
7165    ///
7166    /// 1. **A declared id**, exactly as written: djot's `{#v1}` on a block, and
7167    ///    the auto-ids djot mints for its headings. The only exact answer, so it
7168    ///    goes first — a document that says `{#v1}` has settled the question.
7169    /// 2. **A declared id, slugged.** djot spells a heading's auto-id
7170    ///    `Some-Heading-Here`; nearly every tool that *writes* a link to one
7171    ///    spells it `#some-heading-here`. Comparing slugs is what lets a link
7172    ///    authored anywhere land on a djot heading.
7173    /// 3. **A heading's text, slugged.** Markdown has no ids at all — twig mints
7174    ///    none and `{#custom}` is literal text in a Markdown heading — so for
7175    ///    the format most vaults are written in, the heading's own words are the
7176    ///    only thing a fragment can name. This is the rule every Markdown
7177    ///    renderer already follows, which is what makes `#a-heading` mean in
7178    ///    diaryx what it means on the web.
7179    ///
7180    /// Ties go to the earliest match, then to the widest: a duplicated id is the
7181    /// document's mistake and the first one is the answer every anchor
7182    /// implementation gives, while preferring the wider span picks the section
7183    /// over the heading that opens it — more for a peek to show, same place to
7184    /// land.
7185    pub fn locate(&mut self, id: &str) -> Option<Landing> {
7186        let id = id.trim();
7187        if id.is_empty() {
7188            return None;
7189        }
7190        let nodes = self.nodes();
7191
7192        // Earliest wins, then widest. `Reverse` on the end because `min_by_key`
7193        // is picking, among nodes that start together, the one that ends last.
7194        let pick = |matches: &mut dyn Iterator<Item = &FlatNode>| {
7195            matches
7196                .min_by_key(|n| (n.span.start, std::cmp::Reverse(n.span.end)))
7197                .map(|n| Landing {
7198                    start: n.span.start,
7199                    end: n.span.end,
7200                })
7201        };
7202
7203        if let Some(landing) = pick(&mut nodes.iter().filter(|n| declared_id(n) == Some(id))) {
7204            return Some(landing);
7205        }
7206        let want = slug(id);
7207        if want.is_empty() {
7208            return None;
7209        }
7210        if let Some(landing) = pick(
7211            &mut nodes
7212                .iter()
7213                .filter(|n| declared_id(n).map(slug).as_deref() == Some(&*want)),
7214        ) {
7215            return Some(landing);
7216        }
7217
7218        // A heading by its words. Its span is one line, so the end comes from
7219        // where the *section* it opens gives out — the next heading that is not
7220        // under it, or the end of the document. A Markdown heading has no
7221        // section node to ask (twig only builds those for djot), and a peek that
7222        // showed the heading alone would answer "what does that say" with the
7223        // title of the thing it says.
7224        let heading = nodes
7225            .iter()
7226            .filter(|n| n.kind == Kind::Heading)
7227            .filter(|n| {
7228                n.content_span
7229                    .clone()
7230                    .and_then(|s| self.source.get(s))
7231                    .is_some_and(|text| slug(text) == want)
7232            })
7233            .min_by_key(|n| n.span.start)?;
7234        let level = heading.level.unwrap_or(u32::MAX);
7235        let end = nodes
7236            .iter()
7237            .filter(|n| n.kind == Kind::Heading)
7238            .filter(|n| n.span.start > heading.span.start)
7239            .filter(|n| n.level.unwrap_or(u32::MAX) <= level)
7240            .map(|n| n.span.start)
7241            .min()
7242            .unwrap_or(self.source.len());
7243        Some(Landing {
7244            start: heading.span.start,
7245            end,
7246        })
7247    }
7248
7249    /// Write a footnote at the caret — the toolbar's Footnote button, and the
7250    /// one gesture in the footnote story that *authors* rather than follows.
7251    ///
7252    /// Both halves go in as one twig edit: the `[^1]` where the caret is, and
7253    /// the `[^1]:` definition at the end of the document. Half a footnote is not
7254    /// a footnote — a bare reference with nothing defining it renders as literal
7255    /// brackets — so a single button that wrote only the reference would leave
7256    /// the author to hand-spell the other half in a document that had just
7257    /// stopped showing them what the first half meant. One edit also means one
7258    /// undo takes both back.
7259    ///
7260    /// The definition's body is left empty and **the caret lands in it**, which
7261    /// is the whole point of pressing the button: nobody wants a reference to a
7262    /// note they have not written yet. Getting back to where they were writing
7263    /// is [`footnote_definition_at_caret`](Self::footnote_definition_at_caret) —
7264    /// the same return leg a reader following a reference already uses, so the
7265    /// author is left standing on the near end of a round trip that works.
7266    ///
7267    /// A selection collapses to its *end* rather than being replaced: a
7268    /// reference annotates the words before it, so "select the claim, add a
7269    /// footnote" should mark that claim, not consume it.
7270    pub fn insert_footnote(&mut self) {
7271        if self.read_only || self.refuse_unsupported("footnote", Gesture::InsertFootnote) {
7272            return;
7273        }
7274        let at = self.selection().map_or(self.caret, |(_, end)| end);
7275        self.anchor = None;
7276        self.caret = at;
7277        self.record_caret();
7278        let label = self.next_footnote_label();
7279        match self.editor.insert_footnote(at, &label) {
7280            Ok(change) => {
7281                self.last_edit_kind = None;
7282                self.refresh();
7283                self.anchor = None;
7284                // `change.new` runs from the reference to the end of the
7285                // document, so its start is the `[^1]` just written and
7286                // `footnote_at` resolves it to the note the same way a reader's
7287                // tap does — and to the note's *body*, which is already a caret
7288                // stop even when it is empty (the `[^1]:` marker draws as `[1] `
7289                // and has none), so this needs no snap on top. The fallback is
7290                // the reference's own offset: a format that spelled the pair some
7291                // way leaf can't read back should still leave the caret on the
7292                // edit rather than at the far end of a document it just grew.
7293                self.caret = self
7294                    .footnote_at(change.new.start)
7295                    .and_then(|note| note.offset)
7296                    .unwrap_or(change.new.start);
7297                self.dirty = self.source != self.clean_source;
7298                self.status = None;
7299                self.clamp_caret();
7300                self.record_caret();
7301            }
7302            Err(e) => self.status = Some(format!("footnote: {e}")),
7303        }
7304    }
7305
7306    /// The label to give a footnote the author has not named: the lowest counting
7307    /// number no footnote in the document is already wearing.
7308    ///
7309    /// twig takes the label rather than minting one, because it holds no opinion
7310    /// about what a document's footnotes should be called — and it is right not
7311    /// to. Numbering them is what every author of a numbered note expects, and
7312    /// re-using a taken number would silently point the new reference at somebody
7313    /// else's note (twig reuses an existing definition rather than appending a
7314    /// second one, which is the right rule for citing a note twice on purpose and
7315    /// exactly the wrong accident to have by default).
7316    ///
7317    /// *References* are counted alongside definitions, not just definitions: a
7318    /// document carrying a dangling `[^2]` has a 2 that means something to
7319    /// whoever wrote it, and minting a definition for it here would answer a
7320    /// question nobody asked. Non-numeric labels (`[^why]`) are left out of the
7321    /// count entirely — they take no number, so they block none.
7322    fn next_footnote_label(&mut self) -> String {
7323        let mut taken: Vec<u32> = wysiwyg::footnote_definitions(&mut self.editor)
7324            .into_iter()
7325            .filter_map(|note| wysiwyg::footnote_label(&self.source, note.span.start))
7326            .filter_map(|label| label.parse().ok())
7327            .collect();
7328        taken.extend(
7329            self.nodes()
7330                .into_iter()
7331                .filter(|n| n.kind == Kind::FootnoteReference)
7332                .filter_map(|n| wysiwyg::footnote_reference_label(&self.source, n.span))
7333                .filter_map(|label| label.parse::<u32>().ok()),
7334        );
7335        (1..).find(|n| !taken.contains(n)).unwrap_or(1).to_string()
7336    }
7337
7338    /// The footnote reference under the caret, resolved to the note it names.
7339    /// [`footnote_at`](Self::footnote_at) at the caret's offset.
7340    pub fn footnote_at_caret(&mut self) -> Option<FootnoteRef> {
7341        self.footnote_at(self.caret)
7342    }
7343
7344    /// The footnote reference at `off`, resolved to the note it names — what a
7345    /// frontend shows when a reader activates a `[^1]`.
7346    ///
7347    /// A reference is not a link node, so
7348    /// [`link_destination_at_caret`](Self::link_destination_at_caret) does not
7349    /// (and should not) answer for one: a link names a destination to leave for,
7350    /// a reference names a note that is already in this document. Following one
7351    /// is a move within the page, which is why this hands back an `offset`
7352    /// rather than something to open.
7353    ///
7354    /// Offset-based rather than caret-only because the gesture that wants this
7355    /// most is the one that must not move the caret: a pointer hovering a `[1]`
7356    /// asks what note it names without disturbing where the reader was typing.
7357    /// The caret is just the offset a click already placed —
7358    /// [`footnote_at_caret`](Self::footnote_at_caret) passes it.
7359    ///
7360    /// `None` when `off` stands in no reference. A reference whose note the
7361    /// document never defines is *not* `None` — it answers with the label it
7362    /// looked for and no text, which is what lets a frontend say so instead of
7363    /// silently doing nothing.
7364    pub fn footnote_at(&mut self, off: usize) -> Option<FootnoteRef> {
7365        // Innermost-wins by latest start, the rule its link sibling uses.
7366        let span = self
7367            .nodes()
7368            .into_iter()
7369            .filter(|n| n.kind == Kind::FootnoteReference)
7370            .filter(|n| n.span.start <= off && off < n.span.end)
7371            .max_by_key(|n| n.span.start)?
7372            .span;
7373        let label = wysiwyg::footnote_reference_label(&self.source, span)?.to_string();
7374
7375        // The note itself. Definitions are roots beside `doc` rather than
7376        // children of it, so they're asked for directly — see
7377        // `wysiwyg::footnote_definitions`.
7378        let note = wysiwyg::footnote_definitions(&mut self.editor)
7379            .into_iter()
7380            .find(|m| wysiwyg::footnote_label(&self.source, m.span.start) == Some(&label));
7381        let Some(note) = note else {
7382            return Some(FootnoteRef {
7383                label,
7384                text: None,
7385                offset: None,
7386                end: None,
7387            });
7388        };
7389        let body = wysiwyg::footnote_body_span(&self.source, note.span.clone());
7390        Some(FootnoteRef {
7391            label,
7392            text: body
7393                .clone()
7394                .and_then(|b| self.source.get(b))
7395                .map(str::to_string),
7396            // The body's start, not the definition's — see `FootnoteRef::offset`.
7397            offset: body.clone().map(|b| b.start),
7398            end: body.map(|b| b.end),
7399        })
7400    }
7401
7402    /// The footnote *definition* the caret stands in, and where the reference
7403    /// that names it is. [`footnote_definition_at`](Self::footnote_definition_at)
7404    /// at the caret's offset.
7405    pub fn footnote_definition_at_caret(&mut self) -> Option<FootnoteDef> {
7406        self.footnote_definition_at(self.caret)
7407    }
7408
7409    /// The footnote definition spanning `off`, and where the reference that
7410    /// names it is — the return leg of [`footnote_at`](Self::footnote_at).
7411    ///
7412    /// The mirror image, deliberately: the same gesture that takes a reader from
7413    /// `[1]` down to the note takes them from the note back up to `[1]`, so
7414    /// following a footnote is a round trip rather than a fall. It needs no
7415    /// memory of how the reader arrived — the document says where the reference
7416    /// is — which is what makes it work for a reader who scrolled to the notes
7417    /// themselves, and what keeps it right after an edit moves either end.
7418    ///
7419    /// `None` when `off` stands in no definition. A definition nothing cites is
7420    /// *not* `None`, for [`FootnoteRef`]'s reason in reverse: it answers with
7421    /// its label and no offset, so a frontend can say "nothing refers to this"
7422    /// rather than offer a jump that goes nowhere.
7423    pub fn footnote_definition_at(&mut self, off: usize) -> Option<FootnoteDef> {
7424        // Definitions are roots beside `doc`, so `nodes()` — which walks the
7425        // document body — never reports one. They're asked for directly, the way
7426        // `footnote_at` asks for the note it resolves to.
7427        //
7428        // Closed at the end, unlike the half-open test its neighbours use. A
7429        // definition's span stops at its last content byte — the newline ending
7430        // the line is outside it — so `span.end` is the caret stop at the end of
7431        // the note's own row, not the first byte of anything after. Excluding it
7432        // meant the one caret an author is guaranteed to have, the one left
7433        // sitting at the end of the note they just typed, was in no definition at
7434        // all: writing a note and then asking to go back to its reference
7435        // answered nothing. Two definitions in a row still can't both match —
7436        // there is a blank line between them — and `max_by_key` decides anyway.
7437        let note = wysiwyg::footnote_definitions(&mut self.editor)
7438            .into_iter()
7439            .filter(|m| m.span.start <= off && off <= m.span.end)
7440            .max_by_key(|m| m.span.start)?;
7441        let label = wysiwyg::footnote_label(&self.source, note.span.start)?.to_string();
7442
7443        // The earliest reference carrying this label. `min` rather than a `find`,
7444        // because `nodes()` reports a flattened walk whose order is twig's
7445        // business, not document order. Bound first: the walk needs `&mut self`
7446        // and reading the labels back out needs `&self.source`.
7447        let nodes = self.nodes();
7448        let offset = nodes
7449            .into_iter()
7450            .filter(|n| n.kind == Kind::FootnoteReference)
7451            .filter(|n| {
7452                wysiwyg::footnote_reference_label(&self.source, n.span.clone()) == Some(&*label)
7453            })
7454            // Past the `[^`, onto the label — see `FootnoteDef::offset`.
7455            .map(|n| n.span.start + 2)
7456            .min();
7457        Some(FootnoteDef { label, offset })
7458    }
7459
7460    /// The destination of the image under the caret — what an image prompt shows
7461    /// so editing an existing image starts from its current URL instead of blank,
7462    /// the image analogue of [`link_destination_at_caret`](Self::link_destination_at_caret).
7463    /// `None` when the caret stands in no image. A caret resting just after a
7464    /// block image (its trailing stop) is still "in" it — the half-open span test
7465    /// excludes that offset, which is the intended precision: past the image is
7466    /// past it.
7467    pub fn image_destination_at_caret(&mut self) -> Option<String> {
7468        let off = self.caret;
7469        self.nodes()
7470            .into_iter()
7471            .filter(|n| n.kind == Kind::Image)
7472            .filter(|n| n.span.start <= off && off < n.span.end)
7473            .max_by_key(|n| n.span.start)
7474            .and_then(|n| n.destination)
7475    }
7476
7477    /// The language of the fenced code block the caret stands in — what a
7478    /// language prompt shows so editing it starts from the current value rather
7479    /// than blank. `None` when the caret is in no code block, or in one whose
7480    /// fence carries no language (or an indented block, which has no fence).
7481    pub fn code_language_at_caret(&mut self) -> Option<String> {
7482        let start = self.code_block_start_at_caret()?;
7483        wysiwyg::code_language(&self.source, start)
7484    }
7485
7486    /// Whether the caret stands in a fenced code block — the one a language
7487    /// prompt could edit. A frontend gates its "set language" affordance on this
7488    /// (an indented block, which can't carry a language, reports `false`).
7489    pub fn caret_in_fenced_code(&mut self) -> bool {
7490        self.code_block_start_at_caret()
7491            .is_some_and(|start| wysiwyg::code_info_span(&self.source, start).is_some())
7492    }
7493
7494    /// Set (or clear, with `""`) the language of the fenced code block the caret
7495    /// is in — the prompt's confirm. A no-op when the caret is in no fenced
7496    /// block, and a reported error for a language the format's fence cannot
7497    /// carry.
7498    ///
7499    /// twig rewrites the info string, so the fence's own width — measured
7500    /// against a body neither side touches — is kept, and a language holding a
7501    /// space, a line end or the fence character is refused rather than written
7502    /// out to reparse as something else. Leaf used to splice over the info span
7503    /// itself and `trim()` the input, which handled the one bad case it had
7504    /// thought of.
7505    pub fn set_code_language(&mut self, lang: &str) {
7506        // The read-only gate — this door reaches twig without the splice.
7507        if self.read_only {
7508            return;
7509        }
7510        if self.refuse_unsupported("code language", Gesture::SetCodeLanguage) {
7511            return;
7512        }
7513        if self.code_block_start_at_caret().is_none() {
7514            return;
7515        }
7516        let lang = lang.trim();
7517        // `None` clears the info string; `Some("")` asks for an empty one. Both
7518        // write a bare fence, and the prompt's empty value means "clear".
7519        let want = (!lang.is_empty()).then_some(lang);
7520        self.record_caret();
7521        match self.editor.set_code_language(self.caret, want) {
7522            Ok(_) => {
7523                self.last_edit_kind = None;
7524                self.refresh();
7525                self.anchor = None;
7526                self.dirty = self.source != self.clean_source;
7527                self.status = None;
7528                self.clamp_caret();
7529                self.record_caret();
7530            }
7531            Err(e) => self.status = Some(format!("code language: {e}")),
7532        }
7533    }
7534
7535    /// The `span.start` of the code block covering the caret — the anchor
7536    /// [`wysiwyg::code_info_span`] reads the fence from. `None` when the caret is
7537    /// in none.
7538    fn code_block_start_at_caret(&mut self) -> Option<usize> {
7539        let off = self.caret;
7540        self.nodes()
7541            .into_iter()
7542            .filter(|n| n.kind == Kind::CodeBlock && n.span.start <= off && off <= n.span.end)
7543            .max_by_key(|n| n.span.start)
7544            .map(|n| n.span.start)
7545    }
7546
7547    /// The source range of the text inside the link covering `off` — what sits
7548    /// between its `[` and `]`. `None` when twig reports no link there.
7549    fn link_text_span(&mut self, off: usize) -> Option<std::ops::Range<usize>> {
7550        self.nodes()
7551            .into_iter()
7552            // Two links can touch (`[a](x)[b](y)`), and then one's `span.end` is
7553            // the other's `span.start`; the link that starts latest at or before
7554            // `off` is the one `off` is actually in.
7555            .filter(|n| n.kind == Kind::Link && n.span.start <= off && off < n.span.end)
7556            .max_by_key(|n| n.span.start)
7557            .and_then(|n| n.content_span)
7558    }
7559
7560    // ── undo / redo ───────────────────────────────────────────────────────────
7561    // twig owns the history of *bytes* (it owns the buffer) and now carries the
7562    // caret through it too: `record_caret` stashes each state's caret in twig's
7563    // opaque per-step blob, and undo/redo hand it back with the source they
7564    // restore. So leaf keeps no history of its own — no parallel stacks to march
7565    // in lockstep and silently drift out of it.
7566
7567    /// Undo the last edit step (⌘Z / ^Z), putting the caret and selection back
7568    /// where they were when that step began. Whether it did: `false` when
7569    /// there was nothing to undo, the document is read-only, or twig refused —
7570    /// the answer a host composing several histories into one walks on by.
7571    pub fn undo(&mut self) -> bool {
7572        if self.read_only {
7573            return false;
7574        }
7575        // Stepping through the history ends a group: what comes after is not
7576        // part of the step just taken back.
7577        self.close_undo_group();
7578        let (undone, redoable) = (self.undo_steps, self.redo_steps);
7579        match self.editor.undo() {
7580            Ok(Some(change)) => {
7581                self.after_history(change);
7582                // `refresh` counted the restore as an edit; it was a step back.
7583                self.undo_steps = undone.saturating_sub(1);
7584                self.redo_steps = redoable + 1;
7585                true
7586            }
7587            Ok(None) => {
7588                self.undo_steps = 0;
7589                self.status = Some("nothing to undo".into());
7590                false
7591            }
7592            Err(e) => {
7593                self.status = Some(format!("undo: {e}"));
7594                false
7595            }
7596        }
7597    }
7598
7599    /// Redo the last undone edit step (⇧⌘Z / ^Y), putting the caret and
7600    /// selection back where that step originally left them. Whether it did,
7601    /// as [`undo`](Self::undo) reports.
7602    pub fn redo(&mut self) -> bool {
7603        if self.read_only {
7604            return false;
7605        }
7606        self.close_undo_group();
7607        let (undone, redoable) = (self.undo_steps, self.redo_steps);
7608        match self.editor.redo() {
7609            Ok(Some(change)) => {
7610                self.after_history(change);
7611                // `refresh` counted the restore as an edit; it was a step forward.
7612                self.undo_steps = (undone + 1).min(UNDO_CAP);
7613                self.redo_steps = redoable.saturating_sub(1);
7614                true
7615            }
7616            Ok(None) => {
7617                self.redo_steps = 0;
7618                self.status = Some("nothing to redo".into());
7619                false
7620            }
7621            Err(e) => {
7622                self.status = Some(format!("redo: {e}"));
7623                false
7624            }
7625        }
7626    }
7627
7628    /// Fold the edit just made into the undo step before it — twig's
7629    /// `coalesce_last_undo`, with the `undo_steps` mirror following
7630    /// it. twig merges only when there are two steps to merge. Call it after
7631    /// [`refresh`](Self::refresh) has counted the edit being folded.
7632    ///
7633    /// Inside an [undo group](Self::begin_undo_group) it does nothing: the
7634    /// group's edits are already one step, which [`refresh`](Self::refresh)
7635    /// folds as they come, so a fold here could only reach across the group's
7636    /// start into the step before it.
7637    fn coalesce_last_undo(&mut self) {
7638        if self.undo_group.is_some() {
7639            return;
7640        }
7641        self.fold_last_undo();
7642    }
7643
7644    /// twig's `coalesce_last_undo`, unconditionally, with the mirror following.
7645    fn fold_last_undo(&mut self) {
7646        if self.editor.coalesce_last_undo().is_ok() && self.undo_steps >= 2 {
7647            self.undo_steps -= 1;
7648        }
7649    }
7650
7651    /// Open an undo group: every edit from here to the matching
7652    /// [`end_undo_group`](Self::end_undo_group) is one step, which a single
7653    /// [`undo`](Self::undo) takes back whole and a single [`redo`](Self::redo)
7654    /// puts back — a Replace All over twelve matches, or a Writing Tools
7655    /// session, rather than twelve presses of ⌘Z.
7656    ///
7657    /// Groups nest, and only the outermost end closes one. The step is folded
7658    /// as each edit lands (twig's `coalesce_last_undo`, one edit at a time),
7659    /// so a group of a thousand edits holds one step on the history and never
7660    /// meets twig's cap. Nothing typed before the group folds into it, and
7661    /// nothing typed after: it is a step of its own, even when it is a single
7662    /// edit. A group no edit landed in leaves no step at all.
7663    ///
7664    /// An [`undo`](Self::undo) or [`redo`](Self::redo) closes any open group,
7665    /// whatever its depth — the history has moved, and an edit made after it
7666    /// is not part of the step it moved past. A later `end_undo_group` is
7667    /// then a no-op.
7668    pub fn begin_undo_group(&mut self) {
7669        match &mut self.undo_group {
7670            Some(g) => g.depth += 1,
7671            None => {
7672                self.undo_group = Some(UndoGroup {
7673                    depth: 1,
7674                    has_step: false,
7675                });
7676                // The first edit inside is not a continuation of the typing
7677                // before it.
7678                self.last_edit_kind = None;
7679            }
7680        }
7681    }
7682
7683    /// Close the undo group [`begin_undo_group`](Self::begin_undo_group)
7684    /// opened. A no-op when none is open.
7685    pub fn end_undo_group(&mut self) {
7686        let Some(g) = &mut self.undo_group else {
7687            return;
7688        };
7689        if g.depth > 1 {
7690            g.depth -= 1;
7691        } else {
7692            self.close_undo_group();
7693        }
7694    }
7695
7696    /// Whether an undo group is open.
7697    pub fn in_undo_group(&self) -> bool {
7698        self.undo_group.is_some()
7699    }
7700
7701    /// Close any open group, however deeply nested.
7702    fn close_undo_group(&mut self) {
7703        if self.undo_group.take().is_some() {
7704            // Typing after the group is not a continuation of the last edit
7705            // in it.
7706            self.last_edit_kind = None;
7707        }
7708    }
7709
7710    /// Refresh the cached source and put the caret back where the step being
7711    /// undone/redone had it, clearing any active run.
7712    ///
7713    /// The caret comes from twig's blob for the restored state (what
7714    /// `record_caret` stored). `change` is only the fallback for a state with no
7715    /// blob — a caret at the end of the restored text, which is where this always
7716    /// landed before the blobs were kept. It is the edit site, not where the user
7717    /// was standing, so it's a floor and not the behaviour: undoing should hand
7718    /// back the document *and* the place you were working, which for an edit made
7719    /// anywhere but under the caret are two different places.
7720    fn after_history(&mut self, change: Change) {
7721        self.refresh();
7722        match self
7723            .editor
7724            .caret_blob()
7725            .ok()
7726            .and_then(|b| CaretState::from_blob(&b))
7727        {
7728            Some(state) => {
7729                self.caret = state.caret.min(self.source.len());
7730                self.anchor = state.anchor.map(|a| a.min(self.source.len()));
7731            }
7732            None => {
7733                self.caret = change.new.end.min(self.source.len());
7734                self.anchor = None;
7735            }
7736        }
7737        self.goal_col = None;
7738        self.last_edit_kind = None;
7739        self.dirty = self.source != self.clean_source;
7740        self.status = None;
7741        self.clamp_caret();
7742    }
7743
7744    // ── the file ──────────────────────────────────────────────────────────────
7745
7746    #[cfg(feature = "fs")]
7747    pub fn save(&mut self) {
7748        if self.is_untitled() {
7749            // No path to write and no name to invent: ⌘S on an untitled document
7750            // is a Save As, and only a frontend has a picker to ask with. Say so
7751            // rather than failing at the filesystem with an empty path.
7752            self.status = Some("untitled — save as…".into());
7753            return;
7754        }
7755        let path = self.path.clone();
7756        if self.write(&path) {
7757            self.mark_saved();
7758        }
7759    }
7760
7761    /// Save As: write the document to `path` and *move* it there — `self.path`
7762    /// becomes `path`, and every later [`Doc::save`] writes the new file. That's
7763    /// what Save As means; a copy would leave the user editing a document whose
7764    /// name is no longer where their keystrokes go.
7765    ///
7766    /// The move only happens if the bytes actually landed. A failed write leaves
7767    /// the path, `dirty`, and the disk watermark exactly as they were, with the
7768    /// same `save failed: …` status a failed [`Doc::save`] sets — the document
7769    /// must never come away believing it was saved.
7770    ///
7771    /// An existing `path` is overwritten, and the caller is the one that knows
7772    /// whether to ask first: a Save As picker has already run that prompt, and a
7773    /// second confirmation from down here would be the same question twice.
7774    ///
7775    /// `format` does **not** follow the new extension. The buffer is parsed as
7776    /// the format it was opened with, and re-reading it as another one is a
7777    /// conversion — a different, lossy operation that would throw away the undo
7778    /// history — not a rename. So `notes.md` saved as `notes.dj` holds Markdown
7779    /// in a `.dj` file, and `format_name()` keeps honestly saying `markdown`
7780    /// until it's reopened.
7781    #[cfg(feature = "fs")]
7782    pub fn save_as(&mut self, path: PathBuf) {
7783        if !self.write(&path) {
7784            return;
7785        }
7786        self.path = path;
7787        self.mark_saved();
7788    }
7789
7790    /// Put `source` on disk at `path`, reporting whether it got there. The one
7791    /// place leaf writes a document, so a save and a Save As can't disagree
7792    /// about what a failure looks like.
7793    #[cfg(feature = "fs")]
7794    fn write(&mut self, path: &Path) -> bool {
7795        match std::fs::write(path, self.source.as_bytes()) {
7796            Ok(()) => true,
7797            Err(e) => {
7798                self.status = Some(format!("save failed: {e}"));
7799                false
7800            }
7801        }
7802    }
7803
7804    /// Re-base the document's saved watermark to the current bytes: clears
7805    /// `dirty`, records `source` as the new clean state (so undoing back to here
7806    /// clears the flag again), and re-stamps the on-disk hash.
7807    ///
7808    /// [`Doc::save`]/[`Doc::save_as`] call this after a write lands. It is also
7809    /// the hook a **filesystem-free host** calls itself once it has persisted
7810    /// [`Doc::source`] its own way (a browser download, `localStorage`, a backend
7811    /// `PUT`) — which is why it is public and touches no filesystem: the bytes
7812    /// are already where that host wants them, and this just tells the model they
7813    /// are safe.
7814    pub fn mark_saved(&mut self) {
7815        self.clean_source = self.source.clone();
7816        self.dirty = false;
7817        // The bytes on disk are now ours, so this is the new watermark: without
7818        // re-stamping it, every save would report its own work as an external
7819        // change forever after.
7820        self.disk_hash = Some(hash_bytes(self.source.as_bytes()));
7821        self.status = Some(format!("saved {}", self.file_name()));
7822    }
7823
7824    /// What the file looks like now against the bytes leaf last read or wrote.
7825    ///
7826    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
7827    /// so this is a filesystem round-trip, not a per-frame question — ask it
7828    /// when a window regains focus, on a timer, or before a save.
7829    ///
7830    /// This *only* reports the file. Whether the document also has unsaved edits
7831    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
7832    /// [`DiskState::Changed`] means a save overwrites someone's work and a
7833    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
7834    /// it has no way to ask — so it hands a frontend both halves and lets it put
7835    /// the question to the person who can answer it.
7836    #[cfg(feature = "fs")]
7837    pub fn disk_state(&self) -> DiskState {
7838        let Some(want) = self.disk_hash else {
7839            return DiskState::Untitled;
7840        };
7841        match std::fs::read(&self.path) {
7842            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
7843            Ok(_) => DiskState::Changed,
7844            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
7845            Err(_) => DiskState::Unreadable,
7846        }
7847    }
7848
7849    /// Re-read the file and replace the document with what's there — the other
7850    /// answer to a [`DiskState::Changed`].
7851    ///
7852    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
7853    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
7854    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
7855    /// document shouldn't have to argue with a guard.
7856    ///
7857    /// **The undo history survives, and the reload is one step in it.** The
7858    /// whole buffer is spliced with the file's bytes through the same door every
7859    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
7860    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
7861    /// swapped the document out from under a reader gives them back what they
7862    /// were looking at, marked dirty, and ^Z again carries on into whatever they
7863    /// had done before it. This used to build a fresh parse and drop the stack,
7864    /// on the reasoning that twig's history belongs to the buffer and these are
7865    /// different bytes; that is true of *rebasing* a step onto them and not of
7866    /// recording the swap itself as one, which is all this is. A splice twig
7867    /// won't take falls back to the fresh parse, and only that path still costs
7868    /// the history.
7869    ///
7870    /// The caret keeps its byte offset, clamped to the new length; the selection
7871    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
7872    /// file changed, so it can't know where the caret "still" is. Clamping keeps
7873    /// it where the user left it in the common case (a change further down the
7874    /// file, or none in the text they're sitting in), and never puts it
7875    /// somewhere invalid. A selection has two such offsets and no such excuse —
7876    /// silently reinterpreting one over changed bytes would arm the *next*
7877    /// keystroke to delete something the user never selected.
7878    ///
7879    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
7880    /// document alone with a status.
7881    #[cfg(feature = "fs")]
7882    pub fn reload(&mut self) {
7883        if self.is_untitled() {
7884            self.status = Some("no file to reload".into());
7885            return;
7886        }
7887        let bytes = match std::fs::read(&self.path) {
7888            Ok(b) => b,
7889            Err(e) => {
7890                self.status = Some(format!("reload failed: {e}"));
7891                return;
7892            }
7893        };
7894        let Ok(source) = String::from_utf8(bytes) else {
7895            self.status = Some("reload failed: file is not UTF-8".into());
7896            return;
7897        };
7898        // Already these bytes — someone saved a file back unchanged, or leaf's
7899        // own write is being read back. Re-baseline against it and stop: a
7900        // splice of the text onto itself would put an undo step on the stack for
7901        // something nobody did.
7902        if source == self.source {
7903            self.disk_hash = Some(hash_bytes(source.as_bytes()));
7904            self.clean_source = source;
7905            self.dirty = false;
7906            self.status = Some(format!("reloaded {}", self.file_name()));
7907            return;
7908        }
7909        let caret = self.caret;
7910        // The pre-reload caret, so undoing the swap puts it back where the
7911        // reader was standing — the same bracketing `splice_exact` does.
7912        self.record_caret();
7913        if self
7914            .editor
7915            .edit_range(0, self.source.len(), &source)
7916            .is_ok()
7917        {
7918            self.refresh();
7919        } else {
7920            // twig wouldn't take the splice. Start over from the bytes, which is
7921            // what this always did, and is the one path that still costs the
7922            // history — `format` is the format this document *is*, not what the
7923            // (unchanged) name now says, see `save_as`.
7924            match new_editor(source.as_bytes(), self.format) {
7925                Ok(editor) => {
7926                    self.editor = editor;
7927                    // A fresh editor, and so a fresh history — with no
7928                    // step in it for an open group to fold into.
7929                    self.undo_steps = 0;
7930                    self.redo_steps = 0;
7931                    if let Some(g) = &mut self.undo_group {
7932                        g.has_step = false;
7933                    }
7934                    self.source = source.clone();
7935                    // Not going through `refresh`, so the revision has to move
7936                    // here or every frontend keeps painting the old file from
7937                    // cache.
7938                    self.revision += 1;
7939                }
7940                Err(e) => {
7941                    self.status = Some(format!("reload failed: {e}"));
7942                    return;
7943                }
7944            }
7945        }
7946        self.disk_hash = Some(hash_bytes(source.as_bytes()));
7947        self.clean_source = self.source.clone();
7948        self.caret = caret.min(self.source.len());
7949        self.anchor = None;
7950        self.goal_col = None;
7951        self.last_edit_kind = None;
7952        self.dirty = false;
7953        self.status = Some(format!("reloaded {}", self.file_name()));
7954        self.clamp_caret();
7955        // And the post-reload caret, so a redo restores it.
7956        self.record_caret();
7957    }
7958
7959    /// Re-read the source from twig after it has changed the document. The one
7960    /// funnel every edit, undo, and redo comes through — so it's where the
7961    /// revision moves, and anything cached against the text dies here.
7962    fn refresh(&mut self) {
7963        if let Ok(s) = self.editor.source_str() {
7964            self.source = s;
7965        }
7966        self.revision += 1;
7967        // An edit is a step onto the history and the end of anything undone;
7968        // `undo`/`redo` come through here too and correct this after.
7969        self.undo_steps = (self.undo_steps + 1).min(UNDO_CAP);
7970        self.redo_steps = 0;
7971        // Inside a group, fold each step into the group's first as it lands.
7972        // Not for `undo`/`redo`, which close the group before they get here.
7973        if let Some(g) = &mut self.undo_group {
7974            if g.has_step {
7975                self.fold_last_undo();
7976            } else {
7977                g.has_step = true;
7978            }
7979        }
7980        self.clamp_caret();
7981    }
7982
7983    /// Whether [`undo`](Self::undo) has a step to take back — for a native
7984    /// Edit menu to enable its item by, and exactly when `undo` would move.
7985    pub fn can_undo(&self) -> bool {
7986        !self.read_only && self.undo_steps > 0
7987    }
7988
7989    /// Whether [`redo`](Self::redo) has an undone step to restore.
7990    pub fn can_redo(&self) -> bool {
7991        !self.read_only && self.redo_steps > 0
7992    }
7993
7994    // ── caret movement ─────────────────────────────────────────────────────────
7995    // `extend` grows the selection (Shift+motion): it pins the anchor on the
7996    // first extended step and moves only the caret; an un-extended motion drops
7997    // the selection.
7998
7999    /// Place the caret at byte `offset` (clamped to a char boundary), extending
8000    /// the selection when `extend` is set. The public form of `move_to`, for a
8001    /// frontend that hit-tests pixels straight to a source offset.
8002    pub fn place_caret(&mut self, offset: usize, extend: bool) {
8003        self.goal_col = None;
8004        let before = self.caret;
8005        // A pixel hit-test can land between the visible caret stops — in the
8006        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
8007        // Snap to the nearest real stop so the caret can't come to rest where it
8008        // would draw in one place and type in another. The `(row, col)` click
8009        // path (`click`) already snaps this way through `offset_of_pos`; the
8010        // source view reaches every byte, so it snaps to nothing.
8011        let target = match self.view {
8012            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
8013            // The source view reaches every byte, so there is no stop to snap
8014            // to — but "every byte" still means every *character* boundary. A
8015            // caret resting inside a multi-byte character draws nowhere real
8016            // and panics the next time anything slices there.
8017            View::Source => self.char_boundary_at_or_before(offset),
8018        };
8019        self.move_to(target, extend);
8020        self.clamp_caret();
8021        self.debug_assert_on_a_stop(before);
8022    }
8023
8024    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
8025    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
8026    /// grab the metadata) while the source view still selects the literal whole.
8027    pub fn select_all(&mut self) {
8028        self.anchor = Some(self.caret_floor());
8029        self.caret = self.source.len();
8030        self.goal_col = None;
8031        self.last_edit_kind = None;
8032        self.status = None;
8033    }
8034
8035    /// Select the word (or whitespace / punctuation run) at `offset` — the
8036    /// double-click gesture. Anchors on the run's start with the caret at its
8037    /// end so a following Shift-motion extends from the far edge.
8038    pub fn select_word_at(&mut self, offset: usize) {
8039        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
8040        self.anchor = Some(s);
8041        self.caret = e;
8042        self.goal_col = None;
8043        self.last_edit_kind = None;
8044        self.status = None;
8045        self.clamp_caret();
8046    }
8047
8048    /// Select the whole enclosing text block (paragraph, heading, list item's
8049    /// text…) at `offset` — the triple-click gesture. Reads the range straight
8050    /// from the AST (twig's `content_span`), so it selects the entire *logical*
8051    /// paragraph even when that paragraph soft-wraps across several visual rows —
8052    /// where a visual-row-based select breaks down, because one source offset at
8053    /// a wrap boundary belongs to two rows at once.
8054    pub fn select_block_at(&mut self, offset: usize) {
8055        let off = offset.min(self.source.len());
8056        let range = self
8057            .editor
8058            .ancestors_at(off)
8059            .ok()
8060            .and_then(|chain| {
8061                // Ancestors run root → deepest; the deepest node that is neither
8062                // an inline span nor a multi-block container is the text block
8063                // the caret sits in (a paragraph, a heading, a code block…).
8064                chain
8065                    .into_iter()
8066                    .rev()
8067                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
8068                    .map(|m| m.content_span.unwrap_or(m.span))
8069            })
8070            .unwrap_or_else(|| source_line_range(&self.source, off));
8071        self.anchor = Some(range.start.min(self.source.len()));
8072        self.caret = range.end.min(self.source.len());
8073        self.goal_col = None;
8074        self.last_edit_kind = None;
8075        self.status = None;
8076        self.clamp_caret();
8077    }
8078
8079    /// Select the exact source range `[start, end)` — anchor at `start`, caret
8080    /// at `end` — without snapping either end to a visible caret stop.
8081    ///
8082    /// The one caret verb that takes a range it was *handed* rather than one it
8083    /// worked out, for a host that already knows the bytes it means: a search
8084    /// hit, an annotation's footprint, a quote re-anchored through
8085    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
8086    /// wrong tool for that, and not by a little — it snaps to the nearest
8087    /// *visible* stop, and where a range butts up against a hidden delimiter
8088    /// the nearest stop is the one before it, so selecting the "needle" of
8089    /// `**needle**` comes back with "needl" and an edit against it strands the
8090    /// "e".
8091    ///
8092    /// What `place_caret` does that is bookkeeping rather than snapping still
8093    /// happens here, because a host handing in a range is not asking to opt out
8094    /// of the invariants:
8095    ///
8096    /// - both ends are clamped into the document and up to
8097    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
8098    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
8099    ///   types into the metadata;
8100    /// - both land on character boundaries, so nothing slices a `é` in half;
8101    /// - the sticky vertical goal column is dropped, and any armed inline mark
8102    ///   disarmed, since a range from outside inherits neither.
8103    ///
8104    /// An empty range is a caret rather than a selection —
8105    /// [`selection`](Self::selection) reports `None` for it, as it does for any
8106    /// anchor that has met the caret.
8107    pub fn select_range(&mut self, start: usize, end: usize) {
8108        let floor = self.caret_floor();
8109        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
8110        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
8111        self.anchor = Some(anchor);
8112        self.caret = caret;
8113        self.goal_col = None;
8114        self.status = None;
8115        self.last_edit_kind = None;
8116        self.clear_pending();
8117    }
8118
8119    /// `offset` itself if it is a character boundary, else the boundary before
8120    /// it. An offset that isn't one draws nowhere real and panics the next time
8121    /// anything slices there.
8122    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
8123        let mut o = offset.min(self.source.len());
8124        while o > 0 && !self.source.is_char_boundary(o) {
8125            o -= 1;
8126        }
8127        o
8128    }
8129
8130    /// The lowest source offset the caret may occupy in the active view. In
8131    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
8132    /// the first rendered offset; the source view reaches everything, so it's 0.
8133    fn caret_floor(&self) -> usize {
8134        match self.view {
8135            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
8136            View::Source => 0,
8137        }
8138    }
8139
8140    /// Land in a table cell with its whole content selected — the anchor at the
8141    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
8142    /// like tabbing into a form field: the text comes up selected, so typing
8143    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
8144    /// end`) collapses to a plain caret home (an empty selection is no selection).
8145    fn select_cell(&mut self, start: usize, end: usize) {
8146        self.select_range(start, end);
8147    }
8148
8149    fn move_to(&mut self, offset: usize, extend: bool) {
8150        if extend {
8151            if self.anchor.is_none() {
8152                self.anchor = Some(self.caret);
8153            }
8154        } else {
8155            self.anchor = None;
8156        }
8157        self.caret = offset.min(self.source.len()).max(self.caret_floor());
8158        self.status = None;
8159        // A caret move ends the current typing/deletion run, so the next edit
8160        // starts a fresh undo group rather than coalescing across the gap.
8161        self.last_edit_kind = None;
8162        // Moving away disarms any sticky mark — "start bold" applies only where
8163        // it was asked for, not wherever the caret next lands.
8164        self.clear_pending();
8165    }
8166
8167    // In the source view, motion walks source bytes / source lines. In the
8168    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
8169    // what steps the caret cleanly over hidden delimiters.
8170
8171    pub fn move_left(&mut self, extend: bool) {
8172        self.goal_col = None;
8173        if !extend && let Some((s, _e)) = self.selection() {
8174            self.move_to(s, false);
8175            return;
8176        }
8177        let target = match self.view {
8178            View::Source => {
8179                if self.caret > 0 {
8180                    prev_boundary(&self.source, self.caret)
8181                } else {
8182                    0
8183                }
8184            }
8185            // Walks caret *stops*, not columns: decoration (a table border, a
8186            // cell's padding) is stepped over in one press, and a hidden
8187            // delimiter never holds the caret up — though the end of a mark's
8188            // content is a stop of its own (`VisualMap::mark_ends`), so
8189            // leaving `**bold**` from past its `**` is a press onto the end of
8190            // the bold and another onto the `d`.
8191            View::Wysiwyg => self
8192                .vmap
8193                .caret_stop_before(self.caret)
8194                .unwrap_or(self.caret),
8195        };
8196        let before = self.caret;
8197        self.move_to(target, extend);
8198        self.debug_assert_on_a_stop(before);
8199    }
8200
8201    pub fn move_right(&mut self, extend: bool) {
8202        self.goal_col = None;
8203        if !extend && let Some((_s, e)) = self.selection() {
8204            self.move_to(e, false);
8205            return;
8206        }
8207        let target = match self.view {
8208            View::Source => {
8209                if self.caret < self.source.len() {
8210                    next_boundary(&self.source, self.caret)
8211                } else {
8212                    self.caret
8213                }
8214            }
8215            View::Wysiwyg => self.vmap.caret_stop_after(self.caret).unwrap_or(self.caret),
8216        };
8217        let before = self.caret;
8218        self.move_to(target, extend);
8219        self.debug_assert_on_a_stop(before);
8220    }
8221
8222    /// Move to the start of the previous word (⌥← / Ctrl+←).
8223    pub fn move_word_left(&mut self, extend: bool) {
8224        self.goal_col = None;
8225        let before = self.caret;
8226        let target = self.word_left_from(self.caret);
8227        self.move_to(target, extend);
8228        self.debug_assert_on_a_stop(before);
8229    }
8230
8231    /// Move to the end of the next word (⌥→ / Ctrl+→).
8232    pub fn move_word_right(&mut self, extend: bool) {
8233        self.goal_col = None;
8234        let before = self.caret;
8235        let target = self.word_right_from(self.caret);
8236        self.move_to(target, extend);
8237        self.debug_assert_on_a_stop(before);
8238    }
8239
8240    // Word boundaries are found in the space the *view* is in. The source view
8241    // walks the source, because there the source is what's rendered. WYSIWYG
8242    // walks the rendered text instead: `**` is invisible to the user, so it has
8243    // to be invisible to word motion too — a caret parked inside one draws in
8244    // the column after `bold` and types two bytes earlier, and a word-delete
8245    // that stops there shreds the markup into `a ** c`.
8246
8247    /// The word boundary to the left of `off` in the active view's space.
8248    fn word_left_from(&self, off: usize) -> usize {
8249        match self.view {
8250            View::Source => prev_word(&self.source, off),
8251            View::Wysiwyg => self.glyph_word_left(off),
8252        }
8253    }
8254
8255    /// The word boundary to the right of `off` in the active view's space.
8256    fn word_right_from(&self, off: usize) -> usize {
8257        match self.view {
8258            View::Source => next_word(&self.source, off),
8259            View::Wysiwyg => self.glyph_word_right(off),
8260        }
8261    }
8262
8263    /// The character class of the glyph drawn at stop `off`.
8264    ///
8265    /// Read from the source, because a stop points at the source byte its glyph
8266    /// came from — the source *is* where the rendered character is written. What
8267    /// makes the walk glyph space rather than source space is that it only ever
8268    /// visits stops, and the hidden bytes between them have none.
8269    fn class_at(&self, off: usize) -> Class {
8270        self.source
8271            .get(off..)
8272            .and_then(|s| s.chars().next())
8273            .map_or(Class::Space, classify)
8274    }
8275
8276    /// [`next_word`] in glyph space: skip any leading separators, then consume
8277    /// the following word run, with the stop table standing in for the source's
8278    /// characters.
8279    fn glyph_word_right(&self, from: usize) -> usize {
8280        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
8281            return from;
8282        };
8283        let mut in_word = false;
8284        loop {
8285            match self.class_at(off) {
8286                Class::Word => in_word = true,
8287                _ if in_word => return off,
8288                _ => {}
8289            }
8290            match self.vmap.stop_after(off) {
8291                Some(next) => off = next,
8292                None => return off,
8293            }
8294        }
8295    }
8296
8297    /// [`prev_word`] in glyph space: skip separators walking left, then consume
8298    /// the preceding word run.
8299    fn glyph_word_left(&self, from: usize) -> usize {
8300        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
8301            return from;
8302        };
8303        let mut in_word = false;
8304        while let Some(prev) = self.vmap.stop_before(off) {
8305            match self.class_at(prev) {
8306                Class::Word => in_word = true,
8307                _ if in_word => return off,
8308                _ => {}
8309            }
8310            off = prev;
8311        }
8312        off
8313    }
8314
8315    /// After a motion that walks the visual map, the caret must be *on* the map.
8316    /// A stop is the only offset where the caret draws and edits in the same
8317    /// place, and it's the invariant both a caret parked inside an emoji and one
8318    /// parked inside a `**` were quietly breaking.
8319    ///
8320    /// Only when the caret actually moved: a walk with nowhere to go leaves it
8321    /// where it was, which is wherever the floor or a frontend put it rather
8322    /// than somewhere this motion chose.
8323    fn debug_assert_on_a_stop(&self, before: usize) {
8324        debug_assert!(
8325            self.view != View::Wysiwyg
8326                || self.vmap.num_rows() == 0
8327                || self.caret == before
8328                || self.vmap.is_stop(self.caret),
8329            "motion left the caret at {}, which is not a caret stop: it would draw in \
8330             one place and type in another",
8331            self.caret
8332        );
8333    }
8334
8335    // Up and Down run off the ends of the document rather than stopping dead at
8336    // them: Up from the first row lands at the document's start, Down from the
8337    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
8338    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
8339    // reaching the end of the text is what a reader means by it.
8340    //
8341    // The views used to disagree here by accident rather than by decision: the
8342    // source view fell into the edge behaviour through `row_col_to_offset`
8343    // clamping an out-of-range row to the end of the string, while WYSIWYG had
8344    // no row below to walk to and did nothing at all. They share the rule now,
8345    // each in its own space — the source view reaches every byte, WYSIWYG only
8346    // the offsets it draws.
8347
8348    pub fn move_up(&mut self, extend: bool) {
8349        let (row, col) = self.caret_pos();
8350        let goal = self.goal_col.unwrap_or(col);
8351        let target = match self.view {
8352            View::Source => match row.checked_sub(1) {
8353                Some(r) => row_col_to_offset(&self.source, r, goal),
8354                None => self.reachable_start(),
8355            },
8356            // A table's border rules are drawn but hold no caret, so Up steps
8357            // over them to the row that does.
8358            View::Wysiwyg => match self.vmap.navigable_above(row) {
8359                Some(r) => self.row_target(r, goal),
8360                None => self.reachable_start(),
8361            },
8362        };
8363        self.step_vertical(target, goal, extend);
8364    }
8365
8366    pub fn move_down(&mut self, extend: bool) {
8367        let (row, col) = self.caret_pos();
8368        let goal = self.goal_col.unwrap_or(col);
8369        let target = match self.view {
8370            View::Source => match self.source_row_below(row) {
8371                Some(r) => row_col_to_offset(&self.source, r, goal),
8372                None => self.reachable_end(),
8373            },
8374            View::Wysiwyg => match self.vmap.navigable_below(row) {
8375                Some(r) => self.row_target(r, goal),
8376                None => self.reachable_end(),
8377            },
8378        };
8379        self.step_vertical(target, goal, extend);
8380    }
8381
8382    /// Land a vertical motion at `target`, latching the `goal` column it aimed
8383    /// with so the rest of the run keeps aiming there.
8384    ///
8385    /// A motion with nowhere to go changes *nothing*, the goal column included:
8386    /// the latch used to run before the early return at the top of the document,
8387    /// so an Up that did nothing still armed a column, and the next Down aimed
8388    /// at one the caret had never been in.
8389    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
8390        let before = self.caret;
8391        if target == before {
8392            return;
8393        }
8394        self.goal_col = Some(goal);
8395        self.move_to(target, extend);
8396        self.debug_assert_on_a_stop(before);
8397    }
8398
8399    /// The source line below `row`, or `None` when `row` is the last one. Lines
8400    /// are counted by newline, so a trailing one leaves a real, empty last line
8401    /// for the caret to sit on — the document ends below it, not on it.
8402    fn source_row_below(&self, row: usize) -> Option<usize> {
8403        let last = self.source.bytes().filter(|&b| b == b'\n').count();
8404        (row < last).then_some(row + 1)
8405    }
8406
8407    /// Where a vertical motion aiming at the `goal` column lands on visual row
8408    /// `r`: the column clamped to the row, mapped to its offset, then held
8409    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
8410    /// column belongs to the row below, and a gutter's column 0 points at the
8411    /// block rather than at this row.
8412    fn row_target(&self, r: usize, goal: usize) -> usize {
8413        let (start, end) = self.row_bounds(r);
8414        self.vmap
8415            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
8416            .clamp(start, end)
8417    }
8418
8419    /// The first and last offsets the caret can reach in the active view.
8420    ///
8421    /// Not the same span in both: the source view shows every byte, so it can
8422    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
8423    /// sits below the first stop, and a document's trailing newline is drawn
8424    /// nowhere and so sits past the last.
8425    fn reachable_start(&self) -> usize {
8426        match self.view {
8427            View::Source => 0,
8428            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
8429        }
8430    }
8431
8432    fn reachable_end(&self) -> usize {
8433        match self.view {
8434            View::Source => self.source.len(),
8435            View::Wysiwyg => self
8436                .vmap
8437                .stop_at_or_before(self.source.len())
8438                .unwrap_or(self.caret),
8439        }
8440    }
8441
8442    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
8443    /// including the space a soft wrap ate off its end, which is drawn on this
8444    /// row however much the offset past it belongs to the next one.
8445    fn row_span(&self, r: usize) -> (usize, usize) {
8446        let start = self
8447            .vmap
8448            .row_start(r)
8449            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
8450        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
8451        (start.min(end), end)
8452    }
8453
8454    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
8455    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
8456    /// this row's last position is the one before it — the offset before the
8457    /// space the wrap ate, where the caret draws just past the row's last word
8458    /// and types there too.
8459    ///
8460    /// Aiming at the shared offset instead is what stalled End: it is the row's
8461    /// last *column*, so End pressed on the row reached it and then read back as
8462    /// the row below's start, where a second press ran on to that row's end and
8463    /// the next to the one after — End walking down the paragraph a row a press.
8464    fn row_bounds(&self, r: usize) -> (usize, usize) {
8465        let (start, end) = self.row_span(r);
8466        let wraps = self
8467            .vmap
8468            .navigable_below(r)
8469            .and_then(|b| self.vmap.row_start(b))
8470            .is_some_and(|off| off == end);
8471        match wraps {
8472            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
8473            false => (start, end),
8474        }
8475    }
8476
8477    /// The `[start, end]` of the line Home and End aim at: the visual row in
8478    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
8479    ///
8480    /// A soft-wrapped row is a line here, because it is one to the eye and the
8481    /// eye is what these keys are aimed by — a reader pressing End means the end
8482    /// of the line they can see. (`select_block_at` wants the opposite and reads
8483    /// the AST for it: a triple-click grabs the whole paragraph, however many
8484    /// rows it folds into.)
8485    fn line_bounds(&self) -> (usize, usize) {
8486        let (row, _) = self.caret_pos();
8487        match self.view {
8488            View::Source => {
8489                let start = line_start(&self.source, row);
8490                (start, line_end_from(&self.source, start))
8491            }
8492            View::Wysiwyg => self.row_bounds(row),
8493        }
8494    }
8495
8496    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
8497    /// *drawn* — what a kill takes.
8498    ///
8499    /// The two part only at a soft wrap, over the space the wrap ate: the caret
8500    /// can't stand after it (that offset opens the row below, and End stopping
8501    /// there would walk), but it is on this row, and a kill that spared it would
8502    /// leave a double space behind where the row's text had been. Deleting it
8503    /// joins nothing — a wrap is drawn, not written.
8504    fn line_span(&self) -> (usize, usize) {
8505        let (row, _) = self.caret_pos();
8506        match self.view {
8507            View::Source => self.line_bounds(),
8508            View::Wysiwyg => self.row_span(row),
8509        }
8510    }
8511
8512    /// The first offset in `[start, end]` holding something other than
8513    /// whitespace, or `end` when the line holds nothing else — where Home aims.
8514    ///
8515    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
8516    /// so a hidden delimiter is never taken for the line's first character (nor
8517    /// landed on), and the source view steps the source it is showing.
8518    fn first_non_space(&self, start: usize, end: usize) -> usize {
8519        let mut off = start;
8520        while off < end {
8521            if self.class_at(off) != Class::Space {
8522                return off;
8523            }
8524            off = match self.view {
8525                View::Source => next_boundary(&self.source, off),
8526                View::Wysiwyg => match self.vmap.stop_after(off) {
8527                    Some(next) => next,
8528                    None => return end,
8529                },
8530            };
8531        }
8532        end
8533    }
8534
8535    /// Home: to the first character on the line, or to column 0 when the caret
8536    /// is already on it — the two-press toggle every editor spells this way.
8537    /// The indentation is somewhere the caret has to be able to reach and almost
8538    /// never where a reader is headed, so it costs the second press.
8539    pub fn move_home(&mut self, extend: bool) {
8540        self.goal_col = None;
8541        let (start, end) = self.line_bounds();
8542        let text = self.first_non_space(start, end);
8543        let target = if self.caret == text { start } else { text };
8544        let before = self.caret;
8545        self.move_to(target, extend);
8546        self.debug_assert_on_a_stop(before);
8547    }
8548
8549    /// End: to the end of the line.
8550    pub fn move_end(&mut self, extend: bool) {
8551        self.goal_col = None;
8552        let (_, end) = self.line_bounds();
8553        let before = self.caret;
8554        self.move_to(end, extend);
8555        self.debug_assert_on_a_stop(before);
8556    }
8557
8558    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
8559    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
8560    /// when the caret isn't in a table, or is already in the last/first cell — the
8561    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
8562    /// meaning everywhere else.
8563    pub fn cell_hop(&mut self, forward: bool) -> bool {
8564        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8565            return false;
8566        };
8567        // Flatten to document (row-major) order and step one cell either way.
8568        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
8569        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
8570        let next = if forward {
8571            i.checked_add(1)
8572        } else {
8573            i.checked_sub(1)
8574        };
8575        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
8576            return false; // at the table's edge; leave Tab to the frontend
8577        };
8578        self.select_cell(start, end);
8579        true
8580    }
8581
8582    /// Move the caret to the cell directly above (`down == false`) or below in
8583    /// the same column, landing with the cell's whole content selected (see
8584    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
8585    /// when the caret isn't in a table), so the frontend can fall through — the
8586    /// vertical counterpart of [`Self::cell_hop`].
8587    ///
8588    /// A ragged row that is short a column clamps to its last cell, so Down never
8589    /// falls out of the table over a gap the row above happened to have.
8590    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
8591        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8592            return false;
8593        };
8594        let target = match down {
8595            true => r + 1,
8596            false if r == 0 => return false,
8597            false => r - 1,
8598        };
8599        let Some(row) = grid.get(target) else {
8600            return false;
8601        };
8602        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
8603            return false;
8604        };
8605        self.select_cell(start, end);
8606        true
8607    }
8608
8609    /// The table containing `off` as a row-major grid of `(start, end)` cell
8610    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
8611    /// isn't in a table. Read straight off the visual map's laid-out grid, so
8612    /// every cell (an empty one included, whose derived home twig gives no
8613    /// `content_span` for) is present and in the order Tab walks them.
8614    // Grid, row, column — three returns that only ever travel together, and a
8615    // named type for the pair of them would be read at one call site.
8616    #[allow(clippy::type_complexity)]
8617    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
8618        for t in &self.vmap.tables {
8619            let mut pos = None;
8620            let grid: Vec<Vec<(usize, usize)>> = t
8621                .grid
8622                .iter()
8623                .enumerate()
8624                .map(|(r, row)| {
8625                    row.cells
8626                        .iter()
8627                        .enumerate()
8628                        .map(|(c, cell)| {
8629                            if pos.is_none() && off >= cell.start && off <= cell.end {
8630                                pos = Some((r, c));
8631                            }
8632                            (cell.start, cell.end)
8633                        })
8634                        .collect()
8635                })
8636                .collect();
8637            if let Some((r, c)) = pos {
8638                return Some((grid, r, c));
8639            }
8640        }
8641        None
8642    }
8643
8644    // ── table key policy ──────────────────────────────────────────────────────
8645    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
8646    // as one policy every frontend shares, rather than each re-deriving it. Each
8647    // reports whether it acted *as a table key*; a `false` hands the key back to
8648    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
8649    // everywhere else.
8650
8651    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
8652    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
8653    /// back and simply stays put at the very first cell. `false` when the caret
8654    /// isn't in a table.
8655    pub fn cell_tab(&mut self, forward: bool) -> bool {
8656        if !self.caret_in_table() {
8657            return false;
8658        }
8659        if self.cell_hop(forward) {
8660            return true;
8661        }
8662        // Off the last cell: grow the table by a row and step into its first
8663        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
8664        if forward {
8665            self.append_row_and_enter(0);
8666        }
8667        true
8668    }
8669
8670    /// Return inside a table: drop to the cell below in the same column,
8671    /// appending a new row when the caret is already in the last one. `false`
8672    /// when the caret isn't in a table, so the frontend inserts a newline.
8673    pub fn cell_return(&mut self) -> bool {
8674        if !self.caret_in_table() {
8675            return false;
8676        }
8677        if self.cell_move_vertical(true) {
8678            return true;
8679        }
8680        // Already on the last row: grow one below and drop into the same column.
8681        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
8682        self.append_row_and_enter(col);
8683        true
8684    }
8685
8686    /// Append a row below the caret's (last) row and land in `col` of it. The
8687    /// caret is in the last row, so twig's "insert below" makes the fresh row the
8688    /// table's new last — but twig re-spells the whole table, moving every byte,
8689    /// so the destination is read back from the rebuilt grid by the table's
8690    /// position (stable across a row insert), not from the pre-edit caret.
8691    fn append_row_and_enter(&mut self, col: usize) {
8692        let table = self.caret_table_index();
8693        self.table_insert_row(true);
8694        self.rebuild_map();
8695        let Some((start, end)) = table
8696            .and_then(|ti| self.vmap.tables.get(ti))
8697            .and_then(|t| t.grid.last())
8698            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
8699            .map(|cell| (cell.start, cell.end))
8700        else {
8701            return;
8702        };
8703        self.select_cell(start, end);
8704    }
8705
8706    /// The index, among the document's tables, of the one the caret sits in —
8707    /// `None` when it's in none. Used to re-find a table after an edit re-spells
8708    /// it (a row insert leaves the table order unchanged).
8709    fn caret_table_index(&self) -> Option<usize> {
8710        let off = self.caret;
8711        self.vmap.tables.iter().position(|t| {
8712            t.grid
8713                .iter()
8714                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
8715        })
8716    }
8717
8718    /// Shift+Return inside a table: insert a hard line break *within* the current
8719    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
8720    /// table, so the frontend inserts an ordinary line break.
8721    ///
8722    /// A table row is a single source line, so the newline-spelled hard break
8723    /// can't live in a cell. twig spells the in-cell break the format's way
8724    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
8725    /// break round-trips as structure the renderer reads back as a line — not the
8726    /// opaque raw HTML the old raw-splice left behind.
8727    ///
8728    /// Djot has no idiomatic in-cell break, so twig refuses it
8729    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
8730    /// would render as the literal text `<br>`. The gesture is still *consumed*
8731    /// there — returning `false` would let the frontend insert a real newline,
8732    /// which splits the one-line row — it just leaves the cell unchanged and says
8733    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
8734    ///
8735    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
8736    /// have to be read together: djot is not the only `false`, and naming it in
8737    /// the message was already a guess that HTML — which spells the break as its
8738    /// own `<br>` — would have made wrong.
8739    pub fn cell_line_break(&mut self) -> bool {
8740        if self.read_only || !self.caret_in_table() {
8741            return false;
8742        }
8743        self.record_caret();
8744        match self.editor.insert_line_break(self.caret) {
8745            Ok(change) => {
8746                self.last_edit_kind = None;
8747                self.refresh();
8748                self.caret = change.new.end;
8749                self.anchor = None;
8750                self.goal_col = None;
8751                self.clamp_caret();
8752                self.dirty = self.source != self.clean_source;
8753                self.status = None;
8754                self.record_caret();
8755            }
8756            Err(twig::Error::UnsupportedFormat) => {
8757                self.status = Some(format!(
8758                    "in-cell line breaks aren't supported in {}",
8759                    self.format_name()
8760                ));
8761            }
8762            Err(_) => {}
8763        }
8764        true
8765    }
8766
8767    /// Rebuild the visual map at the width the last build used. A structural edit
8768    /// bumps the revision and swaps the source in, but leaves the *map* stale;
8769    /// when a single gesture edits and then moves over the result (Tab appending
8770    /// a row, then stepping into it), the move needs the map to already show the
8771    /// edit rather than waiting for the frontend's next frame.
8772    fn rebuild_map(&mut self) {
8773        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
8774        self.build_map(wrap);
8775    }
8776
8777    /// Move the caret to the very start of the document (⌘↑ on macOS,
8778    /// Ctrl+Home on Windows/Linux).
8779    pub fn move_doc_start(&mut self, extend: bool) {
8780        self.goal_col = None;
8781        self.move_to(0, extend);
8782    }
8783
8784    /// Move the caret to the very end of the document (⌘↓ on macOS,
8785    /// Ctrl+End on Windows/Linux).
8786    pub fn move_doc_end(&mut self, extend: bool) {
8787        self.goal_col = None;
8788        let end = self.source.len();
8789        self.move_to(end, extend);
8790    }
8791
8792    /// Point the caret at the body cell `(row, col)` the mouse landed on —
8793    /// `col` being a cell of the terminal grid, which is what a display column
8794    /// is. A click on the far cell of a wide character lands at that
8795    /// character's start; the mapping's own doc-comments carry the rule.
8796    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
8797        self.goal_col = None;
8798        let target = match self.view {
8799            View::Source => row_col_to_offset(&self.source, row, col),
8800            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
8801        };
8802        let before = self.caret;
8803        self.move_to(target, extend);
8804        self.debug_assert_on_a_stop(before);
8805    }
8806
8807    /// A click in the blank space under the document's last block.
8808    ///
8809    /// Not a click *on* anything, so it lands on nothing in particular: the
8810    /// caret goes onto an empty paragraph under the last block, wherever the
8811    /// pointer was horizontally — and if the document does not end with one,
8812    /// one is opened, which is the only way to get out from under a block Enter
8813    /// cannot leave. Enter inside a fenced code block is a literal newline (see
8814    /// [`newline`](Self::newline)), so a document that *ends* in a fence had no
8815    /// way out at all; and a click under any last block used to land at the
8816    /// pointer's x on the block's last line, which is what a click on that line
8817    /// means and not what a click under it does.
8818    ///
8819    /// "Ends with an empty paragraph" is two trailing newlines: the first closes
8820    /// the last line and the second opens the blank line the visual map lays
8821    /// out as a navigable empty row (see `emit_trailing_blank_lines`). A
8822    /// document ending inside an *unclosed* fence gets the fence closed first,
8823    /// since a newline written there would only be another line of code. An
8824    /// empty document has nothing to be under, and the caret simply goes to its
8825    /// start.
8826    ///
8827    /// In the source view the gesture is the ordinary one: the caret goes to the
8828    /// end of the source, and nothing is written. A read-only document likewise.
8829    pub fn click_past_end(&mut self) {
8830        self.goal_col = None;
8831        let len = self.source.len();
8832        if self.view == View::Source || self.read_only || self.source.trim().is_empty() {
8833            self.move_to(len, false);
8834            return;
8835        }
8836        let mut tail = String::new();
8837        if let Some(fence) = self.unclosed_fence_at_end() {
8838            if !self.source.ends_with('\n') {
8839                tail.push('\n');
8840            }
8841            tail.push_str(&fence);
8842            tail.push('\n');
8843        }
8844        let joined = format!("{}{tail}", self.source);
8845        let trailing = joined.len() - joined.trim_end_matches('\n').len();
8846        for _ in trailing..2 {
8847            tail.push('\n');
8848        }
8849        if !tail.is_empty() && !self.splice(len, len, &tail, EditKind::Other) {
8850            return;
8851        }
8852        let end = self.source.len();
8853        self.move_to(end, false);
8854    }
8855
8856    /// The closing fence a document ending inside an unclosed fenced code block
8857    /// needs — the opening fence's own run, behind the quote prefix the block
8858    /// wears — or `None` when the last block is closed, indented, or not a code
8859    /// block at all.
8860    ///
8861    /// Unclosed is when twig's content span reaches the block's end: a closing
8862    /// fence line would lie between the two. `code_info_span`'s read of the
8863    /// fence is not used because it starts at the block's span, which inside a
8864    /// quote is the quote marker rather than the fence.
8865    fn unclosed_fence_at_end(&mut self) -> Option<String> {
8866        let content_end = self.source.trim_end_matches('\n').len();
8867        let block = self
8868            .nodes()
8869            .into_iter()
8870            .filter(|n| n.kind == Kind::CodeBlock && n.span.end >= content_end)
8871            .max_by_key(|n| n.span.start)?;
8872        if block.content_span.as_ref()?.end < block.span.end {
8873            return None;
8874        }
8875        let line = self.source[block.span.start..].lines().next()?;
8876        let opening = line.trim_start_matches(['>', ' ', '\t']);
8877        let fence = opening.chars().next().filter(|c| matches!(c, '`' | '~'))?;
8878        let run: String = opening.chars().take_while(|&c| c == fence).collect();
8879        let prefix = self.quote_prefix_at(block.span.start);
8880        Some(format!("{prefix}{run}"))
8881    }
8882
8883    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
8884    /// screen if it has moved since the last frame, and never scroll past the
8885    /// last of `rows`.
8886    ///
8887    /// Only if it has *moved* — that's the whole point. Revealing the caret on
8888    /// every frame ties the viewport to it, and a scroll wheel that fights the
8889    /// caret for the viewport loses: the view snaps back the instant it tries to
8890    /// pass the caret's row, so the document can't be scrolled beyond what's
8891    /// already on screen. A caret move is the frontend's cue to follow; a scroll
8892    /// with the caret sitting still is the reader's cue to leave it alone.
8893    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
8894        if self.drawn_caret != Some(self.caret) {
8895            if caret_row < self.scroll {
8896                self.scroll = caret_row;
8897            } else if height > 0 && caret_row >= self.scroll + height {
8898                self.scroll = caret_row + 1 - height;
8899            }
8900            self.drawn_caret = Some(self.caret);
8901        }
8902        self.scroll = self.scroll.min(rows.saturating_sub(1));
8903    }
8904
8905    /// The caret's screen position `(row, col)` in the active view's grid, with
8906    /// `col` a display column: the cell to draw the caret in, which on a line of
8907    /// `你好` or emoji is not the count of characters before it.
8908    pub fn caret_pos(&self) -> (usize, usize) {
8909        match self.view {
8910            View::Source => offset_to_row_col(&self.source, self.caret),
8911            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
8912        }
8913    }
8914
8915    fn clamp_caret(&mut self) {
8916        if self.caret > self.source.len() {
8917            self.caret = self.source.len();
8918        }
8919        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
8920        // any selection anchor) to the first rendered offset.
8921        let floor = self.caret_floor();
8922        if self.caret < floor {
8923            self.caret = floor;
8924        }
8925        if let Some(a) = self.anchor
8926            && a < floor
8927        {
8928            self.anchor = Some(floor);
8929        }
8930        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
8931            self.caret -= 1;
8932        }
8933    }
8934}
8935
8936// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
8937
8938// Left/right motion and backspace/delete step by *grapheme cluster*, not
8939// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
8940// marks moves and deletes as the single character a user sees. Grapheme
8941// boundaries are a superset of char boundaries, so the caret stays valid for twig.
8942
8943/// How an insert of `text` groups for undo: a single typed character folds into
8944/// the run of typing around it, while a newline or a multi-character insert is a
8945/// step of its own.
8946fn typed_edit_kind(text: &str) -> EditKind {
8947    if text.chars().take(2).count() == 1 && text != "\n" {
8948        EditKind::Insert
8949    } else {
8950        EditKind::Other
8951    }
8952}
8953
8954fn prev_boundary(s: &str, i: usize) -> usize {
8955    let mut cursor = GraphemeCursor::new(i, s.len(), true);
8956    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
8957}
8958
8959fn next_boundary(s: &str, i: usize) -> usize {
8960    let mut cursor = GraphemeCursor::new(i, s.len(), true);
8961    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
8962}
8963
8964// ── word boundaries ──────────────────────────────────────────────────────────
8965// The shared primitive behind word-wise motion, word deletion, and
8966// double-click-to-select-a-word. A "word" is a maximal run of one character
8967// class; whitespace and punctuation are their own classes, so motion skips
8968// cleanly between them the way native text fields do.
8969
8970#[derive(PartialEq, Eq, Clone, Copy)]
8971enum Class {
8972    Word,
8973    Space,
8974    Other,
8975}
8976
8977/// The source range of an inline node's own visible text — the part of it a
8978/// WYSIWYG caret can reach, as against the delimiters that only spell it.
8979/// `None` for a node with no interior to empty (a `str`, a break).
8980///
8981/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
8982/// one delimiter in from the span — the same place the renderer maps it to. A
8983/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
8984/// against the source rather than trusted: a range guessed wrong here is text
8985/// deleted wrong.
8986fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
8987    if let Some(span) = n.content_span.clone() {
8988        return Some(span);
8989    }
8990    match n.kind.as_str() {
8991        "verbatim" | "inline_math" => {
8992            let text = n.text.as_ref()?;
8993            let start = n.span.start + 1;
8994            let range = start..start + text.len();
8995            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
8996        }
8997        _ => None,
8998    }
8999}
9000
9001/// The `id` a node declares, or `None` for one that declares none — the
9002/// attribute djot writes for a `{#v1}` and mints for a heading.
9003///
9004/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
9005/// names nothing, so it reads as absent rather than as the empty string.
9006fn declared_id(n: &FlatNode) -> Option<&str> {
9007    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
9008}
9009
9010/// A heading's words reduced to the form a link fragment spells them in:
9011/// lowercase, runs of anything else collapsed to a single `-`, with none left
9012/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
9013///
9014/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
9015/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
9016/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
9017/// any other language is still a heading someone will link to. Underscores
9018/// survive for the same reason they do on the web: they are word characters
9019/// wherever identifiers are written.
9020fn slug(text: &str) -> String {
9021    let mut out = String::new();
9022    let mut pending = false;
9023    for c in text.chars() {
9024        if c.is_alphanumeric() || c == '_' {
9025            if pending && !out.is_empty() {
9026                out.push('-');
9027            }
9028            pending = false;
9029            out.extend(c.to_lowercase());
9030        } else {
9031            pending = true;
9032        }
9033    }
9034    out
9035}
9036
9037/// The text of the inline run starting at `first` and its siblings, markup
9038/// stripped: each leaf's payload in order, a line break as a space. `nodes` is
9039/// the arena `Doc::nodes` returns, indexed by id.
9040fn inline_text(nodes: &[FlatNode], first: Option<NodeId>, out: &mut String) {
9041    let mut next = first;
9042    while let Some(id) = next {
9043        let Some(n) = nodes.get(id.0 as usize) else {
9044            return;
9045        };
9046        match (&n.text, &n.kind) {
9047            (Some(text), _) => out.push_str(text),
9048            (None, Kind::SoftBreak | Kind::HardBreak) => out.push(' '),
9049            (None, _) => inline_text(nodes, n.first_child, out),
9050        }
9051        next = n.next_sibling;
9052    }
9053}
9054
9055fn is_block_container(kind: &Kind) -> bool {
9056    matches!(
9057        kind,
9058        Kind::Doc
9059            | Kind::Section
9060            | Kind::BlockQuote
9061            | Kind::BulletList
9062            | Kind::OrderedList
9063            | Kind::TaskList
9064            | Kind::ListItem
9065            | Kind::TaskListItem
9066            // Every `container` — a directive in any of its three forms, or a
9067            // promoted HTML element. A *text* directive is really inline, so
9068            // claiming it here is a small overreach, and the deliberate one this
9069            // function's kind-only peer `is_inline_kind` documents: the pair is
9070            // consulted together, and answering "block container" for something
9071            // inline is what keeps an ancestor walk from stopping short of the
9072            // paragraph that actually holds it.
9073            | Kind::Container
9074    )
9075}
9076
9077/// The `[start, end)` byte range of the source line containing `off` (newline
9078/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
9079/// line between paragraphs).
9080fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
9081    let off = off.min(s.len());
9082    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
9083    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
9084    start..end
9085}
9086
9087/// How many leading bytes an outdent takes off `line`: a whole indent level
9088/// where the line has one, and whatever it has where it has less.
9089///
9090/// A leading tab counts as a level on its own. It's indentation some other
9091/// editor wrote, and one tab is one level everywhere it came from — measuring it
9092/// in spaces it doesn't contain would leave it untouchable.
9093fn outdent_width(line: &str, unit: usize) -> usize {
9094    if line.starts_with('\t') {
9095        return 1;
9096    }
9097    line.bytes().take(unit).take_while(|b| *b == b' ').count()
9098}
9099
9100/// A list marker found at the head of a line, together with everything before it
9101/// that a sibling line has to repeat.
9102///
9103/// The three offsets differ only inside a block quote, where `>   - b` opens with
9104/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
9105/// `line_start == marker_start`, and `text` is the plain `"  - "`.
9106#[derive(Clone, Debug)]
9107struct ListMarker {
9108    /// The line's first byte.
9109    line_start: usize,
9110    /// Where the marker proper begins, past any quote prefix. The offset to hand
9111    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
9112    marker_start: usize,
9113    /// `line_start` through the marker's trailing space — quote prefix, indent
9114    /// and bullet together, which is what the next item's line opens with.
9115    text: String,
9116}
9117
9118impl ListMarker {
9119    /// Where the item's content starts — one past the marker's trailing space.
9120    fn content_start(&self) -> usize {
9121        self.line_start + self.text.len()
9122    }
9123}
9124
9125fn classify(c: char) -> Class {
9126    if c == '_' || c.is_alphanumeric() {
9127        Class::Word
9128    } else if c.is_whitespace() {
9129        Class::Space
9130    } else {
9131        Class::Other
9132    }
9133}
9134
9135/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
9136/// skip any leading separators, then consume the following word run.
9137fn next_word(s: &str, i: usize) -> usize {
9138    let mut off = i;
9139    let mut in_word = false;
9140    for c in s[i..].chars() {
9141        if classify(c) == Class::Word {
9142            in_word = true;
9143        } else if in_word {
9144            break;
9145        }
9146        off += c.len_utf8();
9147    }
9148    off
9149}
9150
9151/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
9152/// skip separators walking left, then consume the preceding word run.
9153fn prev_word(s: &str, i: usize) -> usize {
9154    let mut off = i;
9155    let mut in_word = false;
9156    for c in s[..i].chars().rev() {
9157        if classify(c) == Class::Word {
9158            in_word = true;
9159        } else if in_word {
9160            break;
9161        }
9162        off -= c.len_utf8();
9163    }
9164    off
9165}
9166
9167/// The `[start, end)` run of same-class characters surrounding `off` — the
9168/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
9169/// the run ending there is used.
9170fn word_range_at(s: &str, off: usize) -> (usize, usize) {
9171    if s.is_empty() {
9172        return (0, 0);
9173    }
9174    let off = off.min(s.len());
9175    let reference = if off < s.len() {
9176        s[off..].chars().next()
9177    } else {
9178        s[..off].chars().next_back()
9179    };
9180    let Some(rc) = reference else {
9181        return (off, off);
9182    };
9183    let class = classify(rc);
9184
9185    let mut start = off;
9186    for c in s[..start].chars().rev() {
9187        if classify(c) == class {
9188            start -= c.len_utf8();
9189        } else {
9190            break;
9191        }
9192    }
9193    let mut end = off;
9194    for c in s[end..].chars() {
9195        if classify(c) == class {
9196            end += c.len_utf8();
9197        } else {
9198            break;
9199        }
9200    }
9201    (start, end)
9202}
9203
9204/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
9205/// the line's start — terminal cells, not characters, so the column names the
9206/// cell the caret is drawn in even on a line of `你好` or emoji.
9207fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
9208    let off = off.min(s.len());
9209    let mut row = 0;
9210    let mut line_start = 0;
9211    for (i, &b) in s.as_bytes().iter().enumerate() {
9212        if i >= off {
9213            break;
9214        }
9215        if b == b'\n' {
9216            row += 1;
9217            line_start = i + 1;
9218        }
9219    }
9220    (row, wysiwyg::text_width(&s[line_start..off]))
9221}
9222
9223/// The byte offset at display column `col` of `row` (clamped to that line's
9224/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
9225///
9226/// A column landing *inside* a character — the second cell of `你`, or any cell
9227/// but the first of an emoji — resolves to that character's start, which is the
9228/// column the caret would have been drawn at to begin with. So both cells of a
9229/// wide character mean the character, and every offset survives the round trip
9230/// out to a column and back. The walk steps by grapheme cluster for the same
9231/// reason the caret does: a cluster is the character, and the cells belong to it
9232/// rather than to the codepoints spelling it.
9233fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
9234    let start = line_start(s, row);
9235    let end = line_end_from(s, start);
9236    let mut off = start;
9237    let mut at = 0; // the display column `off` sits at
9238    while off < end {
9239        let next = next_boundary(s, off).min(end);
9240        let cells = wysiwyg::text_width(&s[off..next]);
9241        if at + cells > col {
9242            break; // `col` is one of this cluster's own cells
9243        }
9244        at += cells;
9245        off = next;
9246    }
9247    off
9248}
9249
9250fn line_start(s: &str, row: usize) -> usize {
9251    if row == 0 {
9252        return 0;
9253    }
9254    let mut r = 0;
9255    for (i, &b) in s.as_bytes().iter().enumerate() {
9256        if b == b'\n' {
9257            r += 1;
9258            if r == row {
9259                return i + 1;
9260            }
9261        }
9262    }
9263    s.len()
9264}
9265
9266fn line_end_from(s: &str, start: usize) -> usize {
9267    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
9268}
9269
9270/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
9271/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
9272/// twig applies writing the mark out, so the toolbar can light the same button
9273/// that made the node.
9274///
9275/// `None` for every other kind, including the inline nodes that aren't marks at
9276/// all (`str`, `link`, `image`, the math and break kinds): they're things a
9277/// caret stands in, not formatting a button toggles.
9278/// Whether a match from an ancestor chain is an inline run whose delimiters
9279/// the rich view draws nothing for — a mark (`**`, `_`, `==`), or an
9280/// attributed span: `<span data-size="large">…</span>`, djot's `[…]{…}`. The
9281/// span is a [`Kind::Container`], which the kind alone cannot tell from a
9282/// block `<div>`, so the chain's caller passes [`Doc::run_span_ids`] and the
9283/// answer is the node's own. Every delete and caret step that walks over a
9284/// `**` walks over a span's tags by this test; without it Backspace after
9285/// `</span>` took the `>` and left the paragraph unparseable.
9286fn hides_delims(m: &QueryMatch, run_spans: &[NodeId]) -> bool {
9287    inline_kind(&m.kind).is_some() || run_spans.contains(&NodeId(m.node_id))
9288}
9289
9290fn inline_kind(kind: &Kind) -> Option<InlineKind> {
9291    Some(match kind {
9292        Kind::Strong => InlineKind::Strong,
9293        Kind::Emph => InlineKind::Emph,
9294        Kind::Verbatim => InlineKind::Verbatim,
9295        Kind::Mark => InlineKind::Mark,
9296        Kind::Superscript => InlineKind::Superscript,
9297        Kind::Subscript => InlineKind::Subscript,
9298        Kind::Insert => InlineKind::Insert,
9299        Kind::Delete => InlineKind::Delete,
9300        _ => return None,
9301    })
9302}
9303
9304/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
9305/// a highlight's opening `==`.
9306///
9307/// Two enums for one closed vocabulary, and the duplication is the boundary
9308/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
9309/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
9310/// the editor writes. Spelled as a match rather than routed through the two
9311/// crates' name strings so that a colour added on either side is a compile
9312/// error here, where the pairing is decided, rather than a runtime `None` that
9313/// would read as "clear the colour".
9314fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
9315    match color {
9316        MarkColor::Red => twig::MarkColor::Red,
9317        MarkColor::Orange => twig::MarkColor::Orange,
9318        MarkColor::Yellow => twig::MarkColor::Yellow,
9319        MarkColor::Green => twig::MarkColor::Green,
9320        MarkColor::Blue => twig::MarkColor::Blue,
9321        MarkColor::Purple => twig::MarkColor::Purple,
9322        MarkColor::Brown => twig::MarkColor::Brown,
9323    }
9324}
9325
9326/// Where an offset lands after a splice it didn't make — twig's own rule, from
9327/// [`Change`]: shift anything at or past the replaced range's end by the length
9328/// the replacement gained or lost, and leave anything before it alone.
9329///
9330/// An offset *inside* the replaced range has no text of its own to ride any
9331/// more, and lands at the end of what replaced it: for
9332/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
9333/// the prefix is cleared, which then sits where the highlighted text begins.
9334/// One node's attribute list, twig's own `(key, value)` pairs owned — what
9335/// every presentation gesture reads, edits one key of, and passes back whole.
9336type Attrs = Vec<(String, Option<String>)>;
9337
9338/// The name of the leaf directive a page break is — [`Doc::insert_page_break`]
9339/// writes it and the walker draws it, and a frontend that paginates matches a
9340/// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) against it. One spelling,
9341/// stated once.
9342pub const PAGE_BREAK: &str = "page-break";
9343
9344/// `attrs` with `key` set to `value`, or removed when `value` is `None`, and
9345/// every other attribute kept in its place — the read-edit-write half of twig's
9346/// replace-not-merge contract for a `data-` key.
9347///
9348/// **A key that is already there is rewritten where it stands**, and only a key
9349/// the node did not have goes on the end. That is what makes the proposal's
9350/// worked example true: `class="lead center" id="intro"
9351/// data-line-height="1.5"`, right-aligned, is `class="lead right" id="intro"
9352/// data-line-height="1.5"` — the same document with one token changed, and a
9353/// one-line diff. Removing the key and pushing it back would reorder the
9354/// author's attributes on every press, so a document that passed through the
9355/// editor came out shuffled even where nothing about it had changed.
9356///
9357/// A duplicate key — which no format leaf opens can spell, but twig reports
9358/// verbatim — collapses onto the first of its copies, since twig is handed one
9359/// value for one key either way.
9360fn with_attr(attrs: &[(String, Option<String>)], key: &str, value: Option<&str>) -> Attrs {
9361    let mut out: Attrs = Vec::with_capacity(attrs.len() + 1);
9362    let mut written = false;
9363    for (k, v) in attrs {
9364        if k != key {
9365            out.push((k.clone(), v.clone()));
9366            continue;
9367        }
9368        if let Some(new) = value.filter(|_| !written) {
9369            out.push((k.clone(), Some(new.to_string())));
9370            written = true;
9371        }
9372    }
9373    if let Some(new) = value.filter(|_| !written) {
9374        out.push((key.to_string(), Some(new.to_string())));
9375    }
9376    out
9377}
9378
9379/// [`with_attr`] for a `class` token: every token `mine` claims is removed, and
9380/// `token` added, with the rest of the list kept in order.
9381///
9382/// `class` is a space-separated token list, and leaf owns three of the tokens in
9383/// it. A paragraph that arrives as `class="lead center"` and is right-aligned
9384/// goes out as `class="lead right"`; one whose last owned token goes and which
9385/// carried nothing else loses the key, so a block that has lost its whole
9386/// vocabulary is spelled bare again. `class` itself keeps its place among the
9387/// attributes, because [`with_attr`] does the writing.
9388fn with_class_token(
9389    attrs: &[(String, Option<String>)],
9390    mine: impl Fn(&str) -> bool,
9391    token: Option<&str>,
9392) -> Attrs {
9393    let kept: Vec<&str> = attrs
9394        .iter()
9395        .find(|(k, _)| k == "class")
9396        .and_then(|(_, v)| v.as_deref())
9397        .unwrap_or_default()
9398        .split_whitespace()
9399        .filter(|t| !mine(t))
9400        .collect();
9401    let class = kept.into_iter().chain(token).collect::<Vec<_>>().join(" ");
9402    with_attr(
9403        attrs,
9404        "class",
9405        (!class.is_empty()).then_some(class.as_str()),
9406    )
9407}
9408
9409/// An owned attribute list as the borrowed pairs twig's two attribute ops take.
9410///
9411/// A **bare** attribute — one twig reports with no value, such as HTML's `<p
9412/// hidden>` — is passed back as an empty one. Twig refuses a `None` outright
9413/// (djot has no bare attribute, so no format reads one back everywhere), and
9414/// `hidden=""` is the same document where `hidden` is; dropping it instead
9415/// would lose what the author wrote, which is the one thing these gestures
9416/// promise not to do.
9417fn attr_pairs(attrs: &[(String, Option<String>)]) -> Vec<(&str, Option<&str>)> {
9418    attrs
9419        .iter()
9420        .map(|(k, v)| (k.as_str(), Some(v.as_deref().unwrap_or_default())))
9421        .collect()
9422}
9423
9424fn reanchor(off: usize, change: &Change) -> usize {
9425    if off < change.old.start {
9426        return off;
9427    }
9428    if off < change.old.end {
9429        return change.new.end;
9430    }
9431    (off + change.new.end).saturating_sub(change.old.end)
9432}
9433
9434/// [`reanchor`] for an edit that respells the markup *around* a block and
9435/// leaves the block's own bytes alone — which is every attribute gesture.
9436///
9437/// `block` is that block's content span before and after the splice, so an
9438/// offset standing in the text keeps its distance from the text's start and how
9439/// many bytes twig wrote above it never enters the arithmetic. That is the whole
9440/// rule, and it is why nothing here knows how long a `<div …>` is: a second key
9441/// on the same div lengthens the attribute line, clearing the last one takes the
9442/// div away entirely, and both are the same sum. `None` where the splice named
9443/// no block at either end, which is every djot case — the `{…}` line is written
9444/// above the block, and the block itself only shifts past it.
9445///
9446/// Anywhere else it is `reanchor`'s own answer: untouched before the splice,
9447/// shifted by its delta after it, and at the splice's end for an offset that
9448/// stood in markup being rewritten — a caret inside djot's `{…}` line has no
9449/// text to keep.
9450fn reanchor_in_block(
9451    off: usize,
9452    change: &Change,
9453    block: Option<(&Range<usize>, &Range<usize>)>,
9454) -> usize {
9455    if let Some((was, now)) = block
9456        && was.start <= off
9457        && off <= was.end
9458    {
9459        return now.start + (off - was.start).min(now.end - now.start);
9460    }
9461    reanchor(off, change)
9462}
9463
9464/// A watermark for a file's contents (see `Doc::disk_hash`).
9465///
9466/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
9467/// watermark is compared only against one taken by the same process moments
9468/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
9469/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
9470fn hash_bytes(bytes: &[u8]) -> u64 {
9471    use std::hash::{Hash, Hasher};
9472    let mut h = std::collections::hash_map::DefaultHasher::new();
9473    bytes.hash(&mut h);
9474    h.finish()
9475}
9476
9477#[cfg(feature = "fs")]
9478fn detect_format(path: &Path) -> Result<Format> {
9479    let ext = path
9480        .extension()
9481        .and_then(|e| e.to_str())
9482        .unwrap_or("")
9483        .to_ascii_lowercase();
9484    Ok(match ext.as_str() {
9485        "dj" | "djot" => Format::Djot,
9486        "md" | "markdown" => Format::Markdown,
9487        "xml" => Format::Xml,
9488        "html" | "htm" => Format::Html,
9489        other => return Err(anyhow!("unknown document extension: .{other}")),
9490    })
9491}
9492
9493#[cfg(test)]
9494mod tests {
9495    use super::*;
9496    use crate::style::{FontFamily, LineSpacing, SizeStep};
9497
9498    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
9499    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
9500    /// without one is a view no user is ever in.
9501    fn doc_in(view: View, name: &str, body: &str) -> Doc {
9502        // The fixture name doubles as the temp file's, so two tests picking the
9503        // same one raced under the parallel runner and read each other's body —
9504        // a green suite proving the wrong thing. The counter makes that
9505        // unreachable rather than asking every future caller to notice.
9506        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
9507        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9508        let mut p = std::env::temp_dir();
9509        p.push(format!("leaf_test_{name}_{seq}.md"));
9510        std::fs::write(&p, body).unwrap();
9511        let mut d = Doc::open(p).unwrap();
9512        d.view = view;
9513        if view == View::Wysiwyg {
9514            d.build_visual(80);
9515        }
9516        d
9517    }
9518
9519    // Source-view document for the source-behaviour tests. `Doc::open` now
9520    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
9521    // `wysiwyg_doc` builds the rich-text variant on top of this.
9522    fn doc_with(name: &str, body: &str) -> Doc {
9523        doc_in(View::Source, name, body)
9524    }
9525
9526    /// Every visual row's drawn text — what the reader actually sees, which is
9527    /// the only thing the reveal preference is supposed to change.
9528    fn drawn_rows(d: &Doc) -> Vec<String> {
9529        d.vmap
9530            .rows
9531            .iter()
9532            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9533            .collect()
9534    }
9535
9536    /// Put the caret at the first byte of `needle` and rebuild, so the row under
9537    /// it becomes the revealed line.
9538    fn caret_at(d: &mut Doc, needle: &str) {
9539        d.caret = d.source.find(needle).expect("needle in source");
9540        d.build_visual(80);
9541    }
9542
9543    #[test]
9544    fn blockquote_after_a_list_is_not_bulleted() {
9545        // twig nests a following top-level block quote under the `bullet_list`
9546        // (a direct child, not a `list_item`). The map must render it de-nested —
9547        // `│ quote`, never `• │ quote` — with a blank separator, like any block
9548        // that follows a list. Regression for the "combined list + blockquote" bug.
9549        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
9550        d.build_visual(80);
9551        let rows: Vec<String> = d
9552            .vmap
9553            .rows
9554            .iter()
9555            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9556            .collect();
9557        assert!(
9558            rows.iter().any(|r| r == "│ quote"),
9559            "block quote should render on its own gutter, got rows: {rows:?}"
9560        );
9561        assert!(
9562            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
9563            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
9564        );
9565    }
9566
9567    // ── the map is built at most once per (revision, wrap) ───────────────────
9568    //
9569    // A frontend repaints for reasons that have nothing to do with the text — a
9570    // blinking caret, a scroll — and rebuilding the map is O(document). These
9571    // pin *that the cache fires*, which a passing suite can't tell you: a cache
9572    // that never hits is invisible to every other test in this file.
9573    //
9574    // The probe is to wreck the built map and ask for it again. A rebuild
9575    // repairs it; a cache hit hands the wreckage straight back. Nothing else
9576    // can distinguish the two from outside.
9577
9578    #[test]
9579    fn a_rebuild_with_nothing_changed_reuses_the_map() {
9580        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
9581        d.build_visual(80);
9582        assert!(!d.vmap.rows.is_empty());
9583        d.vmap.rows.clear(); // wreck it
9584        d.build_visual(80);
9585        assert!(
9586            d.vmap.rows.is_empty(),
9587            "the map was rebuilt though nothing changed — the cache never fired"
9588        );
9589    }
9590
9591    #[test]
9592    fn an_edit_rebuilds_the_map() {
9593        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
9594        d.build_visual(80);
9595        let before = d.revision();
9596        d.vmap.rows.clear();
9597        d.insert("x");
9598        d.build_visual(80);
9599        assert!(d.revision() > before, "an edit must move the revision");
9600        assert!(
9601            !d.vmap.rows.is_empty(),
9602            "an edited document must not paint from a stale map"
9603        );
9604    }
9605
9606    #[test]
9607    fn a_width_change_rebuilds_the_map() {
9608        // The map is a function of the wrap width too, so a resize is a miss
9609        // even though the text is untouched.
9610        let mut d = doc_in(
9611            View::Wysiwyg,
9612            "cache_width",
9613            "one two three four five six\n",
9614        );
9615        d.build_visual(80);
9616        d.vmap.rows.clear();
9617        d.build_visual(12);
9618        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
9619        // And the unwrapped map is its own key, not the same as any width.
9620        d.vmap.rows.clear();
9621        d.build_visual_unwrapped();
9622        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
9623    }
9624
9625    #[test]
9626    fn a_motion_does_not_rebuild_the_map() {
9627        // The whole point: moving the caret changes nothing the map is built
9628        // from. If a motion bumped the revision, every arrow key would cost a
9629        // full rebuild and the cache would be worthless.
9630        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
9631        d.build_visual(80);
9632        let rev = d.revision();
9633        d.move_right(false);
9634        d.move_right(true);
9635        d.move_down(false);
9636        assert_eq!(d.revision(), rev, "a motion must not move the revision");
9637        d.vmap.rows.clear();
9638        d.build_visual(80);
9639        assert!(
9640            d.vmap.rows.is_empty(),
9641            "a motion should not rebuild the map"
9642        );
9643    }
9644
9645    #[test]
9646    fn saving_does_not_rebuild_the_map() {
9647        // Saving changes `dirty`, not the text.
9648        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
9649        d.insert("x");
9650        d.build_visual(80);
9651        let rev = d.revision();
9652        d.save();
9653        assert_eq!(d.revision(), rev, "a save must not move the revision");
9654        assert!(!d.dirty, "the save should have cleaned the document");
9655    }
9656
9657    #[test]
9658    fn a_reload_rebuilds_the_map() {
9659        // Reload replaces the text without going through `refresh`, so it has to
9660        // move the revision itself — else the editor paints the old file.
9661        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
9662        d.build_visual(80);
9663        let rev = d.revision();
9664        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
9665        d.reload();
9666        assert!(d.revision() > rev, "a reload must move the revision");
9667        d.build_visual(80);
9668        let text: String = d
9669            .vmap
9670            .rows
9671            .iter()
9672            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
9673            .collect();
9674        assert!(
9675            text.contains("wholly new"),
9676            "the reloaded text should be on screen, got {text:?}"
9677        );
9678    }
9679
9680    // ── golden-case harness ──────────────────────────────────────────────────
9681    // The pattern the whole parity suite can reuse: write a fixture with the
9682    // caret marked by `|`, run one action, and compare the rendered result —
9683    // also caret-marked — against the expected string. One readable line per
9684    // behavior, and it exercises the exact `Doc` ops both frontends call.
9685
9686    /// Split a `|`-marked fixture into `(source, caret_offset)`.
9687    fn parse_caret(marked: &str) -> (String, usize) {
9688        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
9689        (marked.replacen('|', "", 1), caret)
9690    }
9691
9692    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
9693    /// selection) so a result reads like the fixtures.
9694    fn render_caret(d: &Doc) -> String {
9695        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
9696        // so the caret always renders inside its own selection.
9697        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
9698        if let Some((s, e)) = d.selection() {
9699            marks.push((s, 0, '['));
9700            marks.push((e, 2, ']'));
9701        }
9702        // Insert right-to-left: descending offset, then descending rank.
9703        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
9704        let mut out = d.source.clone();
9705        for (at, _, ch) in marks {
9706            out.insert(at, ch);
9707        }
9708        out
9709    }
9710
9711    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
9712    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9713        golden_in(View::Source, name, marked, action)
9714    }
9715
9716    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
9717    /// the same fixture has to read the same way in both.
9718    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9719        let (src, caret) = parse_caret(marked);
9720        let mut d = doc_in(view, name, &src);
9721        d.caret = caret;
9722        action(&mut d);
9723        render_caret(&d)
9724    }
9725
9726    #[test]
9727    fn word_motion_walks_word_by_word() {
9728        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
9729        assert_eq!(
9730            g("hello wor|ld", |d| d.move_word_left(false)),
9731            "hello |world"
9732        );
9733        assert_eq!(
9734            g("hello| world", |d| d.move_word_left(false)),
9735            "|hello world"
9736        );
9737        assert_eq!(
9738            g("hel|lo world", |d| d.move_word_right(false)),
9739            "hello| world"
9740        );
9741        assert_eq!(
9742            g("hello| world", |d| d.move_word_right(false)),
9743            "hello world|"
9744        );
9745        // Punctuation is its own class, so motion stops at the boundary.
9746        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
9747    }
9748
9749    #[test]
9750    fn word_motion_extends_the_selection_when_asked() {
9751        assert_eq!(
9752            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
9753            "hello [world|]"
9754        );
9755    }
9756
9757    #[test]
9758    fn delete_word_removes_a_whole_word() {
9759        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
9760        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
9761        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
9762        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
9763    }
9764
9765    // ── Home / End ───────────────────────────────────────────────────────────
9766
9767    #[test]
9768    fn home_toggles_between_the_line_s_text_and_its_margin() {
9769        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
9770        // indent to the markup it spells everywhere it means one, so the fixture
9771        // with whitespace left to walk is a code block, which is verbatim.
9772        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
9773        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
9774        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
9775        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
9776        // A line with no indentation has one place to go, so the toggle is a
9777        // no-op rather than a trip to nowhere.
9778        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
9779        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
9780
9781        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
9782        let indent = d.source.find("    indented").unwrap();
9783        d.caret = indent + 6; // inside "indented"
9784        d.move_home(false);
9785        assert_eq!(
9786            d.caret,
9787            indent + 4,
9788            "wysiwyg: Home aims at the code line's text"
9789        );
9790        d.move_home(false);
9791        assert_eq!(
9792            d.caret, indent,
9793            "wysiwyg: the second press takes the indent"
9794        );
9795        d.move_home(false);
9796        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
9797    }
9798
9799    #[test]
9800    fn end_takes_the_line_the_view_is_showing() {
9801        // The line differs by view for the same document, and that is the point:
9802        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
9803        // as a space on one row and the source view as two lines.
9804        let mut d = doc_with("end_src", "one two\nthree\n");
9805        d.caret = 1;
9806        d.move_end(false);
9807        assert_eq!(d.caret, 7, "source: the end of the source line");
9808
9809        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
9810        d.caret = 1;
9811        d.move_end(false);
9812        assert_eq!(
9813            d.caret, 13,
9814            "wysiwyg: the end of the row, soft break and all"
9815        );
9816    }
9817
9818    #[test]
9819    fn home_and_end_extend_the_selection_when_asked() {
9820        for (view, tag) in VIEWS {
9821            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
9822            d.caret = 6;
9823            d.move_end(true);
9824            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
9825            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
9826            d.caret = 6;
9827            d.move_home(true);
9828            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
9829        }
9830    }
9831
9832    // ── kill to the line's start / end ───────────────────────────────────────
9833
9834    #[test]
9835    fn kill_to_the_line_start_and_end_in_both_views() {
9836        for (view, tag) in VIEWS {
9837            // The gap that reads as a paragraph break in each view: the source
9838            // view's lines are the renderer's rows only where the source says so.
9839            let gap = if view == View::Source { "\n" } else { "\n\n" };
9840            let mut d = doc_in(
9841                view,
9842                &format!("kill_end_{tag}"),
9843                &format!("one two{gap}three\n"),
9844            );
9845            d.caret = 3;
9846            d.delete_to_line_end();
9847            assert_eq!(
9848                d.source,
9849                format!("one{gap}three\n"),
9850                "{tag}: ^K to the line's end"
9851            );
9852            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
9853
9854            let mut d = doc_in(
9855                view,
9856                &format!("kill_start_{tag}"),
9857                &format!("one two{gap}three\n"),
9858            );
9859            d.caret = 7; // the end of the first line
9860            d.delete_to_line_start();
9861            assert_eq!(
9862                d.source,
9863                format!("{gap}three\n"),
9864                "{tag}: ⌘⌫ to the line's start"
9865            );
9866            assert_eq!(d.caret, 0, "{tag}");
9867        }
9868    }
9869
9870    #[test]
9871    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
9872        // The decision: at the boundary both kills do nothing, rather than
9873        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
9874        // at a soft wrap as often as at a newline, where there is nothing
9875        // written to delete — and a source newline is only half of the blank
9876        // line between two paragraphs, so taking it leaves a soft break rather
9877        // than the join it looks like. Backspace and Delete are the keys for it.
9878        for (view, tag) in VIEWS {
9879            let gap = if view == View::Source { "\n" } else { "\n\n" };
9880            let src = format!("one{gap}three\n");
9881            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
9882            d.caret = 3; // the end of "one"
9883            d.delete_to_line_end();
9884            assert_eq!(
9885                d.source, src,
9886                "{tag}: ^K at the line's end joined it to the next"
9887            );
9888
9889            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
9890            d.caret = 3 + gap.len(); // the start of "three"
9891            d.delete_to_line_start();
9892            assert_eq!(
9893                d.source, src,
9894                "{tag}: ⌘⌫ at the line's start joined it to the last"
9895            );
9896        }
9897    }
9898
9899    #[test]
9900    fn a_kill_takes_the_selection_when_there_is_one() {
9901        // What every other delete here does with one, so these two as well.
9902        for (view, tag) in VIEWS {
9903            for (name, kill) in [
9904                (
9905                    "end",
9906                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
9907                ),
9908                ("start", |d: &mut Doc| d.delete_to_line_start()),
9909            ] {
9910                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
9911                d.anchor = Some(4);
9912                d.caret = 7; // "two"
9913                kill(&mut d);
9914                assert_eq!(
9915                    d.source, "one  three\n",
9916                    "{tag}: {name} ignored the selection"
9917                );
9918                assert_eq!(d.selection(), None, "{tag}: {name}");
9919            }
9920        }
9921    }
9922
9923    #[test]
9924    fn a_kill_takes_the_markup_it_empties_with_it() {
9925        // The same hazard a word-delete has: a WYSIWYG range covers what the
9926        // user can see, which for `**bold**` is the word and never the
9927        // delimiters, so a kill that stopped at the text would leave `a ****` —
9928        // markup wrapped around nothing.
9929        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
9930        d.caret = d.source.find("bold").unwrap();
9931        d.delete_to_line_end();
9932        assert_eq!(d.source, "a \n");
9933    }
9934
9935    #[test]
9936    fn a_kill_is_undone_in_one_step() {
9937        for (view, tag) in VIEWS {
9938            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
9939            d.caret = 3;
9940            d.delete_to_line_end();
9941            assert_eq!(d.source, "one\n", "{tag}");
9942            d.undo();
9943            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
9944        }
9945    }
9946
9947    #[test]
9948    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
9949        // Regression: triple-click used move_home/move_end over visual rows, so
9950        // it only worked on a paragraph's first row (a wrap-boundary offset maps
9951        // to the earlier row). select_block_at reads the AST, so every offset in
9952        // the paragraph selects the whole thing.
9953        let body = "one two three four five six seven eight\n";
9954        let mut d = doc_with("sel_block", body);
9955        d.view = View::Wysiwyg;
9956        d.build_visual(12); // force the paragraph to wrap into several rows
9957        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
9958        let para = (0, "one two three four five six seven eight".len());
9959        for off in [0usize, 8, 19, 28, 38] {
9960            d.caret = 0;
9961            d.anchor = None;
9962            d.select_block_at(off);
9963            assert_eq!(
9964                d.selection(),
9965                Some(para),
9966                "offset {off} should select the paragraph"
9967            );
9968        }
9969    }
9970
9971    #[test]
9972    fn select_block_uses_content_span_for_a_heading() {
9973        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
9974        d.select_block_at(4); // inside "Title"
9975        // content_span excludes the "# " marker.
9976        assert_eq!(d.selected_text(), Some("Title"));
9977        d.select_block_at(10); // inside "body"
9978        assert_eq!(d.selected_text(), Some("body"));
9979    }
9980
9981    #[test]
9982    fn select_all_spans_the_document() {
9983        let mut d = doc_with("sel_all", "abc\n\ndef\n");
9984        d.select_all();
9985        assert_eq!(d.selection(), Some((0, d.source.len())));
9986    }
9987
9988    #[test]
9989    fn select_word_at_picks_the_surrounding_word() {
9990        let mut d = doc_with("sel_word", "hello world\n");
9991        d.select_word_at(8); // inside "world"
9992        assert_eq!(d.selection(), Some((6, 11)));
9993        // Double-clicking at end-of-word still grabs the word to its left.
9994        d.select_word_at(5); // the space between the words
9995        assert_eq!(d.selection(), Some((5, 6)));
9996    }
9997
9998    #[test]
9999    fn word_helpers_respect_utf8_boundaries() {
10000        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
10001        assert_eq!(
10002            golden("utf8", "|café ok", |d| d.move_word_right(false)),
10003            "café| ok"
10004        );
10005        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
10006    }
10007
10008    #[test]
10009    fn typing_inserts_at_the_caret_and_advances_it() {
10010        let mut d = doc_with("type", "hello\n");
10011        d.insert("Hi ");
10012        assert_eq!(d.source, "Hi hello\n");
10013        assert_eq!(d.caret, 3);
10014        assert!(d.dirty);
10015    }
10016
10017    #[test]
10018    fn backspace_deletes_the_char_before_the_caret() {
10019        let mut d = doc_with("bs", "hello\n");
10020        d.caret = 3; // after "hel"
10021        d.backspace();
10022        assert_eq!(d.source, "helo\n");
10023        assert_eq!(d.caret, 2);
10024    }
10025
10026    #[test]
10027    fn typing_replaces_the_selection() {
10028        let mut d = doc_with("replace", "a word b\n");
10029        d.anchor = Some(2);
10030        d.caret = 6; // "word" selected
10031        d.insert("X");
10032        assert_eq!(d.source, "a X b\n");
10033        assert_eq!(d.caret, 3);
10034        assert_eq!(d.anchor, None);
10035    }
10036
10037    #[test]
10038    fn toggle_bold_wraps_then_unwraps_the_selection() {
10039        let mut d = doc_with("bold", "a word b\n");
10040        d.anchor = Some(2);
10041        d.caret = 6;
10042        d.toggle(InlineKind::Strong);
10043        assert_eq!(d.source, "a **word** b\n");
10044        // The toggled region stays selected, so a second toggle reverses it.
10045        d.toggle(InlineKind::Strong);
10046        assert_eq!(d.source, "a word b\n");
10047        d.toggle(InlineKind::Strong);
10048        assert_eq!(d.source, "a **word** b\n");
10049    }
10050
10051    #[test]
10052    fn toggle_code_wraps_then_unwraps_the_selection() {
10053        let mut d = doc_with("code_rt", "a word b\n");
10054        d.anchor = Some(2);
10055        d.caret = 6;
10056        d.toggle(InlineKind::Verbatim);
10057        assert_eq!(d.source, "a `word` b\n");
10058        d.toggle(InlineKind::Verbatim);
10059        assert_eq!(d.source, "a word b\n");
10060    }
10061
10062    #[test]
10063    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
10064        // ⌘b at a bare caret, then type: the text comes out bold with no
10065        // selection ever made — the word-processor "start bold here" gesture.
10066        let mut d = doc_with("sticky_wrap", "xy\n");
10067        d.caret = 1; // between x and y
10068        d.toggle(InlineKind::Strong);
10069        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
10070        d.insert("A");
10071        assert_eq!(d.source, "x**A**y\n");
10072    }
10073
10074    #[test]
10075    fn sticky_bold_lights_the_toolbar_before_any_typing() {
10076        // The button must light the instant ⌘b is pressed, or the mode is
10077        // invisible until the first character lands.
10078        let mut d = doc_with("sticky_light", "xy\n");
10079        d.caret = 1;
10080        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10081        d.toggle(InlineKind::Strong);
10082        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10083    }
10084
10085    #[test]
10086    fn sticky_bold_toggled_off_types_normally_again() {
10087        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
10088        // in the flow of typing, the exact sequence the user described.
10089        let mut d = doc_with("sticky_off", "\n");
10090        d.caret = 0;
10091        d.toggle(InlineKind::Strong);
10092        d.insert("a");
10093        d.insert("b"); // continues inside the run, no re-arming
10094        assert_eq!(d.source, "**ab**\n");
10095        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
10096        d.insert("c");
10097        assert_eq!(d.source, "**ab**c\n");
10098    }
10099
10100    #[test]
10101    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
10102        // Once a mark is realised the caret sits inside the run, so plain typing
10103        // extends it rather than starting a second, adjacent bold span.
10104        let mut d = doc_with("sticky_cont", "\n");
10105        d.caret = 0;
10106        d.toggle(InlineKind::Emph);
10107        d.insert("h");
10108        d.insert("i");
10109        assert_eq!(d.source, "*hi*\n");
10110    }
10111
10112    #[test]
10113    fn moving_the_caret_disarms_a_sticky_mark() {
10114        // Arming a mark and then moving away must not style text elsewhere.
10115        let mut d = doc_with("sticky_disarm", "xy\n");
10116        d.caret = 0;
10117        d.toggle(InlineKind::Strong);
10118        d.move_right(false); // caret 0 → 1, disarms
10119        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10120        d.insert("A");
10121        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
10122    }
10123
10124    #[test]
10125    fn stacked_sticky_marks_apply_together() {
10126        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
10127        let mut d = doc_with("sticky_stack", "\n");
10128        d.caret = 0;
10129        d.toggle(InlineKind::Strong);
10130        d.toggle(InlineKind::Emph);
10131        d.insert("x");
10132        // Land the caret on the styled character and confirm both marks are live.
10133        d.anchor = Some(d.source.find('x').unwrap());
10134        d.caret = d.anchor.unwrap() + 1;
10135        let marks = d.active_inline_marks();
10136        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
10137        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
10138    }
10139
10140    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
10141
10142    #[test]
10143    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
10144        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
10145        // The space inside the run made `**bold **`, which is *not* bold — four
10146        // literal asterisks — so the rich view drew them, correctly and
10147        // uselessly, until the next character happened to close the run again.
10148        let mut d = wysiwyg_doc("edge_typing", "a \n");
10149        d.caret = 2;
10150        d.toggle(InlineKind::Strong);
10151        for c in "bold".chars() {
10152            d.insert(&c.to_string());
10153        }
10154        assert_eq!(d.source, "a **bold**\n");
10155        d.insert(" ");
10156        assert_eq!(
10157            d.source, "a **bold** \n",
10158            "the space belongs outside the run"
10159        );
10160        assert!(
10161            d.active_inline_marks().contains(InlineKind::Strong),
10162            "bold is still what's being typed, so the button stays lit"
10163        );
10164        // What the writer is looking at while all this happens: their words.
10165        d.build_visual(80);
10166        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
10167        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
10168        for c in "hey".chars() {
10169            d.insert(&c.to_string());
10170        }
10171        assert_eq!(
10172            d.source, "a **bold hey**\n",
10173            "one bold phrase, not two runs"
10174        );
10175    }
10176
10177    #[test]
10178    fn typing_past_a_space_can_still_leave_the_bold_behind() {
10179        // The other half: the marks stay armed across the space, so ⌘b turns
10180        // them off again there and the next word is plain — the run isn't
10181        // rejoined by a caret that was told not to.
10182        let mut d = wysiwyg_doc("edge_shed", "\n");
10183        d.caret = 0;
10184        d.toggle(InlineKind::Strong);
10185        for c in "bold ".chars() {
10186            d.insert(&c.to_string());
10187        }
10188        assert_eq!(d.source, "**bold** \n");
10189        d.toggle(InlineKind::Strong);
10190        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10191        d.insert("x");
10192        assert_eq!(d.source, "**bold** x\n");
10193    }
10194
10195    #[test]
10196    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
10197        // ⌘b and then a space before any word: the space is not marked (nothing
10198        // is), and the word after it is.
10199        let mut d = wysiwyg_doc("edge_space_first", "a\n");
10200        d.caret = 1;
10201        d.toggle(InlineKind::Strong);
10202        d.insert(" ");
10203        assert_eq!(d.source, "a \n");
10204        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10205        d.insert("b");
10206        assert_eq!(d.source, "a **b**\n");
10207    }
10208
10209    #[test]
10210    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
10211        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
10212        d.caret = 8; // the caret's home at the end of the run's text
10213        d.insert(" ");
10214        assert_eq!(
10215            d.source, "x **bold** \n",
10216            "the space lands past the delimiters"
10217        );
10218        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
10219
10220        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
10221        d.caret = 4; // in front of the "b"
10222        d.insert(" ");
10223        assert_eq!(d.source, "x  **bold** y\n");
10224        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
10225    }
10226
10227    #[test]
10228    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
10229        // Backspace over the last letter of a bold phrase.
10230        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
10231        d.caret = 10; // past the "h"
10232        d.backspace();
10233        assert_eq!(d.source, "a **bold** \n");
10234        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
10235        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10236        d.insert("x");
10237        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
10238    }
10239
10240    #[test]
10241    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
10242        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
10243        // mark, which is only text. The marks live on in the caret instead.
10244        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
10245        d.caret = 5;
10246        d.backspace();
10247        assert_eq!(d.source, "a  c\n");
10248        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10249        d.insert("x");
10250        assert_eq!(d.source, "a **x** c\n");
10251    }
10252
10253    #[test]
10254    fn typing_over_a_whole_bold_word_keeps_it_bold() {
10255        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
10256        d.anchor = Some(4);
10257        d.caret = 8; // the word, not its delimiters
10258        d.insert("x");
10259        assert_eq!(d.source, "a **x** c\n");
10260    }
10261
10262    #[test]
10263    fn a_code_span_keeps_the_space_it_is_given() {
10264        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
10265        // is still verbatim, so nothing is re-spelt. The repair asks the parser
10266        // rather than a table of kinds, and this is the answer it gets.
10267        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
10268        d.caret = 7;
10269        d.insert(" ");
10270        assert_eq!(d.source, "a `code ` c\n");
10271    }
10272
10273    #[test]
10274    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
10275        // A run's closing delimiter has a caret home on each side of it, one
10276        // column apart on screen — and a plain ← off the space after a bold word
10277        // lands on the outer one. The character drawn behind the caret there is
10278        // still the last letter of the phrase, so that is what Backspace takes;
10279        // the byte behind it is a `*` nobody can see.
10280        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
10281        d.caret = 9;
10282        d.move_left(false);
10283        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
10284        d.backspace();
10285        assert_eq!(
10286            d.source, "**bol** x\n",
10287            "a letter of the phrase, not its `*`"
10288        );
10289        assert_eq!(d.caret, 5);
10290
10291        // And the mirror in front of the opening delimiter, where Delete's
10292        // character is the first letter of the run.
10293        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
10294        d.caret = 1;
10295        d.delete_forward();
10296        assert_eq!(d.source, "x**old**\n");
10297        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
10298    }
10299
10300    #[test]
10301    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
10302        // The byte beside the caret at either edge of a bold word is a `*` the
10303        // rich view draws nothing for. Taking it is not the character delete the
10304        // key was pressed for — it unspells the run and puts a literal asterisk
10305        // on screen (`a *bold** c`). The visible character is the one that goes.
10306        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
10307        d.caret = 4; // in front of the "b"
10308        d.backspace();
10309        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
10310
10311        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
10312        d.caret = 8; // past the "d"
10313        d.delete_forward();
10314        assert_eq!(d.source, "a **bold**c\n");
10315        assert_eq!(d.caret, 8, "and the caret stays inside the run");
10316        d.insert("x");
10317        assert_eq!(d.source, "a **boldx**c\n");
10318
10319        // A code span's backticks are hidden the same way, so they are covered
10320        // by the same rule and not by a list of kinds.
10321        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
10322        d.caret = 3;
10323        d.backspace();
10324        assert_eq!(d.source, "a`code` c\n");
10325    }
10326
10327    #[test]
10328    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
10329        // The asterisks are on the screen there and the caret can stand between
10330        // them, so a delete takes exactly the byte it is aimed at.
10331        let mut d = doc_with("edge_open_src", "a **bold** c\n");
10332        d.caret = 4;
10333        d.backspace();
10334        assert_eq!(d.source, "a *bold** c\n");
10335
10336        let mut d = doc_with("edge_close_src", "a **bold** c\n");
10337        d.caret = 8;
10338        d.delete_forward();
10339        assert_eq!(d.source, "a **bold* c\n");
10340    }
10341
10342    #[test]
10343    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
10344        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
10345        // The space had stepped outside the run (the mark-edge rule), taking the
10346        // caret with it, so the delete put it back down on the far side of the
10347        // closing `**` — one place on screen, and the wrong side of it. Typing
10348        // came out plain and the toolbar went dark, with nothing to see.
10349        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
10350        d.caret = 0;
10351        d.toggle(InlineKind::Strong);
10352        for c in "bold".chars() {
10353            d.insert(&c.to_string());
10354        }
10355        d.insert(" ");
10356        assert_eq!(d.source, "**bold** \n");
10357        d.backspace();
10358        assert_eq!(
10359            d.source, "**bold**\n",
10360            "the space goes, the delimiters stay"
10361        );
10362        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
10363        assert!(
10364            d.active_inline_marks().contains(InlineKind::Strong),
10365            "so the button is still lit"
10366        );
10367        d.insert("x");
10368        assert_eq!(
10369            d.source, "**boldx**\n",
10370            "and the next character is still bold"
10371        );
10372    }
10373
10374    #[test]
10375    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
10376        // What the stranded caret did next: the byte behind it was the closing
10377        // `*`, so a second press took that instead of a letter — `**bold*`, the
10378        // styling gone and an asterisk on the screen where the word had been.
10379        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
10380        d.caret = 0;
10381        d.toggle(InlineKind::Strong);
10382        for c in "bold ".chars() {
10383            d.insert(&c.to_string());
10384        }
10385        assert_eq!(d.source, "**bold** \n");
10386        d.backspace();
10387        d.backspace();
10388        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
10389        assert_eq!(d.caret, 5);
10390    }
10391
10392    #[test]
10393    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
10394        // `***both***` closes two runs with one stack of asterisks: the caret has
10395        // to walk in through all of them, or it lands between the emph and the
10396        // strong and types half-marked.
10397        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
10398        d.caret = 11;
10399        d.backspace();
10400        assert_eq!(d.source, "***both***\n");
10401        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
10402        d.insert("x");
10403        assert_eq!(d.source, "***bothx***\n");
10404    }
10405
10406    #[test]
10407    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
10408        // The settle only moves a caret a run actually closed over. Ordinary
10409        // deletes — inside a run, or in plain prose — are untouched.
10410        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
10411        d.caret = 8;
10412        d.backspace();
10413        assert_eq!(d.source, "a **bol** c\n");
10414        assert_eq!(d.caret, 7);
10415
10416        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
10417        d.caret = 5;
10418        d.backspace();
10419        assert_eq!(d.source, "plai\n");
10420        assert_eq!(d.caret, 4);
10421    }
10422
10423    #[test]
10424    fn the_source_view_leaves_a_delete_where_it_landed() {
10425        // The delimiters are on the screen there, so the offset past them is a
10426        // place the caret can be seen to be — nothing to settle.
10427        let mut d = doc_with("edge_bksp_src", "**bold** \n");
10428        d.caret = 9;
10429        d.backspace();
10430        assert_eq!(d.source, "**bold**\n");
10431        assert_eq!(d.caret, 8);
10432    }
10433
10434    #[test]
10435    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
10436        // `***both***` closes two runs with one stack of asterisks; a space that
10437        // clears only the inner one lands against the outer's and breaks that
10438        // instead.
10439        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
10440        d.caret = 9;
10441        d.insert(" ");
10442        assert_eq!(d.source, "a ***both*** \n");
10443        assert_eq!(d.caret, 13);
10444        d.insert("x");
10445        assert_eq!(d.source, "a ***both x***\n");
10446    }
10447
10448    #[test]
10449    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
10450        // The delimiter shuffle is not an edit the writer made, so it is not a
10451        // step they have to undo past.
10452        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
10453        d.caret = 8;
10454        d.insert(" ");
10455        assert_eq!(d.source, "a **bold** \n");
10456        d.undo();
10457        assert_eq!(d.source, "a **bold**\n");
10458    }
10459
10460    #[test]
10461    fn the_source_view_types_the_space_where_it_was_asked_to() {
10462        // The rule is a rich-view courtesy. In the source view the delimiters are
10463        // on the screen and the user is editing the bytes they can see.
10464        let mut d = doc_with("edge_src", "a **bold** c\n");
10465        d.caret = 8;
10466        d.insert(" ");
10467        assert_eq!(d.source, "a **bold ** c\n");
10468    }
10469
10470    #[test]
10471    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
10472        // Double-clicking a word takes the space after it; bolding that must not
10473        // spell `**word **`, which is not bold at all.
10474        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
10475        d.anchor = Some(2);
10476        d.caret = 7; // "word "
10477        d.toggle(InlineKind::Strong);
10478        assert_eq!(d.source, "a **word** b\n");
10479        d.toggle(InlineKind::Strong);
10480        assert_eq!(d.source, "a word b\n");
10481        d.toggle(InlineKind::Strong);
10482        assert_eq!(
10483            d.source, "a **word** b\n",
10484            "reapplying the mark must not wrap stale delimiter offsets"
10485        );
10486        // And a selection of nothing but whitespace has no word to mark.
10487        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
10488        d.anchor = Some(6);
10489        d.caret = 7;
10490        d.toggle(InlineKind::Strong);
10491        assert_eq!(d.source, "a word b\n");
10492        assert!(d.status.is_some());
10493    }
10494
10495    #[test]
10496    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
10497        let mut d = doc_with("head_set", "hello\n");
10498        d.caret = 2; // caret inside the paragraph, no selection
10499        d.set_block(BlockKind::Heading(1));
10500        assert_eq!(d.source, "# hello\n");
10501    }
10502
10503    #[test]
10504    fn set_block_heading_works_in_wysiwyg_view() {
10505        // The app defaults to WYSIWYG; the caret is a source offset either way.
10506        let mut d = wysiwyg_doc("head_wys", "hello\n");
10507        d.caret = 2;
10508        d.set_block(BlockKind::Heading(1));
10509        assert_eq!(d.source, "# hello\n");
10510    }
10511
10512    #[test]
10513    fn toggle_heading_applies_switches_and_reverts() {
10514        let mut d = doc_with("head_toggle", "hello\n");
10515        d.caret = 2;
10516        d.toggle_heading(1);
10517        assert_eq!(d.source, "# hello\n"); // paragraph → H1
10518        d.toggle_heading(2);
10519        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
10520        d.toggle_heading(2);
10521        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
10522    }
10523
10524    #[test]
10525    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
10526        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
10527        // the blank line but the caret rendered on the *next* line, because the
10528        // separator was a non-navigable decoration row. In Preserve flow that
10529        // blank line is a real caret home — the caret must resolve onto it, and
10530        // typing there makes the soft break that continues the paragraph.
10531        let src = "line one:\nsecond line\n";
10532        let mut d = wysiwyg_doc("pre_enter_lineend", src);
10533        d.set_line_flow(LineFlow::Preserve);
10534        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
10535        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
10536        d.newline();
10537        d.build_visual_unwrapped();
10538        assert_eq!(d.source, "line one:\n\nsecond line\n");
10539        assert_eq!(
10540            d.caret, 10,
10541            "caret sits on the new blank line, not the next line"
10542        );
10543        // The blank line is row 1, and the caret resolves onto it — not row 2.
10544        assert_eq!(
10545            d.vmap.pos_of_offset(10),
10546            (1, 0),
10547            "caret renders on the blank row"
10548        );
10549        assert!(
10550            !d.vmap.rows[1].decoration,
10551            "the blank line is navigable in Preserve"
10552        );
10553        // Typing there makes a soft break: one paragraph, three lines.
10554        d.insert("new clause,");
10555        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
10556    }
10557
10558    #[test]
10559    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
10560        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
10561        // that keeps it one paragraph — where Fold would open a second paragraph.
10562        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
10563        d.set_line_flow(LineFlow::Preserve);
10564        d.caret = 3;
10565        d.newline();
10566        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
10567
10568        // End-of-paragraph: Enter then typing continues the same paragraph on a
10569        // new line (a soft break), not a fresh paragraph.
10570        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
10571        d.set_line_flow(LineFlow::Preserve);
10572        d.caret = 3;
10573        d.newline();
10574        d.insert("def");
10575        assert_eq!(
10576            d.source, "abc\ndef\n",
10577            "end-of-line Enter + typing is a soft break"
10578        );
10579    }
10580
10581    #[test]
10582    fn preserve_double_enter_still_makes_a_paragraph() {
10583        // Two Enters in a row promote to a real paragraph break: the second lands
10584        // on the blank line the first opened and takes the empty-line branch.
10585        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
10586        d.set_line_flow(LineFlow::Preserve);
10587        d.caret = 3;
10588        d.newline();
10589        d.newline();
10590        d.insert("def");
10591        assert_eq!(
10592            d.source, "abc\n\ndef\n",
10593            "double Enter is a paragraph break"
10594        );
10595    }
10596
10597    #[test]
10598    fn preserve_backspace_joins_across_a_soft_break() {
10599        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
10600        // soft break it deletes the single newline and joins the two lines.
10601        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
10602        d.set_line_flow(LineFlow::Preserve);
10603        d.build_visual(80);
10604        d.caret = 4; // start of "def", just past the soft break
10605        d.backspace();
10606        assert_eq!(
10607            d.source, "abcdef\n",
10608            "Backspace joins across the soft break"
10609        );
10610        assert_eq!(d.caret, 3, "caret lands where the lines meet");
10611    }
10612
10613    #[test]
10614    fn fold_enter_still_starts_a_new_paragraph() {
10615        // The default flow is unchanged: a lone `\n` would render as an invisible
10616        // space, so Enter keeps opening the paragraph break that actually shows.
10617        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
10618        d.caret = 3;
10619        d.newline();
10620        assert_eq!(
10621            d.source, "abc\n\ndef\n",
10622            "Fold mid-line Enter is a paragraph break"
10623        );
10624    }
10625
10626    #[test]
10627    fn wysiwyg_one_enter_starts_a_new_paragraph() {
10628        // Regression: one Enter left the caret between the two newlines, so typing
10629        // made a soft break (one paragraph) and you needed a second Enter.
10630        let mut d = wysiwyg_doc("wys_enter", "abc\n");
10631        d.caret = 3;
10632        d.newline();
10633        d.insert("def");
10634        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
10635    }
10636
10637    #[test]
10638    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
10639        // Regression: Enter at the caret's natural End-of-line resting place
10640        // after a bold run with nothing following it (on screen: right after
10641        // "bold", before the hidden closing "**") spliced the paragraph break
10642        // at that very byte offset — which sits *before* the closing "**" in
10643        // the source, since the delimiter is hidden and emits no glyph of its
10644        // own for `push_row`'s "end of row" fallback to count. That severed the
10645        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
10646        // "**" alone on the new line instead of leaving "**bold**" intact with
10647        // a fresh empty paragraph after it.
10648        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
10649        d.move_end(false); // the WYSIWYG End key, from caret 0
10650        assert_eq!(
10651            d.caret, 6,
10652            "caret rests right after \"bold\", before the hidden \"**\""
10653        );
10654        d.newline();
10655        assert!(
10656            d.source.starts_with("**bold**"),
10657            "the closing ** must stay attached to \"bold\": got {:?}",
10658            d.source
10659        );
10660        assert_eq!(
10661            d.source, "**bold**\n\n\n",
10662            "a fresh empty paragraph follows the still-intact bold run"
10663        );
10664    }
10665
10666    #[test]
10667    fn source_view_enter_is_a_single_newline() {
10668        let mut d = doc_with("src_enter", "abc\n");
10669        d.caret = 3;
10670        d.newline();
10671        assert_eq!(d.source, "abc\n\n");
10672    }
10673
10674    #[test]
10675    fn heading_applies_at_the_end_of_a_paragraph() {
10676        // The caret at a line end sits at the doc level; set_block must still find
10677        // the block on that line.
10678        let mut d = doc_with("head_end", "abc\n");
10679        d.caret = 3; // end of "abc"
10680        d.toggle_heading(1);
10681        assert_eq!(d.source, "# abc\n");
10682    }
10683
10684    #[test]
10685    fn heading_on_an_empty_new_paragraph_creates_one() {
10686        let mut d = wysiwyg_doc("head_empty", "abc\n");
10687        d.caret = 3;
10688        d.newline(); // caret now on a fresh, empty paragraph
10689        d.toggle_heading(1);
10690        d.insert("Title");
10691        assert!(d.source.contains("# Title"), "got {:?}", d.source);
10692    }
10693
10694    #[test]
10695    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
10696        // The reported bug, end to end: click a blank line with another one under
10697        // it, press H1, type. The text landed in the heading and the caret's
10698        // offset was right (the source view drew it there), but the rich view
10699        // drew it two rows lower, on the trailing blank line — the empty `# `
10700        // heading had left every row below it short by the marker's two bytes,
10701        // and the blank line ended up claiming the heading's own end offset.
10702        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
10703        d.build_visual_unwrapped();
10704        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
10705        d.toggle_heading(1);
10706        for c in "title".chars() {
10707            d.insert(&c.to_string());
10708            d.build_visual_unwrapped(); // as a frontend does, one frame per key
10709        }
10710        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
10711        assert_eq!(
10712            d.caret_pos(),
10713            (4, 5),
10714            "the caret draws at the end of the heading"
10715        );
10716    }
10717
10718    #[test]
10719    fn clicking_an_empty_heading_types_after_its_marker() {
10720        // The same anchor from the other side: the empty heading's row is its own
10721        // caret home, so a click on it must land past the hidden `# `. Landing in
10722        // front of the hashes made the first keystroke un-heading the line.
10723        let mut d = wysiwyg_doc("head_click", "# \n");
10724        d.build_visual_unwrapped();
10725        d.caret = d.vmap.offset_of_pos(0, 0);
10726        d.insert("x");
10727        assert_eq!(d.source, "# x\n");
10728    }
10729
10730    #[test]
10731    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
10732        let mut d = wysiwyg_doc("head_enter", "# Title\n");
10733        d.caret = 7; // end of the heading
10734        d.newline();
10735        d.insert("body");
10736        assert_eq!(d.source, "# Title\n\nbody\n");
10737    }
10738
10739    #[test]
10740    fn wysiwyg_enter_continues_a_bullet_list() {
10741        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
10742        d.caret = 6; // end of "item"
10743        d.newline();
10744        d.insert("two");
10745        assert_eq!(d.source, "- item\n- two\n");
10746    }
10747
10748    #[test]
10749    fn wysiwyg_enter_increments_an_ordered_list() {
10750        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
10751        d.caret = 6; // end of "one"
10752        d.newline();
10753        d.insert("two");
10754        assert_eq!(d.source, "1. one\n2. two\n");
10755    }
10756
10757    #[test]
10758    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
10759        // Regression for the "extra newline" left between a list and the paragraph
10760        // below it. Enter, Enter leaves the list on a fresh empty paragraph
10761        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
10762        // Backspace should then take the caret cleanly back to the end of the list
10763        // item, `- item\n\nnext`, not delete a single newline and strand it on the
10764        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
10765        // no caret can land on. The map is rebuilt between keystrokes exactly as a
10766        // frontend does, since Backspace reads the stop table to place the delete.
10767        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
10768        d.caret = 6; // end of "item"
10769        d.newline();
10770        d.build_visual(80);
10771        d.newline(); // leave the list onto a fresh empty paragraph
10772        d.build_visual(80);
10773        assert_eq!(
10774            d.source, "- item\n\n\n\nnext\n",
10775            "double-Enter opens the empty paragraph"
10776        );
10777        d.backspace();
10778        assert_eq!(
10779            d.source, "- item\n\nnext\n",
10780            "one Backspace collapses the whole gap"
10781        );
10782        assert_eq!(
10783            d.caret, 6,
10784            "and lands the caret back at the end of the list item"
10785        );
10786    }
10787
10788    #[test]
10789    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
10790        // The stop-wise delete must not over-reach when there is no block boundary
10791        // to cross: two blank lines in a row are one caret stop apart, so pressing
10792        // Enter on an empty line and then Backspace removes exactly the one newline
10793        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
10794        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
10795        d.caret = 5; // the empty paragraph the first Enter already opened
10796        d.build_visual(80);
10797        d.newline();
10798        d.build_visual(80);
10799        assert_eq!(
10800            d.source, "abc\n\n\n\n",
10801            "Enter on the blank line adds one newline"
10802        );
10803        d.backspace();
10804        assert_eq!(
10805            d.source, "abc\n\n\n",
10806            "Backspace takes back exactly that one newline"
10807        );
10808    }
10809
10810    #[test]
10811    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
10812        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
10813        d.caret = 6; // end of the empty "- " item
10814        d.newline();
10815        d.insert("p");
10816        assert_eq!(d.source, "- a\n\np\n");
10817    }
10818
10819    #[test]
10820    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
10821        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
10822        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
10823        // not take the list-exit path (which would splice the `- ` away as if
10824        // leaving an empty item); the AST guard sends it to a normal break and
10825        // leaves the underline intact.
10826        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
10827        assert!(
10828            d.nodes().iter().any(|n| n.kind == Kind::Heading),
10829            "precondition: twig parses this as a heading, not a list",
10830        );
10831        d.caret = 7; // on the `- ` underline line
10832        d.newline();
10833        assert!(
10834            d.source.contains("- "),
10835            "the setext underline survives, not spliced away as a list item: {:?}",
10836            d.source,
10837        );
10838    }
10839
10840    #[test]
10841    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
10842        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
10843        d.caret = 7; // end of "abc" inside the fence
10844        d.newline();
10845        d.insert("def");
10846        assert_eq!(d.source, "```\nabc\ndef\n```\n");
10847    }
10848
10849    #[test]
10850    fn wysiwyg_enter_continues_a_block_quote() {
10851        // Enter opens a new *paragraph* inside the quote, not a second line of
10852        // the same one. `> quote\n> more` is a soft break, which under
10853        // `LineFlow::Fold` renders as a space — the keystroke would look like it
10854        // did nothing. The quoted blank line is what makes the break visible, and
10855        // it's the same thing Enter does in running prose.
10856        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
10857        d.caret = 7; // end of "quote"
10858        d.newline();
10859        d.insert("more");
10860        assert_eq!(d.source, "> quote\n>\n> more\n");
10861        // Still one quote, now holding two paragraphs — not a quote and a stray
10862        // line that fell out of it.
10863        let quotes = d
10864            .nodes()
10865            .iter()
10866            .filter(|n| n.kind == Kind::BlockQuote)
10867            .count();
10868        assert_eq!(quotes, 1);
10869    }
10870
10871    #[test]
10872    fn set_block_makes_a_heading_at_the_caret() {
10873        let mut d = doc_with("head", "Title\n\nbody\n");
10874        d.caret = 0;
10875        d.set_block(BlockKind::Heading(2));
10876        assert_eq!(d.source, "## Title\n\nbody\n");
10877        d.set_block(BlockKind::Paragraph);
10878        assert_eq!(d.source, "Title\n\nbody\n");
10879    }
10880
10881    // ── block containers (quote / list) ──────────────────────────────────────
10882
10883    #[test]
10884    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
10885        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
10886        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
10887        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
10888        // A caret at a line end sits at the doc level; the block is still found.
10889        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
10890    }
10891
10892    #[test]
10893    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
10894        // Every source line of the paragraph gets its own `> `, so a caret left
10895        // on its old byte offset falls one prefix per line above it too far
10896        // back — inside the markup it just asked for rather than in its word.
10897        assert_eq!(
10898            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
10899            "> aaa\n> b|bb\n> ccc\n"
10900        );
10901    }
10902
10903    #[test]
10904    fn toggle_blockquote_works_in_wysiwyg_view() {
10905        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
10906        assert_eq!(
10907            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
10908            "> hel|lo\n"
10909        );
10910        assert_eq!(
10911            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
10912            "hel|lo\n"
10913        );
10914    }
10915
10916    #[test]
10917    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
10918        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
10919        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
10920        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
10921        // The *other* kind converts in place instead of nesting, which is what
10922        // makes the two buttons one three-state control.
10923        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
10924        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
10925        // Its own kind, over the only item the list holds, takes it off.
10926        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
10927    }
10928
10929    #[test]
10930    fn toggle_list_works_in_wysiwyg_view() {
10931        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
10932        assert_eq!(
10933            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
10934            "1. hel|lo\n"
10935        );
10936        assert_eq!(
10937            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
10938            "- hel|lo\n"
10939        );
10940        assert_eq!(
10941            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
10942            "hel|lo\n"
10943        );
10944    }
10945
10946    #[test]
10947    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
10948        // The selection has to grow with the markup: twig takes a container off
10949        // only a range covering every block it holds, so the second press can
10950        // reverse the first only if the result is what's selected.
10951        let mut d = doc_with("list_sel", "abc\n\ndef\n");
10952        d.select_all();
10953        d.toggle_list(true);
10954        assert_eq!(d.source, "1. abc\n\n2. def\n");
10955        assert_eq!(d.selection(), Some((0, d.source.len())));
10956        d.toggle_list(true);
10957        assert_eq!(d.source, "abc\n\ndef\n");
10958    }
10959
10960    #[test]
10961    fn toggle_blockquote_nests_a_partly_covered_quote() {
10962        // twig's rule: covering only some of a container's blocks nests, because
10963        // taking the quote off would drag its uncovered siblings out with it.
10964        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
10965        d.caret = 2; // in the first quoted paragraph only
10966        d.toggle_blockquote();
10967        assert_eq!(d.source, "> > a\n>\n> b\n");
10968    }
10969
10970    #[test]
10971    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
10972        // A blank line used to be no block for twig to wrap —
10973        // `toggle_block_container` answered `NotFound` — so Quote and the list
10974        // buttons did nothing on the very line the H1 button works on, and leaf
10975        // lent twig a scratch paragraph to wrap and took it back out again.
10976        // twig 3.2.0 opens an empty container there itself, so what is left here
10977        // is where the caret lands: inside the marker that was just written.
10978        let mut d = doc_with("quote_blank", "\nabc\n");
10979        d.caret = 0;
10980        d.toggle_blockquote();
10981        assert_eq!(d.source, "> \nabc\n");
10982        assert_eq!(
10983            d.caret, 2,
10984            "the caret belongs inside the quote it just opened"
10985        );
10986        assert!(d.status.is_none(), "{:?}", d.status);
10987        assert!(d.dirty);
10988
10989        // And the paragraph below is still its own block: an empty container one
10990        // soft break from `abc` would take that paragraph into the quote with it.
10991        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
10992        d.caret = 0;
10993        d.toggle_blockquote();
10994        d.build_visual(80);
10995        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
10996
10997        // The same from the other side: a blank line directly under a paragraph
10998        // earns the blank line an empty block needs, rather than being read as a
10999        // soft break inside that paragraph.
11000        let mut d = doc_with("list_blank_below", "abc\n");
11001        d.caret = 4;
11002        d.toggle_list(false);
11003        assert_eq!(d.source, "abc\n\n- ");
11004        assert_eq!(d.caret, 7);
11005    }
11006
11007    #[test]
11008    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
11009        // The gesture the rendering fix is for. `newline` inside a quote already
11010        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
11011        // spelling — but the two marker lines it adds belonged to no node until
11012        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
11013        // just made drew as plain prose under the quote.
11014        let mut d = wysiwyg_doc("quote_enter", "> a\n");
11015        d.caret = 3; // past `a`, at the end of the quoted line
11016        d.newline();
11017        assert_eq!(d.source, "> a\n>\n> \n");
11018        d.build_visual(80);
11019        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
11020        // And the caret is on the new line, not stranded on the old one.
11021        assert_eq!(d.caret, 8);
11022    }
11023
11024    #[test]
11025    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
11026        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
11027        // now it is twig's single edit. Either way one ⌘z has to put the blank
11028        // line back rather than undoing into a half-built document.
11029        for open in [
11030            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
11031            &|d: &mut Doc| d.toggle_list(false),
11032            &|d: &mut Doc| d.toggle_list(true),
11033        ] {
11034            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
11035            d.caret = 3;
11036            open(&mut d);
11037            assert_ne!(d.source, "a\n\n\n\nb\n");
11038            d.undo();
11039            assert_eq!(d.source, "a\n\n\n\nb\n");
11040        }
11041    }
11042
11043    #[test]
11044    fn a_container_toggle_is_one_undo_step() {
11045        let mut d = doc_with("quote_undo", "hello\n");
11046        d.caret = 3;
11047        d.insert("X"); // a typing run the structural edit must not fold into
11048        d.toggle_blockquote();
11049        assert_eq!(d.source, "> helXlo\n");
11050        d.undo();
11051        assert_eq!(d.source, "helXlo\n");
11052    }
11053
11054    // ── links ────────────────────────────────────────────────────────────────
11055
11056    #[test]
11057    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
11058        let mut d = doc_with("link_sel", "word here\n");
11059        d.anchor = Some(0);
11060        d.caret = 4;
11061        d.insert_link("http://x.dev");
11062        assert_eq!(d.source, "[word](http://x.dev) here\n");
11063        // The text, not the destination — so a second press re-points the link
11064        // the first one made rather than nesting one inside it.
11065        assert_eq!(d.selected_text(), Some("word"));
11066        d.insert_link("http://y.dev");
11067        assert_eq!(d.source, "[word](http://y.dev) here\n");
11068        assert_eq!(d.selected_text(), Some("word"));
11069    }
11070
11071    #[test]
11072    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
11073        let mut d = doc_with("img_caret", "before after\n");
11074        d.caret = 7; // between "before " and "after"
11075        d.insert_image("cat.png", "a cat");
11076        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
11077        // The caret sits just past the inserted image, nothing selected.
11078        assert_eq!(d.selection(), None);
11079        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
11080    }
11081
11082    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
11083    /// destination at the first space, so the `format!` this used to be wrote
11084    /// something that was not an image at all — and the reader saw the markup as
11085    /// text. twig owns the spelling now, and moves it into the angle form.
11086    #[test]
11087    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
11088        let mut d = doc_with("img_space", "x\n");
11089        d.caret = 0;
11090        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
11091        assert_eq!(
11092            d.source,
11093            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
11094        );
11095        // And it reads back as an image pointing at the unescaped path — the angle
11096        // brackets are spelling, not part of the destination.
11097        d.caret = 2;
11098        assert_eq!(
11099            d.image_destination_at_caret(),
11100            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
11101        );
11102    }
11103
11104    /// A `)` in a caption or a filename must not close the image early.
11105    #[test]
11106    fn insert_image_escapes_a_paren_in_either_half() {
11107        let mut d = doc_with("img_paren", "x\n");
11108        d.caret = 0;
11109        d.insert_image("a)b.png", "");
11110        assert_eq!(d.source, "![](a\\)b.png)x\n");
11111        d.caret = 2;
11112        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
11113    }
11114
11115    #[test]
11116    fn insert_image_uses_the_selection_as_alt_text() {
11117        let mut d = doc_with("img_sel", "caption here\n");
11118        d.anchor = Some(0);
11119        d.caret = 7; // "caption"
11120        d.insert_image("p.png", "ignored fallback");
11121        assert_eq!(d.source, "![caption](p.png) here\n");
11122    }
11123
11124    #[test]
11125    fn insert_image_with_no_alt_leaves_empty_brackets() {
11126        let mut d = doc_with("img_noalt", "\n");
11127        d.caret = 0;
11128        d.insert_image("logo.svg", "");
11129        assert_eq!(d.source, "![](logo.svg)\n");
11130    }
11131
11132    // ── move_block ─────────────────────────────────────────────────────────────
11133
11134    /// A move, then its undo: one step takes the whole thing back.
11135    fn moved(name: &str, body: &str, from: usize, to: usize) -> (String, Doc) {
11136        let mut d = doc_with(name, body);
11137        d.caret = from;
11138        let steps = d.undo_steps;
11139        d.move_block(from, to);
11140        let after = d.source.clone();
11141        assert_eq!(d.undo_steps, steps + 1, "one undo step");
11142        assert!(d.dirty);
11143        d.undo();
11144        assert_eq!(d.source, body, "one undo restores the original");
11145        (after, d)
11146    }
11147
11148    #[test]
11149    fn move_block_carries_a_paragraph_between_two_paragraphs_and_to_the_end() {
11150        let body = "a\n\nb\n\nc\n";
11151        assert_eq!(moved("mv_p1", body, 6, 3).0, "a\n\nc\n\nb\n");
11152        assert_eq!(moved("mv_p2", body, 0, body.len()).0, "b\n\nc\n\na\n");
11153        assert_eq!(moved("mv_p3", body, 3, 0).0, "b\n\na\n\nc\n");
11154    }
11155
11156    #[test]
11157    fn move_block_carries_an_image_block() {
11158        let body = "a\n\n![p](x.png)\n\nc\n";
11159        assert_eq!(moved("mv_img1", body, 4, 0).0, "![p](x.png)\n\na\n\nc\n");
11160        assert_eq!(
11161            moved("mv_img2", body, 4, body.len()).0,
11162            "a\n\nc\n\n![p](x.png)\n"
11163        );
11164    }
11165
11166    #[test]
11167    fn move_block_carries_a_table() {
11168        let body = "a\n\n| h |\n|---|\n| c |\n\nc\n";
11169        assert_eq!(
11170            moved("mv_tbl1", body, 5, 0).0,
11171            "| h |\n|---|\n| c |\n\na\n\nc\n"
11172        );
11173        assert_eq!(
11174            moved("mv_tbl2", body, 5, body.len()).0,
11175            "a\n\nc\n\n| h |\n|---|\n| c |\n"
11176        );
11177    }
11178
11179    #[test]
11180    fn move_block_carries_a_code_block() {
11181        let body = "a\n\n```rs\nx\n```\n\nc\n";
11182        assert_eq!(moved("mv_code1", body, 8, 0).0, "```rs\nx\n```\n\na\n\nc\n");
11183        assert_eq!(
11184            moved("mv_code2", body, 8, body.len()).0,
11185            "a\n\nc\n\n```rs\nx\n```\n"
11186        );
11187    }
11188
11189    #[test]
11190    fn move_block_onto_its_own_boundary_is_a_quiet_no_op() {
11191        let mut d = doc_with("mv_noop", "a\n\nb\n");
11192        let steps = d.undo_steps;
11193        d.move_block(0, 0);
11194        d.move_block(0, 3);
11195        assert_eq!(d.source, "a\n\nb\n");
11196        assert_eq!(d.undo_steps, steps);
11197        assert_eq!(d.status, None);
11198        assert!(!d.dirty);
11199    }
11200
11201    #[test]
11202    fn move_block_into_a_fence_is_refused_with_a_status() {
11203        let mut d = doc_with("mv_fence", "a\n\n```\nx\ny\n```\n");
11204        d.move_block(0, 7);
11205        assert_eq!(d.source, "a\n\n```\nx\ny\n```\n");
11206        assert!(
11207            d.status
11208                .as_deref()
11209                .is_some_and(|s| s.starts_with("move block"))
11210        );
11211    }
11212
11213    #[test]
11214    fn move_block_rides_the_caret_with_the_block() {
11215        // Down: "second" is line 0 of its block, caret 3 bytes from its end.
11216        let mut d = doc_with("mv_caret1", "first\n\nsecond\n\nthird\n");
11217        d.caret = 10; // "sec|ond"
11218        d.move_block(10, d.source.len());
11219        assert_eq!(d.source, "first\n\nthird\n\nsecond\n");
11220        assert_eq!(&d.source[d.caret..], "ond\n");
11221        // Up, across a wrapped paragraph's second line.
11222        let mut d = doc_with("mv_caret2", "first\n\nsecond\nline two\n");
11223        d.caret = 16; // "li|ne two"
11224        d.move_block(16, 0);
11225        assert_eq!(d.source, "second\nline two\n\nfirst\n");
11226        assert_eq!(&d.source[d.caret..], "ne two\n\nfirst\n");
11227        assert_eq!(d.selection(), None);
11228    }
11229
11230    #[test]
11231    fn move_block_keeps_the_caret_on_its_line_through_a_quotes_prefix() {
11232        let mut d = doc_with("mv_quote_caret", "para\n\n> a\n");
11233        d.caret = 2; // "pa|ra"
11234        d.move_block(2, 9); // after a, inside the quote
11235        assert_eq!(d.source, "> a\n>\n> para\n");
11236        assert_eq!(&d.source[d.caret..], "ra\n");
11237    }
11238
11239    #[test]
11240    fn move_block_up_and_down_step_over_siblings() {
11241        let mut d = doc_with("mv_updown", "a\n\nb\n\nc\n");
11242        d.caret = 3;
11243        d.move_block_down();
11244        assert_eq!(d.source, "a\n\nc\n\nb\n");
11245        assert_eq!(&d.source[d.caret..], "b\n");
11246        d.move_block_down();
11247        assert_eq!(d.source, "a\n\nc\n\nb\n", "nothing below the last block");
11248        assert_eq!(d.status.as_deref(), Some("move block: nothing below"));
11249        d.move_block_up();
11250        d.move_block_up();
11251        assert_eq!(d.source, "b\n\na\n\nc\n");
11252        assert_eq!(&d.source[d.caret..], "b\n\na\n\nc\n");
11253        d.move_block_up();
11254        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11255    }
11256
11257    #[test]
11258    fn move_block_up_and_down_reorder_list_items_with_their_children() {
11259        let mut d = doc_with("mv_items", "- a\n  - x\n- b\n- c\n");
11260        d.caret = 12; // in "b"
11261        d.move_block_up();
11262        assert_eq!(d.source, "- b\n- a\n  - x\n- c\n");
11263        assert_eq!(&d.source[d.caret..], "b\n- a\n  - x\n- c\n");
11264        d.caret = 6; // in "a"
11265        d.move_block_down();
11266        assert_eq!(d.source, "- b\n- c\n- a\n  - x\n");
11267        assert_eq!(&d.source[d.caret..], "a\n  - x\n");
11268        // A nested item leaves its list upward, as an item of the outer one.
11269        d.caret = 16; // in "x"
11270        d.move_block_up();
11271        assert_eq!(d.source, "- b\n- c\n- x\n- a\n");
11272    }
11273
11274    #[test]
11275    fn move_block_on_a_lone_item_that_stays_a_bullet_is_no_step() {
11276        let mut d = doc_with("mv_lone_item", "x\n\n- b\n\ny\n");
11277        d.caret = 5;
11278        let steps = d.undo_steps;
11279        d.move_block_up();
11280        assert_eq!(d.source, "x\n\n- b\n\ny\n");
11281        assert_eq!(
11282            d.undo_steps, steps,
11283            "a move that rewrote nothing is no undo step"
11284        );
11285        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11286    }
11287
11288    #[test]
11289    fn move_block_up_leaves_a_container_at_its_first_block_and_down_at_its_last() {
11290        let mut d = doc_with("mv_leave", "x\n\n> a\n>\n> b\n\ny\n");
11291        d.caret = 5; // "a"
11292        d.move_block_up();
11293        assert_eq!(d.source, "x\n\na\n\n> b\n\ny\n");
11294        d.caret = 8; // "b"
11295        d.move_block_down();
11296        assert_eq!(d.source, "x\n\na\n\nb\n\ny\n");
11297        // A tail block leaves its item into the next item's tail, then the list.
11298        let mut d = doc_with("mv_tail", "- a\n\n  t\n- b\n");
11299        d.caret = 7;
11300        d.move_block_down();
11301        assert_eq!(d.source, "- a\n- b\n\n  t\n");
11302        d.move_block_down();
11303        assert_eq!(d.source, "- a\n- b\n\nt\n");
11304        // And a paragraph after a quote steps over the whole quote, not into it.
11305        let mut d = doc_with("mv_over", "x\n\n> a\n>\n> b\n\ny\n");
11306        d.caret = 14;
11307        d.move_block_up();
11308        assert_eq!(d.source, "x\n\ny\n\n> a\n>\n> b\n");
11309        assert_eq!(d.caret, 3);
11310        d.move_block_down();
11311        assert_eq!(d.status, None);
11312        assert_eq!(d.source, "x\n\n> a\n>\n> b\n\ny\n");
11313        // Above a quote that opens the document is offset 0 — before the
11314        // quote, not inside it.
11315        let mut d = doc_with("mv_over_top", "> a\n\ny\n");
11316        d.caret = 5;
11317        d.move_block_up();
11318        assert_eq!(d.source, "y\n\n> a\n");
11319        assert_eq!(d.caret, 0);
11320    }
11321
11322    #[test]
11323    fn move_block_up_from_the_first_block_of_a_quote_that_opens_the_document_leaves_it() {
11324        let mut d = doc_with("mv_top_quote", "> a\n>\n> b\n");
11325        d.caret = 2;
11326        d.move_block_up();
11327        assert_eq!(d.source, "a\n\n> b\n");
11328        assert_eq!(d.caret, 0);
11329        assert_eq!(d.status, None);
11330    }
11331
11332    #[test]
11333    fn move_block_on_a_blank_line_or_read_only_does_nothing() {
11334        let mut d = doc_with("mv_blank", "a\n\nb\n");
11335        d.caret = 2;
11336        d.move_block_down();
11337        assert_eq!(d.source, "a\n\nb\n");
11338        assert_eq!(d.status.as_deref(), Some("move block: no block here"));
11339        d.read_only = true;
11340        d.caret = 0;
11341        d.move_block_down();
11342        d.move_block(0, 5);
11343        assert_eq!(d.source, "a\n\nb\n");
11344    }
11345
11346    #[test]
11347    fn move_block_never_lands_above_hidden_frontmatter() {
11348        let mut d = wysiwyg_doc("mv_fm", "---\nt: x\n---\n\na\n\nb\n");
11349        let b = d.source.find('b').unwrap();
11350        d.move_block(b, 0);
11351        assert_eq!(d.source, "---\nt: x\n---\n\nb\n\na\n");
11352    }
11353
11354    #[test]
11355    fn block_range_at_is_the_block_a_move_picks_up() {
11356        let mut d = doc_with("mv_range", "a\n\n- b\n  - c\n\nd\n");
11357        assert_eq!(d.block_range_at(0), Some(0..1));
11358        assert_eq!(d.block_range_at(5), Some(3..12), "the item with its child");
11359        assert_eq!(d.block_range_at(10), Some(7..12), "the nested item alone");
11360        assert_eq!(d.block_range_at(2), None, "a blank line");
11361    }
11362
11363    #[test]
11364    fn drop_target_at_splits_a_block_at_its_middle_row_and_ends_below_everything() {
11365        let long = "two ".repeat(40).trim_end().to_string(); // wraps to three rows at 80
11366        let mut d = wysiwyg_doc("drop", &format!("one\n\n{long} four\n\nfive\n"));
11367        let rows = d.vmap.rows.len();
11368        assert_eq!(rows, 7, "one, gap, three wrapped rows, gap, five");
11369        assert_eq!(d.drop_target_at(0), Some(DropTarget { offset: 0, row: 0 }));
11370        let two = d.source.find("two").unwrap();
11371        assert_eq!(
11372            d.drop_target_at(1),
11373            Some(DropTarget {
11374                offset: two,
11375                row: 2
11376            }),
11377            "the gap resolves to the block under it"
11378        );
11379        assert_eq!(
11380            d.drop_target_at(2),
11381            Some(DropTarget {
11382                offset: two,
11383                row: 2
11384            })
11385        );
11386        assert_eq!(
11387            d.drop_target_at(3),
11388            Some(DropTarget {
11389                offset: two,
11390                row: 2
11391            })
11392        );
11393        let four_end = d.source.find("four").unwrap() + 4;
11394        assert_eq!(
11395            d.drop_target_at(4),
11396            Some(DropTarget {
11397                offset: four_end,
11398                row: 5
11399            })
11400        );
11401        assert_eq!(
11402            d.drop_target_at(rows + 3),
11403            Some(DropTarget {
11404                offset: d.source.len(),
11405                row: rows
11406            })
11407        );
11408        // And the offsets are ones move_block takes.
11409        let five = d.source.find("five").unwrap();
11410        let t = d.drop_target_at(2).unwrap();
11411        d.move_block(five, t.offset);
11412        assert_eq!(d.source, format!("one\n\nfive\n\n{long} four\n"));
11413    }
11414
11415    #[test]
11416    fn append_media_lands_at_the_end_as_its_own_block() {
11417        let mut d = doc_with("append_mid", "first word and more\n");
11418        d.caret = 0; // an editor nobody has tapped: the caret is at the start
11419        d.append_media(MediaKind::Image, "cat.png", "");
11420        assert_eq!(d.source, "first word and more\n\n![](cat.png)");
11421        assert_eq!(d.selection(), None);
11422        assert_eq!(d.caret, "first word and more\n\n![](cat.png)".len());
11423    }
11424
11425    #[test]
11426    fn append_media_needs_no_separator_after_a_blank_line_or_in_an_empty_document() {
11427        let mut d = doc_with("append_blank", "para\n\n");
11428        d.append_media(MediaKind::Image, "a.png", "");
11429        assert_eq!(d.source, "para\n\n![](a.png)");
11430
11431        let mut e = doc_with("append_empty", "");
11432        e.append_media(MediaKind::Image, "b.png", "");
11433        assert_eq!(e.source, "![](b.png)");
11434
11435        let mut f = doc_with("append_noeol", "no newline at end");
11436        f.anchor = Some(0);
11437        f.caret = 2; // a selection, which the verb ignores
11438        f.append_media(MediaKind::Video, "clip.mp4", "");
11439        assert_eq!(
11440            f.source,
11441            "no newline at end\n\n<video src=\"clip.mp4\" controls></video>"
11442        );
11443    }
11444
11445    #[test]
11446    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
11447        // The round trip is the point: it's no use writing markup the reader
11448        // can't pick up again. This is the pair that only holds from twig 2.5.1
11449        // on — before it, the one-line form went in fine and came back as a
11450        // paragraph of raw tags, publishing no media at all.
11451        let mut d = doc_with("vid_rt", "\n");
11452        d.caret = 0;
11453        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
11454        assert_eq!(
11455            d.source,
11456            "<video src=\"clip.mp4\" controls>a clip</video>\n"
11457        );
11458
11459        d.build_visual(80);
11460        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
11461        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
11462        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
11463        assert_eq!(d.vmap.media[0].alt, "a clip");
11464    }
11465
11466    #[test]
11467    fn insert_media_spells_audio_with_its_own_tag() {
11468        let mut d = doc_with("aud_rt", "\n");
11469        d.caret = 0;
11470        d.insert_media(MediaKind::Audio, "take.mp3", "");
11471        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
11472        d.build_visual(80);
11473        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
11474    }
11475
11476    #[test]
11477    fn insert_media_uses_the_selection_as_fallback_text() {
11478        // The same courtesy `insert_image` does with alt: select a caption,
11479        // insert, and the caption labels the thing rather than being replaced.
11480        let mut d = doc_with("vid_sel", "the talk here\n");
11481        d.anchor = Some(0);
11482        d.caret = 8; // "the talk"
11483        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
11484        assert_eq!(
11485            d.source,
11486            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
11487        );
11488    }
11489
11490    #[test]
11491    fn insert_media_with_an_image_kind_is_just_insert_image() {
11492        let mut d = doc_with("img_via_media", "\n");
11493        d.caret = 0;
11494        d.insert_media(MediaKind::Image, "logo.svg", "x");
11495        assert_eq!(d.source, "![x](logo.svg)\n");
11496    }
11497
11498    // ── thematic breaks ─────────────────────────────────────────────────────
11499
11500    /// The node the source parses as at `caret` — what confirms an inserted
11501    /// `---` actually reads back as a rule, not stray text or a setext heading.
11502    ///
11503    /// The *narrowest* node covering the offset. Every ancestor covers it too,
11504    /// and since twig 2.8 that includes the `doc` root, which now carries a real
11505    /// span (it reported none before, so taking the first match used to land on
11506    /// the block by luck and now always answers `"doc"`).
11507    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
11508        d.nodes()
11509            .into_iter()
11510            .filter(|n| n.span.start <= caret && caret < n.span.end)
11511            .min_by_key(|n| n.span.end - n.span.start)
11512            .map(|n| n.kind)
11513    }
11514
11515    #[test]
11516    fn a_task_box_toggles_at_the_caret_and_reads_back() {
11517        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
11518        d.caret = 8; // inside "todo"
11519        assert_eq!(d.task_checked_at_caret(), Some(false));
11520        d.toggle_task_checked();
11521        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
11522        assert_eq!(d.task_checked_at_caret(), Some(true));
11523        d.toggle_task_checked();
11524        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
11525    }
11526
11527    #[test]
11528    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
11529        // The whole reason `toggle_task_at` exists apart from the caret form:
11530        // ticking a box elsewhere must not move the cursor out of what's being
11531        // typed.
11532        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
11533        d.caret = 8; // inside "first"
11534        let second = d.source.find("second").unwrap();
11535        d.toggle_task_at(second);
11536        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
11537        assert_eq!(d.caret, 8, "the caret stayed in the first item");
11538    }
11539
11540    #[test]
11541    fn a_paragraph_becomes_a_task_item_in_one_undo_step() {
11542        let mut d = doc_with("task_para", "first\n\nplain para\n");
11543        d.caret = d.source.find("para").unwrap();
11544        d.toggle_task_item();
11545        assert_eq!(d.source, "first\n\n- [ ] plain para\n");
11546        assert_eq!(d.task_checked_at_caret(), Some(false));
11547        assert_eq!(d.status, None);
11548        d.undo();
11549        assert_eq!(
11550            d.source, "first\n\nplain para\n",
11551            "one step takes both back"
11552        );
11553    }
11554
11555    #[test]
11556    fn a_blank_line_becomes_an_empty_task_item() {
11557        let mut d = doc_with("task_blank", "first\n\n");
11558        d.caret = d.source.len();
11559        d.toggle_task_item();
11560        assert_eq!(d.task_checked_at_caret(), Some(false), "{:?}", d.source);
11561        assert_eq!(d.status, None);
11562    }
11563
11564    #[test]
11565    fn a_plain_item_gains_and_loses_a_box() {
11566        let mut d = doc_with("task_mint", "- plain\n");
11567        d.caret = 4;
11568        assert_eq!(d.task_checked_at_caret(), None);
11569        d.toggle_task_item();
11570        assert_eq!(d.source, "- [ ] plain\n");
11571        assert_eq!(
11572            d.task_checked_at_caret(),
11573            Some(false),
11574            "a new box arrives unticked"
11575        );
11576        d.toggle_task_item();
11577        assert_eq!(d.source, "- plain\n");
11578    }
11579
11580    #[test]
11581    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
11582        // `set checked` must not silently convert a bullet into a task — that is
11583        // `toggle_task_item`'s job, and twig refuses it here.
11584        let mut d = doc_with("task_none", "- plain\n");
11585        d.caret = 4;
11586        d.toggle_task_checked();
11587        assert_eq!(d.source, "- plain\n", "nothing written");
11588        assert!(
11589            d.status.is_some(),
11590            "the refusal should reach the status line"
11591        );
11592    }
11593
11594    #[test]
11595    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
11596        let mut d = doc_with("task_quote", "> - [ ] nested\n");
11597        d.caret = d.source.find("nested").unwrap();
11598        assert_eq!(d.task_checked_at_caret(), Some(false));
11599        d.toggle_task_checked();
11600        assert_eq!(d.source, "> - [x] nested\n");
11601    }
11602
11603    #[test]
11604    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
11605        // A rule is a block, so twig's `insert_thematic_break` alone lands it
11606        // after the whole paragraph. `split_block` parts the paragraph first and
11607        // the rule is aimed at the *first* half, which is what a rule button is
11608        // understood to do — and what leaf spelled by hand until twig grew both
11609        // halves of the gesture.
11610        let mut d = doc_with("hr_mid", "before after\n");
11611        d.caret = 7; // between "before " and "after"
11612        d.insert_thematic_break();
11613        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11614        assert_eq!(d.selection(), None);
11615        assert_eq!(
11616            kind_at(&mut d, "before \n\n".len()),
11617            Some(Kind::ThematicBreak)
11618        );
11619    }
11620
11621    #[test]
11622    fn insert_thematic_break_at_a_paragraph_s_end_splits_nothing() {
11623        // At the end there is nothing to part, and a split there writes the
11624        // separator anyway — a blank line and the empty slot the next paragraph
11625        // would fill — which the rule then landed above: `para\n\n* * *\n\n\n`,
11626        // two blank lines nothing fills. Now the rule lands after the paragraph,
11627        // where the split-and-aim was sending it regardless. Both formats, and
11628        // both shapes of a last line — terminated, and still being typed —
11629        // because the two reach the split through different doors: Markdown's
11630        // paragraph span stops before its newline, so `para\n` at 4 never split
11631        // there, but `para` at 4 did.
11632        //
11633        // What stands under the rule is the line the caret goes on to, not a
11634        // slot: nothing above the rule but the one blank line, and the caret on
11635        // the line beneath it.
11636        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11637            for src in ["para\n", "para"] {
11638                let mut d = Doc::from_source(src.into(), fmt).unwrap();
11639                d.caret = 4;
11640                d.insert_thematic_break();
11641                assert_eq!(d.source, format!("para\n\n{rule}\n\n"), "{fmt:?} {src:?}");
11642                assert_eq!(d.caret, d.source.len());
11643            }
11644            // Mid-document the slot sat between the rule and the next block;
11645            // the caret's line does now, a blank line either side of it.
11646            let mut d = Doc::from_source("para\n\nnext\n".into(), fmt).unwrap();
11647            d.caret = 4;
11648            d.insert_thematic_break();
11649            assert_eq!(d.source, format!("para\n\n{rule}\n\n\n\nnext\n"), "{fmt:?}");
11650            // Trailing whitespace is nothing to part either.
11651            let mut d = Doc::from_source("para  \n".into(), fmt).unwrap();
11652            d.caret = 4;
11653            d.insert_thematic_break();
11654            assert_eq!(d.source, format!("para  \n\n{rule}\n\n"), "{fmt:?}");
11655        }
11656    }
11657
11658    #[test]
11659    fn insert_thematic_break_at_a_paragraph_s_start_lands_before_it() {
11660        // The split at the start parts nothing, but it is kept on purpose:
11661        // `|para` becomes `\npara` with the caret on a blank line, and twig
11662        // (3.5.2) writes a rule aimed at a blank line ON that line — the only
11663        // way "before the paragraph" is reachable through a gesture that only
11664        // places after. Before 3.5.2 this came out as `\n\n---\n\npara`.
11665        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11666            let mut d = Doc::from_source("para\n".into(), fmt).unwrap();
11667            d.caret = 0;
11668            d.insert_thematic_break();
11669            assert_eq!(d.source, format!("{rule}\n\npara\n"), "{fmt:?}");
11670            let mut d = Doc::from_source("prev\n\npara\n".into(), fmt).unwrap();
11671            d.caret = 6;
11672            d.insert_thematic_break();
11673            assert_eq!(d.source, format!("prev\n\n{rule}\n\npara\n"), "{fmt:?}");
11674        }
11675    }
11676
11677    #[test]
11678    fn insert_thematic_break_on_a_blank_line_takes_that_line() {
11679        // The gap between two blocks is where a click lands the caret; the
11680        // rule goes on the blank, one blank each side, and the caret on the
11681        // line opened under it.
11682        let mut d = doc_with("hr_gap", "a\n\nb\n");
11683        d.caret = 2;
11684        d.insert_thematic_break();
11685        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11686        assert_eq!(d.caret, "a\n\n---\n\n".len());
11687    }
11688
11689    #[test]
11690    fn insert_thematic_break_leaves_the_caret_on_a_line_under_the_rule() {
11691        // The caret used to be left where twig's splice ended, the home past
11692        // the rule, which is drawn on the rule's own row: the writer saw the
11693        // caret beside the rule, and mid-document what they typed next ran
11694        // into the block below. Now it goes on to an empty row under the
11695        // rule's gap from every place a rule is asked for — the end of a
11696        // paragraph, the empty paragraph Enter opened, a list and the line
11697        // Enter leaves a list for, closing the document and before another
11698        // block — and what is typed there is a paragraph of its own.
11699        for (body, caret, typed) in [
11700            ("para\n", 4, "para\n\n---\n\nX"),
11701            ("para\n\n\n", 6, "para\n\n---\n\nX"),
11702            ("- one\n- two\n", 11, "- one\n- two\n\n---\n\nX"),
11703            ("- one\n- two\n\n\n", 13, "- one\n- two\n\n---\n\nX"),
11704            ("a\n\nb\n", 1, "a\n\n---\n\nX\n\nb\n"),
11705            ("a\n\n\n\nb\n", 3, "a\n\n---\n\nX\n\nb\n"),
11706        ] {
11707            let mut d = wysiwyg_doc("hr_caret", body);
11708            d.build_visual(80);
11709            d.caret = caret;
11710            d.insert_thematic_break();
11711            d.build_visual(80);
11712            let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11713            let (row, col) = d.vmap.pos_of_offset(d.caret);
11714            assert_eq!((row, col), (rule + 2, 0), "{body:?} → {:?}", d.source);
11715            assert!(d.vmap.rows[rule + 1].decoration, "the gap under the rule");
11716            assert!(d.vmap.rows[row].glyphs.is_empty(), "an empty line");
11717            d.insert("X");
11718            assert_eq!(d.source, typed, "{body:?}");
11719            let rule_at = d.source.find("---").unwrap();
11720            assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
11721        }
11722        // djot's rule takes in its newline; the line under it is the same.
11723        let mut d = Doc::from_source("a\n\nb\n".into(), Format::Djot).unwrap();
11724        d.view = View::Wysiwyg;
11725        d.caret = 1;
11726        d.insert_thematic_break();
11727        d.build_visual(80);
11728        assert_eq!(d.source, "a\n\n* * *\n\n\n\nb\n");
11729        assert_eq!(d.vmap.pos_of_offset(d.caret), (4, 0));
11730    }
11731
11732    #[test]
11733    fn a_rule_parting_a_paragraph_leaves_the_caret_before_its_second_half() {
11734        // The line under the rule is the paragraph's second half, so that is
11735        // where the caret goes: the text it was standing in front of is still
11736        // in front of it.
11737        let mut d = wysiwyg_doc("hr_parted", "before after\n");
11738        d.caret = 7;
11739        d.insert_thematic_break();
11740        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11741        assert_eq!(d.caret, d.source.find("after").unwrap());
11742        // At the start of a paragraph too, the rule landing above it.
11743        let mut d = wysiwyg_doc("hr_parted_start", "prev\n\npara\n");
11744        d.caret = 6;
11745        d.insert_thematic_break();
11746        assert_eq!(d.caret, d.source.find("para").unwrap());
11747    }
11748
11749    #[test]
11750    fn the_line_under_a_new_rule_is_one_undo_step_with_it() {
11751        let mut d = wysiwyg_doc("hr_undo", "a\n\nb\n");
11752        d.caret = 1;
11753        d.insert_thematic_break();
11754        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11755        d.undo();
11756        assert_eq!(d.source, "a\n\nb\n");
11757        assert!(!d.can_undo());
11758        d.redo();
11759        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11760    }
11761
11762    #[test]
11763    fn a_rule_in_preserve_flow_leaves_the_caret_on_the_first_line_under_it() {
11764        // Preserve draws every blank line as somewhere to type, the first under
11765        // the rule included, so that is the caret's line and the one written.
11766        let mut d = wysiwyg_doc("hr_preserve", "para\n");
11767        d.set_line_flow(LineFlow::Preserve);
11768        d.caret = 4;
11769        d.insert_thematic_break();
11770        assert_eq!(d.source, "para\n\n---\n\n");
11771        assert_eq!(d.caret, "para\n\n---\n".len());
11772        d.build_visual(80);
11773        let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11774        assert_eq!(d.vmap.pos_of_offset(d.caret), (rule + 1, 0));
11775        // Before another block, one blank line more keeps it off that block.
11776        let mut d = wysiwyg_doc("hr_preserve_mid", "a\n\nb\n");
11777        d.set_line_flow(LineFlow::Preserve);
11778        d.caret = 1;
11779        d.insert_thematic_break();
11780        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
11781        assert_eq!(d.caret, "a\n\n---\n".len());
11782    }
11783
11784    #[test]
11785    fn insert_page_break_leaves_the_caret_on_a_line_under_it() {
11786        // The rule button's placement, for the other block the toolbar writes:
11787        // the caret was left at the end of twig's splice, beside the break at
11788        // the end of the document and on the next block's first letter before
11789        // one. djot spells the break as a fence of two lines; the line under
11790        // it is under the closing `:::`.
11791        for (fmt, body, want, typed) in [
11792            (
11793                Format::Markdown,
11794                "a\n\nb\n",
11795                "a\n\n::page-break\n\n\n\nb\n",
11796                "a\n\n::page-break\n\nX\n\nb\n",
11797            ),
11798            (
11799                Format::Markdown,
11800                "a\n",
11801                "a\n\n::page-break\n\n",
11802                "a\n\n::page-break\n\nX",
11803            ),
11804            (
11805                Format::Djot,
11806                "a\n\nb\n",
11807                "a\n\n::: page-break\n:::\n\n\n\nb\n",
11808                "a\n\n::: page-break\n:::\n\nX\n\nb\n",
11809            ),
11810        ] {
11811            let mut d = Doc::from_source(body.into(), fmt).unwrap();
11812            d.view = View::Wysiwyg;
11813            d.caret = 1;
11814            d.insert_page_break();
11815            assert_eq!(d.source, want, "{fmt:?}");
11816            d.build_visual(80);
11817            let (row, col) = d.vmap.pos_of_offset(d.caret);
11818            assert_eq!(col, 0);
11819            assert!(d.vmap.rows[row].glyphs.is_empty(), "{fmt:?}: an empty line");
11820            assert!(
11821                d.vmap.rows[row - 2].leaf_directive.is_some(),
11822                "{fmt:?}: under the break"
11823            );
11824            d.insert("X");
11825            assert_eq!(d.source, typed, "{fmt:?}");
11826            d.undo();
11827            d.undo();
11828            assert_eq!(
11829                d.source, body,
11830                "{fmt:?}: the break and its line are one step"
11831            );
11832        }
11833    }
11834
11835    #[test]
11836    fn a_block_parting_a_paragraph_is_one_undo_step() {
11837        // The split went to twig without leaf counting it, so the first Undo
11838        // took back the block, left the paragraph parted, and reported nothing
11839        // more to undo.
11840        let mut rule = wysiwyg_doc("part_undo_rule", "before after\n");
11841        rule.caret = 7;
11842        rule.insert_thematic_break();
11843        let mut table = wysiwyg_doc("part_undo_table", "before after\n");
11844        table.caret = 7;
11845        table.insert_table(1, 1);
11846        let mut page = wysiwyg_doc("part_undo_page", "before after\n");
11847        page.caret = 7;
11848        page.insert_page_break();
11849        for (name, d) in [
11850            ("rule", &mut rule),
11851            ("table", &mut table),
11852            ("page break", &mut page),
11853        ] {
11854            assert_ne!(d.source, "before after\n", "{name}");
11855            d.undo();
11856            assert_eq!(d.source, "before after\n", "{name}: one Undo");
11857            assert_eq!(d.caret, 7, "{name}: the caret back where it was");
11858            assert!(!d.can_undo(), "{name}");
11859            assert!(d.can_redo(), "{name}");
11860            d.redo();
11861            assert!(!d.source.starts_with("before after"), "{name}: one Redo");
11862            assert!(!d.can_redo(), "{name}");
11863        }
11864        // A table twig would refuse parts nothing: the refusal comes first.
11865        let mut d = wysiwyg_doc("part_undo_zero", "before after\n");
11866        d.caret = 7;
11867        d.insert_table(0, 1);
11868        assert_eq!(d.source, "before after\n");
11869        assert!(!d.can_undo());
11870    }
11871
11872    #[test]
11873    fn enter_at_a_paragraph_s_start_opens_an_empty_paragraph_above_it() {
11874        // twig's split at a paragraph's start writes one newline ahead of it,
11875        // which Fold draws as one more gap, so the first Enter showed nothing.
11876        // A paragraph break opens a line above, the caret staying before the
11877        // text. Past a mark's opening delimiters — where a tap before the
11878        // first letter lands — the split used to cut the mark in two
11879        // (`**\n\nb**`); the break goes in front of them, as it goes in
11880        // front of a heading's `#`, where the heading's own Enter left an
11881        // empty heading over its text as a paragraph. A paragraph that
11882        // opens a div gets its line outside the div, where it draws.
11883        for (body, caret, want, want_caret) in [
11884            ("a\n\nb\n", 3, "a\n\n\n\nb\n", 5),
11885            ("# H\n\nb\n", 5, "# H\n\n\n\nb\n", 7),
11886            ("a\n\n# H\n", 5, "a\n\n\n\n# H\n", 7),
11887            ("a\n\n**b** c\n", 3, "a\n\n\n\n**b** c\n", 5),
11888            ("a\n\n**b** c\n", 5, "a\n\n\n\n**b** c\n", 7),
11889            (
11890                "a\n\n<span data-color=\"orange\">b</span>\n",
11891                29,
11892                "a\n\n\n\n<span data-color=\"orange\">b</span>\n",
11893                31,
11894            ),
11895            (
11896                "a\n\n<div class=\"center\">\n\nb\n\n</div>\n",
11897                25,
11898                "a\n\n\n\n<div class=\"center\">\n\nb\n\n</div>\n",
11899                27,
11900            ),
11901        ] {
11902            let mut d = wysiwyg_doc("enter_para_start", body);
11903            d.build_visual(80);
11904            d.caret = caret;
11905            d.newline();
11906            assert_eq!(d.source, want, "{body:?}");
11907            assert_eq!(d.caret, want_caret, "{body:?}");
11908            d.build_visual(80);
11909            let (row, _) = d.vmap.pos_of_offset(d.caret);
11910            assert!(
11911                d.vmap.rows[row - 2].glyphs.is_empty(),
11912                "{body:?}: an empty line above"
11913            );
11914            assert!(
11915                !d.vmap.rows[row - 2].decoration,
11916                "{body:?}: one the caret can stand on"
11917            );
11918        }
11919        // Past the first letter it is an ordinary split.
11920        let mut d = wysiwyg_doc("enter_para_mid", "a\n\n**b** c\n");
11921        d.caret = 8;
11922        d.newline();
11923        assert_eq!(d.source, "a\n\n**b**\n\nc\n");
11924    }
11925
11926    #[test]
11927    fn enter_again_at_a_paragraph_s_start_opens_one_more_line() {
11928        // The first Enter's paragraph break leaves a gap either side of the
11929        // empty line. A second break drew two lines more; a newline draws one.
11930        let mut d = wysiwyg_doc("enter_para_again", "a\n\nb\n");
11931        d.build_visual(80);
11932        d.caret = 3;
11933        for (want, lines) in [("a\n\n\n\nb\n", 1), ("a\n\n\n\n\nb\n", 2)] {
11934            d.newline();
11935            assert_eq!(d.source, want);
11936            assert_eq!(&d.source[d.caret..], "b\n");
11937            d.build_visual(80);
11938            let empty = d
11939                .vmap
11940                .rows
11941                .iter()
11942                .filter(|r| r.glyphs.is_empty() && !r.decoration)
11943                .count();
11944            assert_eq!(empty, lines, "{want:?}");
11945        }
11946    }
11947
11948    #[test]
11949    fn enter_at_the_first_block_s_start_pushes_it_down() {
11950        // No row was drawn for a blank line above the first block, so Enter
11951        // there wrote a line and the text stayed where it was. Each Enter now
11952        // draws one empty line above it, the caret staying with the text;
11953        // past frontmatter, the line conventionally under it still draws
11954        // nothing until Enter adds to it.
11955        for (body, caret, wants) in [
11956            ("b\n", 0, ["\n\nb\n", "\n\n\nb\n"]),
11957            ("**b** c\n", 2, ["\n\n**b** c\n", "\n\n\n**b** c\n"]),
11958            ("# H\n", 2, ["\n\n# H\n", "\n\n\n# H\n"]),
11959            (
11960                "---\nt: x\n---\n\nb\n",
11961                14,
11962                ["---\nt: x\n---\n\n\nb\n", "---\nt: x\n---\n\n\n\nb\n"],
11963            ),
11964        ] {
11965            let mut d = wysiwyg_doc("enter_first_block", body);
11966            d.build_visual(80);
11967            let empty = |d: &Doc| {
11968                d.vmap
11969                    .rows
11970                    .iter()
11971                    .filter(|r| r.glyphs.is_empty() && !r.decoration)
11972                    .count()
11973            };
11974            assert_eq!(empty(&d), 0, "{body:?}: nothing above the text yet");
11975            d.caret = caret;
11976            for (lines, want) in wants.into_iter().enumerate() {
11977                d.newline();
11978                assert_eq!(d.source, want, "{body:?}");
11979                assert!(d.source[d.caret..].starts_with(&body[caret..]), "{body:?}");
11980                d.build_visual(80);
11981                assert_eq!(empty(&d), lines + 1, "{want:?}");
11982            }
11983            // The caret can go up onto the lines it opened.
11984            d.move_up(false);
11985            let (row, _) = d.vmap.pos_of_offset(d.caret);
11986            assert!(d.vmap.rows[row].glyphs.is_empty(), "{body:?}");
11987            assert!(!d.vmap.rows[row].decoration, "{body:?}");
11988        }
11989    }
11990
11991    /// What a reader sees of a map: each row's text, whether it is a gap,
11992    /// and the presentation it is drawn with. Offsets are left out, since an
11993    /// edit shifts them without anything on screen changing.
11994    fn drawn(d: &Doc) -> Vec<String> {
11995        d.vmap
11996            .rows
11997            .iter()
11998            .map(|r| {
11999                let text: String = r.glyphs.iter().map(|g| g.ch).collect();
12000                format!(
12001                    "{}{text:?} h={:?} lh={:?} a={:?}",
12002                    if r.decoration { "~" } else { "" },
12003                    r.heading,
12004                    r.line_height,
12005                    r.align
12006                )
12007            })
12008            .collect()
12009    }
12010
12011    #[test]
12012    fn enter_and_backspace_anywhere_show_what_they_write_and_undo_in_one_step() {
12013        // Enter that writes what the view does not draw looks like a key that
12014        // did nothing, so it gets pressed again, and the lines pile up unseen
12015        // until something redraws them all at once. The rule, the page break,
12016        // a paragraph's start, the first block's start and the blank page
12017        // were each that bug once. So: at every place the caret can stand, in
12018        // both flows, Enter either changes what is drawn or writes nothing,
12019        // and one Undo takes back whatever it wrote. Enter and Backspace both
12020        // leave the view a fresh open of the text would draw, so nothing
12021        // moves when the view is next rebuilt from scratch.
12022        let cases: &[(Format, &str)] = &[
12023            (
12024                Format::Markdown,
12025                "I talk to myself\n\nI laugh\n\nI cry\n\nknees to nose\n\nlet me go\n",
12026            ),
12027            (Format::Markdown, "I talk to myself\nI laugh\nI cry\n"),
12028            (
12029                Format::Markdown,
12030                "<div data-line-height=\"1.5\">\n\nI laugh\n\nI cry\n\nknees to nose\n\n</div>\n",
12031            ),
12032            (
12033                Format::Markdown,
12034                "<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",
12035            ),
12036            (
12037                Format::Markdown,
12038                "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n",
12039            ),
12040            (
12041                Format::Markdown,
12042                "---\ntitle: x\n---\n\n# Title\n\nbody **bold** and <span data-color=\"red\">red</span>\n",
12043            ),
12044            (Format::Markdown, "\n\n\nafter blank lines\n\n\n\nmid\n\n\n"),
12045            (
12046                Format::Markdown,
12047                "- one\n- two\n\n1. a\n2. b\n\n- [ ] task\n",
12048            ),
12049            (Format::Markdown, "> quoted\n> more\n\n> - in a quote\n"),
12050            (Format::Markdown, "a\n\n---\n\nb\n\n::page-break\n\nc\n"),
12051            (Format::Markdown, "Title\n=====\n\nSub\n---\n\ntext\n"),
12052            (
12053                Format::Markdown,
12054                "```\ncode\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n",
12055            ),
12056            (Format::Djot, "I laugh\n\nI cry\n\nknees to nose\n"),
12057            (
12058                Format::Djot,
12059                "{data-line-height=\"2\"}\nI cry\n\n{data-line-height=\"2\"}\nknees to nose\n",
12060            ),
12061            (Format::Djot, "# Title\n\na\n\n* * *\n\nb\n"),
12062            // HTML is not here: Enter writes blank lines there, which the
12063            // view draws and HTML does not keep. See
12064            // docs/tasks/enter-in-html-writes-whitespace.md.
12065        ];
12066        let mut failures = Vec::new();
12067        for &(format, body) in cases {
12068            for flow in [LineFlow::Fold, LineFlow::Preserve] {
12069                let open = || {
12070                    let mut d = Doc::from_source(body.into(), format).unwrap();
12071                    d.view = View::Wysiwyg;
12072                    d.set_line_flow(flow);
12073                    d.build_visual_unwrapped();
12074                    d
12075                };
12076                // The map a fresh open of the same text would draw. The
12077                // edited map differing from it is a view that changes on the
12078                // next full rebuild, seconds after the key, with no key.
12079                let fresh = |source: &str| {
12080                    let mut ed =
12081                        twig::Editor::new_ext(source.as_bytes(), format, parse_extensions())
12082                            .unwrap();
12083                    let nodes = ed.nodes().unwrap();
12084                    crate::wysiwyg::build(
12085                        &nodes,
12086                        source,
12087                        None,
12088                        flow == LineFlow::Preserve,
12089                        &wysiwyg::Surface::default(),
12090                        None,
12091                    )
12092                };
12093                let probe = open();
12094                let stops: Vec<usize> = (0..=body.len())
12095                    .filter(|&o| probe.vmap.is_stop(o))
12096                    .collect();
12097                for at in stops {
12098                    for enter in [true, false] {
12099                        let mut d = open();
12100                        d.caret = at;
12101                        d.anchor = None;
12102                        let before = drawn(&d);
12103                        if enter {
12104                            d.newline();
12105                        } else {
12106                            d.backspace();
12107                        }
12108                        d.build_visual_unwrapped();
12109                        let key = if enter { "enter" } else { "backspace" };
12110                        let what = format!(
12111                            "{key} {format:?} {flow:?} caret {at} in {body:?} -> {:?}",
12112                            d.source
12113                        );
12114                        if maps_differ(&d.vmap, &fresh(&d.source)) {
12115                            failures.push(format!("redraws differently: {what}"));
12116                        }
12117                        if d.source == body {
12118                            continue;
12119                        }
12120                        if enter && drawn(&d) == before {
12121                            failures.push(format!("drew nothing: {what}"));
12122                        }
12123                        d.undo();
12124                        if d.source != body {
12125                            failures.push(format!("undo left {:?}: {what}", d.source));
12126                        }
12127                    }
12128                }
12129            }
12130        }
12131        assert!(
12132            failures.is_empty(),
12133            "{} failures:\n{}",
12134            failures.len(),
12135            failures.join("\n")
12136        );
12137    }
12138
12139    #[test]
12140    fn enter_opens_a_line_that_draws_inside_a_div_a_quote_and_preserve_flow() {
12141        // Each of these wrote a line the view did not draw, so Enter looked
12142        // dead and every press left one more.
12143        let enter = |format, flow, body: &str, at: usize| {
12144            let mut d = Doc::from_source(body.into(), format).unwrap();
12145            d.view = View::Wysiwyg;
12146            d.set_line_flow(flow);
12147            d.build_visual(80);
12148            d.caret = at;
12149            d.newline();
12150            d.build_visual(80);
12151            d
12152        };
12153        let div = "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n</div>\n";
12154        let end = div.find("knees").unwrap() + "knees".len();
12155
12156        // At the end of a div's last paragraph, the empty paragraph opens
12157        // inside the div, drawn with its line height, and what is typed
12158        // there stays in it.
12159        let mut d = enter(Format::Markdown, LineFlow::Fold, div, end);
12160        let (row, _) = d.vmap.pos_of_offset(d.caret);
12161        let r = &d.vmap.rows[row];
12162        assert!(r.glyphs.is_empty() && !r.decoration, "{:?}", drawn(&d));
12163        assert!(
12164            r.line_height.is_some(),
12165            "the new line keeps the div's spacing"
12166        );
12167        d.insert("x");
12168        assert_eq!(
12169            d.source,
12170            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\nx\n\n</div>\n"
12171        );
12172        // Preserve flow's soft line there draws too.
12173        let d = enter(Format::Markdown, LineFlow::Preserve, div, end);
12174        assert_eq!(
12175            d.source,
12176            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n\n</div>\n"
12177        );
12178        assert_eq!(d.vmap.rows.len(), 4, "{:?}", drawn(&d));
12179        // Between two of the div's paragraphs, the empty line takes its
12180        // spacing as well.
12181        let d = enter(
12182            Format::Markdown,
12183            LineFlow::Fold,
12184            div,
12185            div.find("knees").unwrap(),
12186        );
12187        let (row, _) = d.vmap.pos_of_offset(d.caret);
12188        assert!(
12189            d.vmap.rows[row - 2].line_height.is_some(),
12190            "{:?}",
12191            drawn(&d)
12192        );
12193
12194        // Under `</div>` the blank line is the one Markdown needs to end the
12195        // div. Preserve flow drew it as a line to type on, and Backspace
12196        // there glued the next paragraph to the tag (`</div>after`).
12197        let below = "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n";
12198        let mut d = Doc::from_source(below.into(), Format::Markdown).unwrap();
12199        d.view = View::Wysiwyg;
12200        d.set_line_flow(LineFlow::Preserve);
12201        d.build_visual(80);
12202        assert_eq!(d.vmap.rows.len(), 2, "{:?}", drawn(&d));
12203        d.caret = below.find("after").unwrap();
12204        d.backspace();
12205        assert!(!d.source.contains("</div>after"), "{:?}", d.source);
12206
12207        // At a quote's first line, the line opens above the quote; twig's
12208        // split wrote a quoted blank line above the text, which drew nothing.
12209        let d = enter(
12210            Format::Markdown,
12211            LineFlow::Fold,
12212            "a\n\n> quoted\n> more\n",
12213            5,
12214        );
12215        assert_eq!(d.source, "a\n\n\n\n> quoted\n> more\n");
12216        assert_eq!(&d.source[d.caret..], "quoted\n> more\n");
12217
12218        // Preserve flow at a paragraph's start: past a mark's delimiters its
12219        // newline cut the mark (`**\nb**`), and in djot a heading ran on
12220        // over it unseen.
12221        let d = enter(Format::Markdown, LineFlow::Preserve, "a\n\n**b** c\n", 5);
12222        assert_eq!(d.source, "a\n\n\n**b** c\n");
12223        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 5);
12224        assert_eq!(d.source, "a\n\n\n# Title\n");
12225        // Inside a heading it parts the heading, as in Fold flow.
12226        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 7);
12227        assert_eq!(d.source, "a\n\n# Ti\n\ntle\n");
12228    }
12229
12230    #[test]
12231    fn enter_on_a_blank_page_writes_nothing() {
12232        // With no block to push down, Fold flow draws no line for Enter to
12233        // open, and the newline it wrote was an edit and an undo step that
12234        // showed nothing. Preserve flow draws every line, so there it writes.
12235        for body in ["", "\n", "\n\n  \n", "---\nt: x\n---\n"] {
12236            let mut d = wysiwyg_doc("enter_blank_page", body);
12237            d.build_visual(80);
12238            d.caret = d.source.len();
12239            d.newline();
12240            assert_eq!(d.source, body);
12241            assert!(!d.can_undo(), "{body:?}");
12242            assert!(!d.dirty, "{body:?}");
12243        }
12244        let mut d = wysiwyg_doc("enter_blank_page_preserve", "");
12245        d.set_line_flow(LineFlow::Preserve);
12246        d.build_visual(80);
12247        d.newline();
12248        assert_eq!(d.source, "\n");
12249    }
12250
12251    #[test]
12252    fn enter_beside_a_rule_opens_a_line_under_it() {
12253        // Beside a rule the caret stands at the home past it, which in source is
12254        // the start of the blank line under the rule, and Enter took it for an
12255        // empty paragraph: a lone newline, drawn as one more gap, and the caret
12256        // put on the next block's first line — where typing joined that block.
12257        // It goes on under the rule instead, as the rule button leaves it.
12258        let mut d = wysiwyg_doc("enter_rule", "a\n\n---\n\nb\n");
12259        d.build_visual(80);
12260        d.caret = "a\n\n---\n".len();
12261        d.newline();
12262        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
12263        assert_eq!(d.caret, "a\n\n---\n\n".len());
12264        d.insert("X");
12265        assert_eq!(d.source, "a\n\n---\n\nX\n\nb\n");
12266
12267        // Closing the document.
12268        let mut d = wysiwyg_doc("enter_rule_end", "a\n\n---\n");
12269        d.caret = d.source.len();
12270        d.newline();
12271        assert_eq!(d.source, "a\n\n---\n\n");
12272        assert_eq!(d.caret, d.source.len());
12273
12274        // In a quote, where the lines it writes keep the quote's prefix.
12275        let mut d = wysiwyg_doc("enter_rule_quote", "> a\n>\n> ---\n>\n> b\n");
12276        d.caret = "> a\n>\n> ---\n".len();
12277        d.newline();
12278        assert_eq!(d.source, "> a\n>\n> ---\n>\n> \n>\n> b\n");
12279        d.insert("X");
12280        assert_eq!(d.source, "> a\n>\n> ---\n>\n> X\n>\n> b\n");
12281
12282        // Preserve draws the blank line under a rule as a line, and the caret
12283        // on it: Enter there is a blank line's, one line down.
12284        let mut d = wysiwyg_doc("enter_rule_preserve", "a\n\n---\n\nb\n");
12285        d.set_line_flow(LineFlow::Preserve);
12286        d.caret = "a\n\n---\n".len();
12287        d.newline();
12288        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
12289        assert_eq!(d.caret, "a\n\n---\n\n".len());
12290    }
12291
12292    #[test]
12293    fn insert_table_at_a_paragraph_s_end_splits_nothing() {
12294        // The same door as the rule's, through the placement they share.
12295        let mut d = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12296        d.caret = 4;
12297        d.insert_table(1, 1);
12298        assert_eq!(d.source, "para\n\n|  |\n|---|\n|  |\n");
12299        let mut d = doc_with("table_end_typed", "para");
12300        d.caret = 4;
12301        d.insert_table(1, 1);
12302        assert_eq!(d.source, "para\n\n|  |\n| --- |\n|  |\n");
12303        assert!(d.caret_in_table());
12304    }
12305
12306    #[test]
12307    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
12308        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
12309        // and leaf wrote the first into both until twig started spelling it.
12310        let mut md = doc_with("hr_md", "para\n");
12311        md.caret = 2;
12312        md.insert_thematic_break();
12313        assert_eq!(md.source, "pa\n\n---\n\nra\n");
12314
12315        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12316        dj.caret = 2;
12317        dj.insert_thematic_break();
12318        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
12319    }
12320
12321    #[test]
12322    fn insert_table_parts_the_paragraph_and_lands_in_the_first_header_cell() {
12323        // The table goes *at* the caret the way the rule does: the paragraph is
12324        // parted first, and twig writes the grid after its first half. The
12325        // caret then sits in the first header cell — selected, as Tab would
12326        // leave it — so the next keystroke is the heading.
12327        let mut d = doc_with("table_mid", "before after\n");
12328        d.caret = 7;
12329        d.insert_table(2, 3);
12330        assert_eq!(
12331            d.source,
12332            "before \n\n|  |  |  |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |\n\nafter\n"
12333        );
12334        assert!(d.caret_in_table());
12335        let first_bar = d.source.find('|').unwrap();
12336        assert!(
12337            d.caret > first_bar && d.caret < d.source.find("| ---").unwrap(),
12338            "caret {} is not in the header row",
12339            d.caret
12340        );
12341        d.insert("Name");
12342        assert!(d.source.starts_with("before \n\n| Name |  |  |\n"));
12343        // And the grid the table was written into is one the table keys walk
12344        // (over the map a frontend rebuilds after every edit).
12345        d.build_visual(80);
12346        assert!(d.cell_tab(true));
12347        d.insert("Qty");
12348        assert!(d.source.starts_with("before \n\n| Name | Qty |  |\n"));
12349    }
12350
12351    #[test]
12352    fn insert_table_spells_the_grid_the_format_s_own_way() {
12353        // Djot's delimiter row is unpadded, and leaf never has to know that.
12354        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12355        dj.caret = 2;
12356        dj.insert_table(1, 2);
12357        assert_eq!(dj.source, "pa\n\n|  |  |\n|---|---|\n|  |  |\n\nra\n");
12358        assert!(dj.caret_in_table());
12359    }
12360
12361    #[test]
12362    fn insert_table_refuses_where_the_format_spells_no_table() {
12363        let mut d = Doc::from_source("<p>ab</p>\n".into(), Format::Html).unwrap();
12364        d.caret = 4;
12365        d.insert_table(1, 1);
12366        assert_eq!(d.source, "<p>ab</p>\n");
12367        assert!(d.status.as_deref().unwrap_or("").contains("not supported"));
12368        assert!(!d.capabilities().table);
12369    }
12370
12371    #[test]
12372    fn insert_table_reports_a_zero_shape_and_writes_nothing() {
12373        let mut d = doc_with("table_zero", "para\n");
12374        d.caret = 2;
12375        d.insert_table(0, 2);
12376        assert_eq!(d.source, "para\n");
12377        assert!(d.status.as_deref().unwrap_or("").starts_with("table:"));
12378    }
12379
12380    #[test]
12381    fn clicking_below_a_final_thematic_break_can_type_after_it() {
12382        let mut d = wysiwyg_doc("hr_final_click", "---\n");
12383        d.build_visual(80);
12384        d.click(d.vmap.num_rows() + 2, 0, false);
12385        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
12386        d.insert("after");
12387        assert_eq!(d.source, "---\nafter");
12388    }
12389
12390    #[test]
12391    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
12392        // The same bytes are two documents. In Markdown `  - b` is a nested item
12393        // and the next one belongs beside it, at its indent. In Djot a list
12394        // marker can't interrupt a paragraph, so those bytes are literal text in
12395        // item `a` and there is only one item — writing `  - ` under it would add
12396        // no item at all, just more text, and the new sibling has to go to
12397        // column zero. Both spellings come out of the *enclosing item's* line.
12398        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
12399        md.caret = "- a\n  - b".len();
12400        md.newline();
12401        assert_eq!(md.source, "- a\n  - b\n  - \n");
12402        assert_eq!(list_items(&mut md), 3);
12403
12404        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
12405        dj.view = View::Wysiwyg;
12406        dj.build_visual(80);
12407        dj.caret = "- a\n  - b".len();
12408        dj.newline();
12409        assert_eq!(dj.source, "- a\n  - b\n- \n");
12410        assert_eq!(list_items(&mut dj), 2);
12411
12412        // Where Djot's nesting is real — opened by a blank line — the indent is
12413        // reproduced there too, and the two formats agree again.
12414        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
12415        dj.view = View::Wysiwyg;
12416        dj.build_visual(80);
12417        dj.caret = "- a\n\n  - b".len();
12418        dj.newline();
12419        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
12420        assert_eq!(list_items(&mut dj), 3);
12421    }
12422
12423    #[test]
12424    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
12425        // Tab replaces the line's whole prefix with the one twig spells, so the
12426        // quote markers, the parent's indent and an ordered marker's extra
12427        // column are all its answer rather than leaf's arithmetic.
12428        for (name, body, caret, want) in [
12429            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
12430            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
12431            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
12432            // A checkbox is markup the item's own text wraps past, but a nested
12433            // list may only open at the *list* marker's column — four in from
12434            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
12435            // parses as one item, not two.
12436            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
12437            (
12438                "quoted task",
12439                "> - [ ] a\n> - [ ] b\n",
12440                18,
12441                "> - [ ] a\n>   - [ ] b\n",
12442            ),
12443        ] {
12444            let mut doc = wysiwyg_doc(name, body);
12445            doc.caret = caret;
12446            doc.indent();
12447            assert_eq!(doc.source, want, "{name}");
12448            // The nesting is real, not just indented text.
12449            assert_eq!(list_items(&mut doc), 2, "{name}");
12450        }
12451    }
12452
12453    #[test]
12454    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
12455        // The same bytes, the two formats disagreeing, and a gesture that used
12456        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
12457        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
12458        // so those bytes are literal text inside item `a` — there is nothing to
12459        // outdent, and treating them as a marker turned one item into two, a
12460        // structural edit from a keystroke that should delete one character.
12461        //
12462        // twig's `line_prefix` is what tells them apart: it reports the marker
12463        // on the Markdown line and nothing on the Djot one, which is a
12464        // continuation. No byte scan can reach that answer.
12465        let src = "- a\n  - b\n";
12466        let at = "- a\n  - ".len();
12467
12468        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
12469        md.view = View::Wysiwyg;
12470        md.build_visual(80);
12471        md.caret = at;
12472        md.backspace();
12473        assert_eq!(md.source, "- a\n- b\n");
12474        assert_eq!(list_items(&mut md), 2);
12475
12476        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
12477        dj.view = View::Wysiwyg;
12478        dj.build_visual(80);
12479        dj.caret = at;
12480        dj.backspace();
12481        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
12482        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
12483    }
12484
12485    #[test]
12486    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
12487        // Leaf used to spell the next item from the marker bytes it scanned, and
12488        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
12489        // and dropped out of the checklist. twig reproduces the whole
12490        // continuation, and a fresh item is always unticked however the one above
12491        // it stands.
12492        for (name, body, want) in [
12493            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
12494            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
12495        ] {
12496            let mut doc = wysiwyg_doc(name, body);
12497            doc.caret = body.trim_end_matches('\n').len();
12498            doc.newline();
12499            assert_eq!(doc.source, want, "{name}");
12500            // Both items are checklist items — the new one is a box, not the
12501            // plain bullet the old marker scan left behind — and it is unticked
12502            // whichever way the one above it faces.
12503            let boxes: Vec<Option<bool>> = doc
12504                .nodes()
12505                .iter()
12506                .filter(|n| n.kind == Kind::TaskListItem)
12507                .map(|n| n.checked)
12508                .collect();
12509            assert_eq!(boxes.len(), 2, "{name}");
12510            assert_eq!(boxes[1], Some(false), "{name}");
12511        }
12512    }
12513
12514    #[test]
12515    fn a_split_takes_the_space_the_caret_was_in_front_of() {
12516        // Splicing a break at the caret strands the space the words were parted
12517        // at on the head of the second block, where it reads as an indent nobody
12518        // typed. twig's split consumes it.
12519        for (name, body, caret, want) in [
12520            ("para", "one two\n", 3, "one\n\ntwo\n"),
12521            ("item", "- one two\n", 5, "- one\n- two\n"),
12522            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
12523            // A heading takes leaf's own path, which has to match.
12524            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
12525        ] {
12526            let mut doc = wysiwyg_doc(name, body);
12527            doc.caret = caret;
12528            doc.newline();
12529            assert_eq!(doc.source, want, "{name}");
12530        }
12531    }
12532
12533    #[test]
12534    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
12535        // The one place leaf keeps its own break: `split_block` repeats the `#`,
12536        // and Enter after a title is how the body under it is asked for.
12537        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
12538        doc.caret = "# Title".len();
12539        doc.newline();
12540        doc.insert("body");
12541        assert_eq!(doc.source, "# Title\n\nbody\n");
12542        assert_eq!(
12543            doc.nodes()
12544                .iter()
12545                .filter(|n| n.kind == Kind::Heading)
12546                .count(),
12547            1
12548        );
12549    }
12550
12551    #[test]
12552    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
12553        // A quoted item's marker doesn't open its line, so a scan that starts at
12554        // column zero finds a `>` where it wanted a bullet, calls the line "not a
12555        // list" and hands Enter to the plain-quote branch — which writes `> ` and
12556        // drops the list. The next item has to carry the whole prefix.
12557        for (name, body, want) in [
12558            ("flat", "> - a\n", "> - a\n> - \n"),
12559            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
12560            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
12561            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
12562            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
12563        ] {
12564            let mut doc = wysiwyg_doc(name, body);
12565            doc.caret = body.trim_end_matches('\n').len();
12566            doc.newline();
12567            assert_eq!(doc.source, want, "{name}");
12568            // The marker isn't just spelled right, it parses as an item.
12569            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
12570        }
12571    }
12572
12573    #[test]
12574    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
12575        // Double-Enter exits the list. Unquoted that means a blank line, but a
12576        // *bare* blank line would end the quote too and drop the caret out of it,
12577        // so the separator keeps its `>` and the caret's line keeps its `> `.
12578        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
12579        doc.caret = "> - a\n> - ".len();
12580        doc.newline();
12581        assert_eq!(doc.source, "> - a\n>\n> \n");
12582        assert_eq!(list_items(&mut doc), 1);
12583        // What "still in the quote" means for the next keystroke: the caret sits
12584        // behind the prefix, and what's typed there lands inside the quote as a
12585        // paragraph of its own — not as more of item `a`.
12586        doc.insert("x");
12587        assert_eq!(doc.source, "> - a\n>\n> x\n");
12588        assert!(
12589            doc.editor
12590                .ancestors_at(doc.caret - 1)
12591                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
12592        );
12593    }
12594
12595    #[test]
12596    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
12597        // The marker is hidden block markup, so Backspace over it is structural —
12598        // but only the marker is the list's. Splicing from the line start would
12599        // take the `>` with it and silently unquote the line.
12600        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
12601        doc.caret = "> - ".len();
12602        doc.backspace();
12603        assert_eq!(doc.source, "> a\n");
12604        assert_eq!(list_items(&mut doc), 0);
12605
12606        // A nested one outdents instead, moving the bullet within the quote
12607        // rather than moving the quote.
12608        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
12609        doc.caret = "> - a\n>   - ".len();
12610        doc.backspace();
12611        assert_eq!(doc.source, "> - a\n> - b\n");
12612        assert_eq!(list_items(&mut doc), 2);
12613    }
12614
12615    #[test]
12616    fn only_a_bare_paragraph_is_parted_around_the_caret() {
12617        // The split is deliberately narrow. Parting a fenced block would leave
12618        // two fences with a rule between them, and parting a list item would
12619        // mint an item nobody asked for on the way to a rule that lands after
12620        // the list either way — so both keep the whole block intact and take the
12621        // rule after it. A caret in a quote is likewise left alone.
12622        for (name, body, caret, want) in [
12623            (
12624                "code",
12625                "```\nfn x() {}\n```\n",
12626                8,
12627                "```\nfn x() {}\n```\n\n---\n\n",
12628            ),
12629            ("list", "- one two\n", 6, "- one two\n\n---\n\n"),
12630            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n>\n> \n"),
12631        ] {
12632            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
12633            d.caret = caret;
12634            d.insert_thematic_break();
12635            assert_eq!(d.source, want, "{name}: the block should stay whole");
12636        }
12637    }
12638
12639    #[test]
12640    fn insert_thematic_break_replaces_the_selection() {
12641        // Now that the rule lands *at* the caret again, replacing the selection
12642        // is coherent once more: the text goes, and the rule takes its place.
12643        // The space the deletion left leading the second half is consumed by the
12644        // split rather than opening the new paragraph with it.
12645        let mut d = doc_with("hr_sel", "one two three\n");
12646        d.anchor = Some(4);
12647        d.caret = 7; // "two"
12648        d.insert_thematic_break();
12649        assert_eq!(d.source, "one \n\n---\n\nthree\n");
12650        assert_eq!(d.selection(), None);
12651    }
12652
12653    #[test]
12654    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
12655        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
12656        // because writing `---` into one is code, not a rule — twig now walks out
12657        // to the block that owns the caret's line, so there is nothing to refuse.
12658        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
12659        code.caret = 5; // inside the fenced code
12660        code.insert_thematic_break();
12661        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n\n");
12662        assert_eq!(code.status, None, "no refusal to report any more");
12663
12664        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
12665        table.caret = 3; // in the header row
12666        table.insert_thematic_break();
12667        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n\n");
12668    }
12669
12670    #[test]
12671    fn insert_thematic_break_in_a_list_item_ends_the_list() {
12672        // The un-indented rule cannot continue the list, so it closes the list
12673        // and lands at the top level rather than nested inside it.
12674        let mut d = doc_with("hr_list", "- one\n- two\n");
12675        d.caret = "- one\n- tw".len(); // mid "two"
12676        d.insert_thematic_break();
12677        d.build_visual(80);
12678        let rule_at = d.source.find("---").unwrap();
12679        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12680        assert!(
12681            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
12682                && n.span.start <= rule_at
12683                && rule_at < n.span.end),
12684            "the rule must not be nested inside the list"
12685        );
12686    }
12687
12688    #[test]
12689    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
12690        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
12691        // which is the document the gesture was actually asked for — and the
12692        // line the caret goes on to under it wears the prefix too, as the line
12693        // Enter opens in a quote does.
12694        let mut d = doc_with("hr_quote", "> hello\n");
12695        d.caret = 4; // inside the quoted text
12696        d.insert_thematic_break();
12697        assert_eq!(d.source, "> hello\n>\n> ---\n>\n> \n");
12698        assert_eq!(d.caret, "> hello\n>\n> ---\n>\n> ".len());
12699        d.build_visual(80);
12700        let rule_at = d.source.find("---").unwrap();
12701        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12702        assert!(
12703            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
12704                && n.span.start <= rule_at
12705                && rule_at < n.span.end),
12706            "the rule belongs to the quote it was asked for"
12707        );
12708    }
12709
12710    // ── typing against a block picture ────────────────────────────────────────
12711
12712    /// A rendered-view document with the caret parked on one of the picture's two
12713    /// stops, and the map already built — the state a frontend is in between
12714    /// drawing a frame and the next keystroke.
12715    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
12716        let mut d = doc_in(View::Wysiwyg, name, src);
12717        d.build_visual_unwrapped();
12718        let start = src.find("![").unwrap();
12719        d.caret = match side {
12720            MediaStop::Before => start,
12721            MediaStop::After => start + "![](p.png)".len(),
12722        };
12723        d
12724    }
12725
12726    /// The block media the map publishes, after rebuilding it — "is this still a
12727    /// picture, or has it become a line of text with an image in it?"
12728    fn media_count(d: &mut Doc) -> usize {
12729        d.build_visual_unwrapped();
12730        d.vmap.media.len()
12731    }
12732
12733    #[test]
12734    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
12735        // The accident this prevents: tap the blank page under a photo (which
12736        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
12737        // paragraph with an *inline* image — the photo stops being drawn.
12738        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
12739        d.insert("xy");
12740        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
12741        assert_eq!(media_count(&mut d), 1, "still a picture");
12742    }
12743
12744    #[test]
12745    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
12746        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12747        d.insert("xy");
12748        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
12749        assert_eq!(media_count(&mut d), 1);
12750    }
12751
12752    #[test]
12753    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
12754        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
12755        d.insert("x");
12756        assert_eq!(d.source, "x\n\n![](p.png)\n");
12757        assert_eq!(media_count(&mut d), 1);
12758    }
12759
12760    #[test]
12761    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
12762        // The opened paragraph is part of the keystroke, not an edit the writer
12763        // made — so it undoes with the character, not a step later.
12764        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
12765        d.insert("x");
12766        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
12767        d.undo();
12768        assert_eq!(d.source, "hi\n\n![](p.png)\n");
12769    }
12770
12771    #[test]
12772    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
12773        // ⌘V dissolves the picture exactly as a keystroke does.
12774        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
12775        d.paste("pasted");
12776        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
12777        assert_eq!(media_count(&mut d), 1);
12778    }
12779
12780    #[test]
12781    fn typing_beside_an_inline_image_is_ordinary_editing() {
12782        // An inline image has no placeholder row and no stops of its own. Opening
12783        // a paragraph mid-sentence would be the bug, not the fix.
12784        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
12785        d.build_visual_unwrapped();
12786        d.caret = "see ![](p.png)".len();
12787        d.insert("!");
12788        assert_eq!(d.source, "see ![](p.png)! here\n");
12789    }
12790
12791    #[test]
12792    fn source_view_types_raw_markup_against_an_image_untouched() {
12793        // Source view is for writing the markup itself; a break inserted behind
12794        // the writer's back there would be the editor arguing with them.
12795        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
12796        d.caret = "![](p.png)".len();
12797        d.insert("x");
12798        assert_eq!(d.source, "![](p.png)x\n");
12799    }
12800
12801    #[test]
12802    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
12803        // A selection is replaced, not joined into, so there is nothing to
12804        // protect: the range takes the picture with it.
12805        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
12806        d.anchor = Some(d.caret);
12807        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
12808        d.insert("x");
12809        assert_eq!(d.source, "hi\n\nx\n");
12810    }
12811
12812    #[test]
12813    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
12814        // What this actually cost: a real vault's photo, to one stray Backspace.
12815        // The caret past `![](p.png)` was deleting the closing paren — invisible
12816        // in the rendered view — and the photo became the text `![](p.png`.
12817        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
12818        d.backspace();
12819        assert_eq!(d.source, "hi\n");
12820        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
12821        d.undo();
12822        assert_eq!(
12823            d.source, "hi\n\n![](p.png)\n",
12824            "and comes back in one piece"
12825        );
12826    }
12827
12828    #[test]
12829    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
12830        // Deleting the break here would join the picture to the paragraph above,
12831        // where it is an *inline* image and stops being drawn. Step over the
12832        // boundary; the next press deletes in the paragraph the caret reached.
12833        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12834        d.backspace();
12835        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
12836        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
12837        d.backspace();
12838        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
12839        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
12840    }
12841
12842    #[test]
12843    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
12844        // The mirror. A byte-step here eats the `!` and leaves a link.
12845        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
12846        d.delete_forward();
12847        assert_eq!(d.source, "hi\n\nbye\n");
12848        assert_eq!(media_count(&mut d), 0);
12849    }
12850
12851    #[test]
12852    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
12853        let mut d = doc_at_picture(
12854            "pic_del_after",
12855            "hi\n\n![](p.png)\n\nbye\n",
12856            MediaStop::After,
12857        );
12858        d.delete_forward();
12859        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
12860        assert_eq!(
12861            d.caret,
12862            d.source.find("bye").unwrap(),
12863            "the caret stepped down to `bye`"
12864        );
12865    }
12866
12867    #[test]
12868    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
12869        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
12870        d.backspace();
12871        assert_eq!(d.source, "\n");
12872        assert_eq!(media_count(&mut d), 0);
12873    }
12874
12875    #[test]
12876    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
12877        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
12878        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
12879        d.delete_word_back();
12880        assert_eq!(d.source, "hi there\n");
12881
12882        // And in front of one it runs *through* the paragraph break into the
12883        // prose above, which merges the picture inline — so it steps out first,
12884        // and the second press deletes the word it was aimed at.
12885        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
12886        d.delete_word_back();
12887        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
12888        d.delete_word_back();
12889        assert_eq!(
12890            d.source, "hi \n\n![](p.png)\n",
12891            "the word above went, the picture stayed"
12892        );
12893        assert_eq!(media_count(&mut d), 1);
12894    }
12895
12896    #[test]
12897    fn source_view_deletes_raw_markup_against_an_image_untouched() {
12898        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
12899        d.caret = "![](p.png)".len();
12900        d.backspace();
12901        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
12902    }
12903
12904    #[test]
12905    fn image_destination_at_caret_reads_the_image_under_the_caret() {
12906        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
12907        d.caret = 3; // inside the image markup
12908        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
12909        // Past the image, the caret is in no image.
12910        d.caret = "![a cat](cat.png)".len();
12911        assert_eq!(d.image_destination_at_caret(), None);
12912    }
12913
12914    #[test]
12915    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
12916        // The image is one placeholder row by default, and `set_media_rows` grows
12917        // it to the height the frontend measured: the label row plus blank
12918        // `decoration` fillers that hold the vertical space a raster is drawn into.
12919        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
12920        assert_eq!(d.vmap.media.len(), 1);
12921        let img_row = d.vmap.media[0].rows_span.start;
12922        assert_eq!(
12923            d.vmap.media[0].rows_span,
12924            img_row..img_row + 1,
12925            "default is one row"
12926        );
12927
12928        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
12929        d.build_visual(80);
12930        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
12931        let span = d.vmap.media[0].rows_span.clone();
12932        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
12933        // The label row carries the mark and its glyphs; the three below are blank
12934        // decoration — drawn, but no caret and no text.
12935        assert!(
12936            d.vmap.rows[span.start].media.is_some(),
12937            "mark rides the first row"
12938        );
12939        for r in (span.start + 1)..span.end {
12940            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
12941            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
12942            assert!(
12943                d.vmap.rows[r].media.is_none(),
12944                "only the first row is marked"
12945            );
12946        }
12947    }
12948
12949    #[test]
12950    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
12951        // The extra rows are pure spacers: the caret's only homes stay the stop in
12952        // front of the image and the one just past it, so walking the document top
12953        // to bottom visits the same offsets whether the image is 1 row or 5.
12954        let body = "ab\n\n![x](p.png)\n\ncd\n";
12955        let stops_at = |rows: usize| -> Vec<usize> {
12956            let mut d = wysiwyg_doc("img_stops", body);
12957            if rows > 1 {
12958                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
12959                d.build_visual(80);
12960            }
12961            d.caret = 0;
12962            let mut seen = vec![d.caret];
12963            loop {
12964                d.move_right(false);
12965                if *seen.last().unwrap() == d.caret {
12966                    break;
12967                }
12968                seen.push(d.caret);
12969            }
12970            seen
12971        };
12972        assert_eq!(
12973            stops_at(1),
12974            stops_at(5),
12975            "reserving rows must not add stops"
12976        );
12977    }
12978
12979    #[test]
12980    fn insert_link_repoints_the_link_at_a_bare_caret() {
12981        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
12982        d.caret = 3; // in the link's text, nothing selected
12983        d.insert_link("http://y.dev");
12984        assert_eq!(d.source, "[word](http://y.dev)\n");
12985        assert_eq!(d.selected_text(), Some("word"));
12986    }
12987
12988    #[test]
12989    fn insert_link_on_an_empty_range_autolinks_a_url() {
12990        // A link with no text of its own is an autolink, and twig spells it —
12991        // `<…>` is the canonical form and needs no text typed into it, so the
12992        // caret lands after it rather than selecting a finished link.
12993        let mut d = doc_with("link_empty", "\n");
12994        d.caret = 0;
12995        d.insert_link("http://x.dev");
12996        assert_eq!(d.source, "<http://x.dev>\n");
12997        assert_eq!(d.selection(), None);
12998        assert_eq!(d.caret, 14);
12999    }
13000
13001    #[test]
13002    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
13003        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
13004        // in Markdown, so a destination that can't autolink doubles as the text
13005        // instead — which is then selected, ready to be typed over.
13006        let mut d = doc_with("link_rel", "\n");
13007        d.caret = 0;
13008        d.insert_link("./notes.md");
13009        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
13010        assert_eq!(d.selection(), Some((1, 11)));
13011        d.insert("Notes");
13012        assert_eq!(d.source, "[Notes](./notes.md)\n");
13013    }
13014
13015    #[test]
13016    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
13017        // The autolink's text is its URL, so re-pointing replaces the whole
13018        // node — the caret must not splice a second link inside the first.
13019        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
13020        d.caret = 10;
13021        d.insert_link("https://y.dev");
13022        assert_eq!(d.source, "see <https://y.dev> ok\n");
13023    }
13024
13025    #[test]
13026    fn code_language_reads_and_edits_through_the_fence() {
13027        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
13028        d.caret = 10; // inside the code body
13029        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13030        assert!(d.caret_in_fenced_code());
13031
13032        d.set_code_language("python");
13033        assert!(
13034            d.source.starts_with("```python\n"),
13035            "source: {:?}",
13036            d.source
13037        );
13038        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13039
13040        // Clearing it leaves a bare fence and no label.
13041        d.set_code_language("");
13042        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
13043        assert_eq!(d.code_language_at_caret(), None);
13044
13045        // A caret outside any code block edits nothing.
13046        let mut p = doc_with("code_lang_none", "just prose\n");
13047        assert!(!p.caret_in_fenced_code());
13048        p.set_code_language("rust");
13049        assert_eq!(p.source, "just prose\n");
13050    }
13051
13052    #[test]
13053    fn code_language_reads_and_edits_through_a_quoted_fence() {
13054        let mut d = doc_with("code_lang_quote", "> ```rust\n> let x = 1;\n> ```\n");
13055        d.caret = d.source.find("let").unwrap();
13056        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13057        assert!(d.caret_in_fenced_code());
13058        d.set_code_language("python");
13059        assert!(
13060            d.source.starts_with("> ```python\n"),
13061            "source: {:?}",
13062            d.source
13063        );
13064        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13065    }
13066
13067    #[test]
13068    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
13069        // Markdown's info string ends at whitespace, so `two words` would write
13070        // a fence that reads back with a different language than the one asked
13071        // for. twig refuses it; leaf reports that and leaves the source alone.
13072        // The old splice trimmed the ends and wrote whatever was left.
13073        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
13074        d.caret = 10;
13075        d.set_code_language("two words");
13076        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
13077        assert!(d.status.is_some(), "the refusal should be reported");
13078        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13079    }
13080
13081    #[test]
13082    fn link_destination_at_caret_reads_both_spellings() {
13083        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
13084        d.caret = 5;
13085        assert_eq!(
13086            d.link_destination_at_caret().as_deref(),
13087            Some("https://x.dev")
13088        );
13089        d.caret = 0;
13090        assert_eq!(d.link_destination_at_caret(), None);
13091
13092        // An autolink has no `destination`; its text is the URL.
13093        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
13094        a.caret = 10;
13095        assert_eq!(
13096            a.link_destination_at_caret().as_deref(),
13097            Some("https://x.dev")
13098        );
13099        a.caret = 21;
13100        assert_eq!(a.link_destination_at_caret(), None);
13101    }
13102
13103    #[test]
13104    fn heading_at_caret_is_the_nearest_heading_above() {
13105        let src = "intro\n\n# Title\n\n## The *Second* Part\n\nbody here\n";
13106        let mut d = doc_with("heading_at", src);
13107        // Under no heading at all.
13108        d.caret = 2;
13109        assert_eq!(d.heading_at_caret(), None);
13110        // In a paragraph under a level-2 heading: that heading, its markup
13111        // stripped for the slug, and its own span.
13112        d.caret = src.find("body").unwrap() + 2;
13113        let h = d.heading_at_caret().expect("under `## The Second Part`");
13114        assert_eq!(h.text, "The Second Part");
13115        assert_eq!(h.level, 2);
13116        assert_eq!(&src[h.span.clone()].trim_end(), &"## The *Second* Part");
13117        // Standing in a heading answers with that heading.
13118        let h = d.heading_at(src.find("Title").unwrap()).unwrap();
13119        assert_eq!((h.text.as_str(), h.level), ("Title", 1));
13120        // And the text is what `locate` lands a slug of.
13121        let landing = d.locate("the-second-part").unwrap();
13122        assert_eq!(landing.start, d.heading_at_caret().unwrap().span.start);
13123    }
13124
13125    #[test]
13126    fn locate_finds_the_block_a_declared_id_names() {
13127        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
13128        // verse. The locator has to land on the *verse*, which is the whole
13129        // reason a link carries one.
13130        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
13131                   {#v2}\nYea, I make a record in the language of my father.\n";
13132        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13133        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
13134        assert_eq!(
13135            d.source[v2.start..v2.end].trim_end(),
13136            "Yea, I make a record in the language of my father."
13137        );
13138        // The attribute line is not part of it: `start` is a place to put a
13139        // caret, and `{#v2}` is markup the caret has no business landing in.
13140        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
13141        assert_eq!(d.locate("v99"), None);
13142    }
13143
13144    #[test]
13145    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
13146        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
13147        // Markdown heading is literal text. So `#the-second-part` can only be
13148        // the heading's own words, which is the rule every Markdown renderer
13149        // already follows and therefore the one a link was authored against.
13150        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
13151        let mut d = doc_with("locate_md", src);
13152        let hit = d.locate("the-second-part").expect("the heading's slug");
13153        assert!(d.source[hit.start..].starts_with("## The Second Part"));
13154        // Bounded by the next heading that isn't under it, so a peek shows the
13155        // section rather than only its title.
13156        assert_eq!(
13157            &d.source[hit.start..hit.end],
13158            "## The Second Part\n\nbody\n\n"
13159        );
13160
13161        // A subsection does not end its parent: `# Title` runs to `## Third`'s
13162        // sibling only because there is no other `#`, so it covers the lot.
13163        let title = d.locate("title").expect("the top heading");
13164        assert_eq!(title.end, d.source.len());
13165    }
13166
13167    #[test]
13168    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
13169        // djot mints `Some-Heading-Here`; a link to it is written
13170        // `#some-heading-here` by nearly everything that writes links. Both
13171        // spellings are one question.
13172        let src = "## Some Heading Here\n\nbody\n";
13173        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13174        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
13175        let slugged = d.locate("some-heading-here").expect("the link's spelling");
13176        assert_eq!(exact, slugged);
13177        // The section, not the heading line — there is more to show than a title.
13178        assert_eq!(&d.source[exact.start..exact.end], src);
13179    }
13180
13181    #[test]
13182    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
13183        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
13184        assert_eq!(d.locate(""), None);
13185        assert_eq!(d.locate("   "), None);
13186        // All punctuation: it names nothing, and must not be read as "match the
13187        // first heading whose slug is also empty".
13188        assert_eq!(d.locate("!!!"), None);
13189    }
13190
13191    #[test]
13192    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
13193        // The document's mistake, and the answer every other anchor
13194        // implementation gives — the alternative is for a link to mean whichever
13195        // of the two a walk happened to reach first.
13196        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
13197        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13198        let hit = d.locate("dup").expect("the first `{#dup}`");
13199        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
13200    }
13201
13202    #[test]
13203    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
13204        // The button's whole job: a reference where the caret was, a definition
13205        // to give it meaning, and the caret waiting in the empty note so the
13206        // next keystroke is the note's first word.
13207        let mut d = doc_with("fn_insert", "A claim and more.\n");
13208        d.caret = 7; // just past "A claim"
13209        d.insert_footnote();
13210        assert!(
13211            d.source.starts_with("A claim[^1] and more."),
13212            "{:?}",
13213            d.source
13214        );
13215        assert!(
13216            d.source.contains("[^1]:"),
13217            "the definition too: {:?}",
13218            d.source
13219        );
13220        assert_eq!(d.status, None);
13221
13222        let reference = d.source.find("[^1]").unwrap();
13223        let note = d
13224            .footnote_at(reference + 2)
13225            .expect("the reference just written");
13226        assert_eq!(note.label, "1");
13227        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
13228        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
13229        // …and typing there is typing into the note, not near it.
13230        d.insert("the note");
13231        assert_eq!(
13232            d.footnote_at(reference + 2).and_then(|f| f.text),
13233            Some("the note".to_string())
13234        );
13235    }
13236
13237    #[test]
13238    fn insert_footnote_numbers_past_the_notes_already_written() {
13239        // A second press must not hand back a label somebody else is using: twig
13240        // reuses a defined label rather than appending a rival definition, so a
13241        // repeat of `1` would quietly point the new reference at the old note.
13242        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
13243        d.caret = 7; // past `[^1]`, before " two."
13244        d.insert_footnote();
13245        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
13246        assert_eq!(d.source.matches("[^2]:").count(), 1);
13247    }
13248
13249    #[test]
13250    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
13251        // `[^2]` with no definition is still a 2 that means something to whoever
13252        // wrote it — stepping over it would mint a note for their reference. A
13253        // word label takes no number, so it blocks none.
13254        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
13255        d.caret = d.source.find(" c").unwrap();
13256        d.insert_footnote();
13257        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
13258        assert!(
13259            d.source.starts_with("a[^2] b[^why][^1] c"),
13260            "{:?}",
13261            d.source
13262        );
13263    }
13264
13265    #[test]
13266    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
13267        // A reference annotates the words before it. Consuming the selection —
13268        // which is what an insert normally does — would delete the very claim
13269        // the author selected in order to footnote.
13270        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
13271        d.anchor = Some(2);
13272        d.caret = 7; // "claim" selected
13273        d.insert_footnote();
13274        assert!(
13275            d.source.starts_with("A claim[^1] and more."),
13276            "{:?}",
13277            d.source
13278        );
13279    }
13280
13281    #[test]
13282    fn a_note_just_written_still_knows_where_its_reference_is() {
13283        // The authoring loop in one test: press the button, type the note, ask to
13284        // go back. The caret ends at the note's last byte — which is the *end* of
13285        // the definition's span, the one offset the query used to exclude — so
13286        // this is where the round trip either works or doesn't.
13287        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
13288        d.caret = 7;
13289        d.insert_footnote();
13290        d.insert("the note");
13291        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
13292        let back = d
13293            .footnote_definition_at_caret()
13294            .expect("still in the note we just typed");
13295        assert_eq!(back.label, "1");
13296        // …and following it lands on the reference's label, where a reader's
13297        // return leg lands.
13298        assert_eq!(back.offset, Some(9));
13299        assert_eq!(&d.source[9..10], "1");
13300    }
13301
13302    #[test]
13303    fn insert_footnote_takes_one_undo_for_both_halves() {
13304        // twig writes the pair as a single edit; the point of that is here.
13305        let before = "A claim and more.\n";
13306        let mut d = doc_with("fn_insert_undo", before);
13307        d.caret = 7;
13308        d.insert_footnote();
13309        assert_ne!(d.source, before);
13310        d.undo();
13311        assert_eq!(d.source, before, "one undo takes back both halves");
13312    }
13313
13314    #[test]
13315    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
13316        // HTML is authorable — it spells the inline marks — and has no footnote.
13317        // The refusal says so rather than writing brackets that would render as
13318        // brackets.
13319        let src = "<p>A claim.</p>\n";
13320        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
13321        assert!(!Capabilities::of(Format::Html).footnote);
13322        d.caret = 5;
13323        d.insert_footnote();
13324        assert_eq!(d.source, src, "nothing written");
13325        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
13326    }
13327
13328    #[test]
13329    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
13330        // The empty body is the one place this could go wrong: the definition
13331        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
13332        // byte early would draw up in the paragraph above the note it belongs to.
13333        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
13334        d.place_caret(7, false);
13335        d.insert_footnote();
13336        d.build_visual(80); // the frame a frontend draws after the edit
13337        assert_eq!(
13338            d.vmap.snap_to_stop(d.caret),
13339            d.caret,
13340            "the caret sits on a stop"
13341        );
13342        let (row, _) = d.caret_pos();
13343        assert!(
13344            drawn_rows(&d)[row].contains("[1]"),
13345            "the caret is on the note's row, not above it: {:?}",
13346            drawn_rows(&d)
13347        );
13348    }
13349
13350    #[test]
13351    fn footnote_at_caret_resolves_a_reference_to_its_note() {
13352        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
13353        // blank line, as one has to.
13354        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
13355        d.caret = 9;
13356        let f = d
13357            .footnote_at_caret()
13358            .expect("the caret stands in a reference");
13359        assert_eq!(f.label, "1");
13360        assert_eq!(f.text.as_deref(), Some("the note"));
13361        // The offset points at the note's first word, not at the definition's
13362        // `[` — the marker is decoration with no caret stop on it.
13363        assert_eq!(f.offset, Some(29));
13364        assert_eq!(&d.source[29..37], "the note");
13365        // …and `end` closes the range, so a frontend can ask which rendered rows
13366        // the note occupies rather than re-deriving them from the text.
13367        assert_eq!(f.end, Some(37));
13368        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
13369    }
13370
13371    /// Two definitions in a row: each is its own note, and neither reaches into
13372    /// the other.
13373    ///
13374    /// A djot definition's span used to run past the blank line into the first
13375    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
13376    /// offsets named the *next* note's rows too, showing a reader two footnotes
13377    /// when they had asked about one. twig 3.1 ends the span after the block's
13378    /// own last line; the test outlives the workaround leaf carried for it.
13379    #[test]
13380    fn footnote_at_stops_a_note_at_the_definition_after_it() {
13381        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
13382        for format in [Format::Markdown, Format::Djot] {
13383            let mut d = Doc::from_source(src.to_string(), format).unwrap();
13384            d.caret = 7;
13385            let f = d.footnote_at_caret().expect("a reference");
13386            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
13387            assert_eq!(
13388                &src[f.offset.unwrap()..f.end.unwrap()],
13389                "first note.",
13390                "in {format:?}"
13391            );
13392        }
13393    }
13394
13395    /// The other side of that boundary: a blank line *inside* a definition is
13396    /// interior to it, and the note keeps its second paragraph.
13397    ///
13398    /// This is what the old body scan cost. It stopped at the first line not
13399    /// indented under the note — a blank line is not — so a two-paragraph note
13400    /// came back as its first paragraph, and "go to note" framed half of it.
13401    /// Reading the span twig gives is both simpler and right.
13402    #[test]
13403    fn footnote_at_keeps_a_notes_second_paragraph() {
13404        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
13405        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13406        d.caret = 7;
13407        let f = d.footnote_at_caret().expect("a reference");
13408        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
13409        // And it stops there — `After.` is the next block, not more note.
13410        assert_eq!(
13411            &src[f.offset.unwrap()..f.end.unwrap()],
13412            f.text.as_deref().unwrap()
13413        );
13414        assert!(!f.text.as_deref().unwrap().contains("After"));
13415    }
13416
13417    #[test]
13418    fn footnote_at_bounds_a_note_whose_body_is_empty() {
13419        // `[^1]:` with nothing after it. The range is empty rather than
13420        // inverted, and still points inside the definition — which is what keeps
13421        // a frontend's row lookup from walking off into the block above.
13422        let src = "A claim[^1].\n\n[^1]:\n";
13423        let mut d = doc_with("fn_empty_body", src);
13424        d.caret = 9;
13425        let f = d.footnote_at_caret().expect("a reference");
13426        assert_eq!(f.text.as_deref(), Some(""));
13427        assert_eq!(f.offset, f.end, "an empty note is an empty range");
13428        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
13429    }
13430
13431    #[test]
13432    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
13433        let mut d = doc_with(
13434            "fn_at_caret_none",
13435            "A claim[^1] and more.\n\n[^1]: the note\n",
13436        );
13437        d.caret = 2; // in the prose
13438        assert_eq!(d.footnote_at_caret(), None);
13439    }
13440
13441    #[test]
13442    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
13443        // The two are deliberately separate: a reference names a note in this
13444        // document, a link names somewhere to leave for, and answering one with
13445        // the other is what made a reference click do nothing at all.
13446        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
13447        d.caret = 3; // the `1` of `[^1]`
13448        assert!(d.footnote_at_caret().is_some());
13449        assert_eq!(
13450            d.link_destination_at_caret(),
13451            None,
13452            "a reference is not a link"
13453        );
13454
13455        d.caret = 10; // inside the link's label
13456        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
13457        assert_eq!(
13458            d.link_destination_at_caret().as_deref(),
13459            Some("https://x.dev")
13460        );
13461    }
13462
13463    #[test]
13464    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
13465        // A `[^99]` the document never defines is a real state — a note deleted
13466        // out from under its reference — and the label is what lets a frontend
13467        // say so. `None` here would be indistinguishable from "not on a
13468        // reference", which is the wrong thing to tell a reader.
13469        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
13470        d.caret = 9;
13471        let f = d
13472            .footnote_at_caret()
13473            .expect("the reference is still a reference");
13474        assert_eq!(f.label, "99");
13475        assert_eq!(f.text, None);
13476        assert_eq!(f.offset, None);
13477    }
13478
13479    #[test]
13480    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
13481        // Labels are not always numbers, and a note's body runs past its first
13482        // line — the indented continuation belongs to the note, so it comes back
13483        // with it (source bytes, verbatim, as documented).
13484        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
13485        let mut d = doc_with("fn_word_label", src);
13486        d.caret = 6;
13487        let f = d
13488            .footnote_at_caret()
13489            .expect("the caret stands in a reference");
13490        assert_eq!(f.label, "note");
13491        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
13492    }
13493
13494    #[test]
13495    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
13496        // The point of the offset form: a pointer hovering a reference asks what
13497        // note it names, and must not drag the caret along to ask.
13498        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
13499        d.caret = 0;
13500        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
13501        assert_eq!(f.label, "1");
13502        assert_eq!(f.text.as_deref(), Some("the note"));
13503        assert_eq!(d.caret, 0, "asking must not move the caret");
13504        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
13505    }
13506
13507    #[test]
13508    fn footnote_definition_at_caret_points_back_at_the_reference() {
13509        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
13510        // the caret can rest on — is at 9.
13511        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
13512        d.caret = 30; // inside the note's body
13513        let f = d
13514            .footnote_definition_at_caret()
13515            .expect("the caret stands in a definition");
13516        assert_eq!(f.label, "1");
13517        assert_eq!(f.offset, Some(9));
13518        assert_eq!(&d.source[7..11], "[^1]");
13519    }
13520
13521    #[test]
13522    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
13523        // The two legs have to meet: wherever `footnote_at` sends the caret, the
13524        // definition query must answer for — otherwise arriving at a note leaves
13525        // the reader somewhere the way back isn't offered.
13526        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
13527        let mut d = doc_with("fn_def_marker", src);
13528        let landed = d.footnote_at(9).unwrap().offset.unwrap();
13529        assert_eq!(
13530            d.footnote_definition_at(landed).and_then(|f| f.offset),
13531            Some(9),
13532            "the note a reference sends you to offers the way back"
13533        );
13534    }
13535
13536    #[test]
13537    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
13538        // The two queries answer for disjoint places, which is what lets one
13539        // gesture mean "down to the note" in one and "back up" in the other
13540        // without either having to remember which way the reader is going.
13541        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
13542        d.caret = 2; // prose
13543        assert_eq!(d.footnote_definition_at_caret(), None);
13544        d.caret = 9; // the reference
13545        assert_eq!(d.footnote_definition_at_caret(), None);
13546        assert!(
13547            d.footnote_at_caret().is_some(),
13548            "which is the reference's own query"
13549        );
13550    }
13551
13552    #[test]
13553    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
13554        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
13555        // note", which is false and leaves a frontend unable to explain why the
13556        // way back is missing.
13557        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
13558        let mut d = doc_with("fn_def_orphan", src);
13559        d.caret = src.find("orphan").unwrap();
13560        let f = d
13561            .footnote_definition_at_caret()
13562            .expect("an orphan is still a definition");
13563        assert_eq!(f.label, "2");
13564        assert_eq!(f.offset, None);
13565    }
13566
13567    #[test]
13568    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
13569        // One label, cited twice. The first is where the reader most likely came
13570        // from, and the only answer that doesn't depend on how they got here.
13571        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
13572        let mut d = doc_with("fn_def_repeat", src);
13573        d.caret = src.find("the note").unwrap();
13574        let f = d.footnote_definition_at_caret().expect("a definition");
13575        assert_eq!(
13576            f.offset,
13577            Some(5),
13578            "the first `[^a]`'s label, not the second's"
13579        );
13580        assert_eq!(&src[3..7], "[^a]");
13581    }
13582
13583    #[test]
13584    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
13585        // Down and back up, each leg found from the document rather than from a
13586        // memory of the other — so it still works for a reader who scrolled to
13587        // the notes instead of jumping there.
13588        //
13589        // `place_caret` rather than assigning `caret`, because that is what a
13590        // frontend calls: it snaps to a real caret stop, and a jump that lands
13591        // on a byte the caret can't rest on would arrive somewhere the return
13592        // leg no longer answers for. `build_map` first, since snapping is a
13593        // no-op until the map exists — which is exactly how this went unnoticed
13594        // when the offsets pointed at the `[^` markers.
13595        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
13596        d.build_map(None);
13597        d.place_caret(9, false);
13598        let down = d
13599            .footnote_at_caret()
13600            .expect("a reference")
13601            .offset
13602            .expect("a note");
13603        d.place_caret(down, false);
13604        let up = d
13605            .footnote_definition_at_caret()
13606            .expect("a definition")
13607            .offset
13608            .expect("a reference");
13609        d.place_caret(up, false);
13610        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
13611        assert_eq!(
13612            d.footnote_at_caret().expect("back on the reference").label,
13613            "1"
13614        );
13615    }
13616
13617    #[test]
13618    fn insert_link_hands_the_destination_to_twig_raw() {
13619        // Escaping is twig's, and format-specific: Markdown ends a destination
13620        // at the first space and needs the `<…>` form, where djot would read
13621        // those angle brackets as part of the URL.
13622        let mut d = doc_with("link_space", "word\n");
13623        d.anchor = Some(0);
13624        d.caret = 4;
13625        d.insert_link("a b");
13626        assert_eq!(d.source, "[word](<a b>)\n");
13627    }
13628
13629    #[test]
13630    fn insert_link_reports_a_destination_no_format_can_carry() {
13631        let mut d = doc_with("link_bad", "word\n");
13632        d.anchor = Some(0);
13633        d.caret = 4;
13634        d.insert_link("a\nb");
13635        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
13636        assert!(
13637            d.status.is_some(),
13638            "InvalidArgument should reach the status line"
13639        );
13640        assert!(!d.dirty);
13641    }
13642
13643    #[test]
13644    fn insert_link_works_in_wysiwyg_view() {
13645        let mut d = wysiwyg_doc("link_wys", "word here\n");
13646        d.anchor = Some(0);
13647        d.caret = 4;
13648        d.insert_link("http://x.dev");
13649        assert_eq!(d.source, "[word](http://x.dev) here\n");
13650        assert_eq!(d.selected_text(), Some("word"));
13651        // The map the caret has to keep riding is rebuilt each frame; motion
13652        // over the fresh one must still land on a real stop (the debug_assert).
13653        d.build_visual(80);
13654        d.move_right(false);
13655        d.move_left(false);
13656    }
13657
13658    #[test]
13659    fn click_maps_a_row_col_to_a_byte_offset() {
13660        let mut d = doc_with("click", "ab\ncd\n");
13661        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
13662        assert_eq!(d.caret, 4);
13663    }
13664
13665    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
13666    // stop just as the `(row, col)` click path does, so the caret can never come
13667    // to rest in the blank gap between two paragraphs — where it would draw in one
13668    // place and type in another.
13669    #[test]
13670    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
13671        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
13672        // caret stop (stops are 0,1,3,4).
13673        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
13674        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
13675        d.place_caret(2, false);
13676        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13677        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
13678    }
13679
13680    #[test]
13681    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
13682        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
13683        d.place_caret(0, false); // anchor at the start of "A"
13684        d.place_caret(2, true); // drag into the gap
13685        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13686        let (s, e) = d.selection().expect("a selection");
13687        assert!(
13688            d.vmap.is_stop(s) && d.vmap.is_stop(e),
13689            "selection {s}..{e} off a stop"
13690        );
13691    }
13692
13693    #[test]
13694    fn place_caret_on_a_real_stop_is_left_untouched() {
13695        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
13696        d.place_caret(3, false); // the start of "B" — a genuine stop
13697        assert_eq!(d.caret, 3);
13698    }
13699
13700    // An *empty paragraph* (two blank lines, an intentional blank line the user
13701    // opened) is a real caret stop, unlike the gap — a click into it must stay.
13702    #[test]
13703    fn place_caret_rests_in_an_empty_paragraph() {
13704        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
13705        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
13706        assert!(d.vmap.is_stop(empty));
13707        d.place_caret(empty, false);
13708        assert_eq!(d.caret, empty);
13709    }
13710
13711    // The content end of a hidden mark is a home too (`VisualMap::mark_ends`):
13712    // a drag over the word `bold` ends there, and a caret placed there stays.
13713    #[test]
13714    fn place_caret_rests_at_the_end_of_a_hidden_marks_content() {
13715        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
13716        let mut d = wysiwyg_doc("place_mark_end", src);
13717        let start = src.find("bold").unwrap();
13718        d.place_caret(start, false);
13719        d.place_caret(start + 4, true);
13720        assert_eq!(d.selection(), Some((start, start + 4)), "the whole word");
13721        d.toggle(InlineKind::Strong);
13722        assert_eq!(d.source, src.replace("**bold**", "bold"));
13723    }
13724
13725    #[test]
13726    fn right_steps_onto_the_end_of_a_mark_and_then_past_its_delimiter() {
13727        let mut d = wysiwyg_doc("right_mark_end", "a **bold** b");
13728        d.caret = 7; // before the `d`
13729        d.move_right(false);
13730        assert_eq!(d.caret, 8, "onto the end of the bold");
13731        assert!(d.active_inline_marks().contains(InlineKind::Strong));
13732        d.move_right(false);
13733        assert_eq!(d.caret, 10, "past the closing `**`");
13734        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
13735        d.move_left(false);
13736        assert_eq!(d.caret, 8);
13737        d.move_left(false);
13738        assert_eq!(d.caret, 7);
13739        // Typing at the inner home extends the bold.
13740        d.caret = 8;
13741        d.insert("!");
13742        assert_eq!(d.source, "a **bold!** b");
13743    }
13744
13745    #[test]
13746    fn a_marks_end_home_follows_an_edit_through_the_incremental_map() {
13747        // The splice path shifts the home with the block it is in, and the
13748        // re-rendered block finds its own again.
13749        let mut d = wysiwyg_doc("mark_end_splice", "x\n\na **bold** b\n\ny\n");
13750        d.build_visual_unwrapped();
13751        d.edit(0, 0, "zz");
13752        d.build_visual_unwrapped();
13753        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a shift");
13754        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13755        let at = d.source.find("bold").unwrap();
13756        d.edit(at, at, "very ");
13757        d.build_visual_unwrapped();
13758        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a re-render");
13759        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13760    }
13761
13762    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
13763        doc_in(View::Wysiwyg, name, body)
13764    }
13765
13766    /// How many list items the source actually parses into — the check that a
13767    /// marker Leaf wrote is a marker the format agrees is one.
13768    fn list_items(doc: &mut Doc) -> usize {
13769        doc.editor
13770            .nodes()
13771            .unwrap()
13772            .iter()
13773            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
13774            .count()
13775    }
13776
13777    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
13778    /// incremental (`build_spliced` / `build_cached`) path must always match.
13779    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
13780        reference_map_revealing(source, None)
13781    }
13782
13783    /// [`reference_map`] with a reveal line — the ground truth for the
13784    /// `MarkupMode::Full` builds, where the map is a function of the caret's
13785    /// line as well as the text.
13786    fn reference_map_revealing(source: &str, reveal: Option<Reveal>) -> crate::wysiwyg::VisualMap {
13787        // The same parse `Doc` uses. With twig's plain defaults instead, the two
13788        // sides disagree on what the *document* is before the renderer is even
13789        // reached — a bare `:word` is a text directive to one and prose to the
13790        // other — and the mismatch reads as a splice bug that isn't one.
13791        let mut ed =
13792            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
13793        let nodes = ed.nodes().unwrap();
13794        crate::wysiwyg::build(
13795            &nodes,
13796            source,
13797            None,
13798            false,
13799            &wysiwyg::Surface::default(),
13800            reveal,
13801        )
13802    }
13803
13804    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
13805        if a.rows.len() != b.rows.len() {
13806            return true;
13807        }
13808        for (ra, rb) in a.rows.iter().zip(&b.rows) {
13809            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
13810                return true;
13811            }
13812            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
13813                if ga.ch != gb.ch || ga.src != gb.src {
13814                    return true;
13815                }
13816            }
13817        }
13818        false
13819    }
13820
13821    #[test]
13822    fn incremental_build_matches_a_fresh_build_across_edits() {
13823        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
13824        // fast path, gated on twig's `dirty_range`) or falls back to
13825        // `build_cached`. After each edit the map must be byte-identical to a
13826        // from-scratch build — this is the correctness net under the splice.
13827        let docs = [
13828            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
13829            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
13830            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
13831            // A footnote definition is a root beside `doc`, merged back into the
13832            // top-level list by `wysiwyg::top_blocks`. The random edits below
13833            // make and unmake definitions as they go (a deleted `:` turns one
13834            // back into a paragraph, and vice versa), which is exactly the
13835            // structural churn the splice path has to notice and bail out of.
13836            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
13837            // A comment is a top-level block that draws no rows — a layout entry
13838            // at zero rows either side of blocks that do. The edits below type
13839            // into the blocks around it (a splice past a hidden block), and
13840            // break the comment open into prose and back (a structural change).
13841            "intro\n\n<!-- exec -->\n```\ncode\n```\n\nafter the comment\n\n<!-- trail -->\n",
13842            // Link reference definitions: a hidden block that an edit can turn
13843            // into a paragraph (a deleted `:`) and back, and whose own bytes an
13844            // edit can land in.
13845            "see [a] and [b]\n\n[a]: /a\n\nmid text\n\n[b]: /b\n",
13846            // Blank lines above the first block draw as rows, counted as its
13847            // separator; above it past frontmatter and past a comment too.
13848            "\n\nfirst pushed down\n\nsecond\n",
13849            "---\ntitle: x\n---\n\n\nafter frontmatter\n\nmore\n",
13850            "<!-- lead -->\n\n\nafter a comment\n\nmore\n",
13851            // No `<div>` here yet: an edit that takes the blank line under
13852            // `</div>` leaves a map no fresh build draws. See
13853            // docs/tasks/text-glued-under-a-closing-div.md.
13854        ];
13855        // A deterministic mix: mostly single characters (which stay inside one
13856        // block → splice), plus edits that reshape structure (a paragraph break,
13857        // a heading marker, a code fence → fallback), so both paths are exercised.
13858        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
13859        for src in docs {
13860            let mut d = wysiwyg_doc("diff", src);
13861            d.build_visual_unwrapped();
13862            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
13863
13864            for step in 0..60usize {
13865                let len = d.source.len();
13866                let raw = (step * 13 + 5) % (len + 1);
13867                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
13868                let pre = d.source.clone();
13869                let action;
13870                if step % 3 == 0 && pos < len {
13871                    let end = (pos + 1..=len)
13872                        .find(|&i| d.source.is_char_boundary(i))
13873                        .unwrap();
13874                    action = format!("delete [{pos},{end})");
13875                    d.edit(pos, end, "");
13876                } else {
13877                    let ins = inserts[step % inserts.len()];
13878                    action = format!("insert {ins:?} @ {pos}");
13879                    d.edit(pos, pos, ins);
13880                }
13881                d.build_visual_unwrapped();
13882                if maps_differ(&d.vmap, &reference_map(&d.source)) {
13883                    panic!(
13884                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
13885                        d.source
13886                    );
13887                }
13888            }
13889        }
13890    }
13891
13892    /// A frontend is handed [`Doc::vmap`] and may present it differently:
13893    /// leaf-ratatui splices blank filler rows under an oversized heading so the
13894    /// raster it paints there has somewhere to stand, and leaves them in the map
13895    /// because the caret and the mouse both read it between frames. The splice
13896    /// path addresses that map by *row index*, against the block layout the last
13897    /// build recorded — so handed a map with rows in it that no block owns, it
13898    /// laid the re-rendered block over one of the fillers and carried the rows
13899    /// the block really occupied into the suffix. One stranded copy of the
13900    /// edited line, and everything below it a row further down, per keystroke.
13901    ///
13902    /// A map that isn't the one the layout describes is a map this path can't
13903    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
13904    #[test]
13905    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
13906        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
13907        d.build_visual_unwrapped();
13908
13909        // Stand in for the heading filler rows: two blank rows past the heading
13910        // that no block accounts for. Cloning a real row keeps every field
13911        // plausible — it is the row *count* the splice can't survive.
13912        let filler = d.vmap.rows[0].clone();
13913        d.vmap.rows.insert(1, filler.clone());
13914        d.vmap.rows.insert(1, filler);
13915
13916        // An edit inside the last block: the single-block case the splice path
13917        // is for, and the one the frontend hits on every keystroke.
13918        let at = d.source.len() - 1;
13919        d.edit(at, at, "!");
13920        d.build_visual_unwrapped();
13921
13922        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
13923    }
13924
13925    /// A glyph's [`FaceId`] has to mean the same thing however its row was
13926    /// built. A row comes three ways — a fresh walk, a [`BlockCache`] hit
13927    /// cloned at a shifted offset, and a previous map's rows a splice kept
13928    /// untouched — and only the first of those walks a `data-font` at all. An
13929    /// index into a per-build table would have had the same glyph naming two
13930    /// families the moment a second one appeared; the id is the name's own
13931    /// hash, so nothing is remapped and the table is merged rather than rebuilt.
13932    ///
13933    /// Two families, because one cannot tell a wrong id from a right one.
13934    ///
13935    /// [`FaceId`]: crate::style::FaceId
13936    /// [`BlockCache`]: crate::wysiwyg::BlockCache
13937    #[test]
13938    fn a_spliced_rebuild_still_says_which_family_each_glyph_is_set_in() {
13939        use crate::style::{FaceId, FaceRef};
13940        let garamond = FaceId::of("Garamond");
13941        let futura = FaceId::of("Futura");
13942        let mut d = wysiwyg_doc(
13943            "two_faces",
13944            "x <span data-font=\"Garamond\">alpha</span>\n\ny <span data-font=\"Futura\">beta</span>\n",
13945        );
13946        d.build_visual_unwrapped();
13947
13948        // What the map has to keep saying, whichever path built it.
13949        let check = |d: &Doc, ctx: &str| {
13950            let face_of = |ch: char| {
13951                d.vmap
13952                    .rows
13953                    .iter()
13954                    .flat_map(|r| r.glyphs.iter())
13955                    .find(|g| g.ch == ch)
13956                    .map(|g| g.style.font)
13957            };
13958            assert_eq!(face_of('a'), Some(Some(FaceRef::Named(garamond))), "{ctx}");
13959            assert_eq!(face_of('b'), Some(Some(FaceRef::Named(futura))), "{ctx}");
13960            assert_eq!(d.vmap.face_name(garamond), Some("Garamond"), "{ctx}");
13961            assert_eq!(d.vmap.face_name(futura), Some("Futura"), "{ctx}");
13962            assert_eq!(d.vmap.face_name(FaceId::of("Bodoni")), None, "{ctx}");
13963        };
13964        check(&d, "fresh");
13965
13966        // An edit inside the second block: the single-block case the splice
13967        // path is for. The first block's rows are carried over untouched, so
13968        // its glyphs' ids are the previous build's and the table has to be too.
13969        let at = d.source.find("beta").unwrap();
13970        d.edit(at, at, "z");
13971        d.build_visual_unwrapped();
13972        check(&d, "after an edit in the second block");
13973        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced");
13974
13975        // And the other way round, so the block that was kept is the one that
13976        // is now re-rendered.
13977        let at = d.source.find("alpha").unwrap();
13978        d.edit(at, at, "z");
13979        d.build_visual_unwrapped();
13980        check(&d, "after an edit in the first block");
13981        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced again");
13982
13983        // A structural edit is one the splice bails out of, so the map is
13984        // reassembled by `build_cached` — where an untouched block is a *cache
13985        // hit* and its rows are cloned without a `data-font` being walked
13986        // again. The names the entry stored are what keeps the table honest
13987        // there.
13988        let at = d.source.find("\n\ny ").unwrap();
13989        d.edit(at, at, "\n\nmiddle");
13990        d.build_visual_unwrapped();
13991        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached");
13992        // Twice, because that first `build_cached` is what stores the entries:
13993        // this one is the build where the Garamond block is a *hit*, its rows
13994        // cloned with their ids and no attribute walked to explain them.
13995        let at = d.source.len() - 1;
13996        d.edit(at, at, "\n\ntail");
13997        d.build_visual_unwrapped();
13998        check(&d, "after a structural edit, through the block cache");
13999        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached again");
14000
14001        // A family the edit took the last glyph of leaves the glyphs with no
14002        // face and the table with a name nothing asks for — harmless, and the
14003        // price of not walking the rows the splice exists to avoid walking.
14004        let span = d.source.find("<span data-font=\"Futura\">").unwrap();
14005        let end = d.source.rfind("</span>").unwrap() + "</span>".len();
14006        d.edit(span, end, "beta");
14007        d.build_visual_unwrapped();
14008        assert!(!d.source.contains("Futura"), "{:?}", d.source);
14009        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "the face removed");
14010    }
14011
14012    #[test]
14013    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
14014        // The same correctness net as `incremental_build_matches_a_fresh_build_
14015        // across_edits`, under `MarkupMode::Full` — where the map depends on
14016        // the caret's *line* as well as the text, so the two caches have a new
14017        // way to be wrong. Both are exercised: the block cache can hand back
14018        // rows built for a line that is no longer the revealed one, and the
14019        // splice path can reuse a suffix that still has yesterday's line raw.
14020        //
14021        // Caret motion is interleaved with the edits deliberately, because a
14022        // caret that only ever moved with the edit would never cross a line
14023        // without also dirtying it — the case where a stale reveal survives.
14024        let docs = [
14025            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
14026            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
14027        ];
14028        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
14029        for src in docs {
14030            let mut d = wysiwyg_doc("reveal_diff", src);
14031            d.set_markup_mode(MarkupMode::Full);
14032
14033            for step in 0..60usize {
14034                let len = d.source.len();
14035                let raw = (step * 13 + 5) % (len + 1);
14036                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
14037                let pre = d.source.clone();
14038                let action;
14039                if step % 3 == 0 && pos < len {
14040                    let end = (pos + 1..=len)
14041                        .find(|&i| d.source.is_char_boundary(i))
14042                        .unwrap();
14043                    action = format!("delete [{pos},{end})");
14044                    d.edit(pos, end, "");
14045                } else {
14046                    let ins = inserts[step % inserts.len()];
14047                    action = format!("insert {ins:?} @ {pos}");
14048                    d.edit(pos, pos, ins);
14049                }
14050                // Walk the caret somewhere else in the document, independently
14051                // of where the edit landed.
14052                let want = (step * 29 + 11) % (d.source.len() + 1);
14053                d.caret = (want..=d.source.len())
14054                    .find(|&i| d.source.is_char_boundary(i))
14055                    .unwrap();
14056                d.build_visual_unwrapped();
14057
14058                let want = reference_map_revealing(&d.source, d.reveal_line());
14059                if maps_differ(&d.vmap, &want) {
14060                    panic!(
14061                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
14062                        d.caret, d.source
14063                    );
14064                }
14065            }
14066        }
14067    }
14068
14069    #[test]
14070    fn caret_motion_across_lines_rebuilds_only_under_full() {
14071        // The cache-key change has to earn its keep in both directions: `Full`
14072        // must rebuild when the caret changes line (or the reveal would never
14073        // move), and the hidden modes must *not* (or every arrow key would pay
14074        // for a feature they don't use). The existing `cache_motion` test pins
14075        // the second for the default mode; this pins the pair against a mode
14076        // change alone.
14077        let body = "*one* here\n\n*two* there\n";
14078
14079        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
14080        full.set_markup_mode(MarkupMode::Full);
14081        caret_at(&mut full, "one");
14082        let before = full.revision();
14083        caret_at(&mut full, "two");
14084        assert_eq!(full.revision(), before, "motion is not an edit");
14085        assert!(
14086            drawn_rows(&full).iter().any(|r| r == "*two* there"),
14087            "the map followed the caret: {:?}",
14088            drawn_rows(&full)
14089        );
14090
14091        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
14092        caret_at(&mut hidden, "one");
14093        let key = hidden.vmap_key.clone();
14094        caret_at(&mut hidden, "two");
14095        assert_eq!(
14096            hidden.vmap_key, key,
14097            "a hidden mode rebuilds nothing on motion"
14098        );
14099    }
14100
14101    #[test]
14102    fn wysiwyg_down_crosses_a_paragraph_boundary() {
14103        // Regression: the blank separator row used to share the previous
14104        // paragraph's end offset, so Down got pinned at the boundary (while Up
14105        // still crossed). Both directions must step through it symmetrically.
14106        //
14107        // It's now stepped *over* rather than onto: the blank line between two
14108        // paragraphs is the boundary being drawn, not a line of the document, so
14109        // one press of Down crosses it. The goal column survives the crossing —
14110        // col 3 at the end of "abc" is col 3 at the end of "def".
14111        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
14112        d.caret = 3; // end of "abc" (row 0)
14113        d.move_down(false);
14114        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
14115        assert_eq!(d.caret, 8); // end of "def", col 3 kept
14116        d.move_up(false);
14117        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
14118        assert_eq!(d.caret, 3);
14119    }
14120
14121    #[test]
14122    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
14123        // The second Up and the second Down here run off the ends of the
14124        // document, which is no longer a place a press is swallowed: they carry
14125        // the caret to the start and the end of the text. The claim in the
14126        // middle — that a Down retraces the Up that crossed the paragraph gap —
14127        // is the one this test is for, and it is asserted where it is made.
14128        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
14129        d.caret = 5; // start of "def"
14130        let start = d.caret_pos();
14131        d.move_up(false);
14132        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
14133        d.move_up(false);
14134        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
14135        d.move_down(false);
14136        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
14137        d.move_down(false);
14138        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
14139    }
14140
14141    #[test]
14142    fn wysiwyg_new_paragraph_shows_before_typing() {
14143        // Regression: two Enters at the end of a paragraph produced trailing
14144        // newlines with no AST node, so the caret appeared stuck on the old line
14145        // until a character was typed. It must ride down onto the new line now.
14146        let mut d = doc_with("wys_newpara", "abc\n");
14147        d.view = View::Wysiwyg;
14148        d.caret = 3;
14149        d.insert("\n");
14150        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
14151        assert_eq!(d.source, "abc\n\n\n");
14152        d.build_visual(80);
14153        let (row, _) = d.caret_pos();
14154        assert!(
14155            row >= 2,
14156            "caret should have moved down to the new line, got row {row}"
14157        );
14158        assert!(
14159            d.vmap.num_rows() >= 3,
14160            "the blank lines should render as rows"
14161        );
14162    }
14163
14164    #[test]
14165    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
14166        // The reported bug: Enter at the end of a paragraph that has another
14167        // paragraph below put the caret at the *start of the next paragraph* —
14168        // the empty paragraph it opened had no row, so the caret snapped onto
14169        // "World". It must now sit on its own empty line, with a blank spacer
14170        // above it (the paragraph gap).
14171        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
14172        d.caret = 5; // end of "Hello"
14173        d.newline();
14174        d.build_visual(80);
14175        let (row, col) = d.caret_pos();
14176        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
14177        assert_eq!(
14178            d.vmap.row_width(row),
14179            0,
14180            "caret's row must be empty, not 'World'"
14181        );
14182        assert!(
14183            row >= 2,
14184            "a blank spacer row should sit above the caret, got row {row}"
14185        );
14186        // The row above the caret is a real (empty) gap, and "Hello" stays put.
14187        assert_eq!(
14188            d.vmap.row_width(row - 1),
14189            0,
14190            "the row above the caret is a gap"
14191        );
14192        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
14193        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
14194    }
14195
14196    #[test]
14197    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
14198        // At the document end a single Enter must also show the paragraph gap —
14199        // a blank spacer row above the caret — so the layout already matches how
14200        // it will look once the new paragraph has text.
14201        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
14202        d.caret = 5; // end of "Hello", no trailing newline
14203        d.newline(); // source becomes "Hello\n\n"
14204        d.build_visual(80);
14205        let (row, col) = d.caret_pos();
14206        assert_eq!(col, 0);
14207        assert!(
14208            row >= 2,
14209            "caret should sit below a blank spacer, got row {row}"
14210        );
14211        assert_eq!(
14212            d.vmap.row_width(row - 1),
14213            0,
14214            "the row above the caret is a gap"
14215        );
14216    }
14217
14218    #[test]
14219    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
14220        // The spacer is view-only: typing the new paragraph must not reflow the
14221        // caret onto a different row — the transient view already matched the
14222        // settled one.
14223        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
14224        d.caret = 5;
14225        d.newline();
14226        d.build_visual(80);
14227        let before = d.caret_pos();
14228        d.insert("New");
14229        d.build_visual(80);
14230        let after = d.caret_pos();
14231        assert_eq!(
14232            after.0, before.0,
14233            "typing must not move the caret to another row ({before:?} -> {after:?})"
14234        );
14235    }
14236
14237    #[test]
14238    fn wysiwyg_return_on_the_last_code_line_keeps_the_caret_in_the_block() {
14239        // Return at the end of the block's last line writes an empty line the
14240        // map used to drop, so the caret landed on `after` and the next
14241        // keystroke went into the paragraph below instead of into the code.
14242        let mut d = wysiwyg_doc("code_return", "prose\n\n```\nalpha\nbeta\n```\n\nafter\n");
14243        d.caret = d.source.find("beta").unwrap() + "beta".len();
14244        d.build_visual(80);
14245        let before = d.caret_pos().0;
14246
14247        d.newline();
14248        d.build_visual(80);
14249        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n");
14250
14251        let (row, col) = d.caret_pos();
14252        assert_eq!(row, before + 1, "the caret moves down one row");
14253        assert_eq!(col, 0, "onto the head of the empty line");
14254        let span = d.vmap.code_blocks[0].rows_span.clone();
14255        assert!(
14256            span.contains(&row),
14257            "caret row {row} is outside the block's rows {span:?}"
14258        );
14259
14260        // The whole point: what is typed next is code.
14261        d.insert("gamma");
14262        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\ngamma\n```\n\nafter\n");
14263    }
14264
14265    #[test]
14266    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
14267        let fm = "---\ntitle: hi\n---\n";
14268        let body = format!("{fm}# leaf\n\nbody\n");
14269        let mut d = wysiwyg_doc("wys_fm", &body);
14270        // Opening lifts the caret out of the now-hidden frontmatter.
14271        assert_eq!(
14272            d.caret,
14273            fm.len(),
14274            "caret should start at the first real block"
14275        );
14276        // Left at the content start can't step back into frontmatter.
14277        d.move_left(false);
14278        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
14279        // Doc-start lands on the content floor, not offset 0.
14280        d.move_doc_start(false);
14281        assert_eq!(d.caret, fm.len());
14282        // Select-all + copy never include the frontmatter bytes.
14283        d.select_all();
14284        let sel = d.selected_text().unwrap().to_string();
14285        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
14286        assert!(
14287            sel.starts_with("# leaf"),
14288            "selection should begin at content: {sel:?}"
14289        );
14290    }
14291
14292    #[test]
14293    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
14294        // A fresh note is frontmatter and nothing else. With no rendered block
14295        // to floor the caret it opened at offset 0 — before the opening `---` —
14296        // so the first keystroke wrote itself in front of the metadata and the
14297        // file came out as `This---\ntitle: …`.
14298        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
14299        let mut d = wysiwyg_doc("wys_fm_only", fm);
14300        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
14301        // Nothing is rendered, so the caret draws at the origin of an empty view
14302        // — the same place an empty document puts it.
14303        assert_eq!(d.caret_pos(), (0, 0));
14304        d.insert("This");
14305        assert_eq!(d.source, format!("{fm}This"));
14306    }
14307
14308    /// `select_range` is the verb for a range a host already knows the bytes of,
14309    /// so it must not snap — and must still hold every invariant `place_caret`
14310    /// holds, the frontmatter floor above all.
14311    #[test]
14312    fn select_range_takes_the_range_as_given_but_still_floors_it() {
14313        let fm = "---\ntitle: foo\n---\n\n";
14314        let body = format!("{fm}body foo here\n");
14315        let mut d = wysiwyg_doc("wys_select_range", &body);
14316
14317        // The `foo` in the body: taken exactly, not snapped to a caret stop.
14318        let at = body.rfind("foo").unwrap();
14319        d.select_range(at, at + 3);
14320        assert_eq!(d.selection(), Some((at, at + 3)));
14321        assert_eq!(d.selected_text(), Some("foo"));
14322
14323        // The `foo` in the hidden frontmatter: below the floor, so both ends
14324        // come up to it rather than parking the caret in the metadata, where a
14325        // later keystroke would rewrite `title:`.
14326        let hidden = body.find("foo").unwrap();
14327        assert!(hidden < d.vmap.content_start);
14328        d.select_range(hidden, hidden + 3);
14329        assert!(
14330            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
14331            "a range under the floor must not leave the caret in the frontmatter"
14332        );
14333
14334        // Past the end, and mid-character, are both brought back to something
14335        // sliceable rather than panicking the next reader of the range.
14336        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
14337        let mut d = multi;
14338        d.select_range(2, 9_999);
14339        assert_eq!(d.caret, d.source.len());
14340        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
14341        assert!(d.source.is_char_boundary(d.caret));
14342    }
14343
14344    /// The bug `select_range` exists for: a match butting up against a hidden
14345    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
14346    /// the one before the `**`.
14347    #[test]
14348    fn select_range_does_not_snap_off_a_hidden_delimiter() {
14349        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
14350        let at = d.source.find("needle").unwrap();
14351        d.select_range(at, at + 6);
14352        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
14353    }
14354
14355    #[test]
14356    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
14357        // Backspace deletes `prev_boundary..caret` directly; at the first real
14358        // block that boundary is inside the hidden frontmatter, so it must be a
14359        // no-op rather than eating the closing `---`.
14360        let fm = "---\ntitle: hi\n---\n";
14361        let body = format!("{fm}leaf\n");
14362        let mut d = wysiwyg_doc("wys_fm_bs", &body);
14363        assert_eq!(d.caret, fm.len());
14364        d.backspace();
14365        assert_eq!(d.source, body, "backspace must not touch frontmatter");
14366        d.delete_word_back();
14367        assert_eq!(
14368            d.source, body,
14369            "word-delete must not touch frontmatter either"
14370        );
14371    }
14372
14373    #[test]
14374    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
14375        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
14376        // fenced div, really, since core parses these on for every document
14377        // now (`parse_extensions`). The container is a `directive` node, an
14378        // `is_block_container` kind like `block_quote`, so the caret works
14379        // inside its child paragraph exactly as it would inside a quote: typing
14380        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
14381        // untouched.
14382        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
14383        let mut d = wysiwyg_doc("wys_vis", body);
14384        d.caret = body.find("hello").unwrap() + "hello".len();
14385        d.insert("!");
14386        assert_eq!(
14387            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
14388            "typing inside the block edits its content in place"
14389        );
14390        assert!(
14391            d.source.contains(":::vis{.public .family}"),
14392            "opening fence survives"
14393        );
14394        assert!(d.source.contains(":::\nafter"), "closing fence survives");
14395    }
14396
14397    #[test]
14398    fn source_view_still_reaches_frontmatter() {
14399        // The metadata is only *hidden*, never lost: the source view edits and
14400        // selects it in full, and it's always preserved on save.
14401        let fm = "---\ntitle: hi\n---\n";
14402        let body = format!("{fm}# leaf\n");
14403        let mut d = doc_with("src_fm", &body);
14404        d.select_all();
14405        let sel = d.selected_text().unwrap();
14406        assert!(
14407            sel.contains("title"),
14408            "source view should select everything"
14409        );
14410        d.move_doc_start(false);
14411        assert_eq!(d.caret, 0, "source view can reach offset 0");
14412    }
14413
14414    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
14415
14416    #[test]
14417    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
14418        // The border and padding between two cells all share one source offset,
14419        // so a column-stepping caret would sit on `│` and then stall there
14420        // forever. Right must step: end of "Name" -> start of "Qty".
14421        let mut d = wysiwyg_doc("tbl_right", TABLE);
14422        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
14423        d.move_right(false);
14424        assert_eq!(
14425            d.caret,
14426            TABLE.find("Qty").unwrap(),
14427            "should land in the next cell"
14428        );
14429        let (r, c) = d.caret_pos();
14430        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
14431    }
14432
14433    #[test]
14434    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
14435        let mut d = wysiwyg_doc("tbl_left", TABLE);
14436        d.caret = TABLE.find("Qty").unwrap();
14437        d.move_left(false);
14438        assert_eq!(
14439            d.caret,
14440            TABLE.find("Name").unwrap() + 4,
14441            "end of the previous cell"
14442        );
14443    }
14444
14445    #[test]
14446    fn wysiwyg_down_steps_over_a_table_rule() {
14447        // Between the header and the first body row sits a `├───┼───┤` rule.
14448        // It's drawn but holds no caret, so one Down must reach "Pear".
14449        let mut d = wysiwyg_doc("tbl_down", TABLE);
14450        d.caret = TABLE.find("Name").unwrap();
14451        d.move_down(false);
14452        assert_eq!(
14453            d.caret,
14454            TABLE.find("Pear").unwrap(),
14455            "one Down reaches the body row"
14456        );
14457        d.move_down(false);
14458        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
14459    }
14460
14461    #[test]
14462    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
14463        let mut d = wysiwyg_doc("tbl_tab", TABLE);
14464        d.caret = TABLE.find("Name").unwrap();
14465        // A hop lands with the destination cell's whole content selected, the
14466        // caret at its end — so typing replaces the cell like a form field.
14467        assert!(d.cell_hop(true));
14468        assert_eq!(
14469            d.selected_text(),
14470            Some("Qty"),
14471            "the target cell comes up selected"
14472        );
14473        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
14474        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
14475        assert_eq!(d.selected_text(), Some("Pear"));
14476        assert!(d.cell_hop(false));
14477        assert_eq!(d.selected_text(), Some("Qty"));
14478    }
14479
14480    #[test]
14481    fn tab_outside_a_table_is_not_a_cell_hop() {
14482        // `cell_hop` reports false so the frontend can indent as usual.
14483        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
14484        d.caret = 4;
14485        assert!(!d.cell_hop(true));
14486        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
14487    }
14488
14489    #[test]
14490    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
14491        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14492        d.caret = TABLE.rfind("12").unwrap(); // the final cell
14493        assert!(!d.cell_hop(true), "no cell after the last one");
14494        d.caret = TABLE.find("Name").unwrap();
14495        assert!(!d.cell_hop(false), "no cell before the first one");
14496    }
14497
14498    #[test]
14499    fn wysiwyg_vertical_cell_motion_holds_the_column() {
14500        // Down/Up step to the cell above/below in the *same column*, not back to
14501        // the top-left the way a naive row/col motion over the picture would.
14502        let mut d = wysiwyg_doc("tbl_vert", TABLE);
14503        d.caret = TABLE.find("Qty").unwrap();
14504        // Each vertical hop selects the destination cell, holding the column.
14505        assert!(d.cell_move_vertical(true));
14506        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
14507        assert!(d.cell_move_vertical(true));
14508        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
14509        assert!(!d.cell_move_vertical(true), "no row below the last");
14510        assert!(d.cell_move_vertical(false));
14511        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
14512        assert!(d.cell_move_vertical(false));
14513        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
14514        assert!(!d.cell_move_vertical(false), "no row above the header");
14515    }
14516
14517    #[test]
14518    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
14519        let mut d = wysiwyg_doc("tbl_grow", TABLE);
14520        d.caret = TABLE.rfind("12").unwrap();
14521        let rows_before = d.source.matches('\n').count();
14522        assert!(d.cell_tab(true), "acts as a table key");
14523        assert_eq!(
14524            d.source.matches('\n').count(),
14525            rows_before + 1,
14526            "a fresh row was appended"
14527        );
14528        assert!(d.caret_in_table(), "the caret entered the new row");
14529        // The caret sits in the new row's first cell — past the old last cell.
14530        assert!(d.caret > TABLE.rfind("12").unwrap());
14531    }
14532
14533    #[test]
14534    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
14535        let mut d = wysiwyg_doc("tbl_ret", TABLE);
14536        d.caret = TABLE.find("Name").unwrap();
14537        assert!(d.cell_return(), "acts as a table key");
14538        assert_eq!(
14539            d.selected_text(),
14540            Some("Pear"),
14541            "Return drops one cell, selecting it"
14542        );
14543        // From the last row, Return appends a row and enters it.
14544        d.caret = TABLE.rfind("Fig").unwrap();
14545        let rows_before = d.source.matches('\n').count();
14546        assert!(d.cell_return());
14547        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
14548        assert!(d.caret_in_table());
14549    }
14550
14551    #[test]
14552    fn return_and_tab_outside_a_table_decline() {
14553        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
14554        d.caret = 4;
14555        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
14556        assert!(!d.cell_tab(true), "no table: the frontend indents");
14557        assert!(
14558            !d.cell_line_break(),
14559            "no table: the frontend breaks the line"
14560        );
14561    }
14562
14563    #[test]
14564    fn a_click_under_a_trailing_table_lands_past_it_and_enter_opens_a_line() {
14565        // A document that ends in a table used to end *inside* it: nothing
14566        // past the last cell was a caret stop, so a click in the blank space
14567        // under the grid snapped back into the table and there was no way to
14568        // write a line after it. The bottom border's end is that stop now.
14569        let mut d = wysiwyg_doc("tbl_trail", TABLE);
14570        let rows = d.vmap.num_rows();
14571        d.click(rows + 3, 0, false);
14572        let end = TABLE.trim_end_matches('\n').len();
14573        assert_eq!(d.caret, end, "the caret stands just past the table");
14574        assert!(!d.caret_in_table(), "past the table is outside it");
14575        assert!(!d.cell_return(), "Return there is the frontend's newline");
14576        d.newline();
14577        d.insert("after");
14578        assert_eq!(
14579            d.source,
14580            format!("{TABLE}\nafter\n"),
14581            "Enter opens a paragraph under the table"
14582        );
14583    }
14584
14585    #[test]
14586    fn typing_at_a_table_s_trailing_stop_opens_a_paragraph_first() {
14587        // The stop sits at the end of the table's last source line, and a
14588        // line glued under a table is a row of it — `| Fig | 12 |x` would be a
14589        // three-cell row. So the text gets a paragraph of its own, as it does
14590        // beside a block picture.
14591        let mut d = wysiwyg_doc("tbl_type", TABLE);
14592        d.caret = TABLE.trim_end_matches('\n').len();
14593        d.insert("x");
14594        assert_eq!(d.source, format!("{TABLE}\nx\n"));
14595        assert_eq!(d.caret, TABLE.len() + 2, "the caret follows the text");
14596        // And a paste, which joins the block exactly as typing would.
14597        let mut d = wysiwyg_doc("tbl_paste", TABLE);
14598        d.caret = TABLE.trim_end_matches('\n').len();
14599        d.paste("pasted");
14600        assert_eq!(d.source, format!("{TABLE}\npasted\n"));
14601    }
14602
14603    #[test]
14604    fn right_leaves_a_table_by_its_trailing_stop_and_backspace_steps_back_in() {
14605        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14606        let last_cell_end = TABLE.rfind("12").unwrap() + 2;
14607        let end = TABLE.trim_end_matches('\n').len();
14608        d.caret = last_cell_end;
14609        d.move_right(false);
14610        assert_eq!(d.caret, end, "Right from the last cell leaves the table");
14611        // Backspace there takes no byte: the one behind the caret is the row's
14612        // closing `|`, which the rich view never drew. It steps back instead.
14613        d.backspace();
14614        assert_eq!(d.source, TABLE, "nothing deleted");
14615        assert_eq!(d.caret, last_cell_end, "back into the last cell");
14616        // Down from the last row lands on the same stop, and Up returns.
14617        d.move_down(false);
14618        assert_eq!(d.caret, end, "Down from the last row leaves the table");
14619        d.move_up(false);
14620        assert_eq!(d.caret, last_cell_end);
14621    }
14622
14623    #[test]
14624    fn a_table_s_trailing_stop_sits_between_it_and_the_text_below() {
14625        // With prose under the table, the stop is one hop between the last
14626        // cell and the paragraph — the shape a block picture's second stop has.
14627        let src = format!("{TABLE}\nafter\n");
14628        let mut d = wysiwyg_doc("tbl_mid", &src);
14629        d.caret = TABLE.rfind("12").unwrap() + 2;
14630        d.move_right(false);
14631        assert_eq!(d.caret, TABLE.trim_end_matches('\n').len());
14632        d.move_right(false);
14633        assert_eq!(d.caret, src.find("after").unwrap());
14634        // Typing at the stop still opens a paragraph, and the text below keeps
14635        // its own.
14636        d.move_left(false);
14637        d.insert("x");
14638        assert_eq!(d.source, format!("{TABLE}\nx\n\nafter\n"));
14639    }
14640
14641    #[test]
14642    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
14643        let mut d = wysiwyg_doc("tbl_break", TABLE);
14644        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
14645        assert!(d.cell_line_break(), "acts as a table key");
14646        assert!(
14647            d.source.contains("Pear<br>"),
14648            "spelled as an inline <br>: {}",
14649            d.source
14650        );
14651        assert!(d.caret_in_table(), "still in the cell, past the break");
14652        // The break renders as a real line: the "Pear" cell now draws two lines,
14653        // so the table's picture is one row taller than a single-line table.
14654        d.build_visual(80);
14655        let table = &d.vmap.tables[0];
14656        let cell = &table.grid[1].cells[0]; // first body row, first column
14657        assert!(
14658            cell.glyphs.iter().any(|g| g.ch == '\n'),
14659            "the cell carries the break as a newline glyph for the frontend to split"
14660        );
14661    }
14662
14663    #[test]
14664    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
14665        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
14666        // back as structure — the whole point of routing through insert_line_break
14667        // instead of splicing raw `<br>` bytes.
14668        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
14669        d.caret = TABLE.find("Pear").unwrap() + 4;
14670        assert!(d.cell_line_break());
14671        let kinds: Vec<Kind> = d
14672            .editor
14673            .nodes()
14674            .unwrap()
14675            .iter()
14676            .map(|n| n.kind.clone())
14677            .collect();
14678        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
14679        assert!(
14680            !kinds.contains(&Kind::RawInline),
14681            "still raw HTML: {kinds:?}"
14682        );
14683    }
14684
14685    #[test]
14686    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
14687        // The `<br>` draws as one newline glyph, so Backspace over it must take
14688        // all four bytes — a one-byte delete would strand a visible `<br` in the
14689        // cell (the reported bug).
14690        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
14691        d.caret = TABLE.find("Pear").unwrap() + 4;
14692        assert!(d.cell_line_break());
14693        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
14694        d.backspace(); // caret sits just past the break
14695        assert!(
14696            !d.source.contains("<br"),
14697            "no half-deleted <br left: {}",
14698            d.source
14699        );
14700        assert!(
14701            d.source.contains("| Pear |"),
14702            "the cell is back to one line: {}",
14703            d.source
14704        );
14705    }
14706
14707    #[test]
14708    fn backspace_at_a_cell_start_is_a_wall() {
14709        // The task's repro: two presses used to take the padding and then the
14710        // `|`, merging `d` into `c`'s cell and leaving the row a column short.
14711        let src = "| a | b |\n| - | - |\n| c | d |\n";
14712        let mut d = wysiwyg_doc("tbl_wall_bs", src);
14713        d.place_caret(src.find("d |").unwrap(), false);
14714        for _ in 0..3 {
14715            d.backspace();
14716        }
14717        assert_eq!(d.source, src);
14718        // Inside the padding too — right after the `|`, before the space. Set
14719        // directly: `place_caret` would snap it onto the stop past the space.
14720        d.caret = src.find("| d").unwrap() + 1;
14721        d.backspace();
14722        assert_eq!(d.source, src);
14723        // The row's first cell, and an empty one, are walls the same.
14724        d.place_caret(src.find("c |").unwrap(), false);
14725        d.backspace();
14726        assert_eq!(d.source, src);
14727        // A cell that opens on hidden markup: the wall is the first letter
14728        // drawn, not the `**` in front of it.
14729        let bold = "| a | b |\n| - | - |\n| c | **d** |\n";
14730        let mut d = wysiwyg_doc("tbl_wall_bs_bold", bold);
14731        d.place_caret(bold.find("d**").unwrap(), false);
14732        d.backspace();
14733        assert_eq!(d.source, bold);
14734        let empty = "| a | b |\n| - | - |\n| c |   |\n";
14735        let mut d = wysiwyg_doc("tbl_wall_bs_empty", empty);
14736        d.place_caret(empty.find("|   |").unwrap() + 2, false);
14737        d.backspace();
14738        assert_eq!(d.source, empty);
14739    }
14740
14741    #[test]
14742    fn backspace_inside_a_cell_still_deletes_a_character() {
14743        let src = "| a | b |\n| - | - |\n| c | de |\n";
14744        let mut d = wysiwyg_doc("tbl_wall_bs_mid", src);
14745        d.place_caret(src.find("e |").unwrap(), false);
14746        d.backspace();
14747        assert_eq!(d.source, "| a | b |\n| - | - |\n| c | e |\n");
14748    }
14749
14750    #[test]
14751    fn delete_at_a_cell_end_is_a_wall() {
14752        // The mirror: Delete at `c`'s end would take the padding, then the `|`.
14753        let src = "| a | b |\n| - | - |\n| c | d |\n";
14754        let mut d = wysiwyg_doc("tbl_wall_del", src);
14755        d.place_caret(src.find("c |").unwrap() + 1, false);
14756        for _ in 0..3 {
14757            d.delete_forward();
14758        }
14759        assert_eq!(d.source, src);
14760        // And inside the trailing padding, set directly past the snap.
14761        d.caret = src.find("c |").unwrap() + 2;
14762        d.delete_forward();
14763        assert_eq!(d.source, src);
14764        // The row's last cell is a wall on its closing `|` as well.
14765        d.place_caret(src.find("d |").unwrap() + 1, false);
14766        d.delete_forward();
14767        assert_eq!(d.source, src);
14768        // Mid-cell Delete is untouched.
14769        d.place_caret(src.find("c |").unwrap(), false);
14770        d.delete_forward();
14771        assert_eq!(d.source, "| a | b |\n| - | - |\n|  | d |\n");
14772    }
14773
14774    #[test]
14775    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
14776        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
14777        d.caret = TABLE.find("Pear").unwrap() + 4;
14778        assert!(d.cell_line_break());
14779        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
14780        d.delete_forward();
14781        assert!(
14782            !d.source.contains("<br"),
14783            "no half-deleted <br: {}",
14784            d.source
14785        );
14786        assert!(
14787            d.source.contains("| Pear |"),
14788            "cell back to one line: {}",
14789            d.source
14790        );
14791    }
14792
14793    #[test]
14794    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
14795        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
14796        // still consumed (a real newline would split the one-line row), but the
14797        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
14798        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
14799        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
14800        d.caret = src.find("Pear").unwrap() + 4;
14801        assert!(d.caret_in_table(), "caret should be inside the djot table");
14802        assert!(
14803            d.cell_line_break(),
14804            "the key is consumed, not passed to the frontend"
14805        );
14806        assert_eq!(d.source, src, "the djot cell is left untouched");
14807        assert!(
14808            !d.source.contains("<br>"),
14809            "no non-idiomatic <br> spliced into djot"
14810        );
14811        assert!(
14812            d.status.is_some(),
14813            "the refusal is surfaced on the status line"
14814        );
14815    }
14816
14817    #[test]
14818    fn typing_in_a_cell_edits_that_cell() {
14819        // Editing comes free once offsets map correctly: the caret is a source
14820        // offset, so a normal splice lands inside the pipe table.
14821        let mut d = wysiwyg_doc("tbl_type", TABLE);
14822        d.caret = TABLE.find("Pear").unwrap() + 4;
14823        d.insert("s");
14824        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
14825    }
14826
14827    #[test]
14828    fn motion_and_delete_treat_an_emoji_as_one_character() {
14829        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
14830        // bytes, several codepoints. Right-arrow must clear it in one step, and
14831        // backspace must remove the whole cluster, not a stray joiner.
14832        let family = "👨‍👩‍👧";
14833        let mut d = doc_with("emoji", &format!("a{family}b\n"));
14834        d.caret = 1; // just after 'a', before the emoji
14835        d.move_right(false);
14836        assert_eq!(
14837            d.caret,
14838            1 + family.len(),
14839            "one step clears the whole cluster"
14840        );
14841        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
14842
14843        d.backspace(); // delete the emoji as a unit
14844        assert_eq!(d.source, "ab\n");
14845        assert_eq!(d.caret, 1);
14846    }
14847
14848    #[test]
14849    fn motion_handles_a_combining_accent_as_one_character() {
14850        // "e" + U+0301 (combining acute) renders as one é.
14851        let mut d = doc_with("combining", "e\u{0301}x\n");
14852        d.caret = 0;
14853        d.move_right(false);
14854        assert_eq!(
14855            d.caret,
14856            "e\u{0301}".len(),
14857            "steps past base + combining mark"
14858        );
14859    }
14860
14861    #[test]
14862    fn undo_then_redo_round_trips_an_edit() {
14863        let mut d = doc_with("undo", "hello\n");
14864        d.caret = 5;
14865        d.insert("!");
14866        assert_eq!(d.source, "hello!\n");
14867        d.undo();
14868        assert_eq!(d.source, "hello\n");
14869        assert_eq!(d.caret, 5, "undo restores the caret");
14870        d.redo();
14871        assert_eq!(d.source, "hello!\n");
14872    }
14873
14874    #[test]
14875    fn a_run_of_typing_undoes_as_one_step() {
14876        let mut d = doc_with("coalesce", "\n");
14877        d.caret = 0;
14878        d.insert("a");
14879        d.insert("b");
14880        d.insert("c");
14881        assert_eq!(d.source, "abc\n");
14882        d.undo(); // the whole typed run, not just "c"
14883        assert_eq!(d.source, "\n");
14884        d.undo(); // nothing left — the run was one step
14885        assert_eq!(d.source, "\n");
14886        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
14887    }
14888
14889    // ── IME composition ──────────────────────────────────────────────────────
14890
14891    #[test]
14892    fn a_composition_run_undoes_as_one_step() {
14893        let mut d = doc_with("compose", "\n");
14894        d.caret = 0;
14895        // What an IME does: each step replaces the last one's provisional bytes.
14896        d.edit_composing(0, 0, "k");
14897        d.edit_composing(0, 1, "か");
14898        d.edit_composing(0, 3, "かん");
14899        d.edit_composing(0, 6, "感"); // the commit
14900        d.end_composition();
14901        assert_eq!(d.source, "感\n");
14902        d.undo(); // the whole composition, not its last keystroke
14903        assert_eq!(d.source, "\n");
14904        assert_eq!(d.status.as_deref(), None, "the run was a single step");
14905    }
14906
14907    /// A Replace All the way a host does one: every match, last to first so
14908    /// the offsets still to go stay put, each a selection replaced by an
14909    /// insert, inside one undo group. `select_range` rather than the host's
14910    /// snapping `place_caret`, which would snap against a map these tests do
14911    /// not rebuild between edits.
14912    fn replace_all_in(d: &mut Doc, needle: &str, with: &str) {
14913        let hits: Vec<usize> = d.source.match_indices(needle).map(|(i, _)| i).collect();
14914        d.begin_undo_group();
14915        for at in hits.into_iter().rev() {
14916            d.select_range(at, at + needle.len());
14917            d.insert(with);
14918        }
14919        d.end_undo_group();
14920    }
14921
14922    #[test]
14923    fn a_replace_all_undoes_and_redoes_as_one_step() {
14924        let mut d = wysiwyg_doc("group", "a cat, a **cat**, a cat\n");
14925        d.caret = 0;
14926        d.insert("x");
14927        replace_all_in(&mut d, "cat", "dog");
14928        assert_eq!(d.source, "xa dog, a **dog**, a dog\n");
14929        assert!(d.undo(), "one undo");
14930        assert_eq!(
14931            d.source, "xa cat, a **cat**, a cat\n",
14932            "puts back every match"
14933        );
14934        assert!(d.redo(), "one redo");
14935        assert_eq!(
14936            d.source, "xa dog, a **dog**, a dog\n",
14937            "replaces them all again"
14938        );
14939        assert!(d.undo());
14940        assert!(d.undo(), "the typing before is its own step");
14941        assert_eq!(d.source, "a cat, a **cat**, a cat\n");
14942        assert!(!d.can_undo());
14943    }
14944
14945    #[test]
14946    fn typing_after_a_group_is_a_step_of_its_own() {
14947        // A one-character replacement is an insert like a keystroke, and a
14948        // keystroke after it would coalesce with it outside a group.
14949        let mut d = wysiwyg_doc("group", "a b a\n");
14950        replace_all_in(&mut d, "a", "c");
14951        d.caret = d.source.len() - 1;
14952        d.insert("d");
14953        assert_eq!(d.source, "c b cd\n");
14954        assert!(d.undo());
14955        assert_eq!(d.source, "c b c\n", "the typing alone");
14956        assert!(d.undo());
14957        assert_eq!(d.source, "a b a\n", "then the replacement, whole");
14958    }
14959
14960    #[test]
14961    fn a_group_of_more_edits_than_the_history_holds_is_still_one_step() {
14962        // twig keeps 200 steps; a group folds as it goes, so it never holds
14963        // more than one of them.
14964        let src = format!("start\n{}\n", "x ".repeat(300));
14965        let mut d = wysiwyg_doc("group", &src);
14966        d.caret = 5;
14967        d.insert("!");
14968        replace_all_in(&mut d, "x", "yy");
14969        assert_eq!(d.undo_steps, 2);
14970        assert!(d.undo());
14971        assert_eq!(d.source, src.replacen("start", "start!", 1));
14972        assert!(d.undo());
14973        assert_eq!(d.source, src);
14974        assert!(!d.can_undo());
14975    }
14976
14977    #[test]
14978    fn an_undo_closes_an_open_group() {
14979        let mut d = wysiwyg_doc("group", "one\n");
14980        d.caret = 3;
14981        d.begin_undo_group();
14982        d.begin_undo_group();
14983        d.insert("x");
14984        assert!(d.in_undo_group());
14985        assert!(d.undo());
14986        assert!(
14987            !d.in_undo_group(),
14988            "the history moved, so the group is over"
14989        );
14990        d.end_undo_group();
14991        d.end_undo_group();
14992        assert_eq!(d.source, "one\n");
14993        assert!(d.redo());
14994        assert_eq!(d.source, "onex\n");
14995    }
14996
14997    #[test]
14998    fn a_substitution_behind_the_caret_leaves_the_caret_and_is_its_own_step() {
14999        let mut d = wysiwyg_doc("substitute", "\n");
15000        d.caret = 0;
15001        for c in ["I", " ", "s", "a", "w", " ", "t", "e", "h", " "] {
15002            d.insert(c);
15003        }
15004        assert_eq!(d.source, "I saw teh \n");
15005        let at = d.source.find("teh").unwrap();
15006        assert!(d.substitute(at, at + 3, "the"));
15007        assert_eq!(d.source, "I saw the \n");
15008        assert_eq!(d.caret, 10, "still after the space");
15009        assert!(d.selection().is_none());
15010        d.insert("c");
15011        assert_eq!(d.source, "I saw the c\n");
15012        assert!(d.undo(), "the typing after it is a step of its own");
15013        assert_eq!(d.source, "I saw the \n");
15014        assert!(d.undo(), "the correction is one step");
15015        assert_eq!(d.source, "I saw teh \n", "what was typed");
15016        assert_eq!(d.caret, 10, "with the caret where it stood");
15017        assert!(d.redo());
15018        assert_eq!(d.source, "I saw the \n");
15019        assert!(d.undo());
15020        assert!(d.undo(), "and the typing before it is its own");
15021        assert_eq!(d.source, "\n");
15022        assert!(!d.can_undo());
15023    }
15024
15025    #[test]
15026    fn a_substitution_keeps_the_markup_it_stands_beside() {
15027        // A quote typed just past a bold run: only its own byte changes.
15028        let mut d = wysiwyg_doc("substitute", "A **bold** word\n");
15029        let at = d.source.find(" word").unwrap();
15030        d.caret = at;
15031        d.insert("\"");
15032        assert_eq!(d.source, "A **bold**\" word\n");
15033        assert!(d.substitute(at, at + 1, "\u{201d}"));
15034        assert_eq!(d.source, "A **bold**\u{201d} word\n");
15035        assert_eq!(d.caret, at + "\u{201d}".len());
15036        assert!(
15037            d.marks_at(d.source.find("bold").unwrap())
15038                .iter()
15039                .any(|(k, _)| *k == InlineKind::Strong)
15040        );
15041        // A range that is not one is refused, and changes nothing.
15042        let src = d.source.clone();
15043        assert!(!d.substitute(3, 2, "x"));
15044        assert!(!d.substitute(0, src.len() + 1, "x"));
15045        assert!(!d.substitute(d.source.find('\u{201d}').unwrap() + 1, d.source.len(), "x"));
15046        assert_eq!(d.source, src);
15047    }
15048
15049    #[test]
15050    fn a_substitution_that_half_lands_takes_back_only_its_own_deletion() {
15051        // The deletion lands and twig refuses the literal text: the deleted
15052        // bytes go back, and nothing else moves — not an earlier substitution
15053        // of the same keystroke, not the group it is in, and no redo is left
15054        // to delete them again.
15055        let mut d = wysiwyg_doc("substitute", "\n");
15056        d.set_markup_mode(MarkupMode::None);
15057        d.caret = 0;
15058        for c in ["a", "\"", "b", " ", "\""] {
15059            d.insert(c);
15060        }
15061        assert_eq!(d.source, "a\"b \"\n");
15062
15063        d.refuse_next_literal = true;
15064        assert!(!d.substitute(1, 2, "\u{201c}"));
15065        assert_eq!(d.source, "a\"b \"\n");
15066        assert_eq!(d.caret, 5, "the caret where it stood");
15067        assert!(!d.can_redo(), "no redo step left behind");
15068
15069        d.begin_undo_group();
15070        assert!(d.substitute(4, 5, "\u{201d}"));
15071        d.refuse_next_literal = true;
15072        assert!(!d.substitute(1, 2, "\u{201c}"));
15073        assert!(d.in_undo_group(), "the group is still open");
15074        assert_eq!(d.source, "a\"b \u{201d}\n", "the first substitution stands");
15075        d.end_undo_group();
15076        assert!(!d.can_redo());
15077        assert!(d.undo());
15078        assert_eq!(d.source, "a\"b \"\n", "one step takes the group back");
15079        assert!(d.undo());
15080        assert_eq!(d.source, "\n", "and the typing is still one step");
15081        assert!(!d.can_undo());
15082
15083        // A group whose first edit is the one that half lands has no step.
15084        let mut d = wysiwyg_doc("substitute", "\n");
15085        d.set_markup_mode(MarkupMode::None);
15086        d.caret = 0;
15087        d.insert("\"");
15088        d.begin_undo_group();
15089        d.refuse_next_literal = true;
15090        assert!(!d.substitute(0, 1, "\u{201c}"));
15091        assert!(d.substitute(0, 1, "\u{201c}"));
15092        d.end_undo_group();
15093        assert!(d.undo());
15094        assert_eq!(
15095            d.source, "\"\n",
15096            "the substitution that landed is the group's step"
15097        );
15098        assert!(d.undo());
15099        assert_eq!(d.source, "\n");
15100    }
15101
15102    #[test]
15103    fn a_substitution_is_written_the_way_typing_writes() {
15104        // Where typing is literal, so is a replacement's text.
15105        let mut d = wysiwyg_doc("substitute", "say hi\n");
15106        d.set_markup_mode(MarkupMode::None);
15107        assert!(d.substitute(4, 6, "*hi*"));
15108        assert_eq!(d.source, "say \\*hi\\*\n");
15109        assert!(d.undo());
15110        assert_eq!(d.source, "say hi\n", "one step, escapes and all");
15111    }
15112
15113    #[test]
15114    fn can_undo_is_false_once_a_coalesced_run_is_undone() {
15115        // The task's repro: five characters typed are one twig step, and the
15116        // counter used to say five.
15117        let mut d = wysiwyg_doc("undo_truth", "\n");
15118        d.caret = 0;
15119        for c in ["h", "e", "l", "l", "o"] {
15120            d.insert(c);
15121        }
15122        assert!(d.can_undo());
15123        assert!(d.undo(), "the run undoes");
15124        assert_eq!(d.source, "\n");
15125        assert!(!d.can_undo(), "and nothing is left behind it");
15126        let rev = d.revision();
15127        assert!(!d.undo(), "an undo that does not move says so");
15128        assert_eq!(d.revision(), rev);
15129        assert!(d.can_redo());
15130        assert!(d.redo());
15131        assert_eq!(d.source, "hello\n");
15132        assert!(!d.can_redo());
15133        assert!(!d.redo());
15134    }
15135
15136    #[test]
15137    fn can_undo_is_exact_across_the_gestures_that_coalesce() {
15138        // Each gesture below folds, or may fold, one twig step into another.
15139        // After it, the mirror must name exactly the number of undos twig
15140        // takes — and the same number of redos back.
15141        type Gesture = fn(&mut Doc);
15142        let cases: &[(&str, &str, Gesture)] = &[
15143            ("typing", "\n", |d| {
15144                d.caret = 0;
15145                d.insert("ab");
15146                d.insert("c");
15147                d.move_left(false);
15148                d.insert("x");
15149            }),
15150            ("backspaces", "abcdef\n", |d| {
15151                d.caret = 6;
15152                d.backspace();
15153                d.backspace();
15154                d.insert("z");
15155                d.backspace();
15156            }),
15157            ("ordered list item", "1. one\n2. two\n", |d| {
15158                d.caret = 6;
15159                d.newline();
15160                d.insert("x");
15161            }),
15162            ("list indent", "- one\n- two\n", |d| {
15163                d.caret = d.source.find("two").unwrap();
15164                d.indent();
15165                d.outdent();
15166            }),
15167            ("bold then type", "one two\n", |d| {
15168                d.select_range(0, 3);
15169                d.toggle(InlineKind::Strong);
15170                d.caret = d.source.len() - 1;
15171                d.insert("!");
15172            }),
15173            ("highlight", "one two\n", |d| {
15174                d.select_range(0, 3);
15175                d.highlight(None);
15176                d.highlight(Some(MarkColor::Green));
15177            }),
15178            ("heading and quote", "one\n", |d| {
15179                d.caret = 1;
15180                d.toggle_heading(2);
15181                d.toggle_blockquote();
15182            }),
15183            ("footnote", "one\n", |d| {
15184                d.caret = 3;
15185                d.insert_footnote();
15186                d.insert("note");
15187            }),
15188            ("blocks", "one\n\ntwo\n\nthree\n", |d| {
15189                d.caret = 1;
15190                d.move_block_down();
15191                d.toggle_list(true);
15192                d.set_alignment(Some(Align::Center));
15193                d.insert_page_break();
15194                d.insert_table(2, 2);
15195            }),
15196            ("paste and compose", "\n", |d| {
15197                d.caret = 0;
15198                d.paste("one two");
15199                d.delete_word_back();
15200                d.edit_composing(d.caret, d.caret, "か");
15201                d.edit_composing(d.caret - 3, d.caret, "蚊");
15202                d.end_composition();
15203                d.insert("z");
15204            }),
15205            ("table", "| a | b |\n| - | - |\n| c | d |\n", |d| {
15206                d.place_caret(d.source.find("d |").unwrap(), false);
15207                d.cell_tab(true);
15208                d.insert("e");
15209                d.cell_return();
15210            }),
15211            ("replace all", "cat cat cat\n", |d| {
15212                d.caret = 0;
15213                d.insert("a ");
15214                replace_all_in(d, "cat", "dog");
15215                d.insert("!");
15216            }),
15217            ("nested group", "one\n\ntwo\n", |d| {
15218                d.begin_undo_group();
15219                d.caret = 3;
15220                d.insert("x");
15221                d.begin_undo_group();
15222                d.toggle_heading(1);
15223                d.end_undo_group();
15224                d.insert("y");
15225                d.end_undo_group();
15226                d.backspace();
15227            }),
15228            ("group around a list", "1. one\n2. two\n", |d| {
15229                d.begin_undo_group();
15230                d.caret = 6;
15231                d.newline();
15232                d.insert("x");
15233                d.end_undo_group();
15234            }),
15235            ("substitution", "\n", |d| {
15236                d.caret = 0;
15237                d.insert("t");
15238                d.insert("e");
15239                d.insert("h");
15240                d.insert(" ");
15241                d.substitute(0, 3, "the");
15242                d.insert("c");
15243            }),
15244            ("empty group", "one\n", |d| {
15245                d.caret = 3;
15246                d.insert("x");
15247                d.begin_undo_group();
15248                d.end_undo_group();
15249                d.insert("y");
15250            }),
15251            ("undo inside a group", "one\n", |d| {
15252                d.caret = 3;
15253                d.begin_undo_group();
15254                d.insert("x");
15255                d.undo();
15256                d.insert("y");
15257                d.insert("z");
15258                d.end_undo_group();
15259            }),
15260        ];
15261        for (name, src, gesture) in cases {
15262            let mut d = wysiwyg_doc("undo_exact", src);
15263            gesture(&mut d);
15264            let (steps, after) = (d.undo_steps, d.source.clone());
15265            let mut undone = 0;
15266            while d.can_undo() {
15267                assert!(d.undo(), "{name}: can_undo said yes, undo moved nothing");
15268                undone += 1;
15269            }
15270            assert!(!d.undo(), "{name}: can_undo said no, undo moved");
15271            assert_eq!(undone, steps, "{name}");
15272            assert_eq!(d.source, *src, "{name}: back to the start");
15273            let mut redone = 0;
15274            while d.can_redo() {
15275                assert!(d.redo(), "{name}: can_redo said yes, redo moved nothing");
15276                redone += 1;
15277            }
15278            assert!(!d.redo(), "{name}: can_redo said no, redo moved");
15279            assert_eq!(redone, steps, "{name}");
15280            assert_eq!(d.source, after, "{name}: forward to the end");
15281        }
15282    }
15283
15284    #[test]
15285    fn two_compositions_are_two_undo_steps() {
15286        let mut d = doc_with("compose_two", "\n");
15287        d.caret = 0;
15288        d.edit_composing(0, 0, "か");
15289        d.edit_composing(0, 3, "蚊");
15290        d.end_composition();
15291        d.edit_composing(3, 3, "き");
15292        d.edit_composing(3, 6, "木");
15293        d.end_composition();
15294        assert_eq!(d.source, "蚊木\n");
15295        d.undo();
15296        assert_eq!(d.source, "蚊\n", "only the second composition");
15297        d.undo();
15298        assert_eq!(d.source, "\n");
15299    }
15300
15301    #[test]
15302    fn a_composition_does_not_fold_into_the_typing_around_it() {
15303        let mut d = doc_with("compose_typing", "\n");
15304        d.caret = 0;
15305        d.insert("a");
15306        d.insert("b");
15307        d.edit_composing(2, 2, "か");
15308        d.edit_composing(2, 5, "蚊");
15309        d.end_composition();
15310        d.insert("c");
15311        assert_eq!(d.source, "ab蚊c\n");
15312        d.undo();
15313        assert_eq!(d.source, "ab蚊\n");
15314        d.undo();
15315        assert_eq!(d.source, "ab\n");
15316        d.undo();
15317        assert_eq!(d.source, "\n");
15318    }
15319
15320    #[test]
15321    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
15322        let mut d = doc_with("compose_spurious", "\n");
15323        d.caret = 0;
15324        d.insert("a");
15325        d.end_composition(); // an IME unmarking unprompted
15326        d.insert("b");
15327        assert_eq!(d.source, "ab\n");
15328        d.undo();
15329        assert_eq!(d.source, "\n", "still one typed run");
15330    }
15331
15332    // ── the clipboard's rich flavor ──────────────────────────────────────────
15333
15334    #[test]
15335    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
15336        let mut d = doc_with("sel_inline", "a **bold** c\n");
15337        d.anchor = Some(2);
15338        d.caret = 10; // `**bold**`, inside the paragraph
15339        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
15340    }
15341
15342    #[test]
15343    fn a_whole_block_selection_keeps_its_paragraph() {
15344        let mut d = doc_with("sel_block", "a **bold** c\n");
15345        d.anchor = Some(0);
15346        d.caret = 12; // the entire paragraph
15347        assert_eq!(
15348            d.selection_html().as_deref(),
15349            Some("<p>a <strong>bold</strong> c</p>")
15350        );
15351    }
15352
15353    #[test]
15354    fn a_multi_block_selection_keeps_its_structure() {
15355        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
15356        d.select_all();
15357        let html = d.selection_html().expect("renders");
15358        assert!(html.contains("<p>para</p>"), "{html:?}");
15359        assert!(html.contains("<li>one</li>"), "{html:?}");
15360    }
15361
15362    #[test]
15363    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
15364        // The fragment `Head` is a paragraph standalone; the *document* says it
15365        // sits inside one block, so the wrapper is an artifact either way.
15366        let mut d = doc_with("sel_heading", "# Head line\n");
15367        d.anchor = Some(2);
15368        d.caret = 6;
15369        assert_eq!(d.selection_html().as_deref(), Some("Head"));
15370    }
15371
15372    #[test]
15373    fn no_selection_publishes_no_html() {
15374        let mut d = doc_with("sel_none", "a b\n");
15375        d.caret = 1;
15376        assert_eq!(d.selection_html(), None);
15377    }
15378
15379    #[test]
15380    fn pasting_html_converts_it_and_is_one_undo_step() {
15381        let mut d = doc_with("paste_html", "x\n");
15382        d.caret = 1;
15383        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
15384        assert_eq!(d.source, "xa **b** c\n");
15385        d.undo();
15386        assert_eq!(d.source, "x\n", "the whole paste, in one step");
15387    }
15388
15389    #[test]
15390    fn pasting_html_replaces_the_selection() {
15391        let mut d = doc_with("paste_html_sel", "keep drop\n");
15392        d.anchor = Some(5);
15393        d.caret = 9;
15394        assert!(d.paste_html("<em>new</em>"));
15395        assert_eq!(d.source, "keep *new*\n");
15396    }
15397
15398    #[test]
15399    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
15400        let mut d = doc_with("paste_html_bad", "x\n");
15401        d.caret = 1;
15402        // twig builds no table from HTML; raw `<table>` in prose is worse than
15403        // the plain flavor the caller still holds.
15404        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
15405        assert_eq!(d.source, "x\n", "declined edits nothing");
15406    }
15407
15408    #[test]
15409    fn copy_then_paste_round_trips_through_the_html_flavor() {
15410        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
15411        d.select_all();
15412        let html = d.selection_html().expect("renders");
15413        let mut into = doc_with("clip_round_dst", "\n");
15414        into.caret = 0;
15415        assert!(into.paste_html(&html));
15416        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
15417    }
15418
15419    #[test]
15420    fn moving_the_caret_starts_a_new_undo_group() {
15421        let mut d = doc_with("break", "\n");
15422        d.caret = 0;
15423        d.insert("a");
15424        d.insert("b"); // "ab\n", caret at 2
15425        d.move_left(false); // breaks the run
15426        d.insert("X"); // "aXb\n"
15427        assert_eq!(d.source, "aXb\n");
15428        d.undo();
15429        assert_eq!(
15430            d.source, "ab\n",
15431            "first undo removes only the post-move insert"
15432        );
15433        d.undo();
15434        assert_eq!(d.source, "\n", "second undo removes the earlier run");
15435    }
15436
15437    #[test]
15438    fn undo_reverses_a_format_toggle() {
15439        let mut d = doc_with("fmt_undo", "a word b\n");
15440        d.anchor = Some(2);
15441        d.caret = 6;
15442        d.toggle(InlineKind::Strong);
15443        assert_eq!(d.source, "a **word** b\n");
15444        d.undo();
15445        assert_eq!(d.source, "a word b\n");
15446    }
15447
15448    #[test]
15449    fn undo_back_to_the_saved_state_clears_dirty() {
15450        let mut d = doc_with("dirty_undo", "hello\n");
15451        assert!(!d.dirty);
15452        d.caret = 5;
15453        d.insert("!");
15454        assert!(d.dirty);
15455        d.undo();
15456        assert!(
15457            !d.dirty,
15458            "undoing to the saved source is not a modification"
15459        );
15460    }
15461
15462    #[test]
15463    fn a_new_edit_invalidates_redo() {
15464        let mut d = doc_with("redo_inv", "\n");
15465        d.caret = 0;
15466        d.insert("a");
15467        d.undo();
15468        d.insert("b"); // diverges — the redo of "a" is now gone
15469        d.redo();
15470        assert_eq!(d.source, "b\n");
15471    }
15472
15473    #[test]
15474    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
15475        let mut d = doc_with("can_undo", "hello\n");
15476        assert!(
15477            !d.can_undo() && !d.can_redo(),
15478            "a fresh document has no history"
15479        );
15480        d.caret = 5;
15481        d.insert("!");
15482        assert!(
15483            d.can_undo() && !d.can_redo(),
15484            "an edit is a step to take back"
15485        );
15486        d.undo();
15487        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
15488        d.redo();
15489        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
15490        d.undo();
15491        d.insert("?");
15492        assert!(
15493            d.can_undo() && !d.can_redo(),
15494            "a fresh edit ends the redo chain"
15495        );
15496        // A coalesced run over-counts steps — the bound is what a menu needs,
15497        // and it reconciles the moment twig reports the history empty.
15498        d.insert("a");
15499        d.insert("b");
15500        while d.can_undo() {
15501            d.undo();
15502        }
15503        assert_eq!(d.source, "hello\n");
15504        assert!(!d.can_undo());
15505        // A reading surface has nothing to undo, whatever the history holds.
15506        d.redo();
15507        d.set_read_only(true);
15508        assert!(!d.can_undo() && !d.can_redo());
15509    }
15510
15511    #[test]
15512    fn undo_on_empty_history_is_a_no_op() {
15513        let mut d = doc_with("undo_empty", "hi\n");
15514        d.undo();
15515        assert_eq!(d.source, "hi\n");
15516        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
15517    }
15518
15519    #[test]
15520    fn a_one_character_paste_is_its_own_undo_step() {
15521        for view in [View::Source, View::Wysiwyg] {
15522            let mut d = doc_in(view, "paste_step", "ab\n");
15523            d.caret = 0;
15524            d.insert("x");
15525            d.insert("y"); // a run of typing
15526            d.paste("z"); // one character, but pasted — not part of that run
15527            assert_eq!(d.source, "xyzab\n");
15528            d.undo();
15529            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
15530            assert_eq!(d.caret, 2, "and hands back the caret it found");
15531            d.undo();
15532            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
15533        }
15534    }
15535
15536    #[test]
15537    fn the_same_character_typed_still_joins_the_run() {
15538        // The other half of the pair: `z` is a keystroke here and a paste above,
15539        // and the two undo differently. Nothing about the *string* says which —
15540        // which is why provenance has to come from the door the caller uses.
15541        for view in [View::Source, View::Wysiwyg] {
15542            let mut d = doc_in(view, "typed_run", "ab\n");
15543            d.caret = 0;
15544            d.insert("x");
15545            d.insert("y");
15546            d.insert("z");
15547            d.undo();
15548            assert_eq!(d.source, "ab\n", "one run, one step");
15549        }
15550    }
15551
15552    #[test]
15553    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
15554        for view in [View::Source, View::Wysiwyg] {
15555            let mut d = doc_in(view, "undo_caret", "hello world\n");
15556            d.caret = 11; // standing at the end of "world", away from the edit
15557            d.edit(0, 5, "goodbye");
15558            assert_eq!(d.source, "goodbye world\n");
15559            d.undo();
15560            assert_eq!(d.source, "hello world\n");
15561            // The undone edit ends at offset 5; the user was at 11.
15562            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
15563        }
15564    }
15565
15566    #[test]
15567    fn undo_restores_the_selection_the_edit_replaced() {
15568        for view in [View::Source, View::Wysiwyg] {
15569            let mut d = doc_in(view, "undo_sel", "a word b\n");
15570            d.anchor = Some(2);
15571            d.caret = 6; // "word" selected
15572            d.insert("X");
15573            assert_eq!(d.source, "a X b\n");
15574            d.undo();
15575            assert_eq!(d.source, "a word b\n");
15576            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
15577        }
15578    }
15579
15580    #[test]
15581    fn redo_restores_the_caret_the_edit_left_behind() {
15582        for view in [View::Source, View::Wysiwyg] {
15583            let mut d = doc_in(view, "redo_caret", "hello world\n");
15584            d.caret = 11;
15585            d.edit(0, 5, "goodbye");
15586            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
15587            d.undo();
15588            d.redo();
15589            assert_eq!(d.source, "goodbye world\n");
15590            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
15591        }
15592    }
15593
15594    #[test]
15595    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
15596        for view in [View::Source, View::Wysiwyg] {
15597            let mut d = doc_in(view, "run_caret", "hi\n");
15598            d.caret = 2;
15599            d.insert("a");
15600            d.insert("b");
15601            d.insert("c");
15602            assert_eq!(d.source, "hiabc\n");
15603            d.undo();
15604            assert_eq!(d.source, "hi\n");
15605            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
15606            d.redo();
15607            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
15608        }
15609    }
15610
15611    #[test]
15612    fn undo_restores_the_caret_across_a_format_toggle() {
15613        // A toggle reaches twig without going through `splice`, so it has to
15614        // record its own step — miss it and every stack depth below it is off by
15615        // one, and undo starts handing back another edit's caret.
15616        for view in [View::Source, View::Wysiwyg] {
15617            let mut d = doc_in(view, "fmt_caret", "a word b\n");
15618            d.caret = 8;
15619            d.anchor = Some(2);
15620            d.caret = 6;
15621            d.toggle(InlineKind::Strong);
15622            assert_eq!(d.source, "a **word** b\n");
15623            d.undo();
15624            assert_eq!(d.source, "a word b\n");
15625            assert_eq!(
15626                d.selection(),
15627                Some((2, 6)),
15628                "the toggled selection comes back"
15629            );
15630        }
15631    }
15632
15633    #[test]
15634    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
15635        // The drift that would never announce itself: twig drops its redo stack
15636        // on any fresh edit, so a leaf redo entry that outlives it would restore
15637        // a caret from the timeline that edit abandoned.
15638        for view in [View::Source, View::Wysiwyg] {
15639            let mut d = doc_in(view, "redo_trunc", "hello world\n");
15640            d.caret = 11;
15641            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
15642            d.undo();
15643            assert_eq!(d.caret, 11);
15644            d.caret = 0;
15645            d.insert("X"); // diverges: A's redo is gone from twig
15646            assert_eq!(d.source, "Xhello world\n");
15647
15648            d.redo();
15649            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
15650            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
15651            d.undo();
15652            assert_eq!(d.source, "hello world\n");
15653            assert_eq!(
15654                d.caret, 0,
15655                "the surviving step's caret, not the dropped one"
15656            );
15657        }
15658    }
15659
15660    #[test]
15661    fn indent_and_outdent_move_the_caret_line_with_its_text() {
15662        for view in [View::Source, View::Wysiwyg] {
15663            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
15664            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
15665            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
15666            // Indentation the caret is standing *in* collapses to the line start
15667            // rather than dragging the caret into the text.
15668            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
15669            // A line with none to give back is left exactly as it was.
15670            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
15671            // Less than a full level gives back what it has.
15672            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
15673            // A tab is one level however many spaces it isn't.
15674            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
15675        }
15676    }
15677
15678    #[test]
15679    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
15680        // Why the level is two spaces and not the four both frontends type
15681        // today. Four is markdown's indented-code-block marker, so a Tab on a
15682        // paragraph would silently restyle it as code — a width that changes
15683        // what the document *means* isn't an indent. Pinned because the number
15684        // is the kind of thing a later list-aware pass would reach for.
15685        let mut d = doc_with("indent_kind", "hello\n");
15686        d.caret = 2;
15687        d.indent();
15688        assert_eq!(d.source, "  hello\n");
15689        assert!(
15690            d.nodes().iter().any(|n| n.kind == Kind::Para),
15691            "still prose after a Tab"
15692        );
15693        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
15694
15695        // The four-space level this replaces, for contrast: same text, and twig
15696        // reparses the paragraph into a code block.
15697        let mut wide = doc_with("indent_kind_4", "    hello\n");
15698        wide.build_visual(80);
15699        assert!(
15700            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
15701            "four spaces is a code block, not an indented paragraph"
15702        );
15703    }
15704
15705    #[test]
15706    fn indent_nests_a_list_item_under_its_parent() {
15707        // Tab indents a list item by its own marker width, landing its marker at
15708        // the parent's content column so twig reparses it as a nested list.
15709        for view in [View::Source, View::Wysiwyg] {
15710            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
15711            d.caret = 6; // on the second item
15712            d.indent();
15713            assert_eq!(d.source, "- a\n  - b\n");
15714            let lists = d
15715                .nodes()
15716                .iter()
15717                .filter(|n| n.kind == Kind::BulletList)
15718                .count();
15719            assert_eq!(lists, 2, "the indented item is a nested list");
15720        }
15721    }
15722
15723    #[test]
15724    fn indent_nests_an_ordered_item_at_its_marker_width() {
15725        // An ordered marker `1. ` is three columns wide, so a two-space step
15726        // (which nests a bullet) leaves it flat. Regression: Tab must use the
15727        // marker width, three, so the item actually nests — and the source
15728        // renumbers so the sub-list restarts at 1 and the outer list resumes.
15729        for view in [View::Source, View::Wysiwyg] {
15730            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
15731            d.caret = d.source.find('b').unwrap();
15732            d.indent();
15733            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
15734            let lists = d
15735                .nodes()
15736                .iter()
15737                .filter(|n| n.kind == Kind::OrderedList)
15738                .count();
15739            assert_eq!(lists, 2, "the indented item is a nested ordered list");
15740        }
15741    }
15742
15743    #[test]
15744    fn indent_leaves_a_lists_first_item_put() {
15745        // The first item of a list has no sibling above it to nest under, so Tab
15746        // is a no-op there — the marker stays at column zero rather than being
15747        // shoved into indentation twig can't read as a sub-list.
15748        for view in [View::Source, View::Wysiwyg] {
15749            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
15750            d.caret = 1; // on the FIRST item
15751            d.indent();
15752            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
15753            // The sibling below still nests, proving the guard is per-item.
15754            d.caret = d.source.find('b').unwrap();
15755            d.indent();
15756            assert_eq!(d.source, "- a\n  - b\n");
15757        }
15758    }
15759
15760    #[test]
15761    fn hidden_mode_keeps_typed_markup_literal() {
15762        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
15763        // twig escapes what would open markup, so the source is `\*hi\*` and the
15764        // AST is a plain string. Formatting is the commands' job in this mode.
15765        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
15766        d.insert("*hi*");
15767        assert_eq!(d.source, "\\*hi\\*");
15768        assert!(
15769            d.nodes()
15770                .iter()
15771                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
15772        );
15773    }
15774
15775    #[test]
15776    fn hidden_mode_escapes_a_line_start_block_marker() {
15777        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
15778        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
15779        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
15780        d.insert("# hi");
15781        assert_eq!(d.source, "\\# hi");
15782        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
15783    }
15784
15785    #[test]
15786    fn authoring_modes_keep_typed_markup_live() {
15787        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
15788        // (no escape), the same as source view — escaping is `None`'s alone, and
15789        // it's the axis, not the reveal, that decides.
15790        for (view, mode) in [
15791            (View::Wysiwyg, MarkupMode::Shortcuts),
15792            (View::Wysiwyg, MarkupMode::Full),
15793            (View::Source, MarkupMode::None),
15794        ] {
15795            let mut d = doc_in(view, "live_markup", "");
15796            d.set_markup_mode(mode);
15797            d.insert("*hi*");
15798            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
15799        }
15800    }
15801
15802    #[test]
15803    fn hidden_mode_overwrite_undoes_in_one_step() {
15804        // Typing over a selection escapes the replacement *and* stays a single
15805        // undo — the selection-delete and the literal insert fold together, so
15806        // one undo brings the whole selection back, like a plain overwrite.
15807        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
15808        d.anchor = Some(2);
15809        d.caret = 6; // "word"
15810        d.insert("*");
15811        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
15812        d.undo();
15813        assert_eq!(d.source, "a word b\n");
15814        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
15815    }
15816
15817    #[test]
15818    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
15819        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
15820        // the whole visual character, never stranding the hidden `\`.
15821        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
15822        d.insert("*");
15823        assert_eq!(d.source, "\\*");
15824        d.backspace();
15825        assert_eq!(d.source, "", "the escape backslash went with the *");
15826        // A *literal* backslash (source view, no escape) is an ordinary char.
15827        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
15828        s.caret = 3; // after `b`
15829        s.backspace();
15830        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
15831    }
15832
15833    #[test]
15834    fn hidden_mode_leaves_structural_markup_alone() {
15835        // Enter continues a bullet list by writing a real `- ` marker (an
15836        // `insert_raw`, not the typing path), so Hidden mode's escaping never
15837        // touches it — the list keeps working.
15838        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
15839        d.caret = 6;
15840        d.newline();
15841        d.insert("two");
15842        assert_eq!(d.source, "- item\n- two\n");
15843    }
15844
15845    #[test]
15846    fn markup_mode_defaults_to_none_and_round_trips() {
15847        // Diaryx's default is the clean `None` surface; a markup-fluent
15848        // frontend can climb the ladder, and the choice sticks.
15849        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
15850        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
15851        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
15852            d.set_markup_mode(mode);
15853            assert_eq!(d.markup_mode(), mode);
15854        }
15855    }
15856
15857    #[test]
15858    fn full_mode_reveals_only_the_caret_line() {
15859        // The mode's whole claim: the caret's line shows its raw delimiters and
15860        // every other line stays resolved. Two paragraphs with identical markup
15861        // so the only difference between the rows is where the caret is.
15862        let mut d = doc_in(
15863            View::Wysiwyg,
15864            "reveal_caret_line",
15865            "*one* here\n\n*two* there\n",
15866        );
15867        d.set_markup_mode(MarkupMode::Full);
15868
15869        caret_at(&mut d, "one");
15870        let rows = drawn_rows(&d);
15871        assert!(
15872            rows.iter().any(|r| r == "*one* here"),
15873            "caret's line raw: {rows:?}"
15874        );
15875        assert!(
15876            rows.iter().any(|r| r == "two there"),
15877            "other line resolved: {rows:?}"
15878        );
15879
15880        // Move to the other paragraph: the reveal follows, and the line just
15881        // left goes back to being resolved.
15882        caret_at(&mut d, "two");
15883        let rows = drawn_rows(&d);
15884        assert!(
15885            rows.iter().any(|r| r == "*two* there"),
15886            "caret's line raw: {rows:?}"
15887        );
15888        assert!(
15889            rows.iter().any(|r| r == "one here"),
15890            "left line resolved: {rows:?}"
15891        );
15892    }
15893
15894    #[test]
15895    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
15896        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
15897        // the same treatment as an emphasis's `*`: hidden while the caret is
15898        // elsewhere, shown in full where the caret lands. That falls out of
15899        // `delims` reading the bytes between the mark's span and its content
15900        // span, which is exactly `==🔴 ` and `==`, rather than from a table
15901        // of spellings — so the no-space form `==🟢green==` reveals right too.
15902        let mut d = doc_in(
15903            View::Wysiwyg,
15904            "reveal_coloured_mark",
15905            "a ==🔴 red== one\n\nb ==plain== two\n",
15906        );
15907        d.set_markup_mode(MarkupMode::Full);
15908
15909        caret_at(&mut d, "red");
15910        let rows = drawn_rows(&d);
15911        assert!(
15912            rows.iter().any(|r| r == "a ==🔴 red== one"),
15913            "the caret's line shows the colour it was written with: {rows:?}"
15914        );
15915        assert!(
15916            rows.iter().any(|r| r == "b plain two"),
15917            "and every other line stays resolved: {rows:?}"
15918        );
15919
15920        // Away from it, the emoji goes back to being markup — the reader sees
15921        // the words and the wash.
15922        caret_at(&mut d, "two");
15923        let rows = drawn_rows(&d);
15924        assert!(
15925            rows.iter().any(|r| r == "a red one"),
15926            "resolved again: {rows:?}"
15927        );
15928    }
15929
15930    #[test]
15931    fn hidden_modes_never_reveal_wherever_the_caret_is() {
15932        // The two rungs below `Full` share a rendering: delimiters stay hidden
15933        // even under the caret. `Shortcuts` differing from `None` only in what
15934        // typing does is exactly the point of splitting the axes.
15935        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
15936            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
15937            d.set_markup_mode(mode);
15938            caret_at(&mut d, "one");
15939            let rows = drawn_rows(&d);
15940            assert!(
15941                rows.iter().any(|r| r == "one here"),
15942                "{mode:?} hides: {rows:?}"
15943            );
15944            assert!(
15945                !rows.iter().any(|r| r.contains('*')),
15946                "{mode:?} shows no `*`: {rows:?}"
15947            );
15948        }
15949    }
15950
15951    #[test]
15952    fn revealed_delimiters_are_the_authors_own_spelling() {
15953        // Delimiters are re-read from the source rather than synthesized per
15954        // kind, so a line comes back spelled the way it was written: `_em_` does
15955        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
15956        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
15957        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
15958        d.set_markup_mode(MarkupMode::Full);
15959        caret_at(&mut d, "em");
15960        let rows = drawn_rows(&d);
15961        assert!(
15962            rows.iter().any(|r| r == body.trim_end()),
15963            "the revealed line is its own source: {rows:?}"
15964        );
15965    }
15966
15967    #[test]
15968    fn revealed_heading_shows_its_hashes() {
15969        // The `# ` marker is a block-level prefix, not an inline delimiter, so
15970        // it takes its own path — but it reveals on the same rule.
15971        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
15972        d.set_markup_mode(MarkupMode::Full);
15973
15974        caret_at(&mut d, "Title");
15975        assert!(
15976            drawn_rows(&d).iter().any(|r| r == "# Title"),
15977            "{:?}",
15978            drawn_rows(&d)
15979        );
15980
15981        caret_at(&mut d, "body");
15982        let rows = drawn_rows(&d);
15983        assert!(
15984            rows.iter().any(|r| r == "Title"),
15985            "hashes hidden again: {rows:?}"
15986        );
15987    }
15988
15989    #[test]
15990    fn revealed_delimiters_are_caret_stops() {
15991        // A delimiter that is drawn but can't be reached is worse than one
15992        // that's hidden: the mode exists so the markup can be *edited*. Every
15993        // revealed byte must be somewhere the caret can stand.
15994        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
15995        d.set_markup_mode(MarkupMode::Full);
15996        caret_at(&mut d, "em");
15997        let opener = d.source.find('*').unwrap();
15998        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
15999        assert!(
16000            d.vmap.is_stop(opener + 3),
16001            "the closing `*` is a caret stop"
16002        );
16003    }
16004
16005    #[test]
16006    fn setext_heading_reveals_nothing_across_its_newline() {
16007        // A setext heading's underline is on another line, so it is not the
16008        // caret line's to reveal — and emitting it would inject a `\n` glyph
16009        // that splits the row where the author wrote no break.
16010        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
16011        d.set_markup_mode(MarkupMode::Full);
16012        caret_at(&mut d, "Title");
16013        let rows = drawn_rows(&d);
16014        assert!(
16015            rows.iter().any(|r| r == "Title"),
16016            "title renders alone: {rows:?}"
16017        );
16018        assert!(
16019            !rows.iter().any(|r| r.contains('=')),
16020            "no underline leaks in: {rows:?}"
16021        );
16022    }
16023
16024    #[test]
16025    fn markup_mode_axes_split_the_ladder() {
16026        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
16027        // that authors markup but still hides it, and it's the only rung where
16028        // the two axes disagree.
16029        assert!(!MarkupMode::None.authors());
16030        assert!(!MarkupMode::None.reveals_caret_line());
16031        assert!(MarkupMode::Shortcuts.authors());
16032        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
16033        assert!(MarkupMode::Full.authors());
16034        assert!(MarkupMode::Full.reveals_caret_line());
16035    }
16036
16037    #[test]
16038    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
16039        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
16040        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
16041        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
16042        // nested bullet and `hello` stays prose: the file round-trips instead of
16043        // hiding a heading the user never asked for.
16044        for view in [View::Source, View::Wysiwyg] {
16045            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
16046            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
16047            d.indent();
16048            assert_eq!(d.source, "- hello\n  * \n");
16049            assert!(
16050                d.nodes().iter().all(|n| n.kind != Kind::Heading),
16051                "no heading"
16052            );
16053            // And it's genuinely a nested list, not a flat one.
16054            assert_eq!(
16055                d.nodes()
16056                    .iter()
16057                    .filter(|n| n.kind == Kind::BulletList)
16058                    .count(),
16059                2
16060            );
16061        }
16062    }
16063
16064    #[test]
16065    fn indenting_a_dash_item_with_content_keeps_its_dash() {
16066        // With content, `- x` can't be a setext underline, so there's nothing to
16067        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
16068        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
16069        d.caret = d.source.find('x').unwrap();
16070        d.indent();
16071        assert_eq!(d.source, "- hello\n  - x\n");
16072    }
16073
16074    #[test]
16075    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
16076        // The dash→`*` repair coalesces into the Tab, so a single undo restores
16077        // the whole pre-Tab state rather than stranding a half-collapsed doc.
16078        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
16079        d.caret = d.source.find("- \n").unwrap() + 2;
16080        d.indent();
16081        assert_eq!(d.source, "- hello\n  * \n");
16082        d.undo();
16083        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
16084    }
16085
16086    #[test]
16087    fn indent_leaves_a_nested_lists_first_item_put_too() {
16088        // The guard is about siblings, not depth: the first item of an *inner*
16089        // list (already nested under `a`) still has nothing before it at its own
16090        // level, so Tab can't take it deeper.
16091        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
16092        d.caret = d.source.find('b').unwrap();
16093        d.indent();
16094        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
16095        // But `c` (a sibling of `b`) nests under `b`.
16096        d.caret = d.source.find('c').unwrap();
16097        d.indent();
16098        assert_eq!(d.source, "- a\n  - b\n    - c\n");
16099    }
16100
16101    #[test]
16102    fn backspace_at_a_nested_item_start_outdents_it() {
16103        // Backspace with the caret right after a nested item's marker gives back
16104        // one level of nesting, the mirror of Tab — and renumbers the flattened
16105        // ordered list back to a clean run.
16106        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
16107        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
16108        d.backspace();
16109        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16110    }
16111
16112    #[test]
16113    fn backspace_at_a_top_level_item_start_strips_the_marker() {
16114        // At the outermost level there's no nesting left to give back, so the same
16115        // keystroke drops the bullet and leaves a plain paragraph.
16116        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
16117        d.caret = d.source.find('b').unwrap(); // right after `- `
16118        d.backspace();
16119        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
16120    }
16121
16122    #[test]
16123    fn backspace_mid_item_still_deletes_a_character() {
16124        // The list behaviour is armed only at the item's content start; anywhere
16125        // else Backspace is the ordinary character delete.
16126        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
16127        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
16128        d.backspace();
16129        assert_eq!(d.source, "- b\n");
16130    }
16131
16132    #[test]
16133    fn backspace_at_a_heading_start_strips_the_marker() {
16134        // The `# ` is markup the rich view hides, so Backspace over it takes the
16135        // whole marker and leaves a paragraph. Deleting a byte of it instead left
16136        // `#Title` — no longer a heading, with the hash now literal text the user
16137        // never typed and has to delete again.
16138        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
16139        d.caret = d.source.find('T').unwrap(); // right after `## `
16140        d.backspace();
16141        assert_eq!(d.source, "Title\n");
16142        assert_eq!(
16143            d.caret, 0,
16144            "the caret stays with the text it was in front of"
16145        );
16146    }
16147
16148    #[test]
16149    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
16150        // Only the heading's own marker goes — the quote (or list) it sits in is
16151        // untouched, exactly as un-heading it should be.
16152        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
16153        d.caret = d.source.find('T').unwrap();
16154        d.backspace();
16155        assert_eq!(d.source, "> Title\n");
16156    }
16157
16158    #[test]
16159    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
16160        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
16161        // behind would surface the same stray hash the marker delete just avoided.
16162        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
16163        d.caret = d.source.find('T').unwrap();
16164        d.backspace();
16165        assert_eq!(d.source, "Title\n");
16166        // And it's one edit: a single undo puts the whole heading back.
16167        d.undo();
16168        assert_eq!(d.source, "# Title #\n");
16169    }
16170
16171    #[test]
16172    fn backspace_mid_heading_still_deletes_a_character() {
16173        // The heading behaviour is armed only at the content's start; anywhere
16174        // else Backspace is the ordinary character delete.
16175        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
16176        d.caret = d.source.find('b').unwrap();
16177        d.backspace();
16178        assert_eq!(d.source, "# b\n");
16179    }
16180
16181    #[test]
16182    fn source_view_backspace_still_edits_the_heading_marker_literally() {
16183        // In source view the `# ` is text on the screen the user is deleting a
16184        // byte of, so it keeps its literal meaning — the same split the list
16185        // ladder and Enter draw between the two views.
16186        let mut d = doc_with("bsp_head_src", "# Title\n");
16187        d.caret = d.source.find('T').unwrap();
16188        d.backspace();
16189        assert_eq!(d.source, "#Title\n");
16190    }
16191
16192    #[test]
16193    fn outdent_unnests_an_ordered_item_in_one_press() {
16194        // Shift+Tab gives back exactly the marker width the indent added, so a
16195        // nested ordered item unnests in a single press, and the flattened list
16196        // renumbers back to a clean 1, 2, 3.
16197        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
16198        d.caret = d.source.find('b').unwrap();
16199        d.outdent();
16200        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16201        let lists = d
16202            .nodes()
16203            .iter()
16204            .filter(|n| n.kind == Kind::OrderedList)
16205            .count();
16206        assert_eq!(lists, 1, "back to one flat list");
16207    }
16208
16209    #[test]
16210    fn table_insert_row_adds_a_row_below_the_caret() {
16211        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16212        d.caret = d.source.find('1').unwrap(); // in the body row
16213        d.table_insert_row(true);
16214        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
16215    }
16216
16217    #[test]
16218    fn table_insert_and_delete_column_at_the_caret() {
16219        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16220        d.caret = d.source.find('a').unwrap(); // column 0
16221        d.table_insert_column(true); // add a column to the right of `a`
16222        assert_eq!(
16223            d.source,
16224            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
16225        );
16226        d.caret = d.source.find('b').unwrap(); // now the third column
16227        d.table_delete_column();
16228        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
16229    }
16230
16231    // ── ragged formats ───────────────────────────────────────────────────────
16232    // No format spells every gesture. HTML writes the inline marks as a tag pair
16233    // and no heading, list, quote or link; Markdown spells five of the eight
16234    // marks — the highlight only because leaf parses with `highlight`, which is
16235    // why the question is asked with the extensions; djot spells all eight and
16236    // no in-cell break. leaf asks twig per
16237    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
16238    // op discover the fact on its own — one of them didn't.
16239
16240    /// An HTML document in the rich view, ready for a gesture.
16241    fn html_doc(body: &str) -> Doc {
16242        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
16243        d.view = View::Wysiwyg;
16244        d.build_visual(80);
16245        d
16246    }
16247
16248    #[test]
16249    fn a_table_gesture_leaves_an_html_table_alone() {
16250        // The regression this guard exists for. twig's table editor consults no
16251        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
16252        // HTML `<table>` as a *pipe table* and reported success: the whole
16253        // element replaced by `| a | b |`, silently, on one press of a toolbar
16254        // button. Every grid op went the same way.
16255        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
16256        // A table of named operations, which is what it looks like.
16257        #[allow(clippy::type_complexity)]
16258        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
16259            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
16260            ("delete row", &|d: &mut Doc| d.table_delete_row()),
16261            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
16262            ("delete column", &|d: &mut Doc| d.table_delete_column()),
16263            ("align", &|d: &mut Doc| {
16264                d.table_set_alignment(Alignment::Right)
16265            }),
16266            ("move row", &|d: &mut Doc| d.table_move_row(true)),
16267            ("move column", &|d: &mut Doc| d.table_move_column(true)),
16268        ];
16269        for (name, op) in ops {
16270            let mut d = html_doc(src);
16271            d.caret = d.source.find('a').unwrap();
16272            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
16273            op(&mut d);
16274            assert_eq!(d.source, src, "{name} rewrote an HTML table");
16275            assert!(
16276                !d.dirty,
16277                "{name} marked the document dirty without editing it"
16278            );
16279            assert!(d.status.is_some(), "{name} refused without saying why");
16280        }
16281    }
16282
16283    #[test]
16284    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
16285        // A task box is a form control in HTML and a footnote has no native
16286        // spelling at all — the two gestures twig 3.5 still spells nothing
16287        // for, now that a quote, a list, a link and an image print through
16288        // its renderer (see the test below).
16289        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16290        // A table of named operations, which is what it looks like.
16291        #[allow(clippy::type_complexity)]
16292        let ops: [(&str, &dyn Fn(&mut Doc)); 3] = [
16293            ("task item", &|d: &mut Doc| d.toggle_task_item()),
16294            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
16295            ("footnote", &|d: &mut Doc| d.insert_footnote()),
16296        ];
16297        for (name, op) in ops {
16298            let mut d = html_doc(src);
16299            let at = d.source.find("Hello").unwrap();
16300            d.caret = at;
16301            d.anchor = Some(at + 5); // a selection, for the ops that want one
16302            op(&mut d);
16303            assert_eq!(d.source, src, "{name} edited an HTML document");
16304            assert!(
16305                !d.dirty,
16306                "{name} marked the document dirty without editing it"
16307            );
16308            let status = d.status.as_deref().unwrap_or("");
16309            assert!(
16310                status.contains("html"),
16311                "{name}: the refusal should name the format, got {status:?}"
16312            );
16313        }
16314    }
16315
16316    #[test]
16317    fn html_spells_a_quote_a_list_a_link_and_an_image_through_the_renderer() {
16318        // twig 3.5: where HTML has no marker alphabet it prints the fresh
16319        // node — a `<blockquote>` around the paragraph, a `<ul>`/`<ol>` with
16320        // the paragraph as its item, an `<a>` or `<img>` over the selection.
16321        // Until then every one of these was a refusal; now each is a real
16322        // edit, which is what the toolbar's capability flags say too.
16323        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16324        #[allow(clippy::type_complexity)]
16325        let ops: [(&str, &dyn Fn(&mut Doc), &str); 5] = [
16326            (
16327                "quote",
16328                &|d: &mut Doc| d.toggle_blockquote(),
16329                "<blockquote>",
16330            ),
16331            ("list", &|d: &mut Doc| d.toggle_list(false), "<ul>\n<li>"),
16332            (
16333                "ordered list",
16334                &|d: &mut Doc| d.toggle_list(true),
16335                "<ol>\n<li>",
16336            ),
16337            (
16338                "link",
16339                &|d: &mut Doc| d.insert_link("https://example.dev"),
16340                "<a href=\"https://example.dev\">Hello</a>",
16341            ),
16342            (
16343                "image",
16344                &|d: &mut Doc| d.insert_image("pic.png", "alt"),
16345                "<img alt=\"Hello\" src=\"pic.png\">",
16346            ),
16347        ];
16348        for (name, op, expect) in ops {
16349            let mut d = html_doc(src);
16350            let at = d.source.find("Hello").unwrap();
16351            d.caret = at;
16352            d.anchor = Some(at + 5);
16353            op(&mut d);
16354            assert!(d.source.contains(expect), "{name}: got {:?}", d.source);
16355            assert!(d.dirty, "{name}: a real edit");
16356            assert_eq!(
16357                d.status, None,
16358                "{name}: a supported gesture reports nothing"
16359            );
16360        }
16361    }
16362
16363    #[test]
16364    fn html_spells_a_heading_as_its_tag_pair() {
16365        // twig 3.4 rebuilds a heading or paragraph as its tag pair, attributes
16366        // along — the one block gesture whose HTML shape it can write. So ⌘2
16367        // in an HTML document is a real edit, and ⌘0 takes it back.
16368        let src = "<h1>Title</h1>\n<p>Hello world</p>\n";
16369        let mut d = html_doc(src);
16370        d.caret = d.source.find("Hello").unwrap();
16371        d.toggle_heading(2);
16372        assert_eq!(d.source, "<h1>Title</h1>\n<h2>Hello world</h2>\n");
16373        assert!(d.dirty);
16374        assert_eq!(d.status, None, "a supported gesture reports nothing");
16375        d.toggle_heading(2);
16376        assert_eq!(d.source, src, "the same level again is back to a paragraph");
16377    }
16378
16379    #[test]
16380    fn html_spells_the_inline_marks_and_the_rule() {
16381        // The other half, and why one per-document flag stopped being enough:
16382        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
16383        // already emits and the parser reads straight back as the same mark —
16384        // and the rule button writes an `<hr>`. Refusing these on the old
16385        // "HTML is parse-only" reading would now be leaf's own limitation.
16386        let mut d = html_doc("<p>Hello world</p>\n");
16387        let at = d.source.find("world").unwrap();
16388        d.caret = at;
16389        d.anchor = Some(at + 5);
16390        d.toggle(InlineKind::Strong);
16391        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
16392        assert!(d.dirty);
16393        assert_eq!(d.status, None, "a supported gesture reports nothing");
16394
16395        // And off again — the toggle reverses, which is the property that makes
16396        // authoring in HTML worth offering rather than a one-way trip.
16397        d.toggle(InlineKind::Strong);
16398        assert_eq!(d.source, "<p>Hello world</p>\n");
16399
16400        let mut d = html_doc("<p>Hello world</p>\n");
16401        d.caret = d.source.find("world").unwrap();
16402        d.insert_thematic_break();
16403        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
16404    }
16405
16406    #[test]
16407    fn a_mark_the_format_cannot_spell_arms_nothing() {
16408        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
16409        // sticky mark for the next text typed. Guarding only the twig call
16410        // leaves that path live, promising a mark the gesture will not write and
16411        // then swallowing the error inside `insert`.
16412        //
16413        // Markdown carries this, on the superscript now rather than on the
16414        // highlight: `^x^` is text there in any configuration, whereas twig
16415        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
16416        // which every leaf document does.
16417        let mut d = doc_with("mark", "Hello world\n");
16418        d.view = View::Wysiwyg;
16419        d.build_visual(80);
16420        d.caret = d.source.find("world").unwrap();
16421        d.toggle(InlineKind::Superscript);
16422        assert!(d.pending_marks.is_empty(), "no mark should be armed");
16423        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
16424        d.insert("X");
16425        assert_eq!(d.source, "Hello Xworld\n");
16426    }
16427
16428    #[test]
16429    fn markdown_authors_a_highlight_and_a_strikethrough() {
16430        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
16431        // write. `==x==` is authorable because leaf's own `parse_extensions`
16432        // turns `highlight` on — twig will only mint bytes this editor's reparse
16433        // reads back — and `~~x~~` because GFM strikethrough is parsed by
16434        // default, so the refusal there was never right for any leaf document.
16435        // twig 3.10 adds the underline, spelled `<u>x</u>` and paired back into
16436        // an `insert` under the `html_elements` leaf parses with.
16437        for (kind, marked) in [
16438            (InlineKind::Mark, "a ==word== b\n"),
16439            (InlineKind::Delete, "a ~~word~~ b\n"),
16440            (InlineKind::Insert, "a <u>word</u> b\n"),
16441        ] {
16442            let mut d = doc_with("author_mark", "a word b\n");
16443            d.anchor = Some(2);
16444            d.caret = 6;
16445            d.toggle(kind);
16446            assert_eq!(d.source, marked, "{kind:?}");
16447            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
16448            assert!(d.dirty, "{kind:?}");
16449            // The region stays selected, so the second press reverses it — the
16450            // property that separates authoring from a one-way trip.
16451            d.toggle(kind);
16452            assert_eq!(d.source, "a word b\n", "{kind:?}");
16453        }
16454    }
16455
16456    #[test]
16457    fn an_authored_highlight_reads_back_as_a_mark() {
16458        // The round trip the extension gate exists to protect: what the toggle
16459        // writes, the reparse must read back as a `mark` rather than as two
16460        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
16461        // rebuilt map rather than from the source text.
16462        let mut d = doc_with("mark_roundtrip", "a word b\n");
16463        d.view = View::Wysiwyg;
16464        d.build_visual(80);
16465        d.anchor = Some(2);
16466        d.caret = 6;
16467        d.toggle(InlineKind::Mark);
16468        assert_eq!(d.source, "a ==word== b\n");
16469        d.build_visual(80);
16470        let w = d
16471            .vmap
16472            .rows
16473            .iter()
16474            .flat_map(|r| r.glyphs.iter())
16475            .find(|g| g.ch == 'w')
16476            .expect("the highlighted word");
16477        assert_eq!(w.style.role, crate::Role::Mark(None));
16478    }
16479
16480    #[test]
16481    fn an_authored_underline_reads_back_as_an_insert() {
16482        // The same round trip for `<u>…</u>`: under `html_elements` the tag pair
16483        // is one `insert`, so the word is underlined and the tags are markup the
16484        // caret-off line hides — not two `raw_inline` runs drawn as literal
16485        // HTML around plain text.
16486        let mut d = doc_with("underline_roundtrip", "a word b\nnext\n");
16487        d.view = View::Wysiwyg;
16488        d.build_visual(80);
16489        d.anchor = Some(2);
16490        d.caret = 6;
16491        d.toggle(InlineKind::Insert);
16492        assert_eq!(d.source, "a <u>word</u> b\nnext\n");
16493        d.anchor = None;
16494        d.caret = d.source.find("next").unwrap();
16495        d.build_visual(80);
16496        let glyphs: Vec<_> = d.vmap.rows.iter().flat_map(|r| r.glyphs.iter()).collect();
16497        let w = glyphs
16498            .iter()
16499            .find(|g| g.ch == 'w')
16500            .expect("the underlined word");
16501        assert!(w.style.underline);
16502        assert!(!glyphs.iter().any(|g| g.ch == '<'), "the tags are hidden");
16503    }
16504
16505    #[test]
16506    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
16507        // The three states of one gesture, in the order a palette is pressed:
16508        // an uncoloured highlight takes the prefix, a coloured one has it
16509        // replaced, and `None` takes it away with the space that was part of the
16510        // spelling.
16511        let mut d = doc_with("mark_colour", "a ==word== b\n");
16512        d.caret = d.source.find("word").unwrap();
16513        d.set_mark_color(Some(MarkColor::Red));
16514        assert_eq!(d.source, "a ==🔴 word== b\n");
16515        assert_eq!(d.status, None);
16516        assert!(d.dirty);
16517
16518        d.set_mark_color(Some(MarkColor::Blue));
16519        assert_eq!(d.source, "a ==🔵 word== b\n");
16520
16521        d.set_mark_color(None);
16522        assert_eq!(d.source, "a ==word== b\n");
16523    }
16524
16525    #[test]
16526    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
16527        // The prefix is written *before* the word, so an offset in the word has
16528        // to ride its width — a caret that stayed put would be a caret that
16529        // walked backwards through the text it was standing in.
16530        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
16531        let word = d.source.find("word").unwrap();
16532        d.caret = word + 2; // between `wo` and `rd`
16533        d.set_mark_color(Some(MarkColor::Red));
16534        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
16535
16536        // And back the other way when the prefix goes.
16537        d.set_mark_color(None);
16538        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
16539    }
16540
16541    #[test]
16542    fn the_colour_at_the_caret_is_what_the_palette_lights() {
16543        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
16544        d.caret = d.source.find("red").unwrap();
16545        assert!(d.caret_in_mark());
16546        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
16547
16548        d.caret = d.source.find("plain").unwrap();
16549        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
16550        assert_eq!(d.mark_color_at_caret(), None);
16551
16552        d.caret = d.source.find(" and ").unwrap() + 2;
16553        assert!(!d.caret_in_mark());
16554        assert_eq!(d.mark_color_at_caret(), None);
16555    }
16556
16557    #[test]
16558    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
16559        // The gesture colours a highlight that exists; it does not make one.
16560        // Two presses is the price of a coloured highlight from bare text, and
16561        // the reason is undo — one press that spliced twice would take two
16562        // presses to take back.
16563        let mut d = doc_with("mark_colour_none", "a word b\n");
16564        d.caret = d.source.find("word").unwrap();
16565        d.set_mark_color(Some(MarkColor::Red));
16566        assert_eq!(d.source, "a word b\n");
16567        assert!(d.status.is_some(), "it should say why");
16568        assert!(!d.dirty);
16569
16570        // Clearing where there is nothing to clear is the same refusal, not a
16571        // quiet success — the caret is in no highlight either way.
16572        d.status = None;
16573        d.set_mark_color(None);
16574        assert_eq!(d.source, "a word b\n");
16575        assert!(d.status.is_some());
16576    }
16577
16578    #[test]
16579    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
16580        // twig answers this one *successfully* with a `Change` describing some
16581        // earlier edit, so a caller that trusted the change would jump the caret
16582        // to wherever that was. Core answers it before asking.
16583        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
16584        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
16585        d.caret = d.source.find("word").unwrap();
16586        let (source, caret) = (d.source.clone(), d.caret);
16587        d.set_mark_color(None);
16588        assert_eq!(d.source, source);
16589        assert_eq!(
16590            d.caret, caret,
16591            "the caret must not ride a change that isn't one"
16592        );
16593        assert_eq!(d.status, None, "and it is not an error either");
16594    }
16595
16596    #[test]
16597    fn djot_spells_the_highlight_and_not_its_colour() {
16598        // The reason the palette is its own capability rather than the Highlight
16599        // button's: `{=word=}` is a highlight djot writes happily, and there is
16600        // no djot spelling for a colour on it.
16601        assert!(Capabilities::of(Format::Djot).mark);
16602        assert!(!Capabilities::of(Format::Djot).mark_color);
16603        assert!(Capabilities::of(Format::Markdown).mark_color);
16604
16605        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
16606        d.caret = d.source.find("word").unwrap();
16607        assert!(
16608            d.caret_in_mark(),
16609            "the caret is in a highlight all the same"
16610        );
16611        d.set_mark_color(Some(MarkColor::Red));
16612        assert_eq!(d.source, "a {=word=} b\n");
16613        assert!(
16614            d.status.as_deref().unwrap_or("").contains("djot"),
16615            "and the refusal names the document's format: {:?}",
16616            d.status
16617        );
16618    }
16619
16620    #[test]
16621    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
16622        // The round trip that matters for a palette: the bytes twig writes are
16623        // bytes its own reparse reads back as a colour, so the swatch that was
16624        // pressed is the swatch that lights afterwards.
16625        let mut d = doc_with("mark_colour_undo", "a word b\n");
16626        d.anchor = Some(2);
16627        d.caret = 6;
16628        d.toggle(InlineKind::Mark);
16629        d.caret = d.source.find("word").unwrap();
16630        d.set_mark_color(Some(MarkColor::Green));
16631        assert_eq!(d.source, "a ==🟢 word== b\n");
16632        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
16633
16634        // One splice, one step: the colour comes off and the highlight stays.
16635        d.undo();
16636        assert_eq!(d.source, "a ==word== b\n");
16637        d.undo();
16638        assert_eq!(d.source, "a word b\n");
16639    }
16640
16641    #[test]
16642    fn every_colour_leaf_names_is_one_twig_writes() {
16643        // The two enums are one vocabulary, and this is what says so: each of
16644        // leaf's colours writes an emoji twig's reparse reads back as *that*
16645        // colour, so `twig_mark_color`'s table cannot quietly pair red with
16646        // orange.
16647        for color in MarkColor::ALL {
16648            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
16649            d.caret = d.source.find("word").unwrap();
16650            d.set_mark_color(Some(color));
16651            assert_eq!(d.status, None, "{color:?}");
16652            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
16653        }
16654    }
16655
16656    #[test]
16657    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
16658        // The two presses a coloured highlight is made of, in the state the
16659        // first one leaves: `toggle` selects the whole `==word==` and puts the
16660        // caret one past the closing `==`, which is *not* in the mark. Asking at
16661        // the caret alone would refuse to colour the highlight just written —
16662        // the selection's start is what answers.
16663        let mut d = doc_with("mark_colour_fresh", "a word b\n");
16664        d.anchor = Some(2);
16665        d.caret = 6;
16666        d.toggle(InlineKind::Mark);
16667        assert_eq!(d.source, "a ==word== b\n");
16668        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
16669
16670        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
16671        d.set_mark_color(Some(MarkColor::Yellow));
16672        assert_eq!(d.source, "a ==🟡 word== b\n");
16673        assert_eq!(d.status, None);
16674    }
16675
16676    #[test]
16677    fn one_press_highlights_a_selection_and_colours_it() {
16678        // What a toolbar swatch means over a plain selection, and the undo it
16679        // has to have: one press, one step. Two steps would leave an uncoloured
16680        // highlight behind on the way back, which is a state the author never
16681        // asked for and never saw.
16682        let mut d = doc_with("highlight_one", "a word b\n");
16683        d.anchor = Some(2);
16684        d.caret = 6;
16685        d.highlight(Some(MarkColor::Purple));
16686        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
16687        assert_eq!(d.status, None);
16688
16689        d.undo();
16690        assert_eq!(d.source, "a word b\n", "one press, one undo");
16691    }
16692
16693    #[test]
16694    fn one_press_on_an_existing_highlight_only_recolours_it() {
16695        // The other half: inside a highlight there is nothing to make, so the
16696        // compound is the plain gesture and the text is untouched.
16697        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
16698        d.caret = d.source.find("word").unwrap();
16699        d.highlight(Some(MarkColor::Blue));
16700        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
16701        d.undo();
16702        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
16703    }
16704
16705    #[test]
16706    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
16707        // `None` means "no colour", and over bare text that is the Highlight
16708        // button's own job. The fold must not happen here — there is no second
16709        // splice, and folding would take the *previous* edit into this one.
16710        let mut d = doc_with("highlight_none", "a word b and more\n");
16711        d.caret = d.source.find("more").unwrap() + 4; // after "more"
16712        d.insert("!"); // an earlier edit for a wrong fold to swallow
16713        d.anchor = Some(2);
16714        d.caret = 6;
16715        d.highlight(None);
16716        assert_eq!(d.source, "a ==word== b and more!\n");
16717
16718        d.undo();
16719        assert_eq!(
16720            d.source, "a word b and more!\n",
16721            "only the highlight came off"
16722        );
16723        d.undo();
16724        assert_eq!(
16725            d.source, "a word b and more\n",
16726            "and the edit before it survived"
16727        );
16728    }
16729
16730    #[test]
16731    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
16732        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
16733        // a colour cannot be armed with it — so the compound declines rather
16734        // than leaving half a promise.
16735        let mut d = doc_with("highlight_bare", "a word b\n");
16736        d.caret = 4;
16737        d.highlight(Some(MarkColor::Red));
16738        assert_eq!(d.source, "a word b\n");
16739        assert!(d.pending_marks.is_empty(), "and nothing armed");
16740        assert!(d.status.is_some());
16741    }
16742
16743    #[test]
16744    fn a_read_only_document_takes_no_colour() {
16745        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
16746        d.caret = d.source.find("word").unwrap();
16747        d.set_read_only(true);
16748        d.set_mark_color(Some(MarkColor::Red));
16749        assert_eq!(d.source, "a ==word== b\n");
16750    }
16751
16752    #[test]
16753    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
16754        // The other door into `toggle`: no selection, so nothing reaches twig
16755        // until `insert` realises the armed mark. It is armed now — the guard
16756        // above asks `Doc::supports`, which asks with the extensions — and what
16757        // it writes is the same `==…==`.
16758        let mut d = doc_with("sticky_mark", "xy\n");
16759        d.caret = 1;
16760        d.toggle(InlineKind::Mark);
16761        assert!(d.pending_marks.contains(InlineKind::Mark));
16762        d.insert("Z");
16763        assert_eq!(d.source, "x==Z==y\n");
16764    }
16765
16766    #[test]
16767    fn html_documents_still_take_typed_text() {
16768        // The guard covers *markup* gestures and must not touch plain editing:
16769        // twig's splicer is language-neutral, and typing into an HTML document
16770        // is the thing that does work today.
16771        let mut d = html_doc("<p>Hello world</p>\n");
16772        d.caret = d.source.find("world").unwrap();
16773        d.insert("big ");
16774        assert_eq!(d.source, "<p>Hello big world</p>\n");
16775        assert!(d.dirty);
16776        d.backspace();
16777        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
16778        d.undo();
16779        d.undo();
16780        assert_eq!(d.source, "<p>Hello world</p>\n");
16781    }
16782
16783    #[test]
16784    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
16785        // `authorable` only separates "there is a door in" from "there is not",
16786        // and HTML is on the near side of that line — which is exactly why a
16787        // toolbar must not be built from it.
16788        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
16789        assert!(html.authorable());
16790        assert!(
16791            !Doc::from_source("<r>x</r>".into(), Format::Xml)
16792                .unwrap()
16793                .authorable()
16794        );
16795
16796        let caps = html.capabilities();
16797        assert!(caps.bold && caps.italic && caps.code && caps.mark);
16798        assert!(caps.thematic_break && caps.cell_line_break);
16799        // A heading is a tag pair twig rebuilds (3.4), and since 3.5 so are a
16800        // quote, a list, a code block's language, a link and an image — each
16801        // printed as a fresh node where HTML has no marker to rewrite. A task
16802        // box is a form control and a footnote has no spelling, so those two
16803        // are what keeps the record ragged.
16804        assert!(caps.heading && caps.blockquote && caps.bullet_list);
16805        assert!(caps.link && caps.image && caps.code_language);
16806        assert!(!caps.task && !caps.footnote);
16807        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
16808        // twig's table editor would happily re-emit as `| a | b |`.
16809        assert!(!caps.table);
16810
16811        // The two lightweight formats spell everything leaf offers — and still
16812        // differ from each other, which is the other half of why one boolean
16813        // can't serve.
16814        for fmt in [Format::Markdown, Format::Djot] {
16815            let caps = Capabilities::of(fmt);
16816            assert!(
16817                caps.heading && caps.blockquote && caps.ordered_list,
16818                "{fmt:?}"
16819            );
16820            assert!(
16821                caps.task && caps.link && caps.image && caps.table,
16822                "{fmt:?}"
16823            );
16824        }
16825        // Both spell the highlight, the strikethrough and the underline: djot
16826        // natively, and Markdown because `Capabilities` asks with
16827        // `parse_extensions` rather than with twig's defaults — `==x==` is text
16828        // under those, and a mark under the `highlight` leaf always parses
16829        // with; `<u>x</u>` likewise pairs into an `insert` only under
16830        // `html_elements`.
16831        for fmt in [Format::Markdown, Format::Djot] {
16832            let caps = Capabilities::of(fmt);
16833            assert!(caps.mark && caps.strike && caps.underline, "{fmt:?}");
16834        }
16835        // What still separates them, now that the highlight doesn't: djot has
16836        // no in-cell break, and Markdown spells neither of the scripts.
16837        assert!(Capabilities::of(Format::Djot).superscript);
16838        assert!(!Capabilities::of(Format::Markdown).superscript);
16839        assert!(Capabilities::of(Format::Markdown).cell_line_break);
16840        assert!(!Capabilities::of(Format::Djot).cell_line_break);
16841
16842        // A parse-only format answers no to every one of them, so the coarse
16843        // predicate and the record agree there.
16844        let caps = Capabilities::of(Format::Xml);
16845        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
16846    }
16847
16848    #[test]
16849    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
16850        // The guard exists to name the *document's* format rather than twig's
16851        // internals, so the message has to survive being one leaf writes itself.
16852        // Checked against a gesture twig also refuses, since that is the pair
16853        // most at risk of drifting apart — the task box, once the code
16854        // language stopped being one (twig 3.5).
16855        let mut d = html_doc("<p>Hello</p>\n");
16856        d.caret = d.source.find("Hello").unwrap();
16857        d.toggle_task_item();
16858        assert_eq!(d.status.as_deref(), Some("task: not supported in html"));
16859        assert!(!d.dirty);
16860    }
16861
16862    #[test]
16863    fn table_set_alignment_respells_the_delimiter() {
16864        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16865        d.caret = d.source.find('b').unwrap();
16866        d.table_set_alignment(Alignment::Right);
16867        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
16868    }
16869
16870    #[test]
16871    fn each_empty_table_cell_has_its_own_editable_home() {
16872        // Regression: an empty cell has no twig content_span, so both cells of a
16873        // `|  |  |` row collapsed onto the row's start (before the first `│`).
16874        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
16875        // tell the cells apart. Each empty cell must now have a distinct home
16876        // inside it.
16877        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
16878        let (c0, c1) = {
16879            let cells = &d.vmap.tables[0].grid[1].cells;
16880            (cells[0].start, cells[1].start)
16881        };
16882        assert!(
16883            c0 < c1,
16884            "the two empty cells have distinct homes: {c0} < {c1}"
16885        );
16886        d.caret = c0;
16887        d.insert("x");
16888        assert_eq!(
16889            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
16890            "typed inside the cell"
16891        );
16892    }
16893
16894    #[test]
16895    fn arrows_step_into_each_empty_table_cell() {
16896        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
16897        let (c0, c1) = {
16898            let cells = &d.vmap.tables[0].grid[1].cells;
16899            (cells[0].start, cells[1].start)
16900        };
16901        d.caret = d.source.find('b').unwrap(); // in the header's second cell
16902        let mut seen = std::collections::HashSet::new();
16903        for _ in 0..6 {
16904            d.move_right(false);
16905            seen.insert(d.caret);
16906        }
16907        assert!(
16908            seen.contains(&c0),
16909            "right arrow reaches the first empty cell"
16910        );
16911        assert!(
16912            seen.contains(&c1),
16913            "right arrow reaches the second empty cell"
16914        );
16915    }
16916
16917    #[test]
16918    fn table_op_off_a_table_is_a_no_op_with_a_status() {
16919        let mut d = doc_with("tbl_none", "just text\n");
16920        d.caret = 3;
16921        d.table_insert_row(true);
16922        assert_eq!(d.source, "just text\n", "nothing changed");
16923        assert!(d.status.is_some(), "a status explains why");
16924        assert!(!d.caret_in_table());
16925    }
16926
16927    #[test]
16928    fn enter_in_an_ordered_list_renumbers_the_following_items() {
16929        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
16930        // the renumber pass keeps them sequential, matching what the view draws.
16931        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
16932        d.caret = d.source.find('a').unwrap() + 1; // end of item a
16933        d.newline();
16934        d.insert("x");
16935        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
16936    }
16937
16938    #[test]
16939    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
16940        for view in [View::Source, View::Wysiwyg] {
16941            let mut d = doc_in(view, "outdent_noop", "hello\n");
16942            d.caret = 2;
16943            d.outdent();
16944            assert_eq!(d.source, "hello\n");
16945            assert!(!d.dirty, "a no-op is not a modification");
16946            d.undo();
16947            assert_eq!(
16948                d.status.as_deref(),
16949                Some("nothing to undo"),
16950                "spends no undo step"
16951            );
16952            assert_eq!(d.source, "hello\n");
16953        }
16954    }
16955
16956    #[test]
16957    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
16958        for view in [View::Source, View::Wysiwyg] {
16959            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
16960            d.anchor = Some(0);
16961            d.caret = 7; // through "two"
16962            d.indent();
16963            assert_eq!(
16964                d.source, "  one\n\n  two\n",
16965                "the blank line keeps no trailing pad"
16966            );
16967            // Selected, so a second Tab lands on the same lines rather than on
16968            // whatever the shifted offsets now cover.
16969            assert_eq!(d.selection(), Some((0, 12)));
16970            d.indent();
16971            assert_eq!(d.source, "    one\n\n    two\n");
16972        }
16973    }
16974
16975    #[test]
16976    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
16977        for view in [View::Source, View::Wysiwyg] {
16978            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
16979            d.anchor = Some(0);
16980            d.caret = 15;
16981            d.outdent();
16982            assert_eq!(d.source, "two\none\nnone\n");
16983        }
16984    }
16985
16986    #[test]
16987    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
16988        for view in [View::Source, View::Wysiwyg] {
16989            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
16990            d.anchor = Some(0);
16991            d.caret = 7;
16992            d.indent();
16993            assert_eq!(d.source, "  one\n\n  two\n");
16994            d.undo();
16995            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
16996            assert_eq!(
16997                d.selection(),
16998                Some((0, 7)),
16999                "with the selection it was aimed at"
17000            );
17001            d.redo();
17002            assert_eq!(d.source, "  one\n\n  two\n");
17003            assert_eq!(
17004                d.selection(),
17005                Some((0, 12)),
17006                "redo replays the caret the indent placed, not the one splice left"
17007            );
17008        }
17009    }
17010
17011    #[test]
17012    fn vertical_motion_keeps_the_column() {
17013        let mut d = doc_with("move", "abcd\nef\n");
17014        d.caret = 3; // "abc|d" on row 0, col 3
17015        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
17016        assert_eq!(d.caret, 7); // just after "ef"
17017    }
17018
17019    // ── goal column ──────────────────────────────────────────────────────────
17020
17021    #[test]
17022    fn vertical_motion_goal_column_survives_a_short_line() {
17023        // Regression: re-deriving the column from the clamped position on
17024        // every step permanently forgets it once a short line clamps it.
17025        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
17026        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
17027        assert_eq!(
17028            g("abcd|ef\nxy\nghijkl\n", |d| {
17029                d.move_down(false); // clamps to end of "xy"
17030                d.move_down(false); // restores col 4 on the long line
17031            }),
17032            "abcdef\nxy\nghij|kl\n"
17033        );
17034    }
17035
17036    #[test]
17037    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
17038        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
17039        assert_eq!(d.goal_col, None);
17040        d.caret = 4; // row 0, col 4
17041        d.move_down(false); // clamps into "xy"; goal stays the original col
17042        assert_eq!(d.goal_col, Some(4));
17043        assert_eq!(d.caret_pos(), (1, 2));
17044
17045        // A horizontal motion drops the goal column...
17046        d.move_left(false);
17047        assert_eq!(d.goal_col, None);
17048
17049        // ...so the next vertical motion picks up the *new* column (1), not
17050        // the stale one (4).
17051        d.move_down(false);
17052        assert_eq!(d.goal_col, Some(1));
17053        assert_eq!(d.caret_pos(), (2, 1));
17054    }
17055
17056    #[test]
17057    fn editing_clears_the_goal_column() {
17058        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
17059        d.caret = 4;
17060        d.move_down(false);
17061        assert_eq!(d.goal_col, Some(4));
17062        d.insert("Z");
17063        assert_eq!(d.goal_col, None);
17064    }
17065
17066    #[test]
17067    fn vertical_motion_on_an_empty_document_is_a_no_op() {
17068        let mut d = doc_with("empty_vert", "");
17069        d.move_down(false);
17070        assert_eq!(d.caret, 0);
17071        d.move_up(false);
17072        assert_eq!(d.caret, 0);
17073    }
17074
17075    // ── the document's edges ─────────────────────────────────────────────────
17076
17077    #[test]
17078    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
17079        // The reproduction, and the disagreement: Down on the last line ran to
17080        // the end of the document in the source view — by accident, an
17081        // out-of-range row clamping to the end of the string — and did nothing
17082        // whatever in the view leaf opens in. One rule now, in both.
17083        for (view, tag) in VIEWS {
17084            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
17085            d.caret = 1;
17086            d.move_down(false);
17087            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
17088            d.move_up(false);
17089            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
17090        }
17091    }
17092
17093    #[test]
17094    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
17095        // Down off the bottom is a motion like any other, so it latches a goal
17096        // column — and Up comes back to the column the caret left, not to the
17097        // one the document's end happened to be in.
17098        for (view, tag) in VIEWS {
17099            let gap = if view == View::Source { "\n" } else { "\n\n" };
17100            let src = format!("abcdef{gap}ghijkl");
17101            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
17102            d.caret = 2; // row 0, col 2
17103            d.move_down(false);
17104            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
17105            d.move_down(false);
17106            assert_eq!(
17107                d.caret,
17108                src.len(),
17109                "{tag}: Down off the bottom reaches the end"
17110            );
17111            d.move_up(false);
17112            assert_eq!(
17113                d.caret_pos().1,
17114                2,
17115                "{tag}: Up returns to the column Down left"
17116            );
17117        }
17118    }
17119
17120    #[test]
17121    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
17122        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
17123        // Up that did nothing still armed a goal column, and the next Down aimed
17124        // at a column the caret had never been in.
17125        for (view, tag) in VIEWS {
17126            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
17127            d.caret = 0;
17128            d.move_up(false);
17129            assert_eq!(d.caret, 0, "{tag}: already at the start");
17130            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
17131
17132            d.caret = d.source.len();
17133            d.move_down(false);
17134            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
17135            assert_eq!(
17136                d.goal_col, None,
17137                "{tag}: a no-op Down latched a goal column"
17138            );
17139        }
17140    }
17141
17142    // ── soft wrap ────────────────────────────────────────────────────────────
17143    // Every other test here builds the map at 80 columns, where no fixture is
17144    // long enough to fold. A wrap is where one offset belongs to two rows at
17145    // once, and it broke everything that asks the caret what row it is on.
17146
17147    /// The wrapped fixture these cases share, folded at 12 columns into
17148    /// `one two ` / `three four ` / `five six ` / `seven eight`.
17149    fn wrapped_doc(name: &str) -> Doc {
17150        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
17151        d.build_visual(12);
17152        d
17153    }
17154
17155    #[test]
17156    fn home_and_end_work_from_a_wrapped_row() {
17157        // The reproduction: offset 19 is the `f` of "five", the first character
17158        // of the third row — and also the offset the second row ends at. It
17159        // resolved to the *second* row, so End aimed at a place the caret was
17160        // already in and did nothing, while Home walked backwards onto a row the
17161        // caret had left.
17162        let mut d = wrapped_doc("wrap_home_end");
17163        d.caret = 19;
17164        assert_eq!(
17165            d.caret_pos(),
17166            (2, 0),
17167            "the wrap boundary opens the third row"
17168        );
17169        d.move_end(false);
17170        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
17171        d.move_home(false);
17172        assert_eq!(d.caret, 19, "Home left the row the caret was on");
17173    }
17174
17175    #[test]
17176    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
17177        // The row's end is the last offset that is only ever its own: the offset
17178        // past it opens the row below, and aiming there would send a second
17179        // press on to *that* row's end, and a third to the next — End walking
17180        // down the paragraph rather than sitting where it landed.
17181        let mut d = wrapped_doc("wrap_end_twice");
17182        d.caret = 12; // inside "three", on the second row
17183        d.move_end(false);
17184        assert_eq!(
17185            d.caret, 18,
17186            "the end of `three four`, before the space the wrap ate"
17187        );
17188        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
17189        d.move_end(false);
17190        assert_eq!(d.caret, 18, "a second End moved the caret");
17191        d.move_home(false);
17192        assert_eq!(d.caret, 8, "Home takes the row's own start");
17193    }
17194
17195    #[test]
17196    fn vertical_motion_crosses_a_soft_wrap() {
17197        // Down aimed at the row below's column 0, an offset that resolved *up*
17198        // to the row above's end — so it landed on the offset it already had and
17199        // the caret could never leave a paragraph's first row.
17200        let mut d = wrapped_doc("wrap_down");
17201        d.caret = 0;
17202        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
17203            d.move_down(false);
17204            assert_eq!(d.caret, want, "Down stalled");
17205            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
17206        }
17207        d.move_down(false);
17208        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
17209
17210        // ...and back up, one row per press. The goal column is the end of the
17211        // last row, past every other row's width, so each press clamps to the
17212        // row's own last offset rather than to the one that opens the next.
17213        let mut d = wrapped_doc("wrap_up");
17214        d.caret = 39;
17215        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
17216            d.move_up(false);
17217            assert_eq!(d.caret, want, "Up stalled");
17218            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
17219        }
17220    }
17221
17222    #[test]
17223    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
17224        // The kills take the same line Home and End do, so in WYSIWYG they take
17225        // the visual row — and a soft wrap has no newline in it to delete, so
17226        // nothing is joined by reaching the end of one.
17227        let mut d = wrapped_doc("wrap_kill");
17228        d.caret = 19; // the `f` of "five", opening the third row
17229        d.delete_to_line_end();
17230        // The space the wrap ate goes with the row it was drawn on: sparing it
17231        // would leave "four  seven", two spaces where the row had been.
17232        assert_eq!(d.source, "one two three four seven eight");
17233
17234        // Backwards from the row's last caret position — which is *before* that
17235        // space, so this one survives, being on the far side of the caret.
17236        let mut d = wrapped_doc("wrap_kill_back");
17237        d.caret = 27;
17238        d.delete_to_line_start();
17239        assert_eq!(d.source, "one two three four  seven eight");
17240    }
17241
17242    // ── document start / end ────────────────────────────────────────────────
17243
17244    #[test]
17245    fn move_doc_start_and_end_jump_to_the_edges() {
17246        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
17247        assert_eq!(
17248            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
17249            "|hello\nworld\n"
17250        );
17251        assert_eq!(
17252            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
17253            "hello\nworld\n|"
17254        );
17255        // Already at the edge: a no-op.
17256        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
17257        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
17258    }
17259
17260    #[test]
17261    fn move_doc_start_and_end_extend_the_selection() {
17262        assert_eq!(
17263            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
17264                .move_doc_end(true)),
17265            "hello wor[ld\n|]"
17266        );
17267        assert_eq!(
17268            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
17269                .move_doc_start(true)),
17270            "[|hello wor]ld\n"
17271        );
17272    }
17273
17274    #[test]
17275    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
17276        let mut d = doc_with("empty_edges", "");
17277        d.move_doc_end(false);
17278        assert_eq!(d.caret, 0);
17279        d.move_doc_start(false);
17280        assert_eq!(d.caret, 0);
17281    }
17282
17283    // ── arrow collapses an active selection ─────────────────────────────────
17284
17285    #[test]
17286    fn arrow_collapses_selection_to_its_near_edge() {
17287        let mut d = doc_with("collapse", "hello world\n");
17288
17289        // Forward selection (anchor before caret): Right -> end, Left -> start.
17290        d.anchor = Some(2);
17291        d.caret = 7;
17292        d.move_right(false);
17293        assert_eq!((d.caret, d.anchor), (7, None));
17294
17295        d.anchor = Some(2);
17296        d.caret = 7;
17297        d.move_left(false);
17298        assert_eq!((d.caret, d.anchor), (2, None));
17299
17300        // Backward selection (anchor after caret): edges are the same
17301        // regardless of which end the caret started on.
17302        d.anchor = Some(7);
17303        d.caret = 2;
17304        d.move_right(false);
17305        assert_eq!((d.caret, d.anchor), (7, None));
17306
17307        d.anchor = Some(7);
17308        d.caret = 2;
17309        d.move_left(false);
17310        assert_eq!((d.caret, d.anchor), (2, None));
17311    }
17312
17313    #[test]
17314    fn arrow_with_extend_keeps_growing_the_selection() {
17315        let mut d = doc_with("collapse_extend", "hello world\n");
17316        d.anchor = Some(2);
17317        d.caret = 7;
17318        d.move_right(true); // extend: no collapse, caret steps one further
17319        assert_eq!((d.caret, d.anchor), (8, Some(2)));
17320    }
17321
17322    #[test]
17323    fn arrow_without_a_selection_moves_one_character_as_before() {
17324        let mut d = doc_with("no_collapse", "hello\n");
17325        d.caret = 2;
17326        d.move_right(false);
17327        assert_eq!(d.caret, 3);
17328        d.move_left(false);
17329        assert_eq!(d.caret, 2);
17330    }
17331
17332    /// Press Right until it stops, collecting the offsets walked through. Every
17333    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
17334    /// two stops sharing one source offset can't be moved between, so the caret
17335    /// stalls on the first of them and the walk never reaches the rest.
17336    fn walk_right(d: &mut Doc) -> Vec<usize> {
17337        let mut seen = vec![d.caret];
17338        for _ in 0..2000 {
17339            let before = d.caret;
17340            d.move_right(false);
17341            if d.caret == before {
17342                break;
17343            }
17344            seen.push(d.caret);
17345        }
17346        seen
17347    }
17348
17349    #[test]
17350    fn the_caret_crosses_a_soft_break() {
17351        // A newline inside a paragraph is a `soft_break`, which twig gives no
17352        // span of its own — the space it renders as used to borrow the offset of
17353        // the character before it, and a caret can't move without changing
17354        // offset. Right must walk clean off the end of the first line.
17355        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
17356        d.caret = 0;
17357        let seen = walk_right(&mut d);
17358        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17359    }
17360
17361    #[test]
17362    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
17363        // The paragraph holds one soft break. Folded (the default) it lays out as
17364        // a single reflowed row; Preserve re-lays it as a row per source line.
17365        // The setter must invalidate the cached map for the change to show, and
17366        // again on the way back — so a round trip returns to the folded layout.
17367        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
17368        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
17369        d.build_visual(80);
17370        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
17371
17372        d.set_line_flow(LineFlow::Preserve);
17373        d.build_visual(80);
17374        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
17375
17376        d.set_line_flow(LineFlow::Fold);
17377        d.build_visual(80);
17378        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
17379    }
17380
17381    #[test]
17382    fn the_caret_still_crosses_a_preserved_soft_break() {
17383        // Preserve renders the soft break as a row boundary rather than a space,
17384        // but the caret must still reach every offset — the break's own offset is
17385        // the first row's end stop, so Right walks clean off the end of line one
17386        // onto line two, exactly as it does when the break is folded.
17387        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
17388        d.set_line_flow(LineFlow::Preserve);
17389        d.build_visual(80);
17390        d.caret = 0;
17391        let seen = walk_right(&mut d);
17392        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17393    }
17394
17395    #[test]
17396    fn the_caret_walks_a_code_block() {
17397        // Every glyph of a code block used to map to the block's start, so the
17398        // whole block was a single offset and the caret couldn't move inside it.
17399        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
17400        let mut d = wysiwyg_doc("code_walk", src);
17401        d.caret = 0;
17402        let seen = walk_right(&mut d);
17403        // The fences are markup: hidden, and no caret stop. The code between
17404        // them is reached a character at a time.
17405        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
17406        for off in code.clone() {
17407            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
17408        }
17409        assert!(seen.contains(&code.end), "no stop after the last line");
17410    }
17411
17412    #[test]
17413    fn the_caret_walks_an_indented_code_block() {
17414        // An indented block's text has the four-space indent stripped, so it
17415        // isn't a verbatim slice and its lines have to be re-found. The caret
17416        // lands on the code, never in the indent.
17417        let src = "    indented\n    code\n";
17418        let mut d = wysiwyg_doc("indent_code_walk", src);
17419        d.caret = 0;
17420        let seen = walk_right(&mut d);
17421        assert!(seen.contains(&src.find("indented").unwrap()));
17422        assert!(seen.contains(&src.find("code").unwrap()));
17423        assert!(
17424            !seen.contains(&0) || seen[0] == 0,
17425            "the caret starts where it was put"
17426        );
17427        // Nothing in the stripped indent is a stop.
17428        for off in [1, 2, 3] {
17429            assert!(!seen.contains(&off), "landed in the indent at {off}");
17430        }
17431    }
17432
17433    #[test]
17434    fn the_caret_leaves_a_tight_heading() {
17435        // "# H" with text directly under it: the heading row's end and the
17436        // separator row's end are the same offset. Right used to find the
17437        // separator's copy, set the caret to where it already was, and stop.
17438        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
17439        d.caret = 2; // the "H"
17440        let seen = walk_right(&mut d);
17441        assert!(
17442            seen.len() > 2,
17443            "Right stalled at the heading's end: {seen:?}"
17444        );
17445        assert!(
17446            seen.contains(&8),
17447            "never reached the end of \"text\": {seen:?}"
17448        );
17449    }
17450
17451    #[test]
17452    fn the_caret_skips_the_gap_between_two_paragraphs() {
17453        // The blank line between two paragraphs is the boundary itself. The
17454        // caret used to be able to sit on it, and typing there landed in the
17455        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
17456        // soft break, so the text visibly snapped back up.
17457        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
17458        d.caret = 1; // the end of "A"
17459        d.move_right(false);
17460        assert_eq!(d.caret, 3, "Right stopped in the gap");
17461        d.insert("x");
17462        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
17463    }
17464
17465    #[test]
17466    fn down_from_a_paragraph_lands_on_the_next_one() {
17467        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
17468        d.caret = 0;
17469        d.move_down(false);
17470        assert_eq!(d.caret, 3, "Down stopped in the gap");
17471    }
17472
17473    #[test]
17474    fn clicking_the_gap_lands_on_real_text() {
17475        // A click can still *reach* the gap — it's drawn, so it's clickable.
17476        // It has to resolve to somewhere the caret can be.
17477        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
17478        d.click(1, 0, false); // the gap row
17479        assert!(
17480            d.caret == 1 || d.caret == 3,
17481            "click left the caret in the gap at {}",
17482            d.caret
17483        );
17484        d.insert("x");
17485        // Either edge of the boundary is a fair place to land; inside it isn't.
17486        assert!(
17487            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
17488            "click in the gap typed into the boundary: {:?}",
17489            d.source
17490        );
17491    }
17492
17493    #[test]
17494    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
17495        // Enter inserts a paragraph break, which leaves a blank line spare on
17496        // either side of a new one. That middle line is a real empty paragraph:
17497        // the caret lands there, and typing makes a paragraph rather than
17498        // extending a neighbour.
17499        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
17500        d.caret = 1;
17501        d.newline();
17502        assert_eq!(d.source, "A\n\n\n\nB\n");
17503        d.build_visual(80);
17504        let (row, _) = d.caret_pos();
17505        assert!(
17506            d.vmap.row_is_navigable(row),
17507            "the caret landed on a gap row"
17508        );
17509        d.insert("x");
17510        assert_eq!(
17511            d.source, "A\n\nx\n\nB\n",
17512            "the new paragraph merged into a neighbour"
17513        );
17514    }
17515
17516    #[test]
17517    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
17518        let mut d = wysiwyg_doc("gap_eof", "A\n");
17519        d.caret = 1;
17520        d.newline();
17521        d.build_visual(80);
17522        let (row, _) = d.caret_pos();
17523        assert!(
17524            d.vmap.row_is_navigable(row),
17525            "the caret landed on a gap row"
17526        );
17527        d.insert("x");
17528        assert!(
17529            d.source.starts_with("A\n\n") && d.source.contains('x'),
17530            "typing at the end merged into A: {:?}",
17531            d.source
17532        );
17533    }
17534
17535    // ── click_past_end ───────────────────────────────────────────────────────
17536
17537    /// [`Doc::click_past_end`] on `body`, and the source it left, with the caret
17538    /// rendered as `|`.
17539    fn past_end(name: &str, body: &str) -> (Doc, String) {
17540        let mut d = wysiwyg_doc(name, body);
17541        d.click_past_end();
17542        let out = render_caret(&d);
17543        (d, out)
17544    }
17545
17546    #[test]
17547    fn click_past_end_opens_an_empty_paragraph_under_the_last_block() {
17548        let (mut d, out) = past_end("pe_para", "A\n");
17549        assert_eq!(out, "A\n\n|");
17550        d.build_visual(80);
17551        let (row, _) = d.caret_pos();
17552        assert!(
17553            d.vmap.row_is_navigable(row),
17554            "the caret landed on a gap row"
17555        );
17556        d.insert("x");
17557        assert_eq!(d.source, "A\n\nx", "typing merged into A");
17558    }
17559
17560    #[test]
17561    fn click_past_end_writes_both_newlines_when_the_file_has_none() {
17562        assert_eq!(past_end("pe_bare", "A").1, "A\n\n|");
17563    }
17564
17565    #[test]
17566    fn click_past_end_is_only_a_caret_move_when_the_paragraph_is_already_there() {
17567        let (d, out) = past_end("pe_there", "A\n\n");
17568        assert_eq!(out, "A\n\n|");
17569        assert!(!d.dirty, "a click wrote to a document it did not need to");
17570        assert!(
17571            !d.can_undo(),
17572            "a click that changed nothing left an undo step"
17573        );
17574    }
17575
17576    #[test]
17577    fn click_past_end_leaves_a_closed_fence() {
17578        let (mut d, out) = past_end("pe_fence", "```\ncode\n```\n");
17579        assert_eq!(out, "```\ncode\n```\n\n|");
17580        d.build_visual(80);
17581        let (row, _) = d.caret_pos();
17582        assert!(!d.vmap.rows[row].code, "the caret is still on a code row");
17583        d.insert("x");
17584        assert_eq!(d.source, "```\ncode\n```\n\nx");
17585    }
17586
17587    #[test]
17588    fn click_past_end_closes_an_unclosed_fence_first() {
17589        assert_eq!(past_end("pe_open", "```\ncode\n").1, "```\ncode\n```\n\n|");
17590        assert_eq!(
17591            past_end("pe_open2", "````\ncode").1,
17592            "````\ncode\n````\n\n|"
17593        );
17594        assert_eq!(past_end("pe_tilde", "~~~\ncode\n").1, "~~~\ncode\n~~~\n\n|");
17595        assert_eq!(
17596            past_end("pe_quoted", "> ```\n> code\n").1,
17597            "> ```\n> code\n> ```\n\n|"
17598        );
17599    }
17600
17601    #[test]
17602    fn click_past_end_does_not_close_an_indented_block() {
17603        assert_eq!(past_end("pe_indent", "    code\n").1, "    code\n\n|");
17604    }
17605
17606    #[test]
17607    fn click_past_end_under_a_list_and_a_table_leaves_them() {
17608        let (mut d, out) = past_end("pe_list", "- a\n- b\n");
17609        assert_eq!(out, "- a\n- b\n\n|");
17610        d.insert("x");
17611        assert_eq!(d.source, "- a\n- b\n\nx", "typed into the list");
17612        assert_eq!(
17613            past_end("pe_table", "| a |\n|---|\n| b |\n").1,
17614            "| a |\n|---|\n| b |\n\n|"
17615        );
17616    }
17617
17618    #[test]
17619    fn click_past_end_on_an_empty_document_writes_nothing() {
17620        let (d, out) = past_end("pe_empty", "");
17621        assert_eq!(out, "|");
17622        assert!(!d.dirty);
17623    }
17624
17625    #[test]
17626    fn click_past_end_is_one_undo_step() {
17627        let (mut d, _) = past_end("pe_undo", "A\n");
17628        d.undo();
17629        assert_eq!(d.source, "A\n");
17630    }
17631
17632    #[test]
17633    fn click_past_end_in_the_source_view_only_moves_the_caret() {
17634        let mut d = doc_with("pe_source", "A\n");
17635        d.click_past_end();
17636        assert_eq!(render_caret(&d), "A\n|");
17637        assert!(!d.dirty);
17638    }
17639
17640    #[test]
17641    fn click_past_end_on_a_read_only_document_only_moves_the_caret() {
17642        let mut d = wysiwyg_doc("pe_ro", "A\n");
17643        d.set_read_only(true);
17644        d.click_past_end();
17645        assert_eq!(render_caret(&d), "A\n|");
17646    }
17647
17648    // ── toggle_code_block ────────────────────────────────────────────────────
17649
17650    #[test]
17651    fn toggle_code_block_fences_the_paragraph_at_the_caret_and_reverses() {
17652        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17653        assert_eq!(g("cb_on", "hel|lo\n"), "```\nhel|lo\n```\n");
17654        assert_eq!(g("cb_off", "```\nhel|lo\n```\n"), "hel|lo\n");
17655        assert_eq!(g("cb_end", "hello|\n"), "```\nhello|\n```\n");
17656        assert_eq!(
17657            g("cb_wrap", "aaa\nb|bb\nccc\n"),
17658            "```\naaa\nb|bb\nccc\n```\n"
17659        );
17660        assert_eq!(
17661            g("cb_unwrap", "```\naaa\nb|bb\nccc\n```\n"),
17662            "aaa\nb|bb\nccc\n"
17663        );
17664        // An indented block dedents, and the lines stay one-to-one.
17665        assert_eq!(g("cb_indent", "    co|de\n"), "co|de\n");
17666        // A quote's marker is kept on every line, the fence's included.
17667        assert_eq!(g("cb_quote", "> hel|lo\n"), "> ```\n> hel|lo\n> ```\n");
17668    }
17669
17670    #[test]
17671    fn toggle_code_block_on_a_blank_line_opens_an_empty_fence() {
17672        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17673        assert_eq!(g("cb_blank", "A\n\n|"), "A\n\n```\n|\n```");
17674        assert_eq!(
17675            g("cb_blank_mid", "A\n\n|\n\nB\n"),
17676            "A\n\n```\n|\n```\n\nB\n"
17677        );
17678        // Tight against a neighbour, a blank line goes in on that side.
17679        assert_eq!(g("cb_blank_tight", "A\n|\nB\n"), "A\n\n```\n|\n```\n\nB\n");
17680        // Inside a quote, on a quoted blank line.
17681        assert_eq!(
17682            g("cb_blank_quote", "> A\n>\n> |\n"),
17683            "> A\n>\n> ```\n> |\n> ```\n"
17684        );
17685    }
17686
17687    #[test]
17688    fn toggle_code_block_from_a_blank_line_is_a_block_the_caret_can_type_into() {
17689        let mut d = wysiwyg_doc("cb_type", "A\n\n");
17690        d.click_past_end();
17691        d.toggle_code_block();
17692        assert!(
17693            d.caret_in_code_block(),
17694            "the caret is not in the block it opened"
17695        );
17696        d.insert("let x = 1;");
17697        d.newline();
17698        d.insert("x");
17699        assert_eq!(d.source, "A\n\n```\nlet x = 1;\nx\n```");
17700        d.build_visual(80);
17701        let (row, _) = d.caret_pos();
17702        assert!(d.vmap.rows[row].code, "typed text is not on a code row");
17703        // And back out: the button reverses what it did, text kept.
17704        d.toggle_code_block();
17705        assert_eq!(d.source, "A\n\nlet x = 1;\nx\n");
17706        assert!(!d.caret_in_code_block());
17707    }
17708
17709    #[test]
17710    fn toggle_code_block_over_a_selection_fences_it_whole_and_keeps_it_selected() {
17711        let mut d = wysiwyg_doc("cb_sel", "one\n\ntwo\n\nthree\n");
17712        d.anchor = Some(1);
17713        d.caret = 7;
17714        d.toggle_code_block();
17715        assert_eq!(d.source, "```\none\n\ntwo\n```\n\nthree\n");
17716        assert!(d.selection().is_some(), "the block came back unselected");
17717        d.toggle_code_block();
17718        assert_eq!(
17719            d.source, "one\n\ntwo\n\nthree\n",
17720            "a second press did not reverse the first"
17721        );
17722    }
17723
17724    #[test]
17725    fn toggle_code_block_inside_a_list_item_fences_and_unfences_in_place() {
17726        for (name, before, fenced) in [
17727            ("cb_list", "- it|em\n", "- ```\n  it|em\n  ```\n"),
17728            ("cb_olist", "1. it|em\n", "1. ```\n   it|em\n   ```\n"),
17729            ("cb_task", "- [ ] it|em\n", "- [ ] ```\n  it|em\n  ```\n"),
17730            (
17731                "cb_nested",
17732                "- a\n  - it|em\n",
17733                "- a\n  - ```\n    it|em\n    ```\n",
17734            ),
17735        ] {
17736            let mut d = wysiwyg_doc(name, &before.replace('|', ""));
17737            d.caret = before.find('|').unwrap();
17738            d.toggle_code_block();
17739            assert_eq!(render_caret(&d), fenced, "{name}: fencing");
17740            assert!(
17741                d.caret_in_code_block(),
17742                "{name}: the caret is in the new block"
17743            );
17744            d.toggle_code_block();
17745            assert_eq!(
17746                render_caret(&d),
17747                before,
17748                "{name}: a second press reverses the first"
17749            );
17750        }
17751    }
17752
17753    #[test]
17754    fn toggle_code_block_in_a_list_item_is_one_undo_step() {
17755        let mut d = wysiwyg_doc("cb_list_undo", "- item\n");
17756        d.caret = 4;
17757        d.toggle_code_block();
17758        d.undo();
17759        assert_eq!(render_caret(&d), "- it|em\n");
17760    }
17761
17762    #[test]
17763    fn caret_in_code_block_reads_fenced_and_indented_blocks() {
17764        let mut d = wysiwyg_doc("cb_in", "para\n\n```\ncode\n```\n\n    more\n");
17765        d.caret = 2;
17766        assert!(!d.caret_in_code_block());
17767        d.caret = 11;
17768        assert!(d.caret_in_code_block());
17769        d.caret = 25;
17770        assert!(d.caret_in_code_block(), "an indented block is a code block");
17771    }
17772
17773    #[test]
17774    fn caret_in_blockquote_reads_every_line_of_a_quote_and_nothing_after() {
17775        let src = "para\n\n> # Head\n> body|\n\nafter\n";
17776        let mut d = wysiwyg_doc("bq_in", &src.replace('|', ""));
17777        let quote_start = src.find('>').unwrap();
17778        let body_end = src.find('|').unwrap();
17779        let after = src.find("after").unwrap() - 1;
17780        for (at, inside) in [
17781            (2, false),
17782            (quote_start + 4, true),
17783            (body_end - 2, true),
17784            (body_end, true),
17785            (after, false),
17786            (after + 2, false),
17787        ] {
17788            d.caret = at;
17789            assert_eq!(d.caret_in_blockquote(), inside, "caret at {at}");
17790        }
17791        // A heading in a quote is both: the quote is a layer over the style.
17792        d.caret = quote_start + 4;
17793        assert_eq!(d.current_heading_level(), Some(1));
17794    }
17795
17796    #[test]
17797    fn caret_in_blockquote_follows_the_toggle() {
17798        let mut d = wysiwyg_doc("bq_toggle", "hello\n");
17799        d.caret = 2;
17800        assert!(!d.caret_in_blockquote());
17801        d.toggle_blockquote();
17802        assert!(d.caret_in_blockquote());
17803        d.toggle_blockquote();
17804        assert!(!d.caret_in_blockquote());
17805    }
17806
17807    #[test]
17808    fn toggle_code_block_is_one_undo_step() {
17809        let mut d = wysiwyg_doc("cb_undo", "hello\n");
17810        d.caret = 2;
17811        d.toggle_code_block();
17812        d.undo();
17813        assert_eq!(render_caret(&d), "he|llo\n");
17814    }
17815
17816    #[test]
17817    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
17818        // A paragraph broken over two source lines is one paragraph. Selecting
17819        // it must not stop at the newline inside it — that newline is markup the
17820        // rich-text view exists to hide.
17821        let src = "one two\nthree four\n\nnext\n";
17822        let mut d = wysiwyg_doc("triple_para", src);
17823        d.select_block_at(2);
17824        assert_eq!(
17825            d.selected_text(),
17826            Some("one two\nthree four"),
17827            "stopped at the soft break"
17828        );
17829    }
17830
17831    #[test]
17832    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
17833        // The reader scrolls down past the caret's row. Nothing moved the
17834        // caret, so the view must stay where it was put — the old code revealed
17835        // the caret every frame, which dragged the view straight back and made
17836        // the document unscrollable past the caret.
17837        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
17838        d.caret = 0;
17839        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
17840        d.scroll = 4; // the wheel
17841        d.follow_caret(0, 3, 9);
17842        assert_eq!(
17843            d.scroll, 4,
17844            "the wheel was overruled by a caret that never moved"
17845        );
17846    }
17847
17848    #[test]
17849    fn moving_the_caret_brings_the_view_back_to_it() {
17850        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
17851        d.caret = 0;
17852        d.follow_caret(0, 3, 9);
17853        d.scroll = 6; // scrolled away
17854        d.move_right(false); // ...and now the caret moves
17855        let (row, _) = d.caret_pos();
17856        d.follow_caret(row, 3, 9);
17857        assert!(
17858            d.scroll <= row && row < d.scroll + 3,
17859            "caret row {row} off screen at scroll {}",
17860            d.scroll
17861        );
17862    }
17863
17864    #[test]
17865    fn scrolling_stops_at_the_last_row() {
17866        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
17867        d.caret = 0;
17868        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
17869        d.scroll = 999; // the wheel, spun hard
17870        d.follow_caret(0, 3, 3);
17871        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
17872    }
17873
17874    #[test]
17875    fn every_cell_of_a_wide_table_is_reachable() {
17876        // A table whose cells are far wider than the surface: the columns are
17877        // cut to fit and the text wraps inside them, so no cell hangs off the
17878        // right edge where the caret can never go.
17879        let src = "| Ingredient | Notes |\n|---|---|\n\
17880                   | flour milled coarse | sift it twice before folding it in |\n";
17881        let mut d = wysiwyg_doc("wide_table_walk", src);
17882        d.build_visual(30);
17883        d.caret = 0;
17884        let seen = walk_right(&mut d);
17885        for word in ["Ingredient", "Notes", "coarse", "folding"] {
17886            let at = src.find(word).unwrap();
17887            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
17888        }
17889    }
17890
17891    // ── view parity ──────────────────────────────────────────────────────────
17892    // `doc_with` pins the source view, so everything above tests a view users
17893    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
17894    // deletion golden cases through *both*, plus the WYSIWYG cases the two
17895    // can't share: where the source carries markup the rendered text is a
17896    // different string, and the views agreeing would itself be the bug.
17897
17898    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
17899
17900    /// Run `action` in both views on one `|`-marked fixture and assert they
17901    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
17902    /// source verbatim, so the two views are looking at the same text and any
17903    /// disagreement is one of them having lost the plot.
17904    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
17905        let (src, caret) = parse_caret(marked);
17906        let run = |view: View, tag: &str| {
17907            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
17908            d.caret = caret;
17909            action(&mut d);
17910            render_caret(&d)
17911        };
17912        let source = run(VIEWS[0].0, VIEWS[0].1);
17913        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
17914        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
17915        source
17916    }
17917
17918    #[test]
17919    fn word_motion_agrees_across_the_views_on_plain_prose() {
17920        let g = both_views;
17921        assert_eq!(
17922            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
17923            "hello |world"
17924        );
17925        assert_eq!(
17926            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
17927            "|hello world"
17928        );
17929        assert_eq!(
17930            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
17931            "hello| world"
17932        );
17933        assert_eq!(
17934            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
17935            "hello world|"
17936        );
17937        assert_eq!(
17938            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
17939            "foo|.bar"
17940        );
17941        assert_eq!(
17942            g("par_ext", "hello |world", |d| d.move_word_right(true)),
17943            "hello [world|]"
17944        );
17945    }
17946
17947    #[test]
17948    fn word_deletion_agrees_across_the_views_on_plain_prose() {
17949        let g = both_views;
17950        assert_eq!(
17951            g("par_db", "hello world|", |d| d.delete_word_back()),
17952            "hello |"
17953        );
17954        assert_eq!(
17955            g("par_df", "hello |world", |d| d.delete_word_forward()),
17956            "hello |"
17957        );
17958        assert_eq!(
17959            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
17960            "|bar baz"
17961        );
17962        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
17963    }
17964
17965    #[test]
17966    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
17967        let g = both_views;
17968        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
17969        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
17970        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
17971        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
17972    }
17973
17974    #[test]
17975    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
17976        // The reproduction: the stop table was built one stop per `char`, so
17977        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
17978        // source view, which steps by grapheme, can't reach and backspace can't
17979        // survive. The two views must land on the same offset.
17980        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
17981        for (view, tag) in VIEWS {
17982            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
17983            d.caret = 1;
17984            d.move_right(false);
17985            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
17986
17987            // ...and the edit that used to sever a joiner off the front of it.
17988            d.backspace();
17989            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
17990            assert_eq!(d.caret, 1);
17991        }
17992    }
17993
17994    #[test]
17995    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
17996        for (view, tag) in VIEWS {
17997            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
17998            d.caret = 0;
17999            d.move_right(false);
18000            assert_eq!(
18001                d.caret,
18002                "e\u{0301}".len(),
18003                "{tag} stopped on the combining mark"
18004            );
18005        }
18006    }
18007
18008    #[test]
18009    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
18010        // The general form: whatever route the caret takes through a document
18011        // full of clusters, it never lands between the codepoints of one — so no
18012        // motion-then-backspace sequence can leave a dangling joiner behind.
18013        use unicode_segmentation::UnicodeSegmentation;
18014
18015        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
18016        let mut d = wysiwyg_doc("cluster_walk", src);
18017        d.caret = 0;
18018        let boundaries: Vec<usize> = src
18019            .grapheme_indices(true)
18020            .map(|(i, _)| i)
18021            .chain(std::iter::once(src.len()))
18022            .collect();
18023        for off in walk_right(&mut d) {
18024            assert!(
18025                boundaries.contains(&off),
18026                "Right stopped at {off}, inside a grapheme cluster"
18027            );
18028        }
18029    }
18030
18031    #[test]
18032    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
18033        // The reproduction: ⌥→ from inside the opening `**` computed its
18034        // boundary over the raw source and landed on byte 8 — inside the
18035        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
18036        // "bold". The caret drew past the bold word and sat inside it.
18037        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
18038        d.caret = 2;
18039        d.move_word_right(false);
18040        assert!(
18041            d.vmap.is_stop(d.caret),
18042            "landed at {}, not a caret stop",
18043            d.caret
18044        );
18045        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
18046        // The rendered row is "a bold c": column 6 is the space just past "bold",
18047        // and now the caret is really there rather than only drawn there.
18048        assert_eq!(d.caret_pos(), (0, 6));
18049
18050        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
18051        d.move_word_left(false);
18052        assert_eq!(d.caret, 4);
18053        assert_eq!(d.caret_pos(), (0, 2));
18054    }
18055
18056    #[test]
18057    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
18058        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
18059        // inside the closing `**`, and left "a ** c\n" — delimiters with no
18060        // opener. Glyph space covers the word alone, which would leave
18061        // "a **** c": markup wrapped around nothing. The word and the styling
18062        // that was only ever the word's go together.
18063        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
18064        d.caret = 10;
18065        d.delete_word_back();
18066        assert_eq!(d.source, "a  c\n");
18067        assert_eq!(d.caret, 2);
18068
18069        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
18070        d.caret = 4; // the "b"
18071        d.delete_word_forward();
18072        assert_eq!(d.source, "a  c\n");
18073    }
18074
18075    #[test]
18076    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
18077        let src = "a ***bold*** c\n";
18078        let mut d = wysiwyg_doc("wys_word_del_nest", src);
18079        d.caret = src.find(" c").unwrap();
18080        d.delete_word_back();
18081        assert_eq!(
18082            d.source, "a  c\n",
18083            "the emph inside the strong empties it too"
18084        );
18085
18086        let src = "a `code` c\n";
18087        let mut d = wysiwyg_doc("wys_word_del_code", src);
18088        d.caret = src.find(" c").unwrap();
18089        d.delete_word_back();
18090        assert_eq!(d.source, "a  c\n");
18091    }
18092
18093    #[test]
18094    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
18095        // Only an *emptied* node goes. Take one word of two and the `**` still
18096        // has a job to do — over the word that's left, with the space the delete
18097        // pushed against the opening delimiter moved out in front of it, or the
18098        // run would be no run at all (`** words**` is literal asterisks — see
18099        // the mark-edge rule on `splice`).
18100        let src = "a **two words** c\n";
18101        let mut d = wysiwyg_doc("wys_word_del_partial", src);
18102        d.caret = src.find(" words").unwrap();
18103        d.delete_word_back();
18104        assert_eq!(d.source, "a  **words** c\n");
18105    }
18106
18107    #[test]
18108    fn source_view_word_motion_still_walks_the_markup() {
18109        // The other half of the decision: in the source view the `**` are
18110        // characters like any other — they're on the screen, so word motion has
18111        // to stop at them and a word-delete has to leave them behind. Only
18112        // WYSIWYG hides them, so only WYSIWYG steps over them.
18113        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
18114        assert_eq!(
18115            g("src_word_motion", "a |**bold** c\n", |d| d
18116                .move_word_right(false)),
18117            "a **bold|** c\n"
18118        );
18119        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
18120        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
18121        assert_eq!(
18122            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
18123            "a **| c\n"
18124        );
18125    }
18126
18127    #[test]
18128    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
18129        // The single invariant both bugs violated: the caret draws and edits at
18130        // the same place only when it's on a stop. `debug_assert_on_a_stop`
18131        // makes the same claim in-place; this pins it from the outside, over a
18132        // document with every kind of thing the map has to be careful about.
18133        // At two widths: the wide one every other test builds at, where no
18134        // fixture folds, and one narrow enough that they all do. A soft wrap is
18135        // where an offset stops being on exactly one row, and testing only the
18136        // width that never wraps is how the caret came to be pinned at the first
18137        // one Down reached.
18138        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
18139                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
18140        // A table of named operations, which is what it looks like.
18141        #[allow(clippy::type_complexity)]
18142        let motions: [(&str, fn(&mut Doc)); 8] = [
18143            ("right", |d| d.move_right(false)),
18144            ("left", |d| d.move_left(false)),
18145            ("word_right", |d| d.move_word_right(false)),
18146            ("word_left", |d| d.move_word_left(false)),
18147            ("down", |d| d.move_down(false)),
18148            ("up", |d| d.move_up(false)),
18149            ("home", |d| d.move_home(false)),
18150            ("end", |d| d.move_end(false)),
18151        ];
18152        for width in [80, 12] {
18153            let mut d = wysiwyg_doc("stop_invariant", src);
18154            d.build_visual(width);
18155            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18156            assert!(stops.len() > 20, "fixture should have plenty of stops");
18157            for start in stops {
18158                for (name, motion) in &motions {
18159                    d.caret = start;
18160                    d.anchor = None;
18161                    motion(&mut d);
18162                    assert!(
18163                        d.vmap.is_stop(d.caret),
18164                        "{name} from {start} at width {width} landed at {} — not a caret stop",
18165                        d.caret
18166                    );
18167                }
18168            }
18169        }
18170    }
18171
18172    #[test]
18173    fn no_wysiwyg_motion_is_a_dead_end() {
18174        // Down held to the bottom of a document reaches the bottom, and Up held
18175        // to the top reaches the top — from anywhere, at a width that wraps. The
18176        // invariant above says a motion lands somewhere legal; this one says it
18177        // gets somewhere at all, which is what a caret pinned at a wrap boundary
18178        // was quietly failing to do while every assertion around it held.
18179        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
18180                   - item one two three four five\n\nlast\n";
18181        for width in [80, 12] {
18182            let mut d = wysiwyg_doc("no_dead_end", src);
18183            d.build_visual(width);
18184            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18185            let (first, last) = (stops[0], stops[stops.len() - 1]);
18186            for &start in &stops {
18187                for (name, motion, want) in [
18188                    (
18189                        "down",
18190                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
18191                        last,
18192                    ),
18193                    ("up", |d: &mut Doc| d.move_up(false), first),
18194                ] {
18195                    d.caret = start;
18196                    d.anchor = None;
18197                    d.goal_col = None;
18198                    // Every row, plus the presses the edges take, plus slack.
18199                    for _ in 0..d.vmap.num_rows() + 4 {
18200                        motion(&mut d);
18201                    }
18202                    assert_eq!(
18203                        d.caret, want,
18204                        "{name} held from {start} at width {width} never arrived"
18205                    );
18206                }
18207            }
18208        }
18209    }
18210    // ── display columns ──────────────────────────────────────────────────────
18211    // A `col` is a terminal cell, not a character. The two are the same number
18212    // for the ASCII the fixtures above are written in, which is how they came
18213    // apart in the first place: `你` is one character drawn in two cells, so a
18214    // column counted in characters names a cell the text isn't in — one earlier
18215    // for every wide character to its left.
18216
18217    #[test]
18218    fn a_wide_character_is_two_columns_wide() {
18219        // The reproduction: `你` is one char and two cells, so the caret just
18220        // past it drew at column 1 — inside the character it had already left.
18221        for (view, tag) in VIEWS {
18222            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
18223            d.caret = "你".len();
18224            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
18225            d.caret = "你好".len();
18226            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
18227        }
18228    }
18229
18230    #[test]
18231    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
18232        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
18233        // two-cell — measuring six cells one at a time, but the character they
18234        // spell is drawn in two. Width belongs to the cluster, not the glyph,
18235        // and the frontends measure it the same way.
18236        let family = "👨‍👩‍👧";
18237        for (view, tag) in VIEWS {
18238            let src = format!("a{family}b\n");
18239            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
18240            d.caret = 1 + family.len();
18241            assert_eq!(
18242                d.caret_pos(),
18243                (0, 3),
18244                "{tag}: 'a' is one cell, the family two"
18245            );
18246        }
18247    }
18248
18249    #[test]
18250    fn both_cells_of_a_wide_character_mean_the_character() {
18251        // Clicking the far half of `好` is still clicking `好`: half a character
18252        // is not a place the caret can be, so it comes to rest at the
18253        // character's start — the column it would have been drawn at anyway.
18254        for (view, tag) in VIEWS {
18255            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
18256            for col in [2, 3] {
18257                d.caret = 0;
18258                d.click(0, col, false);
18259                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
18260                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
18261            }
18262            // Past the last cell is the line's end, as it is for ASCII.
18263            d.click(0, 9, false);
18264            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
18265        }
18266    }
18267
18268    #[test]
18269    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
18270        // The mapping is only a mapping if it inverts: the cell the caret is
18271        // drawn in has to be the cell that brings it back to the same offset.
18272        // Over a fixture where a character may be one cell or two, and one
18273        // codepoint or five.
18274        use unicode_segmentation::UnicodeSegmentation;
18275
18276        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
18277
18278        let mut d = doc_in(View::Source, "roundtrip_source", src);
18279        // Every offset the source view's caret can occupy: it steps by grapheme
18280        // cluster, so those are its boundaries.
18281        for (off, _) in src
18282            .grapheme_indices(true)
18283            .chain(std::iter::once((src.len(), "")))
18284        {
18285            d.caret = off;
18286            let (row, col) = d.caret_pos();
18287            d.click(row, col, false);
18288            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
18289        }
18290
18291        // And in WYSIWYG, where the offsets the caret can occupy are the map's
18292        // stops rather than every boundary.
18293        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
18294        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18295        assert!(stops.len() > 20, "fixture should have plenty of stops");
18296        for off in stops {
18297            d.caret = off;
18298            let (row, col) = d.caret_pos();
18299            d.click(row, col, false);
18300            assert_eq!(
18301                d.caret, off,
18302                "wysiwyg: {off} → ({row}, {col}) → {}",
18303                d.caret
18304            );
18305        }
18306    }
18307
18308    #[test]
18309    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
18310        // Down from under `世` lands under the glyph in that cell, not two
18311        // characters further along the line. The goal is a column, so a line of
18312        // wide characters and a line of ASCII line up the way they're drawn.
18313        //
18314        // The gap differs by view: a bare newline inside a paragraph is a soft
18315        // break, which WYSIWYG draws as a space on a single row. The views share
18316        // a grid only where the source's lines are the renderer's rows too.
18317        for (view, tag) in VIEWS {
18318            let gap = if view == View::Source { "\n" } else { "\n\n" };
18319            let src = format!("你好世{gap}abcdef\n");
18320            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
18321            d.caret = "你好".len();
18322            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
18323            d.move_down(false);
18324            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
18325            assert!(
18326                d.source[d.caret..].starts_with('e'),
18327                "{tag}: landed on the wrong glyph"
18328            );
18329        }
18330    }
18331
18332    #[test]
18333    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
18334        // Down from column 3 onto `你好`, whose characters start at columns 0
18335        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
18336        // between the cells of one character, so the caret rests on it — and on
18337        // its start, which is the only offset there that is a caret stop.
18338        for (view, tag) in VIEWS {
18339            let gap = if view == View::Source { "\n" } else { "\n\n" };
18340            let src = format!("abcdef{gap}你好\n");
18341            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
18342            let line = src.find('你').unwrap();
18343            d.caret = 3;
18344            d.move_down(false);
18345            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
18346            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
18347        }
18348    }
18349
18350    #[test]
18351    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
18352        // The column the cell's text is laid out in is measured in cells, so the
18353        // caret walking that text has to be too — the two agreeing is the whole
18354        // point of the grid staying square.
18355        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
18356        let at = d.source.find("你").unwrap();
18357        d.caret = at;
18358        let (row, col) = d.caret_pos();
18359        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
18360        // cells further along.
18361        assert_eq!(col, 2, "the cell's first character");
18362        d.move_right(false);
18363        assert_eq!(
18364            d.caret_pos(),
18365            (row, 4),
18366            "`好` is drawn past `你`'s two cells"
18367        );
18368        assert_eq!(d.caret, at + "你".len());
18369    }
18370
18371    // ── active inline marks ───────────────────────────────────────────────────
18372
18373    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
18374    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
18375        let (src, caret) = parse_caret(marked);
18376        let mut d = doc_in(view, name, &src);
18377        d.caret = caret;
18378        d.active_inline_marks().iter().collect()
18379    }
18380
18381    /// The marks over the selection `[start, end)`.
18382    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
18383        let mut d = doc_in(view, name, src);
18384        d.anchor = Some(start);
18385        d.caret = end;
18386        d.active_inline_marks().iter().collect()
18387    }
18388
18389    #[test]
18390    fn a_caret_in_a_mark_reports_it() {
18391        for (view, tag) in VIEWS {
18392            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
18393            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
18394            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
18395            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
18396            // Plain text under no mark lights nothing — the toolbar's resting state.
18397            assert_eq!(m("a| **bold** b"), [], "{tag}");
18398            assert!(m("plain t|ext").is_empty(), "{tag}");
18399        }
18400    }
18401
18402    #[test]
18403    fn nested_marks_all_report() {
18404        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
18405        // the ancestor chain is a chain, and every mark on it is in force.
18406        for (view, tag) in VIEWS {
18407            assert_eq!(
18408                marks(
18409                    view,
18410                    &format!("marks_nested_{tag}"),
18411                    "**bold and *bo|th*** end"
18412                ),
18413                [InlineKind::Strong, InlineKind::Emph],
18414                "{tag}"
18415            );
18416        }
18417    }
18418
18419    #[test]
18420    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
18421        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
18422        // the first byte of its text and the byte after its last — both inside
18423        // the mark's span, both places typing lands inside the bold. The offset
18424        // past the closing delimiter is the next text, and reports nothing.
18425        let src = "a **bold** b";
18426        let inner_start = src.find("bold").unwrap(); // 4
18427        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
18428        for (view, tag) in VIEWS {
18429            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
18430            for off in [2, 3, inner_start, inner_end, 9] {
18431                d.caret = off;
18432                assert!(
18433                    d.active_inline_marks().contains(InlineKind::Strong),
18434                    "{tag}: offset {off} is inside the strong span"
18435                );
18436            }
18437            for off in [0, 1, 10, 11, 12] {
18438                d.caret = off;
18439                assert!(
18440                    !d.active_inline_marks().contains(InlineKind::Strong),
18441                    "{tag}: offset {off} is outside the strong run"
18442                );
18443            }
18444        }
18445    }
18446
18447    #[test]
18448    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
18449        // Regression: twig resolves an offset that is one node's end and the
18450        // next one's start to the node that *starts* there, so `**bold**|\n`
18451        // isn't bold. With nothing following there's no tie to break and the
18452        // chain still ended at the mark, which made a trailing `\n` — not the
18453        // text — decide whether the caret after a bold word reported bold. It's
18454        // the offset past the mark either way, and typing there is plain either
18455        // way. A blank document typed into is exactly this shape.
18456        for (view, tag) in VIEWS {
18457            let m = |name: String, marked| marks(view, &name, marked);
18458            assert_eq!(
18459                m(format!("marks_eob_{tag}"), "**bold**|"),
18460                [],
18461                "{tag}: no trailing newline"
18462            );
18463            assert_eq!(
18464                m(format!("marks_eol_{tag}"), "**bold**|\n"),
18465                [],
18466                "{tag}: with one"
18467            );
18468            // And the last offset that *is* in the mark still is.
18469            assert_eq!(
18470                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
18471                [InlineKind::Strong],
18472                "{tag}"
18473            );
18474        }
18475    }
18476
18477    #[test]
18478    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
18479        let src = "a **bold** b";
18480        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
18481        for (view, tag) in VIEWS {
18482            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
18483            // The whole bold word, and a slice of it.
18484            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
18485            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
18486            // Ending exactly at the closing delimiter's start is still all-bold:
18487            // an exclusive end sits *past* the last selected character, so the
18488            // question is asked of the character, not the boundary.
18489            assert_eq!(
18490                m(b, d_ + 2),
18491                [InlineKind::Strong],
18492                "{tag}: through the close"
18493            );
18494            // Half in, half out: Bold lit here would claim a press turns it off.
18495            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
18496            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
18497        }
18498    }
18499
18500    #[test]
18501    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
18502        // Both ends are bold, but the space between them isn't — two runs are two
18503        // nodes, which is exactly what the node id catches and a kind-only
18504        // comparison would not.
18505        let src = "**one** **two**";
18506        for (view, tag) in VIEWS {
18507            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
18508            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
18509        }
18510    }
18511
18512    #[test]
18513    fn marks_read_the_document_as_it_is_edited() {
18514        // The point of asking twig every frame instead of caching: the answer has
18515        // to follow the toggle that changed it.
18516        let mut d = wysiwyg_doc("marks_live", "one two\n");
18517        d.anchor = Some(0);
18518        d.caret = 3;
18519        assert!(d.active_inline_marks().is_empty(), "plain to start");
18520        d.toggle(InlineKind::Strong);
18521        assert_eq!(d.source, "**one** two\n");
18522        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
18523        assert!(d.active_inline_marks().contains(InlineKind::Strong));
18524        d.toggle(InlineKind::Strong);
18525        assert!(d.active_inline_marks().is_empty(), "and off again");
18526    }
18527
18528    #[test]
18529    fn a_link_is_not_an_inline_mark() {
18530        // `link`/`str` are inline nodes, but nothing on the inline toolbar
18531        // toggles them — a set with a "link mark" in it would have no button.
18532        for (view, tag) in VIEWS {
18533            assert_eq!(
18534                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
18535                [],
18536                "{tag}"
18537            );
18538        }
18539    }
18540
18541    // ── blank documents ───────────────────────────────────────────────────────
18542
18543    #[test]
18544    fn a_blank_document_is_untitled_empty_and_markdown() {
18545        let mut d = Doc::blank().unwrap();
18546        assert!(d.is_untitled());
18547        assert_eq!(d.path, PathBuf::new());
18548        assert_eq!(
18549            d.file_name(),
18550            "untitled",
18551            "the header has to show something"
18552        );
18553        assert_eq!(d.format_name(), "markdown");
18554        assert_eq!(d.source, "");
18555        assert!(!d.dirty, "nothing typed yet is nothing to lose");
18556        assert_eq!(d.disk_state(), DiskState::Untitled);
18557        // And it's a document you can be in: the default view renders it.
18558        d.build_visual(80);
18559        assert_eq!(d.caret, 0);
18560    }
18561
18562    #[test]
18563    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
18564        let mut d = Doc::blank().unwrap();
18565        d.insert("hello");
18566        assert!(d.dirty);
18567        d.save();
18568        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
18569        assert!(d.dirty, "it must not come away believing it saved");
18570        assert!(d.is_untitled(), "and it still has no file");
18571    }
18572
18573    #[test]
18574    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
18575        let p = temp_path("blank_save_as");
18576        let mut d = Doc::blank().unwrap();
18577        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
18578        // be kept literal (`\#`); this test is about save-as, not escaping (which
18579        // has its own test), so it types nothing that escaping would touch.
18580        d.insert("hi");
18581        d.save_as(p.clone());
18582        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
18583        assert!(!d.is_untitled());
18584        assert!(!d.dirty);
18585        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
18586        assert_eq!(
18587            d.disk_state(),
18588            DiskState::Unchanged,
18589            "the watermark is stamped"
18590        );
18591        // And ⌘S is a plain save from here on.
18592        d.insert("!");
18593        d.save();
18594        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
18595        let _ = std::fs::remove_file(&p);
18596    }
18597
18598    // ── a file that isn't there yet ───────────────────────────────────────────
18599
18600    /// A unique path in the temp dir with the given extension, guaranteed not to
18601    /// exist — what `leaf notes.md` is handed when the file has never been made.
18602    fn missing_path(name: &str, ext: &str) -> PathBuf {
18603        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18604        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18605        let mut p = std::env::temp_dir();
18606        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
18607        let _ = std::fs::remove_file(&p);
18608        p
18609    }
18610
18611    #[test]
18612    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
18613        let p = missing_path("named", "md");
18614        let mut d = Doc::open_or_create(p.clone()).unwrap();
18615
18616        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
18617        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
18618        assert!(
18619            !d.is_untitled(),
18620            "it has the name the user asked for — ^S must not detour to Save As"
18621        );
18622        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
18623        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
18624        assert!(!p.exists(), "and opening it wrote nothing");
18625        // And it's a document you can be in.
18626        d.build_visual(80);
18627        assert_eq!(d.caret, 0);
18628    }
18629
18630    #[test]
18631    fn a_new_file_is_created_by_its_first_save() {
18632        let p = missing_path("first_save", "md");
18633        let mut d = Doc::open_or_create(p.clone()).unwrap();
18634        d.insert("hello\n");
18635        assert!(d.dirty);
18636        d.save();
18637
18638        assert_eq!(
18639            std::fs::read_to_string(&p).unwrap(),
18640            "hello\n",
18641            "a plain ^S wrote it — no Save As, no name to invent"
18642        );
18643        assert!(!d.dirty);
18644        assert_eq!(d.disk_state(), DiskState::Unchanged);
18645        let _ = std::fs::remove_file(&p);
18646    }
18647
18648    #[test]
18649    fn a_new_file_takes_its_format_from_the_extension() {
18650        // The one thing `blank` can't do: with no name it has to assume Markdown,
18651        // and typing djot into a Markdown parse is the wrong buffer.
18652        let dj = missing_path("format", "dj");
18653        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
18654        let md = missing_path("format", "md");
18655        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
18656    }
18657
18658    #[test]
18659    fn a_new_file_reports_itself_missing_until_it_is_saved() {
18660        // Not `Untitled` — that's the answer for a document with no path, and it
18661        // would tell a frontend there is nothing a save could collide with. Here
18662        // there is a path, and the file simply isn't at it yet.
18663        let p = missing_path("disk_state", "md");
18664        let mut d = Doc::open_or_create(p.clone()).unwrap();
18665        assert_eq!(d.disk_state(), DiskState::Missing);
18666
18667        // Somebody else creates it while the buffer is open: that's an overwrite
18668        // the frontend has to be able to prompt about, exactly as for an opened
18669        // file. Their bytes, not ours, so `Changed`.
18670        std::fs::write(&p, "theirs\n").unwrap();
18671        assert_eq!(d.disk_state(), DiskState::Changed);
18672
18673        // Saving makes the file ours and re-stamps the watermark.
18674        d.insert("ours\n");
18675        d.save();
18676        assert_eq!(d.disk_state(), DiskState::Unchanged);
18677        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
18678        let _ = std::fs::remove_file(&p);
18679    }
18680
18681    #[test]
18682    fn open_or_create_still_opens_a_file_that_is_there() {
18683        let d = doc_with("open_or_create_existing", "body\n");
18684        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
18685        assert_eq!(reopened.source, "body\n");
18686        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
18687    }
18688
18689    #[test]
18690    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
18691        // A mistyped flag or a stray argument must not become a buffer promising
18692        // to save somewhere — the same refusal `open` gives a real file.
18693        let mut p = std::env::temp_dir();
18694        p.push("leaf_test_new_bad_ext.wat");
18695        assert!(Doc::open_or_create(p).is_err());
18696        let mut none = std::env::temp_dir();
18697        none.push("leaf_test_new_no_ext");
18698        assert!(Doc::open_or_create(none).is_err());
18699    }
18700
18701    #[test]
18702    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
18703        // Opening reads nothing, so there is nothing to fail on yet; the write is
18704        // where it fails, and it says so rather than claiming a save.
18705        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
18706        let mut d = Doc::open_or_create(p).unwrap();
18707        d.insert("x");
18708        d.save();
18709        assert!(
18710            d.status.as_deref().unwrap().starts_with("save failed:"),
18711            "got {:?}",
18712            d.status
18713        );
18714        assert!(d.dirty, "it must not come away believing it saved");
18715    }
18716
18717    // ── save as ───────────────────────────────────────────────────────────────
18718
18719    /// A unique path in the temp dir that no fixture wrote — a Save As target.
18720    fn temp_path(name: &str) -> PathBuf {
18721        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18722        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18723        let mut p = std::env::temp_dir();
18724        p.push(format!("leaf_test_target_{name}_{seq}.md"));
18725        let _ = std::fs::remove_file(&p);
18726        p
18727    }
18728
18729    #[test]
18730    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
18731        let mut d = doc_with("save_as_move", "original\n");
18732        let old = d.path.clone();
18733        let new = temp_path("save_as_move");
18734        d.insert("edited: ");
18735        d.save_as(new.clone());
18736
18737        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
18738        assert_eq!(
18739            std::fs::read_to_string(&old).unwrap(),
18740            "original\n",
18741            "Save As doesn't touch the file it came from"
18742        );
18743        assert_eq!(d.path, new, "the document moved");
18744        assert!(!d.dirty);
18745        assert_eq!(
18746            d.status.as_deref(),
18747            Some(&*format!("saved {}", d.file_name()))
18748        );
18749
18750        // Every later save follows it, which is the whole difference from a copy.
18751        d.caret = 0;
18752        d.insert("re-");
18753        d.save();
18754        assert_eq!(
18755            std::fs::read_to_string(&new).unwrap(),
18756            "re-edited: original\n"
18757        );
18758        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
18759        let _ = std::fs::remove_file(&new);
18760    }
18761
18762    #[test]
18763    fn save_as_overwrites_an_existing_target() {
18764        // The picker already asked; asking again down here is the same question
18765        // twice, and the second one has no way to be answered.
18766        let new = temp_path("save_as_over");
18767        std::fs::write(&new, "theirs\n").unwrap();
18768        let mut d = doc_with("save_as_over", "ours\n");
18769        d.save_as(new.clone());
18770        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
18771        let _ = std::fs::remove_file(&new);
18772    }
18773
18774    #[test]
18775    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
18776        let mut d = doc_with("save_as_fail", "body\n");
18777        let old = d.path.clone();
18778        d.insert("x");
18779        // A directory that doesn't exist: the write can't land.
18780        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
18781        d.save_as(bad);
18782
18783        assert_eq!(
18784            d.path, old,
18785            "the document must not move to a file that isn't there"
18786        );
18787        assert!(d.dirty, "and must not believe it saved");
18788        assert!(
18789            d.status.as_deref().unwrap().starts_with("save failed:"),
18790            "the same failure a plain save reports, got {:?}",
18791            d.status
18792        );
18793        // The original is still the document's file, and still saveable.
18794        d.save();
18795        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
18796        assert!(!d.dirty);
18797    }
18798
18799    #[test]
18800    fn save_as_renames_without_reparsing_the_format() {
18801        // `.dj` on the name doesn't make the buffer djot: it was parsed as
18802        // Markdown and still is, and saying otherwise would be a conversion the
18803        // user never asked for (and an undo history thrown away to do it).
18804        let mut d = doc_with("save_as_format", "**b**\n");
18805        let mut new = temp_path("save_as_format");
18806        new.set_extension("dj");
18807        d.save_as(new.clone());
18808        assert_eq!(d.format_name(), "markdown");
18809        let _ = std::fs::remove_file(&new);
18810    }
18811
18812    // ── external change / reload ──────────────────────────────────────────────
18813
18814    #[test]
18815    fn an_untouched_file_reports_unchanged() {
18816        let mut d = doc_with("disk_clean", "body\n");
18817        assert_eq!(d.disk_state(), DiskState::Unchanged);
18818        // Editing the buffer is not editing the file.
18819        d.insert("x");
18820        assert_eq!(d.disk_state(), DiskState::Unchanged);
18821        assert!(d.dirty);
18822        // Saving re-stamps the watermark rather than reporting our own bytes back.
18823        d.save();
18824        assert_eq!(d.disk_state(), DiskState::Unchanged);
18825    }
18826
18827    #[test]
18828    fn a_file_written_underneath_reports_changed() {
18829        let mut d = doc_with("disk_changed", "body\n");
18830        std::fs::write(&d.path, "someone else\n").unwrap();
18831        assert_eq!(d.disk_state(), DiskState::Changed);
18832        // Dirty *and* changed is the clobber: both halves are readable, and
18833        // leaf-core takes neither side.
18834        d.insert("x");
18835        assert!(d.dirty && d.disk_state() == DiskState::Changed);
18836        // Saving anyway is allowed — the frontend asked, or chose not to.
18837        d.save();
18838        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
18839        assert_eq!(d.disk_state(), DiskState::Unchanged);
18840    }
18841
18842    #[test]
18843    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
18844        // The hash is what makes this honest: the file was written (a fresh
18845        // mtime), and nothing about the document is stale.
18846        let d = doc_with("disk_same_bytes", "body\n");
18847        std::fs::write(&d.path, "body\n").unwrap();
18848        assert_eq!(d.disk_state(), DiskState::Unchanged);
18849    }
18850
18851    #[test]
18852    fn a_deleted_file_reports_missing() {
18853        let mut d = doc_with("disk_missing", "body\n");
18854        std::fs::remove_file(&d.path).unwrap();
18855        assert_eq!(d.disk_state(), DiskState::Missing);
18856        // A save recreates it, and the document is whole again.
18857        d.save();
18858        assert_eq!(d.disk_state(), DiskState::Unchanged);
18859        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
18860    }
18861
18862    #[test]
18863    fn reload_replaces_the_document_with_the_file() {
18864        for (view, tag) in VIEWS {
18865            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
18866            d.insert("edited ");
18867            assert!(d.dirty);
18868            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
18869            d.reload();
18870
18871            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
18872            assert!(!d.dirty, "{tag}: the file is what we have");
18873            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
18874            assert_eq!(
18875                d.status.as_deref(),
18876                Some(&*format!("reloaded {}", d.file_name()))
18877            );
18878            // The reloaded tree is live, not the old parse.
18879            d.caret = d.source.find("three").unwrap();
18880            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
18881        }
18882    }
18883
18884    #[test]
18885    fn reload_clamps_the_caret_and_drops_the_selection() {
18886        let mut d = doc_with("reload_caret", "a long first line\n");
18887        d.caret = 12;
18888        d.anchor = Some(4);
18889        std::fs::write(&d.path, "short\n").unwrap();
18890        d.reload();
18891        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
18892        assert_eq!(
18893            d.anchor, None,
18894            "a selection over bytes that changed is a lie"
18895        );
18896        assert!(d.selection().is_none());
18897
18898        // A caret the file still has room for stays put.
18899        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
18900        d.caret = 2;
18901        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
18902        d.reload();
18903        assert_eq!(d.caret, 2);
18904    }
18905
18906    /// A silent reload is something that happened *to* a reader — a formatter,
18907    /// a `git checkout` — so it has to be undoable like anything else that
18908    /// changes the document, and undoable as one step rather than as however
18909    /// many the file happens to differ by.
18910    #[test]
18911    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
18912        let mut d = doc_with("reload_undo", "body\n");
18913        d.insert("x");
18914        assert_eq!(d.source, "xbody\n");
18915        std::fs::write(&d.path, "replaced\n").unwrap();
18916        d.reload();
18917        assert_eq!(d.source, "replaced\n");
18918        assert!(!d.dirty, "a reload lands clean");
18919
18920        // One ^Z takes the whole swap off, and hands back the unsaved work it
18921        // replaced — which is unsaved again, because the file no longer says it.
18922        d.undo();
18923        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
18924        assert!(d.dirty, "and what it comes back to is unsaved");
18925        // …and the history under it is still there.
18926        d.undo();
18927        assert_eq!(
18928            d.source, "body\n",
18929            "the typing before the reload undoes too"
18930        );
18931        // Redo walks back up through the reload.
18932        d.redo();
18933        d.redo();
18934        assert_eq!(d.source, "replaced\n");
18935    }
18936
18937    /// A file rewritten with the bytes it already had is not an edit, so it
18938    /// must not leave an undo step behind for something nobody did.
18939    #[test]
18940    fn reloading_identical_bytes_pushes_no_undo_step() {
18941        let mut d = doc_with("reload_same", "body\n");
18942        d.insert("x");
18943        std::fs::write(&d.path, "xbody\n").unwrap();
18944        d.reload();
18945        assert_eq!(d.source, "xbody\n");
18946        assert!(!d.dirty, "the file now says what the buffer does");
18947        d.undo();
18948        assert_eq!(
18949            d.source, "body\n",
18950            "one step back is the typing, not a no-op"
18951        );
18952    }
18953
18954    #[test]
18955    fn a_reload_that_cant_read_leaves_the_document_alone() {
18956        let mut d = doc_with("reload_gone", "body\n");
18957        d.insert("x");
18958        std::fs::remove_file(&d.path).unwrap();
18959        d.reload();
18960        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
18961        assert!(d.dirty);
18962        assert!(
18963            d.status.as_deref().unwrap().starts_with("reload failed:"),
18964            "{:?}",
18965            d.status
18966        );
18967
18968        // And an untitled document has nothing to reload from.
18969        let mut d = Doc::blank().unwrap();
18970        d.insert("typed");
18971        d.reload();
18972        assert_eq!(d.source, "typed");
18973        assert_eq!(d.status.as_deref(), Some("no file to reload"));
18974    }
18975
18976    #[test]
18977    fn a_read_only_document_refuses_every_door() {
18978        let mut d = doc_with("readonly", "one two three\n");
18979        d.insert("x");
18980        assert!(d.dirty, "writable first, so the undo step exists");
18981        d.set_read_only(true);
18982        let before = d.source.clone();
18983        d.insert("y");
18984        d.backspace();
18985        d.undo();
18986        d.redo();
18987        assert_eq!(d.source, before, "no door moved a byte");
18988        d.set_read_only(false);
18989        d.undo();
18990        assert_ne!(d.source, before, "off again, the same doors work");
18991    }
18992
18993    /// The doors that go to twig's own verbs rather than through the splice.
18994    /// Typed text in the rendered view under the default markup mode is the
18995    /// everyday one — it is what a keystroke in leaf-web or the Apple views
18996    /// becomes — and it walked straight past the gate.
18997    #[test]
18998    fn a_read_only_document_refuses_the_doors_around_the_splice() {
18999        let mut d = wysiwyg_doc(
19000            "readonly-doors",
19001            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
19002        );
19003        d.set_markup_mode(MarkupMode::None);
19004        d.set_read_only(true);
19005        let before = d.source.clone();
19006        d.place_caret(3, false);
19007        d.insert("y");
19008        d.insert_link("https://example.com");
19009        d.insert_image("a.png", "alt");
19010        d.insert_thematic_break();
19011        d.insert_footnote();
19012        d.place_caret(0, false);
19013        d.place_caret(3, true);
19014        d.toggle(InlineKind::Strong);
19015        d.toggle_heading(2);
19016        d.set_block(BlockKind::Paragraph);
19017        d.toggle_list(false);
19018        d.toggle_blockquote();
19019        d.toggle_task_item();
19020        d.newline();
19021        d.indent();
19022        d.set_code_language("rust");
19023        let in_cell = d.source.find("| c").unwrap() + 2;
19024        d.place_caret(in_cell, false);
19025        assert!(d.caret_in_table(), "the caret is in the grid");
19026        assert!(!d.cell_line_break(), "the cell break reports the refusal");
19027        assert_eq!(d.source, before, "no door moved a byte");
19028        assert!(!d.dirty, "nothing to save");
19029        d.set_read_only(false);
19030        d.place_caret(3, false);
19031        d.insert("y");
19032        assert_ne!(d.source, before, "off again, the same doors work");
19033    }
19034
19035    #[test]
19036    fn a_selection_quote_carries_its_context_on_char_boundaries() {
19037        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
19038        let start = d.source.find("exact").unwrap();
19039        d.place_caret(start, false);
19040        d.place_caret(start + "exact".len(), true);
19041        let q = d.selection_quote(3).unwrap();
19042        assert_eq!(q.exact, "exact");
19043        assert_eq!(
19044            q.prefix, "你好 ",
19045            "chars, not bytes — the multibyte pair counts as two"
19046        );
19047        assert_eq!(q.suffix, " 世界");
19048        assert_eq!(&d.source[q.start..q.end], "exact");
19049        // At the edges the context clips rather than erring.
19050        d.place_caret(0, false);
19051        d.place_caret(6, true);
19052        let q = d.selection_quote(40).unwrap();
19053        assert_eq!(q.prefix, "");
19054        assert_eq!(q.exact, "before");
19055        // No selection is no quote.
19056        d.place_caret(0, false);
19057        assert!(d.selection_quote(3).is_none());
19058    }
19059
19060    #[test]
19061    fn highlights_are_kept_sorted_and_answer_point_queries() {
19062        let mut d = doc_with("hl", "one two three\n");
19063        d.set_highlights(vec![
19064            Highlight {
19065                start: 8,
19066                end: 13,
19067                id: "b".into(),
19068                color: None,
19069                marker: None,
19070            },
19071            Highlight {
19072                start: 0,
19073                end: 3,
19074                id: "a".into(),
19075                color: Some("#ffe066".into()),
19076                marker: None,
19077            },
19078            Highlight {
19079                start: 5,
19080                end: 5,
19081                id: "empty".into(),
19082                color: None,
19083                marker: None,
19084            },
19085        ]);
19086        assert_eq!(
19087            d.highlights()
19088                .iter()
19089                .map(|h| h.id.as_str())
19090                .collect::<Vec<_>>(),
19091            ["a", "b"],
19092            "sorted by start, the empty range dropped"
19093        );
19094        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
19095        assert_eq!(d.highlight_at(3), None, "end is exclusive");
19096        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
19097        d.set_highlights(Vec::new());
19098        assert!(d.highlights().is_empty(), "a replace is a replace");
19099    }
19100
19101    /// `Highlight::covering` and the cursor over it are what both painters ask
19102    /// per glyph, so they have to answer the same as the scan they replaced —
19103    /// including in the gaps, which is where most glyphs are.
19104    #[test]
19105    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
19106        let hl = |start: usize, end: usize, id: &str| Highlight {
19107            start,
19108            end,
19109            id: id.into(),
19110            color: None,
19111            marker: None,
19112        };
19113        // Disjoint, as search hits are: in a range, in a gap, and past the end.
19114        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
19115        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
19116        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
19117        assert_eq!(
19118            Highlight::covering(&hits, 105),
19119            None,
19120            "a gap covers nothing"
19121        );
19122        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
19123        assert_eq!(Highlight::covering(&hits, 9_999), None);
19124        assert_eq!(Highlight::covering(&[], 0), None);
19125
19126        // Nested: first by start, so a hit inside an annotation still resolves
19127        // to the annotation — and the range that stops short doesn't mask it.
19128        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
19129        assert_eq!(
19130            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
19131            Some("outer")
19132        );
19133        assert_eq!(
19134            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
19135            Some("outer")
19136        );
19137    }
19138
19139    /// The cursor is an optimisation, so the only thing worth asserting is that
19140    /// it is not also a change of answer — at every offset, over a list with a
19141    /// nest in it, walked forwards and then backwards.
19142    #[test]
19143    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
19144        let hl = |start: usize, end: usize, id: &str| Highlight {
19145            start,
19146            end,
19147            id: id.into(),
19148            color: None,
19149            marker: None,
19150        };
19151        let mut list = vec![
19152            hl(0, 20, "outer"),
19153            hl(5, 10, "inner"),
19154            hl(30, 33, "hit"),
19155            hl(40, 43, "hit"),
19156        ];
19157        list.sort_by_key(|h| (h.start, h.end));
19158
19159        let mut cursor = HighlightCursor::new(&list);
19160        for offset in 0..50 {
19161            assert_eq!(
19162                cursor.at(offset).map(|h| h.id.as_str()),
19163                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19164                "cursor disagrees at {offset}"
19165            );
19166        }
19167        // Backwards: the cursor re-seats rather than answering from where it
19168        // had got to, so a painter that revisits a row is still told the truth.
19169        for offset in (0..50).rev() {
19170            assert_eq!(
19171                cursor.at(offset).map(|h| h.id.as_str()),
19172                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19173                "cursor disagrees walking back at {offset}"
19174            );
19175        }
19176    }
19177
19178    // ── the presentation vocabulary ─────────────────────────────────────────
19179
19180    /// A document in `format`, for the gesture tests that want more than the
19181    /// Markdown `doc_with` writes.
19182    fn fmt_doc(body: &str, format: Format) -> Doc {
19183        Doc::from_source(body.to_string(), format).unwrap()
19184    }
19185
19186    /// Alignment is a block property, so the gesture is `set_block_attrs` on
19187    /// the caret's block whatever is selected — and each format spells it its
19188    /// own way: djot's `{…}` line above the block, a `<div>` around it in
19189    /// Markdown (the format has nowhere else to put it), the tag in HTML.
19190    #[test]
19191    fn set_alignment_spells_the_class_the_format_s_own_way() {
19192        let mut dj = fmt_doc("hello\n", Format::Djot);
19193        dj.caret = 1;
19194        dj.set_alignment(Some(Align::Center));
19195        assert_eq!(dj.source, "{.center}\nhello\n");
19196        assert!(dj.dirty);
19197        assert_eq!(dj.status, None);
19198
19199        let mut md = fmt_doc("hello\n", Format::Markdown);
19200        md.caret = 1;
19201        md.set_alignment(Some(Align::Right));
19202        assert_eq!(md.source, "<div class=\"right\">\n\nhello\n\n</div>\n");
19203
19204        let mut html = fmt_doc("<p>hello</p>\n", Format::Html);
19205        html.caret = html.source.find("hello").unwrap();
19206        html.set_alignment(Some(Align::Justify));
19207        assert_eq!(html.source, "<p class=\"justify\">hello</p>\n");
19208    }
19209
19210    /// Each gesture edits **one key and keeps the rest** — twig's contract is
19211    /// replace-not-merge, so leaf reads the node's attributes, edits its own
19212    /// key out of them, and passes the list back whole. A document from
19213    /// elsewhere passes through the editor unharmed.
19214    #[test]
19215    fn a_presentation_gesture_keeps_every_attribute_it_did_not_write() {
19216        let mut d = fmt_doc(
19217            "{.lead .center #intro data-line-height=\"1.5\"}\nhello\n",
19218            Format::Djot,
19219        );
19220        d.caret = d.source.find("hello").unwrap();
19221        d.set_alignment(Some(Align::Right));
19222        // `center` goes, `lead` stays, and neither the id nor the spacing is
19223        // touched.
19224        // The serializer picks the order; what matters is which keys survive.
19225        assert!(d.source.contains(".lead"), "{:?}", d.source);
19226        assert!(d.source.contains(".right"), "{:?}", d.source);
19227        assert!(!d.source.contains(".center"), "{:?}", d.source);
19228        assert!(d.source.contains("#intro"), "{:?}", d.source);
19229        assert!(
19230            d.source.contains("data-line-height=\"1.5\""),
19231            "{:?}",
19232            d.source
19233        );
19234        assert_eq!(d.alignment_at_caret(), Some(Align::Right));
19235        assert_eq!(
19236            d.line_spacing_at_caret(),
19237            Some(LineHeight::Step(LineSpacing::OneHalf))
19238        );
19239
19240        // And the other way round: the spacing gesture leaves the classes be.
19241        d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19242        assert!(d.source.contains(".lead"), "{:?}", d.source);
19243        assert!(d.source.contains(".right"), "{:?}", d.source);
19244        assert_eq!(
19245            d.line_spacing_at_caret(),
19246            Some(LineHeight::Step(LineSpacing::Double))
19247        );
19248    }
19249
19250    /// Clearing is the same gesture with `None`: the key goes, the tokens leaf
19251    /// owns go out of `class`, and a block left with nothing at all is spelled
19252    /// bare again — in Markdown by unwrapping the div twig wrapped it in.
19253    #[test]
19254    fn none_clears_a_key_and_an_empty_set_unwraps_the_block() {
19255        let mut dj = fmt_doc("{.lead .center}\nhello\n", Format::Djot);
19256        dj.caret = dj.source.find("hello").unwrap();
19257        dj.set_alignment(None);
19258        assert_eq!(dj.source, "{.lead}\nhello\n", "the foreign class stays");
19259        assert_eq!(dj.alignment_at_caret(), None);
19260
19261        let mut bare = fmt_doc("{.center}\nhello\n", Format::Djot);
19262        bare.caret = bare.source.find("hello").unwrap();
19263        bare.set_alignment(None);
19264        assert_eq!(
19265            bare.source, "hello\n",
19266            "the last key takes the line with it"
19267        );
19268
19269        let mut md = fmt_doc("hello\n", Format::Markdown);
19270        md.caret = 1;
19271        md.set_alignment(Some(Align::Center));
19272        assert_eq!(md.source, "<div class=\"center\">\n\nhello\n\n</div>\n");
19273        md.caret = md.source.find("hello").unwrap();
19274        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::OneFifteen)));
19275        assert_eq!(
19276            md.source, "<div class=\"center\" data-line-height=\"1.15\">\n\nhello\n\n</div>\n",
19277            "the second key rewrites the div rather than nesting a second"
19278        );
19279        md.caret = md.source.find("hello").unwrap();
19280        md.set_alignment(None);
19281        md.caret = md.source.find("hello").unwrap();
19282        md.set_line_spacing(None);
19283        assert_eq!(md.source, "hello\n", "an empty set unwraps the div");
19284    }
19285
19286    /// Size, face and colour are the run's over a selection and the block's
19287    /// with none — so "make this paragraph larger" is a click with the caret in
19288    /// it rather than a select-all first.
19289    #[test]
19290    fn a_run_gesture_wraps_a_selection_and_sets_the_block_without_one() {
19291        // With a selection: a span, in each format's own spelling.
19292        let mut dj = fmt_doc("a big b\n", Format::Djot);
19293        dj.anchor = Some(2);
19294        dj.caret = 5;
19295        dj.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19296        assert_eq!(dj.source, "a [big]{data-size=\"large\"} b\n");
19297        assert_eq!(
19298            dj.font_size_at_caret(),
19299            Some(FontSize::Step(SizeStep::Large))
19300        );
19301
19302        let mut md = fmt_doc("a big b\n", Format::Markdown);
19303        md.anchor = Some(2);
19304        md.caret = 5;
19305        md.set_text_color(Some(TextColor::Named(MarkColor::Blue)));
19306        assert_eq!(md.source, "a <span data-color=\"blue\">big</span> b\n");
19307        assert_eq!(
19308            md.text_color_at_caret(),
19309            Some(TextColor::Named(MarkColor::Blue))
19310        );
19311
19312        // Without one: the caret's block, through the block gesture.
19313        let mut block = fmt_doc("a big b\n", Format::Djot);
19314        block.caret = 3;
19315        block.set_font_family(Some(FontFace::Generic(FontFamily::Monospace)));
19316        assert_eq!(block.source, "{data-font=\"monospace\"}\na big b\n");
19317        assert_eq!(
19318            block.font_family_at_caret(),
19319            Some(FontFace::Generic(FontFamily::Monospace))
19320        );
19321    }
19322
19323    /// The *Other…* row of each of the four menus: a value goes into the
19324    /// document in its canonical spelling and comes back out of the query as
19325    /// the same value. One round trip per property, because the four go out
19326    /// through different doors — two block gestures, and the run three through
19327    /// the span that `wrap_range_attrs` mints.
19328    #[test]
19329    fn an_exact_value_round_trips_through_the_gesture_and_the_query() {
19330        // Size: the run three, over a selection.
19331        let mut d = fmt_doc("a big b\n", Format::Djot);
19332        d.anchor = Some(2);
19333        d.caret = 5;
19334        d.set_font_size(FontSize::points(14.0));
19335        assert_eq!(d.source, "a [big]{data-size=\"14pt\"} b\n");
19336        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19337
19338        // Colour, onto the same span — the gesture keeps the size it finds.
19339        d.set_text_color(Some(TextColor::Rgb {
19340            r: 0xc0,
19341            g: 0x30,
19342            b: 0x30,
19343        }));
19344        assert_eq!(
19345            d.source,
19346            "a [big]{data-size=\"14pt\" data-color=\"#c03030\"} b\n"
19347        );
19348        assert_eq!(
19349            d.text_color_at_caret(),
19350            Some(TextColor::Rgb {
19351                r: 0xc0,
19352                g: 0x30,
19353                b: 0x30
19354            })
19355        );
19356
19357        // Face: a family name, as given.
19358        d.set_font_family(Some(FontFace::Named("Garamond".into())));
19359        assert!(
19360            d.source.contains("data-font=\"Garamond\""),
19361            "{:?}",
19362            d.source
19363        );
19364        assert_eq!(
19365            d.font_family_at_caret(),
19366            Some(FontFace::Named("Garamond".into()))
19367        );
19368
19369        // Line spacing: a block gesture, and an exact ratio.
19370        let mut block = fmt_doc("hello\n", Format::Djot);
19371        block.caret = 1;
19372        block.set_line_spacing(LineHeight::ratio(1.3));
19373        assert_eq!(block.source, "{data-line-height=\"1.3\"}\nhello\n");
19374        assert_eq!(block.line_spacing_at_caret(), LineHeight::ratio(1.3));
19375
19376        // And a value spelled long is written back short, so the same press
19377        // twice writes the same bytes: `14.0pt` in, `14pt` out.
19378        let mut long = fmt_doc("{data-size=\"14.0pt\"}\nhello\n", Format::Djot);
19379        long.caret = long.source.find("hello").unwrap();
19380        assert_eq!(long.font_size_at_caret(), FontSize::points(14.0));
19381        let in_force = long.font_size_at_caret();
19382        long.set_font_size(in_force);
19383        assert_eq!(long.source, "{data-size=\"14pt\"}\nhello\n");
19384    }
19385
19386    /// A value the grammar does not cover is what it was before the vocabulary
19387    /// opened: carried untouched by the document, answered `None` by the query
19388    /// so the menu ticks *Default*, and rewritten only by a gesture on its own
19389    /// key. leaf is not going to grow a CSS parser to guess at `1.3em`.
19390    #[test]
19391    fn a_value_outside_the_grammar_is_carried_and_the_menu_ticks_the_default() {
19392        let src =
19393            "{data-size=\"huge\" data-color=\"rgb(1,2,3)\" data-line-height=\"1.3em\"}\nhello\n";
19394        let mut d = fmt_doc(src, Format::Djot);
19395        d.caret = d.source.find("hello").unwrap();
19396        assert_eq!(d.font_size_at_caret(), None);
19397        assert_eq!(d.text_color_at_caret(), None);
19398        assert_eq!(d.line_spacing_at_caret(), None);
19399
19400        // The keys are still there, untouched, after a gesture on a *different*
19401        // key — "edit one key and keep the rest" holds for a value it cannot
19402        // read as readily as for one it can.
19403        d.set_alignment(Some(Align::Center));
19404        assert!(d.source.contains("data-size=\"huge\""), "{:?}", d.source);
19405        assert!(
19406            d.source.contains("data-color=\"rgb(1,2,3)\""),
19407            "{:?}",
19408            d.source
19409        );
19410        assert!(
19411            d.source.contains("data-line-height=\"1.3em\""),
19412            "{:?}",
19413            d.source
19414        );
19415        // And the gesture on its *own* key replaces it, which is the one way a
19416        // carried value ever changes.
19417        d.caret = d.source.find("hello").unwrap();
19418        d.set_font_size(FontSize::points(12.0));
19419        assert!(d.source.contains("data-size=\"12pt\""), "{:?}", d.source);
19420        assert!(!d.source.contains("huge"), "{:?}", d.source);
19421    }
19422
19423    /// The nearest node wins whichever *form* either node wrote: a value inside
19424    /// a name, a name inside a value. The fold has one rule and does not learn
19425    /// a second one for exact values.
19426    #[test]
19427    fn the_nearest_node_wins_whether_it_named_a_size_or_measured_one() {
19428        // A value inside a name: the block says `small`, the span says `14pt`.
19429        let mut d = fmt_doc(
19430            "{data-size=\"small\"}\nx [y]{data-size=\"14pt\"} z\n",
19431            Format::Djot,
19432        );
19433        d.caret = d.source.find('y').unwrap();
19434        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19435        d.caret = d.source.find('x').unwrap();
19436        assert_eq!(
19437            d.font_size_at_caret(),
19438            Some(FontSize::Step(SizeStep::Small))
19439        );
19440
19441        // And a name inside a value, which is the same rule read the other way.
19442        let mut e = fmt_doc(
19443            "{data-size=\"14pt\" data-color=\"#c03030\"}\nx [y]{data-size=\"small\"} z\n",
19444            Format::Djot,
19445        );
19446        e.caret = e.source.find('y').unwrap();
19447        assert_eq!(
19448            e.font_size_at_caret(),
19449            Some(FontSize::Step(SizeStep::Small))
19450        );
19451        assert_eq!(
19452            e.text_color_at_caret(),
19453            Some(TextColor::Rgb {
19454                r: 0xc0,
19455                g: 0x30,
19456                b: 0x30
19457            }),
19458            "the block's colour still reaches the span"
19459        );
19460        e.caret = e.source.find('x').unwrap();
19461        assert_eq!(e.font_size_at_caret(), FontSize::points(14.0));
19462    }
19463
19464    /// twig re-styles the span a range already lies in rather than nesting a
19465    /// second, and an empty set unwraps it — so a second press of the menu
19466    /// fixes the size instead of building `[[big]{.a}]{.b}`, and the entry that
19467    /// means "the theme's own" takes the span away.
19468    #[test]
19469    fn a_second_run_gesture_re_styles_the_span_and_none_unwraps_it() {
19470        let mut d = fmt_doc("a big b\n", Format::Djot);
19471        d.anchor = Some(2);
19472        d.caret = 5;
19473        d.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19474        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19475
19476        // The selection `wrap_range_attrs` left behind covers the whole span;
19477        // colouring it now keeps the size, because the gesture reads the span's
19478        // attributes before it edits its own key.
19479        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19480        assert_eq!(
19481            d.source, "a [big]{data-size=\"large\" data-color=\"red\"} b\n",
19482            "one span, both keys"
19483        );
19484        assert_eq!(
19485            d.font_size_at_caret(),
19486            Some(FontSize::Step(SizeStep::Large))
19487        );
19488        assert_eq!(
19489            d.text_color_at_caret(),
19490            Some(TextColor::Named(MarkColor::Red))
19491        );
19492
19493        d.set_text_color(None);
19494        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19495        d.set_font_size(None);
19496        assert_eq!(d.source, "a big b\n", "the last key unwraps the span");
19497        assert_eq!(d.font_size_at_caret(), None);
19498    }
19499
19500    /// The queries read the nearest node that names the property: the span the
19501    /// caret is in, then its block, then the `div`s around it.
19502    #[test]
19503    fn a_presentation_query_reads_the_nearest_node_that_names_it() {
19504        let mut d = fmt_doc(
19505            "{.center data-size=\"small\" data-font=\"serif\"}\nx [y]{data-size=\"xx-large\"} z\n",
19506            Format::Djot,
19507        );
19508        // In the span: its own size, the block's face and alignment.
19509        d.caret = d.source.find('y').unwrap();
19510        assert_eq!(
19511            d.font_size_at_caret(),
19512            Some(FontSize::Step(SizeStep::XxLarge))
19513        );
19514        assert_eq!(
19515            d.font_family_at_caret(),
19516            Some(FontFace::Generic(FontFamily::Serif))
19517        );
19518        assert_eq!(d.alignment_at_caret(), Some(Align::Center));
19519        assert_eq!(d.line_spacing_at_caret(), None);
19520        assert_eq!(d.text_color_at_caret(), None);
19521
19522        // Outside it: the block's size.
19523        d.caret = d.source.find('x').unwrap();
19524        assert_eq!(
19525            d.font_size_at_caret(),
19526            Some(FontSize::Step(SizeStep::Small))
19527        );
19528
19529        // And through a Markdown div, which is where a Markdown block's
19530        // attributes live.
19531        let mut md = fmt_doc(
19532            "<div class=\"center\" data-size=\"large\">\n\nhello\n\n</div>\n",
19533            Format::Markdown,
19534        );
19535        md.caret = md.source.find("hello").unwrap();
19536        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19537        assert_eq!(
19538            md.font_size_at_caret(),
19539            Some(FontSize::Step(SizeStep::Large))
19540        );
19541
19542        // A document that names none of it answers `None` everywhere, which is
19543        // "the theme's own" and what every toolbar draws unlit.
19544        let mut plain = doc_with("plain_presentation", "hello\n");
19545        plain.caret = 1;
19546        assert_eq!(plain.alignment_at_caret(), None);
19547        assert_eq!(plain.line_spacing_at_caret(), None);
19548        assert_eq!(plain.font_size_at_caret(), None);
19549        assert_eq!(plain.font_family_at_caret(), None);
19550        assert_eq!(plain.text_color_at_caret(), None);
19551    }
19552
19553    /// A djot fenced div is anonymous the way an attributed span is, and is a
19554    /// block all the same — the *form* is the whole of what tells them apart.
19555    /// Read as a span it poisoned both halves: the run gesture copied the div's
19556    /// entire attribute set onto the span it minted, duplicating the `id`, and
19557    /// the run and block queries answered off a node the walker draws nothing
19558    /// for.
19559    #[test]
19560    fn a_djot_fenced_div_is_not_an_attributed_span() {
19561        let src = "{.center data-size=\"small\" #box}\n:::\nhello world\n:::\n";
19562        let mut d = fmt_doc(src, Format::Djot);
19563        let at = d.source.find("world").unwrap();
19564        d.anchor = Some(at);
19565        d.caret = at + "world".len();
19566        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19567        assert_eq!(
19568            d.source,
19569            "{.center data-size=\"small\" #box}\n:::\nhello [world]{data-color=\"red\"}\n:::\n",
19570            "the span carries its own key and nothing of the div's"
19571        );
19572
19573        // And the queries stop at the block: a djot div is not a `<div>`, the
19574        // walker lends its keys to nothing inside it, and a query that said
19575        // otherwise would tick a menu entry no glyph on screen obeys.
19576        assert_eq!(
19577            d.text_color_at_caret(),
19578            Some(TextColor::Named(MarkColor::Red))
19579        );
19580        assert_eq!(d.font_size_at_caret(), None);
19581        assert_eq!(d.alignment_at_caret(), None);
19582    }
19583
19584    /// Clearing a property the block does not name and a `div` around it does
19585    /// would write nothing and change nothing — twig's `set_block_attrs`
19586    /// reaches one node, and the div is not it. The gesture says so instead of
19587    /// leaving the author pressing an entry that never ticks.
19588    #[test]
19589    fn clearing_a_property_an_enclosing_div_names_says_so_and_writes_nothing() {
19590        // Markdown, two paragraphs in one div: not the sole-child shape twig
19591        // writes, so `block_attrs_at_caret` reads the paragraph and the
19592        // paragraph names none of it.
19593        let src = "<div class=\"center\" data-line-height=\"1.5\" data-size=\"large\">\n\nhello\n\nworld\n\n</div>\n";
19594        let mut md = fmt_doc(src, Format::Markdown);
19595        md.caret = md.source.find("hello").unwrap();
19596        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19597
19598        md.set_alignment(None);
19599        assert_eq!(md.source, src, "nothing written");
19600        assert!(!md.dirty);
19601        assert_eq!(
19602            md.status.as_deref(),
19603            Some("alignment: set on the div around the block")
19604        );
19605        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19606
19607        // The same for a `data-` key, at both levels — the block pair and the
19608        // run three, the run three at a bare caret being the block gesture.
19609        md.set_line_spacing(None);
19610        assert_eq!(md.source, src);
19611        assert_eq!(
19612            md.status.as_deref(),
19613            Some("line spacing: set on the div around the block")
19614        );
19615        md.set_font_size(None);
19616        assert_eq!(md.source, src);
19617        assert_eq!(
19618            md.status.as_deref(),
19619            Some("size: set on the div around the block")
19620        );
19621
19622        // HTML has no sole-child fold at all: a block's attributes go on the
19623        // block, so the div around one is always out of reach.
19624        let html_src = "<div class=\"center\"><p>hi</p></div>\n";
19625        let mut html = fmt_doc(html_src, Format::Html);
19626        html.caret = html.source.find("hi").unwrap();
19627        assert_eq!(html.alignment_at_caret(), Some(Align::Center));
19628        html.set_alignment(None);
19629        assert_eq!(html.source, html_src);
19630        assert!(!html.dirty);
19631        assert_eq!(
19632            html.status.as_deref(),
19633            Some("alignment: set on the div around the block")
19634        );
19635
19636        // And it is a refusal, not a rule against clearing: a block that names
19637        // the property itself still loses it, div or no div.
19638        let mut own = fmt_doc(
19639            "<div class=\"center\"><p class=\"right\">hi</p></div>\n",
19640            Format::Html,
19641        );
19642        own.caret = own.source.find("hi").unwrap();
19643        own.set_alignment(None);
19644        assert_eq!(own.source, "<div class=\"center\"><p>hi</p></div>\n");
19645        assert_eq!(own.status, None);
19646    }
19647
19648    /// An edited key is rewritten **where it stands**. The proposal's worked
19649    /// example is the test: a paragraph that came in as `id="intro"
19650    /// class="lead center" data-line-height="1.5"` and is right-aligned goes
19651    /// out as the same list with one token changed. Removing the key and
19652    /// pushing it back shuffled a document's attributes on every press.
19653    #[test]
19654    fn an_edited_key_keeps_its_place_among_the_attributes() {
19655        let mut html = fmt_doc(
19656            "<p id=\"intro\" class=\"lead center\" data-line-height=\"1.5\">hello</p>\n",
19657            Format::Html,
19658        );
19659        html.caret = html.source.find("hello").unwrap();
19660        html.set_alignment(Some(Align::Right));
19661        assert_eq!(
19662            html.source,
19663            "<p id=\"intro\" class=\"lead right\" data-line-height=\"1.5\">hello</p>\n"
19664        );
19665
19666        // A `data-` key the same way, and a key the block did not have still
19667        // goes on the end.
19668        html.caret = html.source.find("hello").unwrap();
19669        html.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19670        assert_eq!(
19671            html.source,
19672            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\">hello</p>\n"
19673        );
19674        html.caret = html.source.find("hello").unwrap();
19675        html.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19676        assert_eq!(
19677            html.source,
19678            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\" data-size=\"large\">hello</p>\n"
19679        );
19680
19681        // Djot writes the same list in its own spelling, and the order is the
19682        // author's there too.
19683        let mut dj = fmt_doc(
19684            "{#intro .lead .center data-line-height=\"1.5\"}\nhello\n",
19685            Format::Djot,
19686        );
19687        dj.caret = dj.source.find("hello").unwrap();
19688        dj.set_alignment(Some(Align::Right));
19689        assert_eq!(
19690            dj.source,
19691            "{#intro .lead .right data-line-height=\"1.5\"}\nhello\n"
19692        );
19693    }
19694
19695    /// A page break is a block, so twig alone lands one after the caret's whole
19696    /// block; the paragraph is parted at the caret first, exactly as
19697    /// `insert_thematic_break` parts it, and each format spells the directive
19698    /// its own way.
19699    #[test]
19700    fn insert_page_break_parts_the_paragraph_and_spells_the_directive() {
19701        let mut md = doc_with("page_break_md", "hello world\n");
19702        md.caret = 5;
19703        md.insert_page_break();
19704        assert_eq!(md.source, "hello\n\n::page-break\n\nworld\n");
19705        assert!(md.dirty);
19706        assert_eq!(md.status, None);
19707
19708        let mut dj = fmt_doc("hello world\n", Format::Djot);
19709        dj.caret = 5;
19710        dj.insert_page_break();
19711        assert_eq!(dj.source, "hello\n\n::: page-break\n:::\n\nworld\n");
19712
19713        // At a block's end there is no second half to mint, so the break simply
19714        // follows the block — the rule the rule button already has.
19715        let mut end = doc_with("page_break_end", "hello\n");
19716        end.caret = 5;
19717        end.insert_page_break();
19718        assert_eq!(end.source, "hello\n\n::page-break\n\n");
19719        assert_eq!(end.caret, end.source.len(), "on the line under the break");
19720
19721        // And it reaches the map as the placeholder row a frontend paginates on.
19722        end.view = View::Wysiwyg;
19723        end.build_visual(80);
19724        assert_eq!(
19725            end.vmap
19726                .rows
19727                .iter()
19728                .find_map(|r| r.leaf_directive.as_ref())
19729                .map(|m| m.name.as_str()),
19730            Some(PAGE_BREAK)
19731        );
19732
19733        // HTML and AsciiDoc spell it their own way, and draw it the same.
19734        for (fmt, src, spelled) in [
19735            (Format::Html, "<p>hello</p>\n", "<page-break></page-break>"),
19736            (Format::Asciidoc, "hello\n", "<<<"),
19737        ] {
19738            let mut d = fmt_doc(src, fmt);
19739            d.caret = d.source.find("hello").unwrap() + 5;
19740            d.insert_page_break();
19741            assert!(d.source.contains(spelled), "{fmt:?}: {:?}", d.source);
19742            d.view = View::Wysiwyg;
19743            d.build_visual(80);
19744            let marks = d
19745                .vmap
19746                .rows
19747                .iter()
19748                .filter_map(|r| r.leaf_directive.as_ref())
19749                .map(|m| m.name.as_str())
19750                .collect::<Vec<_>>();
19751            assert_eq!(marks, [PAGE_BREAK], "{fmt:?}");
19752        }
19753    }
19754
19755    /// The vocabulary's capabilities, per format. The two block properties are
19756    /// `SetBlockAttrs` and the three run ones `WrapRangeAttrs`, which is why
19757    /// AsciiDoc can align a paragraph and not size a run: its `[#id.role]#text#`
19758    /// keeps an id and a role and has no slot for a `data-` key.
19759    #[test]
19760    fn the_presentation_capabilities_are_ragged_per_format() {
19761        for fmt in [Format::Markdown, Format::Djot, Format::Html] {
19762            let c = Capabilities::of(fmt);
19763            assert!(c.alignment, "{fmt:?} alignment");
19764            assert!(c.line_spacing, "{fmt:?} line spacing");
19765            assert!(c.font_size, "{fmt:?} size");
19766            assert!(c.font_family, "{fmt:?} face");
19767            assert!(c.text_color, "{fmt:?} colour");
19768        }
19769        // Markdown spells both only under the extensions leaf parses with — a
19770        // `<div>` and a `<span>` read back as containers under `html_elements`,
19771        // and `::page-break` as a directive under `directives`. Ask twig's own
19772        // defaults and the answer is no, which is why `Capabilities` is built
19773        // with `supports_with`.
19774        assert!(!Format::Markdown.supports(Gesture::SetBlockAttrs));
19775        assert!(!Format::Markdown.supports(Gesture::WrapRangeAttrs));
19776        assert!(!Format::Markdown.supports(Gesture::InsertDirective));
19777
19778        let adoc = Capabilities::of(Format::Asciidoc);
19779        assert!(adoc.alignment && adoc.line_spacing, "AsciiDoc's `[…]` line");
19780        assert!(
19781            !adoc.font_size && !adoc.font_family && !adoc.text_color,
19782            "AsciiDoc has no inline spelling that keeps a data- key"
19783        );
19784
19785        // XML spells none of it, and neither page break — nor has it blocks a
19786        // caret could name for a move.
19787        let xml = Capabilities::of(Format::Xml);
19788        assert!(!xml.alignment && !xml.font_size && !xml.page_break && !xml.move_block);
19789        for f in [Format::Markdown, Format::Djot, Format::Html] {
19790            assert!(Capabilities::of(f).move_block, "{f:?} moves blocks");
19791        }
19792        for f in [
19793            Format::Markdown,
19794            Format::Djot,
19795            Format::Html,
19796            Format::Asciidoc,
19797        ] {
19798            assert!(Capabilities::of(f).page_break, "{f:?} breaks pages");
19799        }
19800    }
19801
19802    /// A format that cannot spell a property refuses in its own words and
19803    /// writes nothing — the guard every other gesture has.
19804    #[test]
19805    fn a_presentation_gesture_a_format_cannot_spell_is_refused_with_a_reason() {
19806        let src = "<doc><p>hello</p></doc>\n";
19807        #[allow(clippy::type_complexity)]
19808        let ops: [(&str, &dyn Fn(&mut Doc)); 6] = [
19809            ("alignment", &|d: &mut Doc| {
19810                d.set_alignment(Some(Align::Center))
19811            }),
19812            ("line spacing", &|d: &mut Doc| {
19813                d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)))
19814            }),
19815            ("size", &|d: &mut Doc| {
19816                d.set_font_size(Some(FontSize::Step(SizeStep::Large)))
19817            }),
19818            ("face", &|d: &mut Doc| {
19819                d.set_font_family(Some(FontFace::Generic(FontFamily::Serif)))
19820            }),
19821            ("colour", &|d: &mut Doc| {
19822                d.set_text_color(Some(TextColor::Named(MarkColor::Red)))
19823            }),
19824            ("page break", &|d: &mut Doc| d.insert_page_break()),
19825        ];
19826        for (name, op) in ops {
19827            let mut d = fmt_doc(src, Format::Xml);
19828            let at = d.source.find("hello").unwrap();
19829            d.caret = at;
19830            d.anchor = Some(at + 5);
19831            op(&mut d);
19832            assert_eq!(d.source, src, "{name} edited an XML document");
19833            assert!(!d.dirty, "{name} marked the document dirty");
19834            let status = d.status.as_deref().unwrap_or("");
19835            assert!(
19836                status.contains("xml"),
19837                "{name}: the refusal should name the format, got {status:?}"
19838            );
19839        }
19840
19841        // AsciiDoc is the ragged one: the block gesture works where the run
19842        // gesture does not, and a *selection* is what tells the two apart.
19843        let mut adoc = fmt_doc("hello world\n", Format::Asciidoc);
19844        adoc.anchor = Some(0);
19845        adoc.caret = 5;
19846        adoc.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19847        assert_eq!(adoc.source, "hello world\n", "no inline spelling");
19848        assert!(adoc.status.is_some());
19849    }
19850
19851    /// A read-only document takes none of it, and a caret on a blank line has
19852    /// no block to carry an attribute — both say so rather than writing.
19853    #[test]
19854    fn a_presentation_gesture_respects_read_only_and_a_blank_line() {
19855        let mut ro = fmt_doc("hello\n", Format::Djot);
19856        ro.read_only = true;
19857        ro.caret = 1;
19858        ro.set_alignment(Some(Align::Center));
19859        assert_eq!(ro.source, "hello\n");
19860
19861        let mut blank = fmt_doc("a\n\n\nb\n", Format::Djot);
19862        blank.caret = 2; // the empty line between the two paragraphs
19863        blank.set_alignment(Some(Align::Center));
19864        assert_eq!(blank.source, "a\n\n\nb\n");
19865        assert!(
19866            blank.status.as_deref().unwrap_or("").contains("no block"),
19867            "got {:?}",
19868            blank.status
19869        );
19870    }
19871
19872    /// A block attribute gesture keeps the caret on the **text** it was on, not
19873    /// on the byte offset it had. Markdown has nowhere to put a paragraph's
19874    /// attributes but a `<div>` around it, and twig splices the div and the
19875    /// block it wraps as one region — so a caret that kept its offset landed in
19876    /// the markup, and every press after the first answered "no block at the
19877    /// caret" with the toolbar's queries reading nothing.
19878    #[test]
19879    fn a_markdown_block_gesture_keeps_the_caret_on_its_text() {
19880        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
19881        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
19882        md.caret = md.source.find("brown").unwrap() + 2; // "br|own"
19883
19884        // Wrapping: the div and two blank lines open above the block.
19885        md.set_alignment(Some(Align::Center));
19886        assert_eq!(
19887            md.source,
19888            "<div class=\"center\">\n\nthe quick brown fox\n\n</div>\n"
19889        );
19890        assert_eq!(word(&md), 2, "the caret left its word: {}", md.caret);
19891        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19892
19893        // Re-styling: the attribute line changes length under the same caret,
19894        // and the second press reaches the same block rather than nothing.
19895        md.set_alignment(Some(Align::Right));
19896        assert_eq!(
19897            md.source, "<div class=\"right\">\n\nthe quick brown fox\n\n</div>\n",
19898            "a second press re-styles the div"
19899        );
19900        assert_eq!(md.status, None);
19901        assert_eq!(word(&md), 2);
19902
19903        // A second key on the same div — the line grows, the caret rides it.
19904        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19905        assert_eq!(
19906            md.source,
19907            "<div class=\"right\" data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
19908        );
19909        assert_eq!(word(&md), 2);
19910        assert_eq!(
19911            md.line_spacing_at_caret(),
19912            Some(LineHeight::Step(LineSpacing::Double))
19913        );
19914
19915        // Unwrapping: the line shrinks, and then the div goes altogether.
19916        md.set_alignment(None);
19917        assert_eq!(
19918            md.source,
19919            "<div data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
19920        );
19921        assert_eq!(word(&md), 2);
19922        md.set_line_spacing(None);
19923        assert_eq!(md.source, "the quick brown fox\n", "the last key unwraps");
19924        assert_eq!(word(&md), 2, "the caret came back down with the block");
19925        assert_eq!(md.alignment_at_caret(), None);
19926        assert_eq!(md.status, None);
19927    }
19928
19929    /// The same rule in djot, where the spelling is a `{…}` line *above* the
19930    /// block rather than a wrapper around it: inserting it pushes the block
19931    /// down, re-styling it changes the line's length, and clearing the last key
19932    /// takes the line away again. The caret rides all three.
19933    #[test]
19934    fn a_djot_attribute_line_keeps_the_caret_on_its_text() {
19935        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
19936        let mut dj = fmt_doc("the quick brown fox\n", Format::Djot);
19937        dj.caret = dj.source.find("brown").unwrap() + 2;
19938
19939        dj.set_alignment(Some(Align::Center));
19940        assert_eq!(dj.source, "{.center}\nthe quick brown fox\n");
19941        assert_eq!(word(&dj), 2);
19942        assert_eq!(dj.alignment_at_caret(), Some(Align::Center));
19943
19944        dj.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19945        assert_eq!(
19946            dj.source, "{.center data-line-height=\"2\"}\nthe quick brown fox\n",
19947            "a second press edits the line the first wrote"
19948        );
19949        assert_eq!(word(&dj), 2);
19950
19951        dj.set_alignment(None);
19952        assert_eq!(dj.source, "{data-line-height=\"2\"}\nthe quick brown fox\n");
19953        assert_eq!(word(&dj), 2);
19954
19955        dj.set_line_spacing(None);
19956        assert_eq!(dj.source, "the quick brown fox\n");
19957        assert_eq!(word(&dj), 2);
19958        assert_eq!(dj.status, None);
19959    }
19960
19961    /// The run gestures with no selection are the block gesture, so they keep
19962    /// the caret the same way — and a heading keeps it inside the heading's own
19963    /// text, past the `# ` its content span starts after. A selection rides
19964    /// along whole: a block gesture is not a run gesture, and what was selected
19965    /// before the press is still selected after it.
19966    #[test]
19967    fn a_block_gesture_carries_a_selection_and_a_heading_caret_too() {
19968        // No selection: the run gesture goes through the block door.
19969        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
19970        md.caret = md.source.find("brown").unwrap() + 2;
19971        md.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19972        assert_eq!(
19973            md.source,
19974            "<div data-size=\"large\">\n\nthe quick brown fox\n\n</div>\n"
19975        );
19976        assert_eq!(md.caret - md.source.find("brown").unwrap(), 2);
19977        assert_eq!(
19978            md.font_size_at_caret(),
19979            Some(FontSize::Step(SizeStep::Large))
19980        );
19981        md.set_font_size(Some(FontSize::Step(SizeStep::Small)));
19982        assert_eq!(
19983            md.font_size_at_caret(),
19984            Some(FontSize::Step(SizeStep::Small)),
19985            "the second press reached the same block"
19986        );
19987
19988        // A selection: alignment is the block's whatever is selected, and the
19989        // words stay selected.
19990        let mut sel = fmt_doc("the quick brown fox\n", Format::Markdown);
19991        let at = sel.source.find("brown").unwrap();
19992        sel.anchor = Some(at);
19993        sel.caret = at + 5;
19994        sel.set_alignment(Some(Align::Center));
19995        let now = sel.source.find("brown").unwrap();
19996        assert_eq!(sel.selection(), Some((now, now + 5)), "the words moved out");
19997
19998        // A heading: the content span starts past the `# `.
19999        let mut h = fmt_doc("# hi there\n\nbody\n", Format::Markdown);
20000        h.caret = h.source.find("there").unwrap() + 1;
20001        h.set_alignment(Some(Align::Right));
20002        assert_eq!(
20003            h.source,
20004            "<div class=\"right\">\n\n# hi there\n\n</div>\n\nbody\n"
20005        );
20006        assert_eq!(h.caret, h.source.find("there").unwrap() + 1);
20007        assert_eq!(h.alignment_at_caret(), Some(Align::Right));
20008    }
20009
20010    /// A djot document open in the rich view, with its map built as
20011    /// [`wysiwyg_doc`] builds a Markdown one's.
20012    fn wysiwyg_djot(body: &str) -> Doc {
20013        let mut d = fmt_doc(body, Format::Djot);
20014        d.view = View::Wysiwyg;
20015        d.build_visual(80);
20016        d
20017    }
20018
20019    /// Backspace at the start of a block whose presentation is spelled as
20020    /// hidden markup before it strips that presentation, the way Backspace at
20021    /// a heading's start strips its `#`. The ordinary delete fused djot's
20022    /// `{.center}` line onto the text and took the blank line a Markdown div
20023    /// needs between its tag and its paragraph.
20024    #[test]
20025    fn backspace_at_the_start_of_a_centred_paragraph_strips_its_attributes() {
20026        let mut md = wysiwyg_doc(
20027            "wys_attr_bksp",
20028            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
20029        );
20030        md.caret = md.source.find("hello").unwrap();
20031        md.backspace();
20032        assert_eq!(
20033            md.source, "above\n\nhello\n\nbelow\n",
20034            "the div is unwrapped"
20035        );
20036        assert_eq!(md.caret, 7, "the caret stays at the start of its text");
20037        md.backspace();
20038        assert_eq!(
20039            md.source, "above\nhello\n\nbelow\n",
20040            "the next press joins the paragraphs, as it always did"
20041        );
20042
20043        let mut dj = wysiwyg_djot("above\n\n{.center}\nhello\n\nbelow\n");
20044        dj.caret = dj.source.find("hello").unwrap();
20045        dj.backspace();
20046        assert_eq!(
20047            dj.source, "above\n\nhello\n\nbelow\n",
20048            "the attribute line goes"
20049        );
20050        assert_eq!(dj.caret, 7);
20051
20052        // A heading's own marker is the nearer hidden markup, and goes first;
20053        // the attributes are the next press's.
20054        let mut dj = wysiwyg_djot("{.center}\n# Title\n");
20055        dj.caret = dj.source.find("Title").unwrap();
20056        dj.backspace();
20057        assert_eq!(dj.source, "{.center}\nTitle\n", "the `#` first");
20058        dj.build_visual(80);
20059        dj.backspace();
20060        assert_eq!(dj.source, "Title\n", "then the attributes");
20061        assert_eq!(dj.caret, 0);
20062    }
20063
20064    /// A div around several blocks has no sole child for twig to unwrap, so
20065    /// at its first block the caret steps back to the stop before rather than
20066    /// taking the div apart; a later block has an ordinary paragraph above it
20067    /// and joins as any paragraph does.
20068    #[test]
20069    fn backspace_at_the_first_of_a_div_s_blocks_steps_back_and_a_later_one_joins() {
20070        let src = "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n";
20071        let mut d = wysiwyg_doc("wys_div_first", src);
20072        d.caret = d.source.find("hello").unwrap();
20073        d.backspace();
20074        assert_eq!(d.source, src, "nothing is deleted");
20075        assert_eq!(d.caret, 5, "the caret steps back to the end of `above`");
20076
20077        let mut d = wysiwyg_doc("wys_div_later", src);
20078        d.caret = d.source.find("world").unwrap();
20079        d.backspace();
20080        assert_eq!(
20081            d.source, "above\n\n<div class=\"center\">\n\nhello\nworld\n\n</div>\n",
20082            "a later block joins the one above it"
20083        );
20084    }
20085
20086    /// Backspace at the start of the paragraph after a Markdown div joins it
20087    /// into the div's last paragraph — the join any two paragraphs make, with
20088    /// the hidden `</div>` carried past the joined text. The ordinary delete
20089    /// took the newline under the tag, which drew nothing different, and the
20090    /// next press took the `>` and left the div unclosed.
20091    #[test]
20092    fn backspace_after_a_div_joins_the_paragraph_into_it() {
20093        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20094        let mut d = wysiwyg_doc("wys_div_join", src);
20095        d.caret = d.source.find("below").unwrap();
20096        d.backspace();
20097        assert_eq!(
20098            d.source,
20099            "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n"
20100        );
20101        assert_eq!(
20102            d.caret,
20103            d.source.find("below").unwrap(),
20104            "the caret stays at the start of the joined text"
20105        );
20106        d.build_visual(80);
20107        assert_eq!(
20108            d.alignment_at_caret(),
20109            Some(Align::Center),
20110            "and is centred now"
20111        );
20112        d.undo();
20113        assert_eq!(d.source, src, "one undo step");
20114
20115        // A list closes the div: the paragraph joins the last item's text,
20116        // under the item's continuation indent, inside the div.
20117        let src = "<div class=\"center\">\n\n- item\n\n</div>\n\nbelow\n";
20118        let mut d = wysiwyg_doc("wys_div_list", src);
20119        d.caret = d.source.find("below").unwrap();
20120        d.backspace();
20121        assert_eq!(
20122            d.source, "<div class=\"center\">\n\n- item\n  below\n\n</div>\n",
20123            "the paragraph joins the item"
20124        );
20125        assert_eq!(d.caret, d.source.find("below").unwrap());
20126
20127        // And where twig has nothing to join into — a code block above — the
20128        // caret steps back to the stop before, and nothing is deleted.
20129        let src = "```\ncode\n```\n\nbelow\n";
20130        let mut d = wysiwyg_doc("wys_code_then_para", src);
20131        d.caret = d.source.find("below").unwrap();
20132        d.backspace();
20133        assert_eq!(d.source, src, "nothing is deleted");
20134        assert!(
20135            d.caret < d.source.find("below").unwrap(),
20136            "the caret stepped back"
20137        );
20138    }
20139
20140    /// Backspace on a blank line collapses to the stop before it — but not
20141    /// across hidden markup, which that collapse deleted whole: a `</div>`,
20142    /// or a comment between two blocks. There the blank line goes alone, and
20143    /// the caret lands where the collapse would have put it.
20144    #[test]
20145    fn backspace_on_a_blank_line_after_hidden_markup_keeps_the_markup() {
20146        let mut d = wysiwyg_doc(
20147            "wys_div_blank",
20148            "<div class=\"center\">\n\nhello\n\n</div>\n\n\n\nbelow\n",
20149        );
20150        d.caret = d.source.find("below").unwrap() - 2; // the empty paragraph
20151        assert!(
20152            d.vmap.is_stop(d.caret),
20153            "the empty paragraph is a caret home"
20154        );
20155        d.backspace();
20156        assert_eq!(
20157            d.source, "<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
20158            "the blank line goes and the div stays closed"
20159        );
20160        assert_eq!(
20161            d.caret,
20162            d.source.find("hello").unwrap() + 5,
20163            "onto the end of `hello`"
20164        );
20165
20166        let mut d = wysiwyg_doc("wys_comment_blank", "above\n\n<!-- note -->\n\n\n\nbelow\n");
20167        d.caret = d.source.find("below").unwrap() - 2;
20168        assert!(d.vmap.is_stop(d.caret));
20169        d.backspace();
20170        assert_eq!(
20171            d.source, "above\n\n<!-- note -->\n\nbelow\n",
20172            "the comment stays"
20173        );
20174        assert_eq!(d.caret, 5);
20175    }
20176
20177    /// Backspace at the end of an attributed span steps inside its hidden
20178    /// closing tag the way it steps inside a `**`, and takes the span with
20179    /// its last letter. Before, the byte-step took the `>` of `</span>`,
20180    /// which left the paragraph unparseable: it vanished from the rich view,
20181    /// and the Backspace after that joined the next block into the wreck.
20182    #[test]
20183    fn backspace_walks_into_a_sized_span_and_takes_the_emptied_span_with_its_space() {
20184        let src = "above\n\nThis <span data-size=\"x-large\">is</span> a test\n\nTest 2\n";
20185        let mut d = wysiwyg_doc("wys_span_bs", src);
20186        d.caret = d.source.find("a test").unwrap() + 6;
20187        for _ in 0..7 {
20188            d.backspace();
20189        }
20190        assert_eq!(
20191            d.source,
20192            "above\n\nThis <span data-size=\"x-large\">is</span>\n\nTest 2\n"
20193        );
20194        d.backspace();
20195        assert_eq!(
20196            d.source, "above\n\nThis <span data-size=\"x-large\">i</span>\n\nTest 2\n",
20197            "the first Backspace after the tag takes the letter, not the `>`"
20198        );
20199        d.backspace();
20200        assert_eq!(
20201            d.source, "above\n\nThis \n\nTest 2\n",
20202            "the last letter takes the span with it"
20203        );
20204        assert_eq!(d.caret, 12, "the caret is where the letter was");
20205        d.backspace();
20206        assert_eq!(d.source, "above\n\nThis\n\nTest 2\n");
20207        assert_eq!(d.caret, 11);
20208        d.build_visual(80);
20209        assert!(
20210            d.vmap
20211                .rows
20212                .iter()
20213                .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "This"),
20214            "the paragraph is still drawn"
20215        );
20216    }
20217
20218    #[test]
20219    fn backspace_walks_into_a_djot_sized_span_too() {
20220        let mut d = wysiwyg_djot("This [is]{data-size=\"x-large\"}\n\nTest 2\n");
20221        d.caret = d.source.find("\n\nTest 2").unwrap();
20222        // The caret home at the paragraph's end is inside the span, before
20223        // its `]`: the map offers no stop after `]{…}`.
20224        d.build_visual(80);
20225        assert_eq!(d.vmap.stop_before(31), Some(8));
20226        d.caret = 8;
20227        d.backspace();
20228        assert_eq!(d.source, "This [i]{data-size=\"x-large\"}\n\nTest 2\n");
20229        d.backspace();
20230        assert_eq!(
20231            d.source, "This \n\nTest 2\n",
20232            "the attribute block outside the span goes with it"
20233        );
20234        d.backspace();
20235        assert_eq!(d.source, "This\n\nTest 2\n");
20236        assert_eq!(d.caret, 4);
20237    }
20238
20239    /// A span that is empty as the file was written has no stop of its own;
20240    /// Backspace reaching it from behind takes it with the character before
20241    /// it, the character the key looked aimed at.
20242    #[test]
20243    fn backspace_over_an_already_empty_span_takes_it_with_the_character_before() {
20244        let src = "This <span data-size=\"x-large\"></span> a test\n";
20245        let mut d = wysiwyg_doc("wys_span_empty", src);
20246        d.caret = d.source.find(" a test").unwrap();
20247        d.backspace();
20248        assert_eq!(d.source, "This a test\n");
20249        assert_eq!(d.caret, 4);
20250    }
20251
20252    /// The mirror: Delete in front of a span's opening tag takes its first
20253    /// letter, and the span with its last.
20254    #[test]
20255    fn delete_walks_into_a_sized_span_and_takes_the_span_with_its_last_letter() {
20256        let src = "This <span data-size=\"x-large\">is</span> a test\n";
20257        let mut d = wysiwyg_doc("wys_span_del", src);
20258        d.caret = 5;
20259        d.delete_forward();
20260        assert_eq!(
20261            d.source,
20262            "This <span data-size=\"x-large\">s</span> a test\n"
20263        );
20264        d.delete_forward();
20265        assert_eq!(d.source, "This  a test\n");
20266        assert_eq!(d.caret, 5);
20267        d.delete_forward();
20268        assert_eq!(d.source, "This a test\n");
20269        assert_eq!(d.caret, 5);
20270    }
20271
20272    /// The block version of the span's emptying rule. Centre a one-letter
20273    /// paragraph — Markdown spells that as a `<div>` around it — and
20274    /// Backspace the letter: the div goes with it, leaving a plain blank line
20275    /// the caret is at home on, in the incremental map and the from-scratch
20276    /// one alike. Before, the letter went alone; the emptied div drew a
20277    /// caret home only the stale map had, and the next Backspace collapsed
20278    /// the line and left `<div class="center">\n\n</div>` standing invisibly
20279    /// in the file.
20280    #[test]
20281    fn backspace_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20282        let mut d = wysiwyg_doc("wys_div_empty", "Try the toolbar.\n\nT\n");
20283        d.caret = d.source.len() - 1;
20284        d.set_alignment(Some(Align::Center));
20285        assert_eq!(
20286            d.source,
20287            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n"
20288        );
20289        d.backspace();
20290        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20291        assert_eq!(d.caret, 18, "on the blank line where the letter was");
20292        // The host rebuilds the map after every key; the spliced map and a
20293        // fresh one both give the line a caret home.
20294        d.build_visual_unwrapped();
20295        assert!(d.vmap.is_stop(18));
20296        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20297        d.backspace();
20298        assert_eq!(
20299            d.source, "Try the toolbar.\n",
20300            "then the blank line collapses"
20301        );
20302        assert_eq!(d.caret, 16);
20303
20304        // With a block after the div the blank line keeps a gap each side.
20305        let mut d = wysiwyg_doc(
20306            "wys_div_empty_mid",
20307            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n\nbelow\n",
20308        );
20309        d.caret = d.source.find("T\n").unwrap() + 1;
20310        d.backspace();
20311        assert_eq!(d.source, "Try the toolbar.\n\n\n\nbelow\n");
20312        assert_eq!(d.caret, 18);
20313        d.build_visual_unwrapped();
20314        assert!(d.vmap.is_stop(18));
20315        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20316    }
20317
20318    /// djot spells the same paragraph as a `{.center}` line above it, and
20319    /// twig has no node at all for that line once the paragraph is gone —
20320    /// so the line goes with the letter too.
20321    #[test]
20322    fn backspace_that_empties_a_centred_paragraph_takes_its_djot_attrs_line_too() {
20323        let mut d = fmt_doc("Try the toolbar.\n\nT\n", Format::Djot);
20324        d.build_visual(80);
20325        d.caret = d.source.len() - 1;
20326        d.set_alignment(Some(Align::Center));
20327        assert_eq!(d.source, "Try the toolbar.\n\n{.center}\nT\n");
20328        d.backspace();
20329        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20330        assert_eq!(d.caret, 18);
20331        d.build_visual(80);
20332        assert!(d.vmap.is_stop(18));
20333    }
20334
20335    /// The rule is for a block that would be no block: a div holding more
20336    /// keeps its tags, and an emptied heading is still a heading.
20337    #[test]
20338    fn emptying_a_paragraph_keeps_a_div_that_holds_more_and_a_heading_its_marker() {
20339        let mut d = wysiwyg_doc(
20340            "wys_div_more",
20341            "<div class=\"center\">\n\nText\n\nT\n\n</div>\n",
20342        );
20343        d.caret = d.source.find("T\n").unwrap() + 1;
20344        d.backspace();
20345        assert_eq!(d.source, "<div class=\"center\">\n\nText\n\n\n\n</div>\n");
20346        assert_eq!(d.caret, 28, "the blank line inside the div, as after Enter");
20347
20348        let mut d = wysiwyg_doc(
20349            "wys_div_heading",
20350            "<div class=\"center\">\n\n# T\n\n</div>\n",
20351        );
20352        d.caret = d.source.find("T\n").unwrap() + 1;
20353        d.backspace();
20354        assert_eq!(d.source, "<div class=\"center\">\n\n# \n\n</div>\n");
20355        assert_eq!(d.caret, 24);
20356        d.build_visual(80);
20357        assert!(
20358            d.vmap.is_stop(24),
20359            "the empty heading is still a caret home"
20360        );
20361    }
20362
20363    /// The mirror: Delete in front of the letter takes the div with it.
20364    #[test]
20365    fn delete_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20366        let mut d = wysiwyg_doc(
20367            "wys_div_empty_del",
20368            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n",
20369        );
20370        d.caret = d.source.find("T\n").unwrap();
20371        d.delete_forward();
20372        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20373        assert_eq!(d.caret, 18);
20374        d.build_visual(80);
20375        assert!(d.vmap.is_stop(18));
20376
20377        let mut d = fmt_doc("Try the toolbar.\n\n{.center}\nT\n", Format::Djot);
20378        d.build_visual(80);
20379        d.caret = d.source.find("T\n").unwrap();
20380        d.delete_forward();
20381        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20382        assert_eq!(d.caret, 18);
20383    }
20384
20385    /// Backspace at a block's start is twig's join, spelled per format — so
20386    /// the cases the one-newline delete got wrong come out right: a
20387    /// paragraph joins onto a heading's line, HTML's `</p><p>` goes as one,
20388    /// and a quote's prefix is written on the joined line.
20389    #[test]
20390    fn backspace_at_a_block_start_joins_it_the_format_s_way() {
20391        let mut d = wysiwyg_doc("wys_join_heading", "# Title\n\nbelow\n");
20392        d.caret = d.source.find("below").unwrap();
20393        d.backspace();
20394        assert_eq!(d.source, "# Title below\n", "onto the heading's line");
20395        assert_eq!(d.caret, d.source.find("below").unwrap());
20396        d.undo();
20397        assert_eq!(d.source, "# Title\n\nbelow\n", "one undo step");
20398
20399        let mut d = wysiwyg_doc("wys_join_quote", "> a\n\nb\n");
20400        d.caret = d.source.find('b').unwrap();
20401        d.backspace();
20402        assert_eq!(d.source, "> a\n> b\n", "into the quote, with its prefix");
20403        assert_eq!(d.caret, d.source.find('b').unwrap());
20404
20405        let mut h = fmt_doc("<p>above</p>\n<p class=\"x\">below</p>\n", Format::Html);
20406        h.view = View::Wysiwyg;
20407        h.build_visual(80);
20408        h.caret = h.source.find("below").unwrap();
20409        h.backspace();
20410        assert_eq!(
20411            h.source, "<p>above\nbelow</p>\n",
20412            "one paragraph, the tag gone whole"
20413        );
20414        assert_eq!(h.caret, h.source.find("below").unwrap());
20415    }
20416
20417    /// Delete at the end of a block's content is the same join aimed at the
20418    /// block after it, and the caret stays where the joined text now begins.
20419    #[test]
20420    fn delete_at_a_block_end_joins_the_next_block_into_it() {
20421        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20422        let mut d = wysiwyg_doc("wys_del_join", src);
20423        d.caret = d.source.find("hello").unwrap() + 5;
20424        d.delete_forward();
20425        assert_eq!(
20426            d.source, "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n",
20427            "below joins hello inside the div"
20428        );
20429        assert_eq!(
20430            d.caret,
20431            d.source.find("hello").unwrap() + 5,
20432            "the caret stays"
20433        );
20434
20435        let mut d = wysiwyg_doc("wys_del_join_head", "above\n\n# Title\n");
20436        d.caret = 5;
20437        d.delete_forward();
20438        assert_eq!(
20439            d.source, "above\nTitle\n",
20440            "the heading's marker goes with the join"
20441        );
20442        assert_eq!(d.caret, 5);
20443
20444        // A code block after the paragraph: nothing to join, the caret steps
20445        // forward onto the next stop and nothing is deleted.
20446        let src = "above\n\n```\ncode\n```\n";
20447        let mut d = wysiwyg_doc("wys_del_code", src);
20448        d.caret = 5;
20449        d.delete_forward();
20450        assert_eq!(d.source, src);
20451        assert!(d.caret > 5, "the caret stepped forward");
20452    }
20453
20454    // ── Text statistics ──────────────────────────────────────────────────────
20455
20456    /// The counts of `body`, from a document open in the WYSIWYG view — the
20457    /// shape every case below starts from.
20458    fn counts_of(name: &str, body: &str) -> TextCounts {
20459        doc_in(View::Wysiwyg, name, body).counts()
20460    }
20461
20462    #[test]
20463    fn counts_tally_plain_prose() {
20464        let c = counts_of(
20465            "counts_prose",
20466            "The quick brown fox jumps over the lazy dog.\n",
20467        );
20468        assert_eq!(
20469            c,
20470            TextCounts {
20471                words: 9,
20472                characters: 44,
20473                characters_without_spaces: 36,
20474                paragraphs: 1,
20475            }
20476        );
20477    }
20478
20479    #[test]
20480    fn counts_read_the_text_and_not_the_markup() {
20481        // The `**` are four bytes of source and no part of the word.
20482        assert_eq!(
20483            counts_of("counts_marks", "a **bold** word\n"),
20484            TextCounts {
20485                words: 3,
20486                characters: 11,
20487                characters_without_spaces: 9,
20488                paragraphs: 1,
20489            }
20490        );
20491        // A link is its label; the destination is plumbing, however long.
20492        assert_eq!(
20493            counts_of(
20494                "counts_link",
20495                "see [the label](https://example.com/a/b/c) here\n"
20496            ),
20497            TextCounts {
20498                words: 4,
20499                characters: 18,
20500                characters_without_spaces: 15,
20501                paragraphs: 1,
20502            }
20503        );
20504    }
20505
20506    #[test]
20507    fn counts_spend_nothing_on_a_picture() {
20508        // A block image renders as a `🖼 alt` placeholder — a picture, not a
20509        // sentence, and not a paragraph either.
20510        assert_eq!(
20511            counts_of("counts_image", "![a long caption](pic.png)\n"),
20512            TextCounts::default()
20513        );
20514        // And it adds nothing to the prose around it.
20515        assert_eq!(
20516            counts_of("counts_image_prose", "text\n\n![a long caption](pic.png)\n"),
20517            TextCounts {
20518                words: 1,
20519                characters: 4,
20520                characters_without_spaces: 4,
20521                paragraphs: 1,
20522            }
20523        );
20524    }
20525
20526    #[test]
20527    fn counts_spend_nothing_on_drawn_furniture() {
20528        // A thematic break is drawn, not written, and an empty paragraph has
20529        // nothing in it — neither is a paragraph of the document.
20530        assert_eq!(
20531            counts_of("counts_rule", "one\n\n---\n\ntwo\n"),
20532            TextCounts {
20533                words: 2,
20534                characters: 6,
20535                characters_without_spaces: 6,
20536                paragraphs: 2,
20537            }
20538        );
20539    }
20540
20541    #[test]
20542    fn counts_measure_characters_as_a_reader_does() {
20543        // Four Han characters (each its own word under UAX#29), one ZWJ emoji
20544        // family that is a single grapheme cluster, and two letters.
20545        let c = counts_of(
20546            "counts_graphemes",
20547            "你好世界 👩\u{200d}👩\u{200d}👧\u{200d}👦 ok\n",
20548        );
20549        assert_eq!(
20550            c,
20551            TextCounts {
20552                words: 5,
20553                characters: 9,
20554                characters_without_spaces: 7,
20555                paragraphs: 1,
20556            }
20557        );
20558    }
20559
20560    #[test]
20561    fn counts_take_a_code_block_as_one_paragraph() {
20562        let c = counts_of("counts_code", "```rust\nlet x = 1;\n\nlet y = 2;\n```\n");
20563        assert_eq!(
20564            c,
20565            TextCounts {
20566                words: 6,
20567                characters: 20,
20568                characters_without_spaces: 14,
20569                paragraphs: 1,
20570            }
20571        );
20572    }
20573
20574    #[test]
20575    fn counts_take_a_table_as_one_paragraph() {
20576        // The box-drawn borders and the column padding are the renderer's, not
20577        // the author's; the cells are what was written.
20578        let c = counts_of("counts_table", "| a b | c |\n| - | - |\n| d | e |\n");
20579        assert_eq!(
20580            c,
20581            TextCounts {
20582                words: 5,
20583                characters: 6,
20584                characters_without_spaces: 5,
20585                paragraphs: 1,
20586            }
20587        );
20588    }
20589
20590    #[test]
20591    fn counts_give_every_item_and_every_quoted_paragraph_its_own_paragraph() {
20592        let c = counts_of(
20593            "counts_blocks",
20594            "- one\n- two\n- three\n\n> first quoted\n>\n> second quoted\n",
20595        );
20596        assert_eq!(
20597            c,
20598            TextCounts {
20599                words: 7,
20600                characters: 36,
20601                characters_without_spaces: 34,
20602                paragraphs: 5,
20603            }
20604        );
20605    }
20606
20607    #[test]
20608    fn counts_leave_the_frontmatter_out() {
20609        // The WYSIWYG view doesn't render it and a writer didn't write it.
20610        let c = counts_of(
20611            "counts_frontmatter",
20612            "---\ntitle: Hidden\n---\n\nvisible words here\n",
20613        );
20614        assert_eq!(
20615            c,
20616            TextCounts {
20617                words: 3,
20618                characters: 18,
20619                characters_without_spaces: 16,
20620                paragraphs: 1,
20621            }
20622        );
20623    }
20624
20625    #[test]
20626    fn counts_of_an_empty_document_are_all_zero() {
20627        assert_eq!(counts_of("counts_empty", ""), TextCounts::default());
20628    }
20629
20630    /// UAX#29 puts a boundary at the hyphen, so a hyphenated compound is two
20631    /// words. Recorded rather than corrected: it is what the algorithm says,
20632    /// and what every other UAX#29 counter reports.
20633    #[test]
20634    fn counts_split_a_hyphenated_compound_in_two() {
20635        let c = counts_of("counts_hyphen", "well-known example\n");
20636        assert_eq!(c.words, 3);
20637        assert_eq!(c.characters, 18);
20638        // Punctuation on its own is no word, and an apostrophe doesn't split one.
20639        assert_eq!(counts_of("counts_punct", "don't ... stop\n").words, 2);
20640    }
20641
20642    #[test]
20643    fn selection_counts_measure_the_selection_and_nothing_without_one() {
20644        let src = "alpha beta\n\ngamma delta\n";
20645        let mut d = doc_in(View::Wysiwyg, "counts_sel", src);
20646        assert_eq!(d.selection_counts(), None, "no selection, no counts");
20647
20648        // From the `b` of `beta` to the end of `gamma`: two blocks clipped.
20649        d.select_range(6, 17);
20650        assert_eq!(
20651            d.selection_counts(),
20652            Some(TextCounts {
20653                words: 2,
20654                characters: 9,
20655                characters_without_spaces: 9,
20656                paragraphs: 2,
20657            })
20658        );
20659    }
20660
20661    /// The count is of the document, not of the window it is shown in — so
20662    /// ⌘E must not move it, and neither must a resize or an edit made with no
20663    /// map built at all.
20664    #[test]
20665    fn counts_agree_across_the_views() {
20666        let src =
20667            "# Head\n\nA **bold** word, a [label](http://x), and more.\n\n- item one\n- item two\n";
20668        let mut d = doc_in(View::Wysiwyg, "counts_views", src);
20669        let wysiwyg = d.counts();
20670        assert!(wysiwyg.words > 0 && wysiwyg.paragraphs == 4);
20671
20672        d.toggle_view();
20673        assert_eq!(d.view, View::Source);
20674        d.build_source();
20675        assert_eq!(d.counts(), wysiwyg, "the source view counts the same text");
20676
20677        // A narrower measure is a narrower window, not a shorter document.
20678        d.toggle_view();
20679        d.build_visual(24);
20680        assert_eq!(d.counts(), wysiwyg, "wrapping is not an input");
20681
20682        // And an edit made in the source view, with the visual map left stale,
20683        // still counts the document as it now stands.
20684        d.toggle_view();
20685        d.caret = d.source.len();
20686        d.insert("\n\ntail words\n");
20687        let after = d.counts();
20688        assert_eq!(after.paragraphs, wysiwyg.paragraphs + 1);
20689        assert_eq!(after.words, wysiwyg.words + 2);
20690    }
20691
20692    // ── math ─────────────────────────────────────────────────────────────────
20693
20694    #[test]
20695    fn a_formula_reveals_on_the_caret_line_in_the_hidden_modes() {
20696        // The rule the proposal states: a formula's content is its TeX, not
20697        // its picture, so it reveals on the caret's line in *every* mode —
20698        // and nothing else on that line does outside `Full`.
20699        let mut d = doc_in(
20700            View::Wysiwyg,
20701            "math_reveal",
20702            "*one* $x+y$ here\n\ntwo there\n",
20703        );
20704        d.set_inline_pictures(true);
20705        assert_eq!(d.markup_mode(), MarkupMode::None);
20706
20707        // Away from the formula's line: the atom, and no reveal at all.
20708        caret_at(&mut d, "two");
20709        assert!(
20710            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20711            "{:?}",
20712            drawn_rows(&d)
20713        );
20714        assert_eq!(d.vmap.math.len(), 1);
20715        assert_eq!(d.reveal_line(), None, "a line with no math keys nothing");
20716
20717        // On it: the formula is its source, the emphasis is still resolved.
20718        caret_at(&mut d, "here");
20719        assert!(
20720            drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"),
20721            "{:?}",
20722            drawn_rows(&d)
20723        );
20724        assert!(d.vmap.math.is_empty());
20725        assert_eq!(d.reveal_line(), Some(Reveal::math(0..16)));
20726
20727        // Off again, and the picture is back.
20728        caret_at(&mut d, "two");
20729        assert!(drawn_rows(&d).iter().any(|r| r == "one ∑ here"));
20730
20731        // The same in Shortcuts; and Full reveals the emphasis too.
20732        d.set_markup_mode(MarkupMode::Shortcuts);
20733        caret_at(&mut d, "here");
20734        assert!(drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"));
20735        d.set_markup_mode(MarkupMode::Full);
20736        caret_at(&mut d, "here");
20737        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20738    }
20739
20740    #[test]
20741    fn an_unrevealed_map_shows_the_carets_line_as_a_page_does() {
20742        let mut d = doc_in(
20743            View::Wysiwyg,
20744            "math_unrevealed",
20745            "*one* $x+y$ here\n\ntwo there\n",
20746        );
20747        d.set_inline_pictures(true);
20748        d.set_markup_mode(MarkupMode::Full);
20749        caret_at(&mut d, "here");
20750        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20751        let (screen, caret) = (d.visual_key(), d.caret);
20752
20753        // On paper: the delimiters hidden and the formula a picture, though
20754        // the caret has not moved off the line.
20755        d.set_unrevealed(true);
20756        d.build_visual(80);
20757        assert!(
20758            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20759            "{:?}",
20760            drawn_rows(&d)
20761        );
20762        assert_eq!(d.vmap.math.len(), 1);
20763        assert_eq!(d.caret, caret);
20764
20765        // Off again: the screen's map is back as it was, and the next build
20766        // reuses it rather than building it over.
20767        d.set_unrevealed(false);
20768        assert_eq!(d.visual_key(), screen);
20769        d.build_visual(80);
20770        assert_eq!(d.visual_key(), screen);
20771        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20772        assert_eq!(d.caret, caret);
20773    }
20774
20775    #[test]
20776    fn a_formula_closed_by_typing_reveals_at_once() {
20777        // The reveal line is decided from the last build's layout, which
20778        // across an edit is stale: the keystroke that closes a `$…$` asks a
20779        // layout that knew no math. `build_map` asks again once the new
20780        // layout is in, so the formula does not snap to its picture under
20781        // the caret.
20782        let mut d = doc_in(View::Wysiwyg, "math_typed", "say \n");
20783        d.set_inline_pictures(true);
20784        d.set_markup_mode(MarkupMode::Shortcuts);
20785        d.caret = 4;
20786        for ch in ["$", "x", "$"] {
20787            d.insert(ch);
20788            d.build_visual(80);
20789        }
20790        assert_eq!(d.source, "say $x$\n");
20791        assert_eq!(
20792            drawn_rows(&d)[0],
20793            "say $x$",
20794            "source, not a picture, under the caret"
20795        );
20796        assert!(d.vmap.math.is_empty());
20797        // Leaving the line folds it — there is only one line, so add one.
20798        d.newline();
20799        d.insert("more");
20800        d.build_visual(80);
20801        assert_eq!(drawn_rows(&d)[0], "say ∑");
20802        assert_eq!(d.vmap.math.len(), 1);
20803        // And deleting the formula while revealed drops the reveal with it.
20804        d.caret = 7;
20805        d.build_visual(80);
20806        assert_eq!(drawn_rows(&d)[0], "say $x$");
20807        for _ in 0..3 {
20808            d.backspace();
20809        }
20810        d.build_visual(80);
20811        assert_eq!(d.source, "say \n\nmore\n");
20812        assert_eq!(d.reveal_line(), None);
20813    }
20814
20815    #[test]
20816    fn a_display_block_is_edited_where_it_stands() {
20817        let mut d = doc_in(
20818            View::Wysiwyg,
20819            "math_block",
20820            "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n",
20821        );
20822        caret_at(&mut d, "end");
20823        assert_eq!(
20824            drawn_rows(&d),
20825            vec!["intro", "", "∑ \\int_0^1 x", "", "end"]
20826        );
20827        // Up from `end` lands on the placeholder, whose glyphs all carry the
20828        // block's start — which is on its `$$` line, so the block reveals.
20829        d.move_up(false);
20830        d.build_visual(80);
20831        assert_eq!(d.caret, 7);
20832        assert_eq!(
20833            drawn_rows(&d),
20834            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
20835        );
20836        // Down walks the source lines, still revealed; typing edits the TeX.
20837        d.move_down(false);
20838        d.build_visual(80);
20839        assert_eq!(d.caret, 10);
20840        d.move_end(false);
20841        d.insert("^2");
20842        d.build_visual(80);
20843        assert_eq!(d.source, "intro\n\n$$\n\\int_0^1 x^2\n$$\n\nend\n");
20844        assert_eq!(drawn_rows(&d)[3], "\\int_0^1 x^2");
20845        // Out below, and it folds to the placeholder with the new TeX.
20846        d.move_down(false);
20847        d.move_down(false);
20848        d.move_down(false);
20849        d.build_visual(80);
20850        assert_eq!(drawn_rows(&d)[2], "∑ \\int_0^1 x^2");
20851        assert_eq!(d.vmap.math[0].tex, "\n\\int_0^1 x^2\n");
20852    }
20853
20854    #[test]
20855    fn set_math_rows_reserves_filler_rows_by_tex() {
20856        let mut d = doc_in(View::Wysiwyg, "math_rows", "$$\nx\n$$\n\nend\n");
20857        caret_at(&mut d, "end");
20858        assert_eq!(d.vmap.math[0].rows_span, 0..1);
20859        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
20860        d.build_visual(80);
20861        assert_eq!(d.vmap.math[0].rows_span, 0..3);
20862        assert_eq!(drawn_rows(&d)[..3], ["∑ x", "", ""]);
20863        // Cheap when nothing changed.
20864        let key = d.visual_key();
20865        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
20866        d.build_visual(80);
20867        assert_eq!(d.visual_key(), key);
20868    }
20869
20870    #[test]
20871    fn a_dollar_typed_in_shortcuts_authors_math() {
20872        let mut d = doc_in(View::Wysiwyg, "math_dollar_sc", "\n");
20873        d.set_markup_mode(MarkupMode::Shortcuts);
20874        d.caret = 0;
20875        d.insert("$x$");
20876        assert_eq!(d.source, "$x$\n");
20877        d.caret = 1;
20878        assert_eq!(d.breadcrumb(), "doc › para › inline_math");
20879
20880        // `None` keeps typed syntax literal, and under the math extension a
20881        // `$` is syntax: twig escapes it, and the paragraph stays text.
20882        let mut d = doc_in(View::Wysiwyg, "math_dollar_none", "\n");
20883        assert_eq!(d.markup_mode(), MarkupMode::None);
20884        d.caret = 0;
20885        d.insert("$x$");
20886        assert_eq!(d.source, "\\$x\\$\n");
20887        d.caret = 2;
20888        assert_eq!(d.breadcrumb(), "doc › para › str");
20889    }
20890
20891    #[test]
20892    fn counts_see_a_formula_as_a_picture_however_it_is_written() {
20893        let c = counts_of(
20894            "counts_math",
20895            "the sum $\\sum_i x_i$ and\n\n$$\ny = mx + c\n$$\n",
20896        );
20897        // `the sum … and` is three words; neither formula counts, and the
20898        // display block is not a paragraph of text.
20899        assert_eq!(c.words, 3);
20900        assert_eq!(c.paragraphs, 1);
20901    }
20902}