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    /// [`Doc::mark_saved`] for a host whose write is not instantaneous: `saved`
7825    /// is the source it read before writing, and the edits made since are
7826    /// still unsaved.
7827    ///
7828    /// A host that reads [`Doc::source`], hands it to a write that takes a
7829    /// while, and then calls `mark_saved` loses whatever was typed meanwhile:
7830    /// the flag is cleared over text that never reached the disk, so nothing
7831    /// saves it again. Here `saved` becomes the clean state and the disk
7832    /// watermark, and `dirty` is whether the buffer has moved on from it.
7833    pub fn mark_saved_as(&mut self, saved: &str) {
7834        self.clean_source = saved.to_string();
7835        self.dirty = self.source != self.clean_source;
7836        self.disk_hash = Some(hash_bytes(saved.as_bytes()));
7837        if !self.dirty {
7838            self.status = Some(format!("saved {}", self.file_name()));
7839        }
7840    }
7841
7842    /// What the file looks like now against the bytes leaf last read or wrote.
7843    ///
7844    /// Reads the file and hashes it (see `disk_hash` for why it isn't an mtime),
7845    /// so this is a filesystem round-trip, not a per-frame question — ask it
7846    /// when a window regains focus, on a timer, or before a save.
7847    ///
7848    /// This *only* reports the file. Whether the document also has unsaved edits
7849    /// is `dirty`, and the interesting case is the conjunction: `dirty` plus
7850    /// [`DiskState::Changed`] means a save overwrites someone's work and a
7851    /// [`Doc::reload`] discards the user's. leaf-core deliberately won't choose —
7852    /// it has no way to ask — so it hands a frontend both halves and lets it put
7853    /// the question to the person who can answer it.
7854    #[cfg(feature = "fs")]
7855    pub fn disk_state(&self) -> DiskState {
7856        let Some(want) = self.disk_hash else {
7857            return DiskState::Untitled;
7858        };
7859        match std::fs::read(&self.path) {
7860            Ok(bytes) if hash_bytes(&bytes) == want => DiskState::Unchanged,
7861            Ok(_) => DiskState::Changed,
7862            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DiskState::Missing,
7863            Err(_) => DiskState::Unreadable,
7864        }
7865    }
7866
7867    /// Re-read the file and replace the document with what's there — the other
7868    /// answer to a [`DiskState::Changed`].
7869    ///
7870    /// **Discards unsaved changes, unconditionally.** It doesn't check `dirty`
7871    /// first: a frontend that wants to protect unsaved work asks (`dirty` +
7872    /// [`Doc::disk_state`]) *before* calling this, and one reloading a clean
7873    /// document shouldn't have to argue with a guard.
7874    ///
7875    /// **The undo history survives, and the reload is one step in it.** The
7876    /// whole buffer is spliced with the file's bytes through the same door every
7877    /// other edit goes through, as an [`EditKind::Other`] that coalesces with
7878    /// nothing on either side — so ^Z after a formatter or a `git checkout` has
7879    /// swapped the document out from under a reader gives them back what they
7880    /// were looking at, marked dirty, and ^Z again carries on into whatever they
7881    /// had done before it. This used to build a fresh parse and drop the stack,
7882    /// on the reasoning that twig's history belongs to the buffer and these are
7883    /// different bytes; that is true of *rebasing* a step onto them and not of
7884    /// recording the swap itself as one, which is all this is. A splice twig
7885    /// won't take falls back to the fresh parse, and only that path still costs
7886    /// the history.
7887    ///
7888    /// The caret keeps its byte offset, clamped to the new length; the selection
7889    /// is dropped. Anything cleverer would be a lie: leaf doesn't know how the
7890    /// file changed, so it can't know where the caret "still" is. Clamping keeps
7891    /// it where the user left it in the common case (a change further down the
7892    /// file, or none in the text they're sitting in), and never puts it
7893    /// somewhere invalid. A selection has two such offsets and no such excuse —
7894    /// silently reinterpreting one over changed bytes would arm the *next*
7895    /// keystroke to delete something the user never selected.
7896    ///
7897    /// Nothing is touched unless the whole reload succeeds; a failure leaves the
7898    /// document alone with a status.
7899    #[cfg(feature = "fs")]
7900    pub fn reload(&mut self) {
7901        if self.is_untitled() {
7902            self.status = Some("no file to reload".into());
7903            return;
7904        }
7905        let bytes = match std::fs::read(&self.path) {
7906            Ok(b) => b,
7907            Err(e) => {
7908                self.status = Some(format!("reload failed: {e}"));
7909                return;
7910            }
7911        };
7912        let Ok(source) = String::from_utf8(bytes) else {
7913            self.status = Some("reload failed: file is not UTF-8".into());
7914            return;
7915        };
7916        // Already these bytes — someone saved a file back unchanged, or leaf's
7917        // own write is being read back. Re-baseline against it and stop: a
7918        // splice of the text onto itself would put an undo step on the stack for
7919        // something nobody did.
7920        if source == self.source {
7921            self.disk_hash = Some(hash_bytes(source.as_bytes()));
7922            self.clean_source = source;
7923            self.dirty = false;
7924            self.status = Some(format!("reloaded {}", self.file_name()));
7925            return;
7926        }
7927        let caret = self.caret;
7928        // The pre-reload caret, so undoing the swap puts it back where the
7929        // reader was standing — the same bracketing `splice_exact` does.
7930        self.record_caret();
7931        if self
7932            .editor
7933            .edit_range(0, self.source.len(), &source)
7934            .is_ok()
7935        {
7936            self.refresh();
7937        } else {
7938            // twig wouldn't take the splice. Start over from the bytes, which is
7939            // what this always did, and is the one path that still costs the
7940            // history — `format` is the format this document *is*, not what the
7941            // (unchanged) name now says, see `save_as`.
7942            match new_editor(source.as_bytes(), self.format) {
7943                Ok(editor) => {
7944                    self.editor = editor;
7945                    // A fresh editor, and so a fresh history — with no
7946                    // step in it for an open group to fold into.
7947                    self.undo_steps = 0;
7948                    self.redo_steps = 0;
7949                    if let Some(g) = &mut self.undo_group {
7950                        g.has_step = false;
7951                    }
7952                    self.source = source.clone();
7953                    // Not going through `refresh`, so the revision has to move
7954                    // here or every frontend keeps painting the old file from
7955                    // cache.
7956                    self.revision += 1;
7957                }
7958                Err(e) => {
7959                    self.status = Some(format!("reload failed: {e}"));
7960                    return;
7961                }
7962            }
7963        }
7964        self.disk_hash = Some(hash_bytes(source.as_bytes()));
7965        self.clean_source = self.source.clone();
7966        self.caret = caret.min(self.source.len());
7967        self.anchor = None;
7968        self.goal_col = None;
7969        self.last_edit_kind = None;
7970        self.dirty = false;
7971        self.status = Some(format!("reloaded {}", self.file_name()));
7972        self.clamp_caret();
7973        // And the post-reload caret, so a redo restores it.
7974        self.record_caret();
7975    }
7976
7977    /// Re-read the source from twig after it has changed the document. The one
7978    /// funnel every edit, undo, and redo comes through — so it's where the
7979    /// revision moves, and anything cached against the text dies here.
7980    fn refresh(&mut self) {
7981        if let Ok(s) = self.editor.source_str() {
7982            self.source = s;
7983        }
7984        self.revision += 1;
7985        // An edit is a step onto the history and the end of anything undone;
7986        // `undo`/`redo` come through here too and correct this after.
7987        self.undo_steps = (self.undo_steps + 1).min(UNDO_CAP);
7988        self.redo_steps = 0;
7989        // Inside a group, fold each step into the group's first as it lands.
7990        // Not for `undo`/`redo`, which close the group before they get here.
7991        if let Some(g) = &mut self.undo_group {
7992            if g.has_step {
7993                self.fold_last_undo();
7994            } else {
7995                g.has_step = true;
7996            }
7997        }
7998        self.clamp_caret();
7999    }
8000
8001    /// Whether [`undo`](Self::undo) has a step to take back — for a native
8002    /// Edit menu to enable its item by, and exactly when `undo` would move.
8003    pub fn can_undo(&self) -> bool {
8004        !self.read_only && self.undo_steps > 0
8005    }
8006
8007    /// Whether [`redo`](Self::redo) has an undone step to restore.
8008    pub fn can_redo(&self) -> bool {
8009        !self.read_only && self.redo_steps > 0
8010    }
8011
8012    // ── caret movement ─────────────────────────────────────────────────────────
8013    // `extend` grows the selection (Shift+motion): it pins the anchor on the
8014    // first extended step and moves only the caret; an un-extended motion drops
8015    // the selection.
8016
8017    /// Place the caret at byte `offset` (clamped to a char boundary), extending
8018    /// the selection when `extend` is set. The public form of `move_to`, for a
8019    /// frontend that hit-tests pixels straight to a source offset.
8020    pub fn place_caret(&mut self, offset: usize, extend: bool) {
8021        self.goal_col = None;
8022        let before = self.caret;
8023        // A pixel hit-test can land between the visible caret stops — in the
8024        // blank gap a paragraph break is drawn with, or inside a hidden delimiter.
8025        // Snap to the nearest real stop so the caret can't come to rest where it
8026        // would draw in one place and type in another. The `(row, col)` click
8027        // path (`click`) already snaps this way through `offset_of_pos`; the
8028        // source view reaches every byte, so it snaps to nothing.
8029        let target = match self.view {
8030            View::Wysiwyg => self.vmap.snap_to_stop(offset.min(self.source.len())),
8031            // The source view reaches every byte, so there is no stop to snap
8032            // to — but "every byte" still means every *character* boundary. A
8033            // caret resting inside a multi-byte character draws nowhere real
8034            // and panics the next time anything slices there.
8035            View::Source => self.char_boundary_at_or_before(offset),
8036        };
8037        self.move_to(target, extend);
8038        self.clamp_caret();
8039        self.debug_assert_on_a_stop(before);
8040    }
8041
8042    /// Select the whole document (⌘A / Ctrl+A) — everything reachable in the
8043    /// active view, so in WYSIWYG it starts below hidden frontmatter (copy won't
8044    /// grab the metadata) while the source view still selects the literal whole.
8045    pub fn select_all(&mut self) {
8046        self.anchor = Some(self.caret_floor());
8047        self.caret = self.source.len();
8048        self.goal_col = None;
8049        self.last_edit_kind = None;
8050        self.status = None;
8051    }
8052
8053    /// Select the word (or whitespace / punctuation run) at `offset` — the
8054    /// double-click gesture. Anchors on the run's start with the caret at its
8055    /// end so a following Shift-motion extends from the far edge.
8056    pub fn select_word_at(&mut self, offset: usize) {
8057        let (s, e) = word_range_at(&self.source, offset.min(self.source.len()));
8058        self.anchor = Some(s);
8059        self.caret = e;
8060        self.goal_col = None;
8061        self.last_edit_kind = None;
8062        self.status = None;
8063        self.clamp_caret();
8064    }
8065
8066    /// Select the whole enclosing text block (paragraph, heading, list item's
8067    /// text…) at `offset` — the triple-click gesture. Reads the range straight
8068    /// from the AST (twig's `content_span`), so it selects the entire *logical*
8069    /// paragraph even when that paragraph soft-wraps across several visual rows —
8070    /// where a visual-row-based select breaks down, because one source offset at
8071    /// a wrap boundary belongs to two rows at once.
8072    pub fn select_block_at(&mut self, offset: usize) {
8073        let off = offset.min(self.source.len());
8074        let range = self
8075            .editor
8076            .ancestors_at(off)
8077            .ok()
8078            .and_then(|chain| {
8079                // Ancestors run root → deepest; the deepest node that is neither
8080                // an inline span nor a multi-block container is the text block
8081                // the caret sits in (a paragraph, a heading, a code block…).
8082                chain
8083                    .into_iter()
8084                    .rev()
8085                    .find(|m| !wysiwyg::is_inline_kind(&m.kind) && !is_block_container(&m.kind))
8086                    .map(|m| m.content_span.unwrap_or(m.span))
8087            })
8088            .unwrap_or_else(|| source_line_range(&self.source, off));
8089        self.anchor = Some(range.start.min(self.source.len()));
8090        self.caret = range.end.min(self.source.len());
8091        self.goal_col = None;
8092        self.last_edit_kind = None;
8093        self.status = None;
8094        self.clamp_caret();
8095    }
8096
8097    /// Select the exact source range `[start, end)` — anchor at `start`, caret
8098    /// at `end` — without snapping either end to a visible caret stop.
8099    ///
8100    /// The one caret verb that takes a range it was *handed* rather than one it
8101    /// worked out, for a host that already knows the bytes it means: a search
8102    /// hit, an annotation's footprint, a quote re-anchored through
8103    /// [`Doc::selection_quote`]. [`place_caret`](Self::place_caret) is the
8104    /// wrong tool for that, and not by a little — it snaps to the nearest
8105    /// *visible* stop, and where a range butts up against a hidden delimiter
8106    /// the nearest stop is the one before it, so selecting the "needle" of
8107    /// `**needle**` comes back with "needl" and an edit against it strands the
8108    /// "e".
8109    ///
8110    /// What `place_caret` does that is bookkeeping rather than snapping still
8111    /// happens here, because a host handing in a range is not asking to opt out
8112    /// of the invariants:
8113    ///
8114    /// - both ends are clamped into the document and up to
8115    ///   [`caret_floor`](Self::caret_floor) — in WYSIWYG the leading
8116    ///   frontmatter is hidden, and a caret parked in it draws nowhere and
8117    ///   types into the metadata;
8118    /// - both land on character boundaries, so nothing slices a `é` in half;
8119    /// - the sticky vertical goal column is dropped, and any armed inline mark
8120    ///   disarmed, since a range from outside inherits neither.
8121    ///
8122    /// An empty range is a caret rather than a selection —
8123    /// [`selection`](Self::selection) reports `None` for it, as it does for any
8124    /// anchor that has met the caret.
8125    pub fn select_range(&mut self, start: usize, end: usize) {
8126        let floor = self.caret_floor();
8127        let anchor = self.char_boundary_at_or_before(start.clamp(floor, self.source.len()));
8128        let caret = self.char_boundary_at_or_before(end.clamp(floor, self.source.len()));
8129        self.anchor = Some(anchor);
8130        self.caret = caret;
8131        self.goal_col = None;
8132        self.status = None;
8133        self.last_edit_kind = None;
8134        self.clear_pending();
8135    }
8136
8137    /// `offset` itself if it is a character boundary, else the boundary before
8138    /// it. An offset that isn't one draws nowhere real and panics the next time
8139    /// anything slices there.
8140    fn char_boundary_at_or_before(&self, offset: usize) -> usize {
8141        let mut o = offset.min(self.source.len());
8142        while o > 0 && !self.source.is_char_boundary(o) {
8143            o -= 1;
8144        }
8145        o
8146    }
8147
8148    /// The lowest source offset the caret may occupy in the active view. In
8149    /// WYSIWYG, leading frontmatter is hidden and unreachable, so the floor is
8150    /// the first rendered offset; the source view reaches everything, so it's 0.
8151    fn caret_floor(&self) -> usize {
8152        match self.view {
8153            View::Wysiwyg => self.vmap.content_start.min(self.source.len()),
8154            View::Source => 0,
8155        }
8156    }
8157
8158    /// Land in a table cell with its whole content selected — the anchor at the
8159    /// cell's start, the caret at its end — so a Tab/Return hop into a cell reads
8160    /// like tabbing into a form field: the text comes up selected, so typing
8161    /// replaces it and an arrow collapses to an edge. An empty cell (`start ==
8162    /// end`) collapses to a plain caret home (an empty selection is no selection).
8163    fn select_cell(&mut self, start: usize, end: usize) {
8164        self.select_range(start, end);
8165    }
8166
8167    fn move_to(&mut self, offset: usize, extend: bool) {
8168        if extend {
8169            if self.anchor.is_none() {
8170                self.anchor = Some(self.caret);
8171            }
8172        } else {
8173            self.anchor = None;
8174        }
8175        self.caret = offset.min(self.source.len()).max(self.caret_floor());
8176        self.status = None;
8177        // A caret move ends the current typing/deletion run, so the next edit
8178        // starts a fresh undo group rather than coalescing across the gap.
8179        self.last_edit_kind = None;
8180        // Moving away disarms any sticky mark — "start bold" applies only where
8181        // it was asked for, not wherever the caret next lands.
8182        self.clear_pending();
8183    }
8184
8185    // In the source view, motion walks source bytes / source lines. In the
8186    // WYSIWYG view it walks the rendered glyph grid (the visual map), which is
8187    // what steps the caret cleanly over hidden delimiters.
8188
8189    pub fn move_left(&mut self, extend: bool) {
8190        self.goal_col = None;
8191        if !extend && let Some((s, _e)) = self.selection() {
8192            self.move_to(s, false);
8193            return;
8194        }
8195        let target = match self.view {
8196            View::Source => {
8197                if self.caret > 0 {
8198                    prev_boundary(&self.source, self.caret)
8199                } else {
8200                    0
8201                }
8202            }
8203            // Walks caret *stops*, not columns: decoration (a table border, a
8204            // cell's padding) is stepped over in one press, and a hidden
8205            // delimiter never holds the caret up — though the end of a mark's
8206            // content is a stop of its own (`VisualMap::mark_ends`), so
8207            // leaving `**bold**` from past its `**` is a press onto the end of
8208            // the bold and another onto the `d`.
8209            View::Wysiwyg => self
8210                .vmap
8211                .caret_stop_before(self.caret)
8212                .unwrap_or(self.caret),
8213        };
8214        let before = self.caret;
8215        self.move_to(target, extend);
8216        self.debug_assert_on_a_stop(before);
8217    }
8218
8219    pub fn move_right(&mut self, extend: bool) {
8220        self.goal_col = None;
8221        if !extend && let Some((_s, e)) = self.selection() {
8222            self.move_to(e, false);
8223            return;
8224        }
8225        let target = match self.view {
8226            View::Source => {
8227                if self.caret < self.source.len() {
8228                    next_boundary(&self.source, self.caret)
8229                } else {
8230                    self.caret
8231                }
8232            }
8233            View::Wysiwyg => self.vmap.caret_stop_after(self.caret).unwrap_or(self.caret),
8234        };
8235        let before = self.caret;
8236        self.move_to(target, extend);
8237        self.debug_assert_on_a_stop(before);
8238    }
8239
8240    /// Move to the start of the previous word (⌥← / Ctrl+←).
8241    pub fn move_word_left(&mut self, extend: bool) {
8242        self.goal_col = None;
8243        let before = self.caret;
8244        let target = self.word_left_from(self.caret);
8245        self.move_to(target, extend);
8246        self.debug_assert_on_a_stop(before);
8247    }
8248
8249    /// Move to the end of the next word (⌥→ / Ctrl+→).
8250    pub fn move_word_right(&mut self, extend: bool) {
8251        self.goal_col = None;
8252        let before = self.caret;
8253        let target = self.word_right_from(self.caret);
8254        self.move_to(target, extend);
8255        self.debug_assert_on_a_stop(before);
8256    }
8257
8258    // Word boundaries are found in the space the *view* is in. The source view
8259    // walks the source, because there the source is what's rendered. WYSIWYG
8260    // walks the rendered text instead: `**` is invisible to the user, so it has
8261    // to be invisible to word motion too — a caret parked inside one draws in
8262    // the column after `bold` and types two bytes earlier, and a word-delete
8263    // that stops there shreds the markup into `a ** c`.
8264
8265    /// The word boundary to the left of `off` in the active view's space.
8266    fn word_left_from(&self, off: usize) -> usize {
8267        match self.view {
8268            View::Source => prev_word(&self.source, off),
8269            View::Wysiwyg => self.glyph_word_left(off),
8270        }
8271    }
8272
8273    /// The word boundary to the right of `off` in the active view's space.
8274    fn word_right_from(&self, off: usize) -> usize {
8275        match self.view {
8276            View::Source => next_word(&self.source, off),
8277            View::Wysiwyg => self.glyph_word_right(off),
8278        }
8279    }
8280
8281    /// The character class of the glyph drawn at stop `off`.
8282    ///
8283    /// Read from the source, because a stop points at the source byte its glyph
8284    /// came from — the source *is* where the rendered character is written. What
8285    /// makes the walk glyph space rather than source space is that it only ever
8286    /// visits stops, and the hidden bytes between them have none.
8287    fn class_at(&self, off: usize) -> Class {
8288        self.source
8289            .get(off..)
8290            .and_then(|s| s.chars().next())
8291            .map_or(Class::Space, classify)
8292    }
8293
8294    /// [`next_word`] in glyph space: skip any leading separators, then consume
8295    /// the following word run, with the stop table standing in for the source's
8296    /// characters.
8297    fn glyph_word_right(&self, from: usize) -> usize {
8298        let Some(mut off) = self.vmap.stop_at_or_after(from) else {
8299            return from;
8300        };
8301        let mut in_word = false;
8302        loop {
8303            match self.class_at(off) {
8304                Class::Word => in_word = true,
8305                _ if in_word => return off,
8306                _ => {}
8307            }
8308            match self.vmap.stop_after(off) {
8309                Some(next) => off = next,
8310                None => return off,
8311            }
8312        }
8313    }
8314
8315    /// [`prev_word`] in glyph space: skip separators walking left, then consume
8316    /// the preceding word run.
8317    fn glyph_word_left(&self, from: usize) -> usize {
8318        let Some(mut off) = self.vmap.stop_at_or_before(from) else {
8319            return from;
8320        };
8321        let mut in_word = false;
8322        while let Some(prev) = self.vmap.stop_before(off) {
8323            match self.class_at(prev) {
8324                Class::Word => in_word = true,
8325                _ if in_word => return off,
8326                _ => {}
8327            }
8328            off = prev;
8329        }
8330        off
8331    }
8332
8333    /// After a motion that walks the visual map, the caret must be *on* the map.
8334    /// A stop is the only offset where the caret draws and edits in the same
8335    /// place, and it's the invariant both a caret parked inside an emoji and one
8336    /// parked inside a `**` were quietly breaking.
8337    ///
8338    /// Only when the caret actually moved: a walk with nowhere to go leaves it
8339    /// where it was, which is wherever the floor or a frontend put it rather
8340    /// than somewhere this motion chose.
8341    fn debug_assert_on_a_stop(&self, before: usize) {
8342        debug_assert!(
8343            self.view != View::Wysiwyg
8344                || self.vmap.num_rows() == 0
8345                || self.caret == before
8346                || self.vmap.is_stop(self.caret),
8347            "motion left the caret at {}, which is not a caret stop: it would draw in \
8348             one place and type in another",
8349            self.caret
8350        );
8351    }
8352
8353    // Up and Down run off the ends of the document rather than stopping dead at
8354    // them: Up from the first row lands at the document's start, Down from the
8355    // last at its end. That's Cocoa's rule (`moveUp:`/`moveDown:` past the edge
8356    // are `moveToBeginningOfDocument:`/`moveToEndOfDocument:`), and holding ↓
8357    // reaching the end of the text is what a reader means by it.
8358    //
8359    // The views used to disagree here by accident rather than by decision: the
8360    // source view fell into the edge behaviour through `row_col_to_offset`
8361    // clamping an out-of-range row to the end of the string, while WYSIWYG had
8362    // no row below to walk to and did nothing at all. They share the rule now,
8363    // each in its own space — the source view reaches every byte, WYSIWYG only
8364    // the offsets it draws.
8365
8366    pub fn move_up(&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 row.checked_sub(1) {
8371                Some(r) => row_col_to_offset(&self.source, r, goal),
8372                None => self.reachable_start(),
8373            },
8374            // A table's border rules are drawn but hold no caret, so Up steps
8375            // over them to the row that does.
8376            View::Wysiwyg => match self.vmap.navigable_above(row) {
8377                Some(r) => self.row_target(r, goal),
8378                None => self.reachable_start(),
8379            },
8380        };
8381        self.step_vertical(target, goal, extend);
8382    }
8383
8384    pub fn move_down(&mut self, extend: bool) {
8385        let (row, col) = self.caret_pos();
8386        let goal = self.goal_col.unwrap_or(col);
8387        let target = match self.view {
8388            View::Source => match self.source_row_below(row) {
8389                Some(r) => row_col_to_offset(&self.source, r, goal),
8390                None => self.reachable_end(),
8391            },
8392            View::Wysiwyg => match self.vmap.navigable_below(row) {
8393                Some(r) => self.row_target(r, goal),
8394                None => self.reachable_end(),
8395            },
8396        };
8397        self.step_vertical(target, goal, extend);
8398    }
8399
8400    /// Land a vertical motion at `target`, latching the `goal` column it aimed
8401    /// with so the rest of the run keeps aiming there.
8402    ///
8403    /// A motion with nowhere to go changes *nothing*, the goal column included:
8404    /// the latch used to run before the early return at the top of the document,
8405    /// so an Up that did nothing still armed a column, and the next Down aimed
8406    /// at one the caret had never been in.
8407    fn step_vertical(&mut self, target: usize, goal: usize, extend: bool) {
8408        let before = self.caret;
8409        if target == before {
8410            return;
8411        }
8412        self.goal_col = Some(goal);
8413        self.move_to(target, extend);
8414        self.debug_assert_on_a_stop(before);
8415    }
8416
8417    /// The source line below `row`, or `None` when `row` is the last one. Lines
8418    /// are counted by newline, so a trailing one leaves a real, empty last line
8419    /// for the caret to sit on — the document ends below it, not on it.
8420    fn source_row_below(&self, row: usize) -> Option<usize> {
8421        let last = self.source.bytes().filter(|&b| b == b'\n').count();
8422        (row < last).then_some(row + 1)
8423    }
8424
8425    /// Where a vertical motion aiming at the `goal` column lands on visual row
8426    /// `r`: the column clamped to the row, mapped to its offset, then held
8427    /// inside the row's own [bounds](Self::row_bounds) — a wrapped row's last
8428    /// column belongs to the row below, and a gutter's column 0 points at the
8429    /// block rather than at this row.
8430    fn row_target(&self, r: usize, goal: usize) -> usize {
8431        let (start, end) = self.row_bounds(r);
8432        self.vmap
8433            .offset_of_pos(r, goal.min(self.vmap.row_width(r)))
8434            .clamp(start, end)
8435    }
8436
8437    /// The first and last offsets the caret can reach in the active view.
8438    ///
8439    /// Not the same span in both: the source view shows every byte, so it can
8440    /// reach every byte. WYSIWYG reaches only what it draws — hidden frontmatter
8441    /// sits below the first stop, and a document's trailing newline is drawn
8442    /// nowhere and so sits past the last.
8443    fn reachable_start(&self) -> usize {
8444        match self.view {
8445            View::Source => 0,
8446            View::Wysiwyg => self.vmap.stop_at_or_after(0).unwrap_or(self.caret),
8447        }
8448    }
8449
8450    fn reachable_end(&self) -> usize {
8451        match self.view {
8452            View::Source => self.source.len(),
8453            View::Wysiwyg => self
8454                .vmap
8455                .stop_at_or_before(self.source.len())
8456                .unwrap_or(self.caret),
8457        }
8458    }
8459
8460    /// The `[start, end]` offsets visual row `r` *draws* — everything on it,
8461    /// including the space a soft wrap ate off its end, which is drawn on this
8462    /// row however much the offset past it belongs to the next one.
8463    fn row_span(&self, r: usize) -> (usize, usize) {
8464        let start = self
8465            .vmap
8466            .row_start(r)
8467            .unwrap_or_else(|| self.vmap.offset_of_pos(r, 0));
8468        let end = self.vmap.offset_of_pos(r, self.vmap.row_width(r));
8469        (start.min(end), end)
8470    }
8471
8472    /// [`row_span`](Self::row_span) narrowed to where the caret can stand: a
8473    /// soft wrap's shared offset opens the row below (see `pos_of_offset`), so
8474    /// this row's last position is the one before it — the offset before the
8475    /// space the wrap ate, where the caret draws just past the row's last word
8476    /// and types there too.
8477    ///
8478    /// Aiming at the shared offset instead is what stalled End: it is the row's
8479    /// last *column*, so End pressed on the row reached it and then read back as
8480    /// the row below's start, where a second press ran on to that row's end and
8481    /// the next to the one after — End walking down the paragraph a row a press.
8482    fn row_bounds(&self, r: usize) -> (usize, usize) {
8483        let (start, end) = self.row_span(r);
8484        let wraps = self
8485            .vmap
8486            .navigable_below(r)
8487            .and_then(|b| self.vmap.row_start(b))
8488            .is_some_and(|off| off == end);
8489        match wraps {
8490            true => (start, self.vmap.stop_before(end).unwrap_or(end).max(start)),
8491            false => (start, end),
8492        }
8493    }
8494
8495    /// The `[start, end]` of the line Home and End aim at: the visual row in
8496    /// WYSIWYG, the logical line in the source view. Both ends are caret stops.
8497    ///
8498    /// A soft-wrapped row is a line here, because it is one to the eye and the
8499    /// eye is what these keys are aimed by — a reader pressing End means the end
8500    /// of the line they can see. (`select_block_at` wants the opposite and reads
8501    /// the AST for it: a triple-click grabs the whole paragraph, however many
8502    /// rows it folds into.)
8503    fn line_bounds(&self) -> (usize, usize) {
8504        let (row, _) = self.caret_pos();
8505        match self.view {
8506            View::Source => {
8507                let start = line_start(&self.source, row);
8508                (start, line_end_from(&self.source, start))
8509            }
8510            View::Wysiwyg => self.row_bounds(row),
8511        }
8512    }
8513
8514    /// The same line as [`line_bounds`](Self::line_bounds), as far as it is
8515    /// *drawn* — what a kill takes.
8516    ///
8517    /// The two part only at a soft wrap, over the space the wrap ate: the caret
8518    /// can't stand after it (that offset opens the row below, and End stopping
8519    /// there would walk), but it is on this row, and a kill that spared it would
8520    /// leave a double space behind where the row's text had been. Deleting it
8521    /// joins nothing — a wrap is drawn, not written.
8522    fn line_span(&self) -> (usize, usize) {
8523        let (row, _) = self.caret_pos();
8524        match self.view {
8525            View::Source => self.line_bounds(),
8526            View::Wysiwyg => self.row_span(row),
8527        }
8528    }
8529
8530    /// The first offset in `[start, end]` holding something other than
8531    /// whitespace, or `end` when the line holds nothing else — where Home aims.
8532    ///
8533    /// Walks the space the view is in, as word motion does: WYSIWYG steps stops,
8534    /// so a hidden delimiter is never taken for the line's first character (nor
8535    /// landed on), and the source view steps the source it is showing.
8536    fn first_non_space(&self, start: usize, end: usize) -> usize {
8537        let mut off = start;
8538        while off < end {
8539            if self.class_at(off) != Class::Space {
8540                return off;
8541            }
8542            off = match self.view {
8543                View::Source => next_boundary(&self.source, off),
8544                View::Wysiwyg => match self.vmap.stop_after(off) {
8545                    Some(next) => next,
8546                    None => return end,
8547                },
8548            };
8549        }
8550        end
8551    }
8552
8553    /// Home: to the first character on the line, or to column 0 when the caret
8554    /// is already on it — the two-press toggle every editor spells this way.
8555    /// The indentation is somewhere the caret has to be able to reach and almost
8556    /// never where a reader is headed, so it costs the second press.
8557    pub fn move_home(&mut self, extend: bool) {
8558        self.goal_col = None;
8559        let (start, end) = self.line_bounds();
8560        let text = self.first_non_space(start, end);
8561        let target = if self.caret == text { start } else { text };
8562        let before = self.caret;
8563        self.move_to(target, extend);
8564        self.debug_assert_on_a_stop(before);
8565    }
8566
8567    /// End: to the end of the line.
8568    pub fn move_end(&mut self, extend: bool) {
8569        self.goal_col = None;
8570        let (_, end) = self.line_bounds();
8571        let before = self.caret;
8572        self.move_to(end, extend);
8573        self.debug_assert_on_a_stop(before);
8574    }
8575
8576    /// Hop to the next (Tab) or previous (Shift+Tab) table cell, landing with the
8577    /// cell's whole content selected (see [`Self::select_cell`]). Returns `false`
8578    /// when the caret isn't in a table, or is already in the last/first cell — the
8579    /// frontend then does whatever Tab normally does (indent), so Tab keeps its
8580    /// meaning everywhere else.
8581    pub fn cell_hop(&mut self, forward: bool) -> bool {
8582        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8583            return false;
8584        };
8585        // Flatten to document (row-major) order and step one cell either way.
8586        let i: usize = grid[..r].iter().map(Vec::len).sum::<usize>() + c;
8587        let flat: Vec<(usize, usize)> = grid.into_iter().flatten().collect();
8588        let next = if forward {
8589            i.checked_add(1)
8590        } else {
8591            i.checked_sub(1)
8592        };
8593        let Some(&(start, end)) = next.and_then(|j| flat.get(j)) else {
8594            return false; // at the table's edge; leave Tab to the frontend
8595        };
8596        self.select_cell(start, end);
8597        true
8598    }
8599
8600    /// Move the caret to the cell directly above (`down == false`) or below in
8601    /// the same column, landing with the cell's whole content selected (see
8602    /// [`Self::select_cell`]). Returns `false` at the grid's top/bottom edge (or
8603    /// when the caret isn't in a table), so the frontend can fall through — the
8604    /// vertical counterpart of [`Self::cell_hop`].
8605    ///
8606    /// A ragged row that is short a column clamps to its last cell, so Down never
8607    /// falls out of the table over a gap the row above happened to have.
8608    pub fn cell_move_vertical(&mut self, down: bool) -> bool {
8609        let Some((grid, r, c)) = self.table_grid_at(self.caret) else {
8610            return false;
8611        };
8612        let target = match down {
8613            true => r + 1,
8614            false if r == 0 => return false,
8615            false => r - 1,
8616        };
8617        let Some(row) = grid.get(target) else {
8618            return false;
8619        };
8620        let Some(&(start, end)) = row.get(c).or_else(|| row.last()) else {
8621            return false;
8622        };
8623        self.select_cell(start, end);
8624        true
8625    }
8626
8627    /// The table containing `off` as a row-major grid of `(start, end)` cell
8628    /// caret homes, plus the `(row, col)` the caret sits in — `None` when `off`
8629    /// isn't in a table. Read straight off the visual map's laid-out grid, so
8630    /// every cell (an empty one included, whose derived home twig gives no
8631    /// `content_span` for) is present and in the order Tab walks them.
8632    // Grid, row, column — three returns that only ever travel together, and a
8633    // named type for the pair of them would be read at one call site.
8634    #[allow(clippy::type_complexity)]
8635    fn table_grid_at(&self, off: usize) -> Option<(Vec<Vec<(usize, usize)>>, usize, usize)> {
8636        for t in &self.vmap.tables {
8637            let mut pos = None;
8638            let grid: Vec<Vec<(usize, usize)>> = t
8639                .grid
8640                .iter()
8641                .enumerate()
8642                .map(|(r, row)| {
8643                    row.cells
8644                        .iter()
8645                        .enumerate()
8646                        .map(|(c, cell)| {
8647                            if pos.is_none() && off >= cell.start && off <= cell.end {
8648                                pos = Some((r, c));
8649                            }
8650                            (cell.start, cell.end)
8651                        })
8652                        .collect()
8653                })
8654                .collect();
8655            if let Some((r, c)) = pos {
8656                return Some((grid, r, c));
8657            }
8658        }
8659        None
8660    }
8661
8662    // ── table key policy ──────────────────────────────────────────────────────
8663    // The three keys a table gives its own meaning — Tab, Return, Shift+Return —
8664    // as one policy every frontend shares, rather than each re-deriving it. Each
8665    // reports whether it acted *as a table key*; a `false` hands the key back to
8666    // the frontend's ordinary handling (indent, newline) so it keeps its meaning
8667    // everywhere else.
8668
8669    /// Tab / Shift+Tab inside a table. Tab steps to the next cell, appending a
8670    /// fresh row and entering it when it runs off the last one; Shift+Tab steps
8671    /// back and simply stays put at the very first cell. `false` when the caret
8672    /// isn't in a table.
8673    pub fn cell_tab(&mut self, forward: bool) -> bool {
8674        if !self.caret_in_table() {
8675            return false;
8676        }
8677        if self.cell_hop(forward) {
8678            return true;
8679        }
8680        // Off the last cell: grow the table by a row and step into its first
8681        // cell. (Shift+Tab at the first cell has nowhere to go and just holds.)
8682        if forward {
8683            self.append_row_and_enter(0);
8684        }
8685        true
8686    }
8687
8688    /// Return inside a table: drop to the cell below in the same column,
8689    /// appending a new row when the caret is already in the last one. `false`
8690    /// when the caret isn't in a table, so the frontend inserts a newline.
8691    pub fn cell_return(&mut self) -> bool {
8692        if !self.caret_in_table() {
8693            return false;
8694        }
8695        if self.cell_move_vertical(true) {
8696            return true;
8697        }
8698        // Already on the last row: grow one below and drop into the same column.
8699        let col = self.table_grid_at(self.caret).map_or(0, |(_, _, c)| c);
8700        self.append_row_and_enter(col);
8701        true
8702    }
8703
8704    /// Append a row below the caret's (last) row and land in `col` of it. The
8705    /// caret is in the last row, so twig's "insert below" makes the fresh row the
8706    /// table's new last — but twig re-spells the whole table, moving every byte,
8707    /// so the destination is read back from the rebuilt grid by the table's
8708    /// position (stable across a row insert), not from the pre-edit caret.
8709    fn append_row_and_enter(&mut self, col: usize) {
8710        let table = self.caret_table_index();
8711        self.table_insert_row(true);
8712        self.rebuild_map();
8713        let Some((start, end)) = table
8714            .and_then(|ti| self.vmap.tables.get(ti))
8715            .and_then(|t| t.grid.last())
8716            .and_then(|row| row.cells.get(col.min(row.cells.len().saturating_sub(1))))
8717            .map(|cell| (cell.start, cell.end))
8718        else {
8719            return;
8720        };
8721        self.select_cell(start, end);
8722    }
8723
8724    /// The index, among the document's tables, of the one the caret sits in —
8725    /// `None` when it's in none. Used to re-find a table after an edit re-spells
8726    /// it (a row insert leaves the table order unchanged).
8727    fn caret_table_index(&self) -> Option<usize> {
8728        let off = self.caret;
8729        self.vmap.tables.iter().position(|t| {
8730            t.grid
8731                .iter()
8732                .any(|row| row.cells.iter().any(|c| off >= c.start && off <= c.end))
8733        })
8734    }
8735
8736    /// Shift+Return inside a table: insert a hard line break *within* the current
8737    /// cell, via twig's `insert_line_break`. `false` when the caret isn't in a
8738    /// table, so the frontend inserts an ordinary line break.
8739    ///
8740    /// A table row is a single source line, so the newline-spelled hard break
8741    /// can't live in a cell. twig spells the in-cell break the format's way
8742    /// (`<br>` for Markdown) and reparses it as a *semantic* `hard_break`, so the
8743    /// break round-trips as structure the renderer reads back as a line — not the
8744    /// opaque raw HTML the old raw-splice left behind.
8745    ///
8746    /// Djot has no idiomatic in-cell break, so twig refuses it
8747    /// (`UnsupportedFormat`) rather than emit a `<br>` that any other djot reader
8748    /// would render as the literal text `<br>`. The gesture is still *consumed*
8749    /// there — returning `false` would let the frontend insert a real newline,
8750    /// which splits the one-line row — it just leaves the cell unchanged and says
8751    /// so on the status line. A rollback (`EditConflict`) is swallowed the same.
8752    ///
8753    /// Which formats refuse is [`Capabilities::cell_line_break`], and the two
8754    /// have to be read together: djot is not the only `false`, and naming it in
8755    /// the message was already a guess that HTML — which spells the break as its
8756    /// own `<br>` — would have made wrong.
8757    pub fn cell_line_break(&mut self) -> bool {
8758        if self.read_only || !self.caret_in_table() {
8759            return false;
8760        }
8761        self.record_caret();
8762        match self.editor.insert_line_break(self.caret) {
8763            Ok(change) => {
8764                self.last_edit_kind = None;
8765                self.refresh();
8766                self.caret = change.new.end;
8767                self.anchor = None;
8768                self.goal_col = None;
8769                self.clamp_caret();
8770                self.dirty = self.source != self.clean_source;
8771                self.status = None;
8772                self.record_caret();
8773            }
8774            Err(twig::Error::UnsupportedFormat) => {
8775                self.status = Some(format!(
8776                    "in-cell line breaks aren't supported in {}",
8777                    self.format_name()
8778                ));
8779            }
8780            Err(_) => {}
8781        }
8782        true
8783    }
8784
8785    /// Rebuild the visual map at the width the last build used. A structural edit
8786    /// bumps the revision and swaps the source in, but leaves the *map* stale;
8787    /// when a single gesture edits and then moves over the result (Tab appending
8788    /// a row, then stepping into it), the move needs the map to already show the
8789    /// edit rather than waiting for the frontend's next frame.
8790    fn rebuild_map(&mut self) {
8791        let wrap = self.vmap_key.as_ref().and_then(|(_, w, _)| *w);
8792        self.build_map(wrap);
8793    }
8794
8795    /// Move the caret to the very start of the document (⌘↑ on macOS,
8796    /// Ctrl+Home on Windows/Linux).
8797    pub fn move_doc_start(&mut self, extend: bool) {
8798        self.goal_col = None;
8799        self.move_to(0, extend);
8800    }
8801
8802    /// Move the caret to the very end of the document (⌘↓ on macOS,
8803    /// Ctrl+End on Windows/Linux).
8804    pub fn move_doc_end(&mut self, extend: bool) {
8805        self.goal_col = None;
8806        let end = self.source.len();
8807        self.move_to(end, extend);
8808    }
8809
8810    /// Point the caret at the body cell `(row, col)` the mouse landed on —
8811    /// `col` being a cell of the terminal grid, which is what a display column
8812    /// is. A click on the far cell of a wide character lands at that
8813    /// character's start; the mapping's own doc-comments carry the rule.
8814    pub fn click(&mut self, row: usize, col: usize, extend: bool) {
8815        self.goal_col = None;
8816        let target = match self.view {
8817            View::Source => row_col_to_offset(&self.source, row, col),
8818            View::Wysiwyg => self.vmap.offset_of_pos(row, col),
8819        };
8820        let before = self.caret;
8821        self.move_to(target, extend);
8822        self.debug_assert_on_a_stop(before);
8823    }
8824
8825    /// A click in the blank space under the document's last block.
8826    ///
8827    /// Not a click *on* anything, so it lands on nothing in particular: the
8828    /// caret goes onto an empty paragraph under the last block, wherever the
8829    /// pointer was horizontally — and if the document does not end with one,
8830    /// one is opened, which is the only way to get out from under a block Enter
8831    /// cannot leave. Enter inside a fenced code block is a literal newline (see
8832    /// [`newline`](Self::newline)), so a document that *ends* in a fence had no
8833    /// way out at all; and a click under any last block used to land at the
8834    /// pointer's x on the block's last line, which is what a click on that line
8835    /// means and not what a click under it does.
8836    ///
8837    /// "Ends with an empty paragraph" is two trailing newlines: the first closes
8838    /// the last line and the second opens the blank line the visual map lays
8839    /// out as a navigable empty row (see `emit_trailing_blank_lines`). A
8840    /// document ending inside an *unclosed* fence gets the fence closed first,
8841    /// since a newline written there would only be another line of code. An
8842    /// empty document has nothing to be under, and the caret simply goes to its
8843    /// start.
8844    ///
8845    /// In the source view the gesture is the ordinary one: the caret goes to the
8846    /// end of the source, and nothing is written. A read-only document likewise.
8847    pub fn click_past_end(&mut self) {
8848        self.goal_col = None;
8849        let len = self.source.len();
8850        if self.view == View::Source || self.read_only || self.source.trim().is_empty() {
8851            self.move_to(len, false);
8852            return;
8853        }
8854        let mut tail = String::new();
8855        if let Some(fence) = self.unclosed_fence_at_end() {
8856            if !self.source.ends_with('\n') {
8857                tail.push('\n');
8858            }
8859            tail.push_str(&fence);
8860            tail.push('\n');
8861        }
8862        let joined = format!("{}{tail}", self.source);
8863        let trailing = joined.len() - joined.trim_end_matches('\n').len();
8864        for _ in trailing..2 {
8865            tail.push('\n');
8866        }
8867        if !tail.is_empty() && !self.splice(len, len, &tail, EditKind::Other) {
8868            return;
8869        }
8870        let end = self.source.len();
8871        self.move_to(end, false);
8872    }
8873
8874    /// The closing fence a document ending inside an unclosed fenced code block
8875    /// needs — the opening fence's own run, behind the quote prefix the block
8876    /// wears — or `None` when the last block is closed, indented, or not a code
8877    /// block at all.
8878    ///
8879    /// Unclosed is when twig's content span reaches the block's end: a closing
8880    /// fence line would lie between the two. `code_info_span`'s read of the
8881    /// fence is not used because it starts at the block's span, which inside a
8882    /// quote is the quote marker rather than the fence.
8883    fn unclosed_fence_at_end(&mut self) -> Option<String> {
8884        let content_end = self.source.trim_end_matches('\n').len();
8885        let block = self
8886            .nodes()
8887            .into_iter()
8888            .filter(|n| n.kind == Kind::CodeBlock && n.span.end >= content_end)
8889            .max_by_key(|n| n.span.start)?;
8890        if block.content_span.as_ref()?.end < block.span.end {
8891            return None;
8892        }
8893        let line = self.source[block.span.start..].lines().next()?;
8894        let opening = line.trim_start_matches(['>', ' ', '\t']);
8895        let fence = opening.chars().next().filter(|c| matches!(c, '`' | '~'))?;
8896        let run: String = opening.chars().take_while(|&c| c == fence).collect();
8897        let prefix = self.quote_prefix_at(block.span.start);
8898        Some(format!("{prefix}{run}"))
8899    }
8900
8901    /// Settle `scroll` for a frame about to be drawn: follow the caret onto the
8902    /// screen if it has moved since the last frame, and never scroll past the
8903    /// last of `rows`.
8904    ///
8905    /// Only if it has *moved* — that's the whole point. Revealing the caret on
8906    /// every frame ties the viewport to it, and a scroll wheel that fights the
8907    /// caret for the viewport loses: the view snaps back the instant it tries to
8908    /// pass the caret's row, so the document can't be scrolled beyond what's
8909    /// already on screen. A caret move is the frontend's cue to follow; a scroll
8910    /// with the caret sitting still is the reader's cue to leave it alone.
8911    pub fn follow_caret(&mut self, caret_row: usize, height: usize, rows: usize) {
8912        if self.drawn_caret != Some(self.caret) {
8913            if caret_row < self.scroll {
8914                self.scroll = caret_row;
8915            } else if height > 0 && caret_row >= self.scroll + height {
8916                self.scroll = caret_row + 1 - height;
8917            }
8918            self.drawn_caret = Some(self.caret);
8919        }
8920        self.scroll = self.scroll.min(rows.saturating_sub(1));
8921    }
8922
8923    /// The caret's screen position `(row, col)` in the active view's grid, with
8924    /// `col` a display column: the cell to draw the caret in, which on a line of
8925    /// `你好` or emoji is not the count of characters before it.
8926    pub fn caret_pos(&self) -> (usize, usize) {
8927        match self.view {
8928            View::Source => offset_to_row_col(&self.source, self.caret),
8929            View::Wysiwyg => self.vmap.pos_of_offset(self.caret),
8930        }
8931    }
8932
8933    fn clamp_caret(&mut self) {
8934        if self.caret > self.source.len() {
8935            self.caret = self.source.len();
8936        }
8937        // In WYSIWYG the caret can't sit inside hidden frontmatter; lift it (and
8938        // any selection anchor) to the first rendered offset.
8939        let floor = self.caret_floor();
8940        if self.caret < floor {
8941            self.caret = floor;
8942        }
8943        if let Some(a) = self.anchor
8944            && a < floor
8945        {
8946            self.anchor = Some(floor);
8947        }
8948        while self.caret > 0 && !self.source.is_char_boundary(self.caret) {
8949            self.caret -= 1;
8950        }
8951    }
8952}
8953
8954// ── byte-offset ⇄ (row, col) helpers ─────────────────────────────────────────
8955
8956// Left/right motion and backspace/delete step by *grapheme cluster*, not
8957// codepoint, so an emoji (a ZWJ sequence) or a base letter plus its combining
8958// marks moves and deletes as the single character a user sees. Grapheme
8959// boundaries are a superset of char boundaries, so the caret stays valid for twig.
8960
8961/// How an insert of `text` groups for undo: a single typed character folds into
8962/// the run of typing around it, while a newline or a multi-character insert is a
8963/// step of its own.
8964fn typed_edit_kind(text: &str) -> EditKind {
8965    if text.chars().take(2).count() == 1 && text != "\n" {
8966        EditKind::Insert
8967    } else {
8968        EditKind::Other
8969    }
8970}
8971
8972fn prev_boundary(s: &str, i: usize) -> usize {
8973    let mut cursor = GraphemeCursor::new(i, s.len(), true);
8974    cursor.prev_boundary(s, 0).ok().flatten().unwrap_or(0)
8975}
8976
8977fn next_boundary(s: &str, i: usize) -> usize {
8978    let mut cursor = GraphemeCursor::new(i, s.len(), true);
8979    cursor.next_boundary(s, 0).ok().flatten().unwrap_or(s.len())
8980}
8981
8982// ── word boundaries ──────────────────────────────────────────────────────────
8983// The shared primitive behind word-wise motion, word deletion, and
8984// double-click-to-select-a-word. A "word" is a maximal run of one character
8985// class; whitespace and punctuation are their own classes, so motion skips
8986// cleanly between them the way native text fields do.
8987
8988#[derive(PartialEq, Eq, Clone, Copy)]
8989enum Class {
8990    Word,
8991    Space,
8992    Other,
8993}
8994
8995/// The source range of an inline node's own visible text — the part of it a
8996/// WYSIWYG caret can reach, as against the delimiters that only spell it.
8997/// `None` for a node with no interior to empty (a `str`, a break).
8998///
8999/// twig reports no `content_span` for `verbatim`/`inline_math`, whose text sits
9000/// one delimiter in from the span — the same place the renderer maps it to. A
9001/// longer fence (`` ``a`` ``) breaks that assumption, so the guess is checked
9002/// against the source rather than trusted: a range guessed wrong here is text
9003/// deleted wrong.
9004fn inline_content_span(n: &FlatNode, source: &str) -> Option<std::ops::Range<usize>> {
9005    if let Some(span) = n.content_span.clone() {
9006        return Some(span);
9007    }
9008    match n.kind.as_str() {
9009        "verbatim" | "inline_math" => {
9010            let text = n.text.as_ref()?;
9011            let start = n.span.start + 1;
9012            let range = start..start + text.len();
9013            (source.get(range.clone()) == Some(text.as_str())).then_some(range)
9014        }
9015        _ => None,
9016    }
9017}
9018
9019/// The `id` a node declares, or `None` for one that declares none — the
9020/// attribute djot writes for a `{#v1}` and mints for a heading.
9021///
9022/// A bare attribute (`{#v1 hidden}`'s `hidden`) has no value, and a bare `id`
9023/// names nothing, so it reads as absent rather than as the empty string.
9024fn declared_id(n: &FlatNode) -> Option<&str> {
9025    n.attrs.iter().find(|(k, _)| k == "id")?.1.as_deref()
9026}
9027
9028/// A heading's words reduced to the form a link fragment spells them in:
9029/// lowercase, runs of anything else collapsed to a single `-`, with none left
9030/// dangling at either end. `## Some Heading Here` → `some-heading-here`.
9031///
9032/// The rule every Markdown renderer follows, and applied to djot's own auto-ids
9033/// too so that `#some-heading-here` and `#Some-Heading-Here` are one question.
9034/// Unicode-aware (`is_alphanumeric`, not an ASCII test), because a heading in
9035/// any other language is still a heading someone will link to. Underscores
9036/// survive for the same reason they do on the web: they are word characters
9037/// wherever identifiers are written.
9038fn slug(text: &str) -> String {
9039    let mut out = String::new();
9040    let mut pending = false;
9041    for c in text.chars() {
9042        if c.is_alphanumeric() || c == '_' {
9043            if pending && !out.is_empty() {
9044                out.push('-');
9045            }
9046            pending = false;
9047            out.extend(c.to_lowercase());
9048        } else {
9049            pending = true;
9050        }
9051    }
9052    out
9053}
9054
9055/// The text of the inline run starting at `first` and its siblings, markup
9056/// stripped: each leaf's payload in order, a line break as a space. `nodes` is
9057/// the arena `Doc::nodes` returns, indexed by id.
9058fn inline_text(nodes: &[FlatNode], first: Option<NodeId>, out: &mut String) {
9059    let mut next = first;
9060    while let Some(id) = next {
9061        let Some(n) = nodes.get(id.0 as usize) else {
9062            return;
9063        };
9064        match (&n.text, &n.kind) {
9065            (Some(text), _) => out.push_str(text),
9066            (None, Kind::SoftBreak | Kind::HardBreak) => out.push(' '),
9067            (None, _) => inline_text(nodes, n.first_child, out),
9068        }
9069        next = n.next_sibling;
9070    }
9071}
9072
9073fn is_block_container(kind: &Kind) -> bool {
9074    matches!(
9075        kind,
9076        Kind::Doc
9077            | Kind::Section
9078            | Kind::BlockQuote
9079            | Kind::BulletList
9080            | Kind::OrderedList
9081            | Kind::TaskList
9082            | Kind::ListItem
9083            | Kind::TaskListItem
9084            // Every `container` — a directive in any of its three forms, or a
9085            // promoted HTML element. A *text* directive is really inline, so
9086            // claiming it here is a small overreach, and the deliberate one this
9087            // function's kind-only peer `is_inline_kind` documents: the pair is
9088            // consulted together, and answering "block container" for something
9089            // inline is what keeps an ancestor walk from stopping short of the
9090            // paragraph that actually holds it.
9091            | Kind::Container
9092    )
9093}
9094
9095/// The `[start, end)` byte range of the source line containing `off` (newline
9096/// excluded) — the fallback when `off` sits outside any AST block (e.g. a blank
9097/// line between paragraphs).
9098fn source_line_range(s: &str, off: usize) -> std::ops::Range<usize> {
9099    let off = off.min(s.len());
9100    let start = s[..off].rfind('\n').map(|p| p + 1).unwrap_or(0);
9101    let end = s[off..].find('\n').map(|p| off + p).unwrap_or(s.len());
9102    start..end
9103}
9104
9105/// How many leading bytes an outdent takes off `line`: a whole indent level
9106/// where the line has one, and whatever it has where it has less.
9107///
9108/// A leading tab counts as a level on its own. It's indentation some other
9109/// editor wrote, and one tab is one level everywhere it came from — measuring it
9110/// in spaces it doesn't contain would leave it untouchable.
9111fn outdent_width(line: &str, unit: usize) -> usize {
9112    if line.starts_with('\t') {
9113        return 1;
9114    }
9115    line.bytes().take(unit).take_while(|b| *b == b' ').count()
9116}
9117
9118/// A list marker found at the head of a line, together with everything before it
9119/// that a sibling line has to repeat.
9120///
9121/// The three offsets differ only inside a block quote, where `>   - b` opens with
9122/// a `> ` quote marker the line's own text doesn't own. Outside one they collapse:
9123/// `line_start == marker_start`, and `text` is the plain `"  - "`.
9124#[derive(Clone, Debug)]
9125struct ListMarker {
9126    /// The line's first byte.
9127    line_start: usize,
9128    /// Where the marker proper begins, past any quote prefix. The offset to hand
9129    /// the AST: a quoted item's span opens at its bullet, not at the `>`.
9130    marker_start: usize,
9131    /// `line_start` through the marker's trailing space — quote prefix, indent
9132    /// and bullet together, which is what the next item's line opens with.
9133    text: String,
9134}
9135
9136impl ListMarker {
9137    /// Where the item's content starts — one past the marker's trailing space.
9138    fn content_start(&self) -> usize {
9139        self.line_start + self.text.len()
9140    }
9141}
9142
9143fn classify(c: char) -> Class {
9144    if c == '_' || c.is_alphanumeric() {
9145        Class::Word
9146    } else if c.is_whitespace() {
9147        Class::Space
9148    } else {
9149        Class::Other
9150    }
9151}
9152
9153/// The offset at the end of the next word to the right of `i` (⌥→ / Ctrl+→):
9154/// skip any leading separators, then consume the following word run.
9155fn next_word(s: &str, i: usize) -> usize {
9156    let mut off = i;
9157    let mut in_word = false;
9158    for c in s[i..].chars() {
9159        if classify(c) == Class::Word {
9160            in_word = true;
9161        } else if in_word {
9162            break;
9163        }
9164        off += c.len_utf8();
9165    }
9166    off
9167}
9168
9169/// The offset at the start of the word to the left of `i` (⌥← / Ctrl+←):
9170/// skip separators walking left, then consume the preceding word run.
9171fn prev_word(s: &str, i: usize) -> usize {
9172    let mut off = i;
9173    let mut in_word = false;
9174    for c in s[..i].chars().rev() {
9175        if classify(c) == Class::Word {
9176            in_word = true;
9177        } else if in_word {
9178            break;
9179        }
9180        off -= c.len_utf8();
9181    }
9182    off
9183}
9184
9185/// The `[start, end)` run of same-class characters surrounding `off` — the
9186/// word (or whitespace/punctuation run) a double-click selects. At end-of-text
9187/// the run ending there is used.
9188fn word_range_at(s: &str, off: usize) -> (usize, usize) {
9189    if s.is_empty() {
9190        return (0, 0);
9191    }
9192    let off = off.min(s.len());
9193    let reference = if off < s.len() {
9194        s[off..].chars().next()
9195    } else {
9196        s[..off].chars().next_back()
9197    };
9198    let Some(rc) = reference else {
9199        return (off, off);
9200    };
9201    let class = classify(rc);
9202
9203    let mut start = off;
9204    for c in s[..start].chars().rev() {
9205        if classify(c) == class {
9206            start -= c.len_utf8();
9207        } else {
9208            break;
9209        }
9210    }
9211    let mut end = off;
9212    for c in s[end..].chars() {
9213        if classify(c) == class {
9214            end += c.len_utf8();
9215        } else {
9216            break;
9217        }
9218    }
9219    (start, end)
9220}
9221
9222/// `(row, col)` of byte offset `off`, `col` counted in *display columns* from
9223/// the line's start — terminal cells, not characters, so the column names the
9224/// cell the caret is drawn in even on a line of `你好` or emoji.
9225fn offset_to_row_col(s: &str, off: usize) -> (usize, usize) {
9226    let off = off.min(s.len());
9227    let mut row = 0;
9228    let mut line_start = 0;
9229    for (i, &b) in s.as_bytes().iter().enumerate() {
9230        if i >= off {
9231            break;
9232        }
9233        if b == b'\n' {
9234            row += 1;
9235            line_start = i + 1;
9236        }
9237    }
9238    (row, wysiwyg::text_width(&s[line_start..off]))
9239}
9240
9241/// The byte offset at display column `col` of `row` (clamped to that line's
9242/// end) — the inverse of [`offset_to_row_col`], which it has to agree with.
9243///
9244/// A column landing *inside* a character — the second cell of `你`, or any cell
9245/// but the first of an emoji — resolves to that character's start, which is the
9246/// column the caret would have been drawn at to begin with. So both cells of a
9247/// wide character mean the character, and every offset survives the round trip
9248/// out to a column and back. The walk steps by grapheme cluster for the same
9249/// reason the caret does: a cluster is the character, and the cells belong to it
9250/// rather than to the codepoints spelling it.
9251fn row_col_to_offset(s: &str, row: usize, col: usize) -> usize {
9252    let start = line_start(s, row);
9253    let end = line_end_from(s, start);
9254    let mut off = start;
9255    let mut at = 0; // the display column `off` sits at
9256    while off < end {
9257        let next = next_boundary(s, off).min(end);
9258        let cells = wysiwyg::text_width(&s[off..next]);
9259        if at + cells > col {
9260            break; // `col` is one of this cluster's own cells
9261        }
9262        at += cells;
9263        off = next;
9264    }
9265    off
9266}
9267
9268fn line_start(s: &str, row: usize) -> usize {
9269    if row == 0 {
9270        return 0;
9271    }
9272    let mut r = 0;
9273    for (i, &b) in s.as_bytes().iter().enumerate() {
9274        if b == b'\n' {
9275            r += 1;
9276            if r == row {
9277                return i + 1;
9278            }
9279        }
9280    }
9281    s.len()
9282}
9283
9284fn line_end_from(s: &str, start: usize) -> usize {
9285    s[start..].find('\n').map(|p| start + p).unwrap_or(s.len())
9286}
9287
9288/// twig's node-kind name for an inline mark, back to the [`InlineKind`] a
9289/// frontend names when it calls [`Doc::toggle`] — the inverse of the mapping
9290/// twig applies writing the mark out, so the toolbar can light the same button
9291/// that made the node.
9292///
9293/// `None` for every other kind, including the inline nodes that aren't marks at
9294/// all (`str`, `link`, `image`, the math and break kinds): they're things a
9295/// caret stands in, not formatting a button toggles.
9296/// Whether a match from an ancestor chain is an inline run whose delimiters
9297/// the rich view draws nothing for — a mark (`**`, `_`, `==`), or an
9298/// attributed span: `<span data-size="large">…</span>`, djot's `[…]{…}`. The
9299/// span is a [`Kind::Container`], which the kind alone cannot tell from a
9300/// block `<div>`, so the chain's caller passes [`Doc::run_span_ids`] and the
9301/// answer is the node's own. Every delete and caret step that walks over a
9302/// `**` walks over a span's tags by this test; without it Backspace after
9303/// `</span>` took the `>` and left the paragraph unparseable.
9304fn hides_delims(m: &QueryMatch, run_spans: &[NodeId]) -> bool {
9305    inline_kind(&m.kind).is_some() || run_spans.contains(&NodeId(m.node_id))
9306}
9307
9308fn inline_kind(kind: &Kind) -> Option<InlineKind> {
9309    Some(match kind {
9310        Kind::Strong => InlineKind::Strong,
9311        Kind::Emph => InlineKind::Emph,
9312        Kind::Verbatim => InlineKind::Verbatim,
9313        Kind::Mark => InlineKind::Mark,
9314        Kind::Superscript => InlineKind::Superscript,
9315        Kind::Subscript => InlineKind::Subscript,
9316        Kind::Insert => InlineKind::Insert,
9317        Kind::Delete => InlineKind::Delete,
9318        _ => return None,
9319    })
9320}
9321
9322/// leaf's [`MarkColor`] as twig's — the palette twig writes as the emoji after
9323/// a highlight's opening `==`.
9324///
9325/// Two enums for one closed vocabulary, and the duplication is the boundary
9326/// working: core's is what a *frontend* names (`style::MarkColor`, beside the
9327/// [`Role`](crate::Role) that carries it into the glyph map) and twig's is what
9328/// the editor writes. Spelled as a match rather than routed through the two
9329/// crates' name strings so that a colour added on either side is a compile
9330/// error here, where the pairing is decided, rather than a runtime `None` that
9331/// would read as "clear the colour".
9332fn twig_mark_color(color: MarkColor) -> twig::MarkColor {
9333    match color {
9334        MarkColor::Red => twig::MarkColor::Red,
9335        MarkColor::Orange => twig::MarkColor::Orange,
9336        MarkColor::Yellow => twig::MarkColor::Yellow,
9337        MarkColor::Green => twig::MarkColor::Green,
9338        MarkColor::Blue => twig::MarkColor::Blue,
9339        MarkColor::Purple => twig::MarkColor::Purple,
9340        MarkColor::Brown => twig::MarkColor::Brown,
9341    }
9342}
9343
9344/// Where an offset lands after a splice it didn't make — twig's own rule, from
9345/// [`Change`]: shift anything at or past the replaced range's end by the length
9346/// the replacement gained or lost, and leave anything before it alone.
9347///
9348/// An offset *inside* the replaced range has no text of its own to ride any
9349/// more, and lands at the end of what replaced it: for
9350/// [`Doc::set_mark_color`] that is a caret standing on the colour prefix when
9351/// the prefix is cleared, which then sits where the highlighted text begins.
9352/// One node's attribute list, twig's own `(key, value)` pairs owned — what
9353/// every presentation gesture reads, edits one key of, and passes back whole.
9354type Attrs = Vec<(String, Option<String>)>;
9355
9356/// The name of the leaf directive a page break is — [`Doc::insert_page_break`]
9357/// writes it and the walker draws it, and a frontend that paginates matches a
9358/// [`DirectiveMark`](crate::wysiwyg::DirectiveMark) against it. One spelling,
9359/// stated once.
9360pub const PAGE_BREAK: &str = "page-break";
9361
9362/// `attrs` with `key` set to `value`, or removed when `value` is `None`, and
9363/// every other attribute kept in its place — the read-edit-write half of twig's
9364/// replace-not-merge contract for a `data-` key.
9365///
9366/// **A key that is already there is rewritten where it stands**, and only a key
9367/// the node did not have goes on the end. That is what makes the proposal's
9368/// worked example true: `class="lead center" id="intro"
9369/// data-line-height="1.5"`, right-aligned, is `class="lead right" id="intro"
9370/// data-line-height="1.5"` — the same document with one token changed, and a
9371/// one-line diff. Removing the key and pushing it back would reorder the
9372/// author's attributes on every press, so a document that passed through the
9373/// editor came out shuffled even where nothing about it had changed.
9374///
9375/// A duplicate key — which no format leaf opens can spell, but twig reports
9376/// verbatim — collapses onto the first of its copies, since twig is handed one
9377/// value for one key either way.
9378fn with_attr(attrs: &[(String, Option<String>)], key: &str, value: Option<&str>) -> Attrs {
9379    let mut out: Attrs = Vec::with_capacity(attrs.len() + 1);
9380    let mut written = false;
9381    for (k, v) in attrs {
9382        if k != key {
9383            out.push((k.clone(), v.clone()));
9384            continue;
9385        }
9386        if let Some(new) = value.filter(|_| !written) {
9387            out.push((k.clone(), Some(new.to_string())));
9388            written = true;
9389        }
9390    }
9391    if let Some(new) = value.filter(|_| !written) {
9392        out.push((key.to_string(), Some(new.to_string())));
9393    }
9394    out
9395}
9396
9397/// [`with_attr`] for a `class` token: every token `mine` claims is removed, and
9398/// `token` added, with the rest of the list kept in order.
9399///
9400/// `class` is a space-separated token list, and leaf owns three of the tokens in
9401/// it. A paragraph that arrives as `class="lead center"` and is right-aligned
9402/// goes out as `class="lead right"`; one whose last owned token goes and which
9403/// carried nothing else loses the key, so a block that has lost its whole
9404/// vocabulary is spelled bare again. `class` itself keeps its place among the
9405/// attributes, because [`with_attr`] does the writing.
9406fn with_class_token(
9407    attrs: &[(String, Option<String>)],
9408    mine: impl Fn(&str) -> bool,
9409    token: Option<&str>,
9410) -> Attrs {
9411    let kept: Vec<&str> = attrs
9412        .iter()
9413        .find(|(k, _)| k == "class")
9414        .and_then(|(_, v)| v.as_deref())
9415        .unwrap_or_default()
9416        .split_whitespace()
9417        .filter(|t| !mine(t))
9418        .collect();
9419    let class = kept.into_iter().chain(token).collect::<Vec<_>>().join(" ");
9420    with_attr(
9421        attrs,
9422        "class",
9423        (!class.is_empty()).then_some(class.as_str()),
9424    )
9425}
9426
9427/// An owned attribute list as the borrowed pairs twig's two attribute ops take.
9428///
9429/// A **bare** attribute — one twig reports with no value, such as HTML's `<p
9430/// hidden>` — is passed back as an empty one. Twig refuses a `None` outright
9431/// (djot has no bare attribute, so no format reads one back everywhere), and
9432/// `hidden=""` is the same document where `hidden` is; dropping it instead
9433/// would lose what the author wrote, which is the one thing these gestures
9434/// promise not to do.
9435fn attr_pairs(attrs: &[(String, Option<String>)]) -> Vec<(&str, Option<&str>)> {
9436    attrs
9437        .iter()
9438        .map(|(k, v)| (k.as_str(), Some(v.as_deref().unwrap_or_default())))
9439        .collect()
9440}
9441
9442fn reanchor(off: usize, change: &Change) -> usize {
9443    if off < change.old.start {
9444        return off;
9445    }
9446    if off < change.old.end {
9447        return change.new.end;
9448    }
9449    (off + change.new.end).saturating_sub(change.old.end)
9450}
9451
9452/// [`reanchor`] for an edit that respells the markup *around* a block and
9453/// leaves the block's own bytes alone — which is every attribute gesture.
9454///
9455/// `block` is that block's content span before and after the splice, so an
9456/// offset standing in the text keeps its distance from the text's start and how
9457/// many bytes twig wrote above it never enters the arithmetic. That is the whole
9458/// rule, and it is why nothing here knows how long a `<div …>` is: a second key
9459/// on the same div lengthens the attribute line, clearing the last one takes the
9460/// div away entirely, and both are the same sum. `None` where the splice named
9461/// no block at either end, which is every djot case — the `{…}` line is written
9462/// above the block, and the block itself only shifts past it.
9463///
9464/// Anywhere else it is `reanchor`'s own answer: untouched before the splice,
9465/// shifted by its delta after it, and at the splice's end for an offset that
9466/// stood in markup being rewritten — a caret inside djot's `{…}` line has no
9467/// text to keep.
9468fn reanchor_in_block(
9469    off: usize,
9470    change: &Change,
9471    block: Option<(&Range<usize>, &Range<usize>)>,
9472) -> usize {
9473    if let Some((was, now)) = block
9474        && was.start <= off
9475        && off <= was.end
9476    {
9477        return now.start + (off - was.start).min(now.end - now.start);
9478    }
9479    reanchor(off, change)
9480}
9481
9482/// A watermark for a file's contents (see `Doc::disk_hash`).
9483///
9484/// `DefaultHasher` is not stable across Rust releases, which doesn't matter: a
9485/// watermark is compared only against one taken by the same process moments
9486/// earlier, and never outlives it. 64 bits leaves a collision — an external edit
9487/// that hashes to exactly what leaf wrote — at odds no filesystem race gets near.
9488fn hash_bytes(bytes: &[u8]) -> u64 {
9489    use std::hash::{Hash, Hasher};
9490    let mut h = std::collections::hash_map::DefaultHasher::new();
9491    bytes.hash(&mut h);
9492    h.finish()
9493}
9494
9495#[cfg(feature = "fs")]
9496fn detect_format(path: &Path) -> Result<Format> {
9497    let ext = path
9498        .extension()
9499        .and_then(|e| e.to_str())
9500        .unwrap_or("")
9501        .to_ascii_lowercase();
9502    Ok(match ext.as_str() {
9503        "dj" | "djot" => Format::Djot,
9504        "md" | "markdown" => Format::Markdown,
9505        "xml" => Format::Xml,
9506        "html" | "htm" => Format::Html,
9507        other => return Err(anyhow!("unknown document extension: .{other}")),
9508    })
9509}
9510
9511#[cfg(test)]
9512mod tests {
9513    use super::*;
9514    use crate::style::{FontFamily, LineSpacing, SizeStep};
9515
9516    /// A document open in `view`. WYSIWYG motion reads the visual map, which the
9517    /// renderer stamps each frame, so the map is built here too — a WYSIWYG doc
9518    /// without one is a view no user is ever in.
9519    fn doc_in(view: View, name: &str, body: &str) -> Doc {
9520        // The fixture name doubles as the temp file's, so two tests picking the
9521        // same one raced under the parallel runner and read each other's body —
9522        // a green suite proving the wrong thing. The counter makes that
9523        // unreachable rather than asking every future caller to notice.
9524        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
9525        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9526        let mut p = std::env::temp_dir();
9527        p.push(format!("leaf_test_{name}_{seq}.md"));
9528        std::fs::write(&p, body).unwrap();
9529        let mut d = Doc::open(p).unwrap();
9530        d.view = view;
9531        if view == View::Wysiwyg {
9532            d.build_visual(80);
9533        }
9534        d
9535    }
9536
9537    // Source-view document for the source-behaviour tests. `Doc::open` now
9538    // defaults to WYSIWYG (leaf's default view), so pin the source view here;
9539    // `wysiwyg_doc` builds the rich-text variant on top of this.
9540    fn doc_with(name: &str, body: &str) -> Doc {
9541        doc_in(View::Source, name, body)
9542    }
9543
9544    /// Every visual row's drawn text — what the reader actually sees, which is
9545    /// the only thing the reveal preference is supposed to change.
9546    fn drawn_rows(d: &Doc) -> Vec<String> {
9547        d.vmap
9548            .rows
9549            .iter()
9550            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9551            .collect()
9552    }
9553
9554    /// Put the caret at the first byte of `needle` and rebuild, so the row under
9555    /// it becomes the revealed line.
9556    fn caret_at(d: &mut Doc, needle: &str) {
9557        d.caret = d.source.find(needle).expect("needle in source");
9558        d.build_visual(80);
9559    }
9560
9561    #[test]
9562    fn blockquote_after_a_list_is_not_bulleted() {
9563        // twig nests a following top-level block quote under the `bullet_list`
9564        // (a direct child, not a `list_item`). The map must render it de-nested —
9565        // `│ quote`, never `• │ quote` — with a blank separator, like any block
9566        // that follows a list. Regression for the "combined list + blockquote" bug.
9567        let mut d = doc_in(View::Wysiwyg, "bq_after_list", "- item\n\n> quote\n");
9568        d.build_visual(80);
9569        let rows: Vec<String> = d
9570            .vmap
9571            .rows
9572            .iter()
9573            .map(|r| r.glyphs.iter().map(|g| g.ch).collect())
9574            .collect();
9575        assert!(
9576            rows.iter().any(|r| r == "│ quote"),
9577            "block quote should render on its own gutter, got rows: {rows:?}"
9578        );
9579        assert!(
9580            !rows.iter().any(|r| r.contains('•') && r.contains('│')),
9581            "no row should carry both a bullet and a quote gutter, got rows: {rows:?}"
9582        );
9583    }
9584
9585    // ── the map is built at most once per (revision, wrap) ───────────────────
9586    //
9587    // A frontend repaints for reasons that have nothing to do with the text — a
9588    // blinking caret, a scroll — and rebuilding the map is O(document). These
9589    // pin *that the cache fires*, which a passing suite can't tell you: a cache
9590    // that never hits is invisible to every other test in this file.
9591    //
9592    // The probe is to wreck the built map and ask for it again. A rebuild
9593    // repairs it; a cache hit hands the wreckage straight back. Nothing else
9594    // can distinguish the two from outside.
9595
9596    #[test]
9597    fn a_rebuild_with_nothing_changed_reuses_the_map() {
9598        let mut d = doc_in(View::Wysiwyg, "cache_hit", "# Title\n\nbody\n");
9599        d.build_visual(80);
9600        assert!(!d.vmap.rows.is_empty());
9601        d.vmap.rows.clear(); // wreck it
9602        d.build_visual(80);
9603        assert!(
9604            d.vmap.rows.is_empty(),
9605            "the map was rebuilt though nothing changed — the cache never fired"
9606        );
9607    }
9608
9609    #[test]
9610    fn an_edit_rebuilds_the_map() {
9611        let mut d = doc_in(View::Wysiwyg, "cache_edit", "# Title\n\nbody\n");
9612        d.build_visual(80);
9613        let before = d.revision();
9614        d.vmap.rows.clear();
9615        d.insert("x");
9616        d.build_visual(80);
9617        assert!(d.revision() > before, "an edit must move the revision");
9618        assert!(
9619            !d.vmap.rows.is_empty(),
9620            "an edited document must not paint from a stale map"
9621        );
9622    }
9623
9624    #[test]
9625    fn a_width_change_rebuilds_the_map() {
9626        // The map is a function of the wrap width too, so a resize is a miss
9627        // even though the text is untouched.
9628        let mut d = doc_in(
9629            View::Wysiwyg,
9630            "cache_width",
9631            "one two three four five six\n",
9632        );
9633        d.build_visual(80);
9634        d.vmap.rows.clear();
9635        d.build_visual(12);
9636        assert!(!d.vmap.rows.is_empty(), "a resize must rebuild the map");
9637        // And the unwrapped map is its own key, not the same as any width.
9638        d.vmap.rows.clear();
9639        d.build_visual_unwrapped();
9640        assert!(!d.vmap.rows.is_empty(), "unwrapped is a different map");
9641    }
9642
9643    #[test]
9644    fn a_motion_does_not_rebuild_the_map() {
9645        // The whole point: moving the caret changes nothing the map is built
9646        // from. If a motion bumped the revision, every arrow key would cost a
9647        // full rebuild and the cache would be worthless.
9648        let mut d = doc_in(View::Wysiwyg, "cache_motion", "# Title\n\nbody text\n");
9649        d.build_visual(80);
9650        let rev = d.revision();
9651        d.move_right(false);
9652        d.move_right(true);
9653        d.move_down(false);
9654        assert_eq!(d.revision(), rev, "a motion must not move the revision");
9655        d.vmap.rows.clear();
9656        d.build_visual(80);
9657        assert!(
9658            d.vmap.rows.is_empty(),
9659            "a motion should not rebuild the map"
9660        );
9661    }
9662
9663    #[test]
9664    fn saving_does_not_rebuild_the_map() {
9665        // Saving changes `dirty`, not the text.
9666        let mut d = doc_in(View::Wysiwyg, "cache_save", "# Title\n\nbody\n");
9667        d.insert("x");
9668        d.build_visual(80);
9669        let rev = d.revision();
9670        d.save();
9671        assert_eq!(d.revision(), rev, "a save must not move the revision");
9672        assert!(!d.dirty, "the save should have cleaned the document");
9673    }
9674
9675    #[test]
9676    fn a_reload_rebuilds_the_map() {
9677        // Reload replaces the text without going through `refresh`, so it has to
9678        // move the revision itself — else the editor paints the old file.
9679        let mut d = doc_in(View::Wysiwyg, "cache_reload", "# Title\n\nbody\n");
9680        d.build_visual(80);
9681        let rev = d.revision();
9682        std::fs::write(&d.path, "# Other\n\nwholly new\n").unwrap();
9683        d.reload();
9684        assert!(d.revision() > rev, "a reload must move the revision");
9685        d.build_visual(80);
9686        let text: String = d
9687            .vmap
9688            .rows
9689            .iter()
9690            .flat_map(|r| r.glyphs.iter().map(|g| g.ch))
9691            .collect();
9692        assert!(
9693            text.contains("wholly new"),
9694            "the reloaded text should be on screen, got {text:?}"
9695        );
9696    }
9697
9698    // ── golden-case harness ──────────────────────────────────────────────────
9699    // The pattern the whole parity suite can reuse: write a fixture with the
9700    // caret marked by `|`, run one action, and compare the rendered result —
9701    // also caret-marked — against the expected string. One readable line per
9702    // behavior, and it exercises the exact `Doc` ops both frontends call.
9703
9704    /// Split a `|`-marked fixture into `(source, caret_offset)`.
9705    fn parse_caret(marked: &str) -> (String, usize) {
9706        let caret = marked.find('|').expect("fixture needs a `|` caret marker");
9707        (marked.replacen('|', "", 1), caret)
9708    }
9709
9710    /// Render a doc's source with `|` at the caret (and `[`…`]` around any
9711    /// selection) so a result reads like the fixtures.
9712    fn render_caret(d: &Doc) -> String {
9713        // (offset, rank, char); rank keeps coincident markers ordered `[ | ]`
9714        // so the caret always renders inside its own selection.
9715        let mut marks: Vec<(usize, u8, char)> = vec![(d.caret, 1, '|')];
9716        if let Some((s, e)) = d.selection() {
9717            marks.push((s, 0, '['));
9718            marks.push((e, 2, ']'));
9719        }
9720        // Insert right-to-left: descending offset, then descending rank.
9721        marks.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
9722        let mut out = d.source.clone();
9723        for (at, _, ch) in marks {
9724            out.insert(at, ch);
9725        }
9726        out
9727    }
9728
9729    /// Load a `|`-marked fixture, run `action`, return the caret-marked result.
9730    fn golden(name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9731        golden_in(View::Source, name, marked, action)
9732    }
9733
9734    /// [`golden`] in a chosen view — the editing ops are the view's to share, so
9735    /// the same fixture has to read the same way in both.
9736    fn golden_in(view: View, name: &str, marked: &str, action: impl FnOnce(&mut Doc)) -> String {
9737        let (src, caret) = parse_caret(marked);
9738        let mut d = doc_in(view, name, &src);
9739        d.caret = caret;
9740        action(&mut d);
9741        render_caret(&d)
9742    }
9743
9744    #[test]
9745    fn word_motion_walks_word_by_word() {
9746        let g = |m, f: fn(&mut Doc)| golden("word_motion", m, f);
9747        assert_eq!(
9748            g("hello wor|ld", |d| d.move_word_left(false)),
9749            "hello |world"
9750        );
9751        assert_eq!(
9752            g("hello| world", |d| d.move_word_left(false)),
9753            "|hello world"
9754        );
9755        assert_eq!(
9756            g("hel|lo world", |d| d.move_word_right(false)),
9757            "hello| world"
9758        );
9759        assert_eq!(
9760            g("hello| world", |d| d.move_word_right(false)),
9761            "hello world|"
9762        );
9763        // Punctuation is its own class, so motion stops at the boundary.
9764        assert_eq!(g("|foo.bar", |d| d.move_word_right(false)), "foo|.bar");
9765    }
9766
9767    #[test]
9768    fn word_motion_extends_the_selection_when_asked() {
9769        assert_eq!(
9770            golden("word_sel", "hello |world", |d| d.move_word_right(true)),
9771            "hello [world|]"
9772        );
9773    }
9774
9775    #[test]
9776    fn delete_word_removes_a_whole_word() {
9777        let g = |m, f: fn(&mut Doc)| golden("del_word", m, f);
9778        assert_eq!(g("hello world|", |d| d.delete_word_back()), "hello |");
9779        assert_eq!(g("hello |world", |d| d.delete_word_forward()), "hello |");
9780        assert_eq!(g("foo |bar baz", |d| d.delete_word_back()), "|bar baz");
9781    }
9782
9783    // ── Home / End ───────────────────────────────────────────────────────────
9784
9785    #[test]
9786    fn home_toggles_between_the_line_s_text_and_its_margin() {
9787        // Source: the indentation is what the toggle is for. WYSIWYG resolves an
9788        // indent to the markup it spells everywhere it means one, so the fixture
9789        // with whitespace left to walk is a code block, which is verbatim.
9790        let g = |m, f: fn(&mut Doc)| golden("smart_home", m, f);
9791        assert_eq!(g("    inden|ted", |d| d.move_home(false)), "    |indented");
9792        assert_eq!(g("    |indented", |d| d.move_home(false)), "|    indented");
9793        assert_eq!(g("|    indented", |d| d.move_home(false)), "    |indented");
9794        // A line with no indentation has one place to go, so the toggle is a
9795        // no-op rather than a trip to nowhere.
9796        assert_eq!(g("hel|lo", |d| d.move_home(false)), "|hello");
9797        assert_eq!(g("|hello", |d| d.move_home(false)), "|hello");
9798
9799        let mut d = wysiwyg_doc("smart_home_wys", "```\n    indented\n```\n");
9800        let indent = d.source.find("    indented").unwrap();
9801        d.caret = indent + 6; // inside "indented"
9802        d.move_home(false);
9803        assert_eq!(
9804            d.caret,
9805            indent + 4,
9806            "wysiwyg: Home aims at the code line's text"
9807        );
9808        d.move_home(false);
9809        assert_eq!(
9810            d.caret, indent,
9811            "wysiwyg: the second press takes the indent"
9812        );
9813        d.move_home(false);
9814        assert_eq!(d.caret, indent + 4, "wysiwyg: the toggle swaps back");
9815    }
9816
9817    #[test]
9818    fn end_takes_the_line_the_view_is_showing() {
9819        // The line differs by view for the same document, and that is the point:
9820        // a bare newline inside a paragraph is a soft break, which WYSIWYG draws
9821        // as a space on one row and the source view as two lines.
9822        let mut d = doc_with("end_src", "one two\nthree\n");
9823        d.caret = 1;
9824        d.move_end(false);
9825        assert_eq!(d.caret, 7, "source: the end of the source line");
9826
9827        let mut d = wysiwyg_doc("end_wys", "one two\nthree\n");
9828        d.caret = 1;
9829        d.move_end(false);
9830        assert_eq!(
9831            d.caret, 13,
9832            "wysiwyg: the end of the row, soft break and all"
9833        );
9834    }
9835
9836    #[test]
9837    fn home_and_end_extend_the_selection_when_asked() {
9838        for (view, tag) in VIEWS {
9839            let mut d = doc_in(view, &format!("home_end_ext_{tag}"), "hello world");
9840            d.caret = 6;
9841            d.move_end(true);
9842            assert_eq!(d.selection(), Some((6, 11)), "{tag}: End extends");
9843            let mut d = doc_in(view, &format!("home_ext_{tag}"), "hello world");
9844            d.caret = 6;
9845            d.move_home(true);
9846            assert_eq!(d.selection(), Some((0, 6)), "{tag}: Home extends");
9847        }
9848    }
9849
9850    // ── kill to the line's start / end ───────────────────────────────────────
9851
9852    #[test]
9853    fn kill_to_the_line_start_and_end_in_both_views() {
9854        for (view, tag) in VIEWS {
9855            // The gap that reads as a paragraph break in each view: the source
9856            // view's lines are the renderer's rows only where the source says so.
9857            let gap = if view == View::Source { "\n" } else { "\n\n" };
9858            let mut d = doc_in(
9859                view,
9860                &format!("kill_end_{tag}"),
9861                &format!("one two{gap}three\n"),
9862            );
9863            d.caret = 3;
9864            d.delete_to_line_end();
9865            assert_eq!(
9866                d.source,
9867                format!("one{gap}three\n"),
9868                "{tag}: ^K to the line's end"
9869            );
9870            assert_eq!(d.caret, 3, "{tag}: the caret stays where it kills from");
9871
9872            let mut d = doc_in(
9873                view,
9874                &format!("kill_start_{tag}"),
9875                &format!("one two{gap}three\n"),
9876            );
9877            d.caret = 7; // the end of the first line
9878            d.delete_to_line_start();
9879            assert_eq!(
9880                d.source,
9881                format!("{gap}three\n"),
9882                "{tag}: ⌘⌫ to the line's start"
9883            );
9884            assert_eq!(d.caret, 0, "{tag}");
9885        }
9886    }
9887
9888    #[test]
9889    fn a_kill_at_the_line_s_edge_leaves_the_lines_joined() {
9890        // The decision: at the boundary both kills do nothing, rather than
9891        // eating the line break. "Line" is the view's own — in WYSIWYG it ends
9892        // at a soft wrap as often as at a newline, where there is nothing
9893        // written to delete — and a source newline is only half of the blank
9894        // line between two paragraphs, so taking it leaves a soft break rather
9895        // than the join it looks like. Backspace and Delete are the keys for it.
9896        for (view, tag) in VIEWS {
9897            let gap = if view == View::Source { "\n" } else { "\n\n" };
9898            let src = format!("one{gap}three\n");
9899            let mut d = doc_in(view, &format!("kill_edge_end_{tag}"), &src);
9900            d.caret = 3; // the end of "one"
9901            d.delete_to_line_end();
9902            assert_eq!(
9903                d.source, src,
9904                "{tag}: ^K at the line's end joined it to the next"
9905            );
9906
9907            let mut d = doc_in(view, &format!("kill_edge_start_{tag}"), &src);
9908            d.caret = 3 + gap.len(); // the start of "three"
9909            d.delete_to_line_start();
9910            assert_eq!(
9911                d.source, src,
9912                "{tag}: ⌘⌫ at the line's start joined it to the last"
9913            );
9914        }
9915    }
9916
9917    #[test]
9918    fn a_kill_takes_the_selection_when_there_is_one() {
9919        // What every other delete here does with one, so these two as well.
9920        for (view, tag) in VIEWS {
9921            for (name, kill) in [
9922                (
9923                    "end",
9924                    (|d: &mut Doc| d.delete_to_line_end()) as fn(&mut Doc),
9925                ),
9926                ("start", |d: &mut Doc| d.delete_to_line_start()),
9927            ] {
9928                let mut d = doc_in(view, &format!("kill_sel_{name}_{tag}"), "one two three\n");
9929                d.anchor = Some(4);
9930                d.caret = 7; // "two"
9931                kill(&mut d);
9932                assert_eq!(
9933                    d.source, "one  three\n",
9934                    "{tag}: {name} ignored the selection"
9935                );
9936                assert_eq!(d.selection(), None, "{tag}: {name}");
9937            }
9938        }
9939    }
9940
9941    #[test]
9942    fn a_kill_takes_the_markup_it_empties_with_it() {
9943        // The same hazard a word-delete has: a WYSIWYG range covers what the
9944        // user can see, which for `**bold**` is the word and never the
9945        // delimiters, so a kill that stopped at the text would leave `a ****` —
9946        // markup wrapped around nothing.
9947        let mut d = wysiwyg_doc("kill_widen", "a **bold**\n");
9948        d.caret = d.source.find("bold").unwrap();
9949        d.delete_to_line_end();
9950        assert_eq!(d.source, "a \n");
9951    }
9952
9953    #[test]
9954    fn a_kill_is_undone_in_one_step() {
9955        for (view, tag) in VIEWS {
9956            let mut d = doc_in(view, &format!("kill_undo_{tag}"), "one two three\n");
9957            d.caret = 3;
9958            d.delete_to_line_end();
9959            assert_eq!(d.source, "one\n", "{tag}");
9960            d.undo();
9961            assert_eq!(d.source, "one two three\n", "{tag}: a kill takes one undo");
9962        }
9963    }
9964
9965    #[test]
9966    fn select_block_grabs_the_whole_paragraph_from_any_wrapped_row() {
9967        // Regression: triple-click used move_home/move_end over visual rows, so
9968        // it only worked on a paragraph's first row (a wrap-boundary offset maps
9969        // to the earlier row). select_block_at reads the AST, so every offset in
9970        // the paragraph selects the whole thing.
9971        let body = "one two three four five six seven eight\n";
9972        let mut d = doc_with("sel_block", body);
9973        d.view = View::Wysiwyg;
9974        d.build_visual(12); // force the paragraph to wrap into several rows
9975        assert!(d.vmap.num_rows() > 1, "test needs a wrapped paragraph");
9976        let para = (0, "one two three four five six seven eight".len());
9977        for off in [0usize, 8, 19, 28, 38] {
9978            d.caret = 0;
9979            d.anchor = None;
9980            d.select_block_at(off);
9981            assert_eq!(
9982                d.selection(),
9983                Some(para),
9984                "offset {off} should select the paragraph"
9985            );
9986        }
9987    }
9988
9989    #[test]
9990    fn select_block_uses_content_span_for_a_heading() {
9991        let mut d = doc_with("sel_head", "# Title\n\nbody\n");
9992        d.select_block_at(4); // inside "Title"
9993        // content_span excludes the "# " marker.
9994        assert_eq!(d.selected_text(), Some("Title"));
9995        d.select_block_at(10); // inside "body"
9996        assert_eq!(d.selected_text(), Some("body"));
9997    }
9998
9999    #[test]
10000    fn select_all_spans_the_document() {
10001        let mut d = doc_with("sel_all", "abc\n\ndef\n");
10002        d.select_all();
10003        assert_eq!(d.selection(), Some((0, d.source.len())));
10004    }
10005
10006    #[test]
10007    fn select_word_at_picks_the_surrounding_word() {
10008        let mut d = doc_with("sel_word", "hello world\n");
10009        d.select_word_at(8); // inside "world"
10010        assert_eq!(d.selection(), Some((6, 11)));
10011        // Double-clicking at end-of-word still grabs the word to its left.
10012        d.select_word_at(5); // the space between the words
10013        assert_eq!(d.selection(), Some((5, 6)));
10014    }
10015
10016    #[test]
10017    fn word_helpers_respect_utf8_boundaries() {
10018        // "café" is 5 bytes ('é' is two); motion must land on char boundaries.
10019        assert_eq!(
10020            golden("utf8", "|café ok", |d| d.move_word_right(false)),
10021            "café| ok"
10022        );
10023        assert_eq!(golden("utf8b", "café |ok", |d| d.delete_word_back()), "|ok");
10024    }
10025
10026    #[test]
10027    fn typing_inserts_at_the_caret_and_advances_it() {
10028        let mut d = doc_with("type", "hello\n");
10029        d.insert("Hi ");
10030        assert_eq!(d.source, "Hi hello\n");
10031        assert_eq!(d.caret, 3);
10032        assert!(d.dirty);
10033    }
10034
10035    #[test]
10036    fn backspace_deletes_the_char_before_the_caret() {
10037        let mut d = doc_with("bs", "hello\n");
10038        d.caret = 3; // after "hel"
10039        d.backspace();
10040        assert_eq!(d.source, "helo\n");
10041        assert_eq!(d.caret, 2);
10042    }
10043
10044    #[test]
10045    fn typing_replaces_the_selection() {
10046        let mut d = doc_with("replace", "a word b\n");
10047        d.anchor = Some(2);
10048        d.caret = 6; // "word" selected
10049        d.insert("X");
10050        assert_eq!(d.source, "a X b\n");
10051        assert_eq!(d.caret, 3);
10052        assert_eq!(d.anchor, None);
10053    }
10054
10055    #[test]
10056    fn toggle_bold_wraps_then_unwraps_the_selection() {
10057        let mut d = doc_with("bold", "a word b\n");
10058        d.anchor = Some(2);
10059        d.caret = 6;
10060        d.toggle(InlineKind::Strong);
10061        assert_eq!(d.source, "a **word** b\n");
10062        // The toggled region stays selected, so a second toggle reverses it.
10063        d.toggle(InlineKind::Strong);
10064        assert_eq!(d.source, "a word b\n");
10065        d.toggle(InlineKind::Strong);
10066        assert_eq!(d.source, "a **word** b\n");
10067    }
10068
10069    #[test]
10070    fn toggle_code_wraps_then_unwraps_the_selection() {
10071        let mut d = doc_with("code_rt", "a word b\n");
10072        d.anchor = Some(2);
10073        d.caret = 6;
10074        d.toggle(InlineKind::Verbatim);
10075        assert_eq!(d.source, "a `word` b\n");
10076        d.toggle(InlineKind::Verbatim);
10077        assert_eq!(d.source, "a word b\n");
10078    }
10079
10080    #[test]
10081    fn sticky_bold_with_no_selection_wraps_the_next_typed_text() {
10082        // ⌘b at a bare caret, then type: the text comes out bold with no
10083        // selection ever made — the word-processor "start bold here" gesture.
10084        let mut d = doc_with("sticky_wrap", "xy\n");
10085        d.caret = 1; // between x and y
10086        d.toggle(InlineKind::Strong);
10087        assert_eq!(d.source, "xy\n", "arming a mark must not edit the document");
10088        d.insert("A");
10089        assert_eq!(d.source, "x**A**y\n");
10090    }
10091
10092    #[test]
10093    fn sticky_bold_lights_the_toolbar_before_any_typing() {
10094        // The button must light the instant ⌘b is pressed, or the mode is
10095        // invisible until the first character lands.
10096        let mut d = doc_with("sticky_light", "xy\n");
10097        d.caret = 1;
10098        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10099        d.toggle(InlineKind::Strong);
10100        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10101    }
10102
10103    #[test]
10104    fn sticky_bold_toggled_off_types_normally_again() {
10105        // ⌘b, type, ⌘b, type: the first run is bold, the second is not — all
10106        // in the flow of typing, the exact sequence the user described.
10107        let mut d = doc_with("sticky_off", "\n");
10108        d.caret = 0;
10109        d.toggle(InlineKind::Strong);
10110        d.insert("a");
10111        d.insert("b"); // continues inside the run, no re-arming
10112        assert_eq!(d.source, "**ab**\n");
10113        d.toggle(InlineKind::Strong); // ⌘b again — shed bold
10114        d.insert("c");
10115        assert_eq!(d.source, "**ab**c\n");
10116    }
10117
10118    #[test]
10119    fn continued_typing_after_a_sticky_run_stays_in_the_run() {
10120        // Once a mark is realised the caret sits inside the run, so plain typing
10121        // extends it rather than starting a second, adjacent bold span.
10122        let mut d = doc_with("sticky_cont", "\n");
10123        d.caret = 0;
10124        d.toggle(InlineKind::Emph);
10125        d.insert("h");
10126        d.insert("i");
10127        assert_eq!(d.source, "*hi*\n");
10128    }
10129
10130    #[test]
10131    fn moving_the_caret_disarms_a_sticky_mark() {
10132        // Arming a mark and then moving away must not style text elsewhere.
10133        let mut d = doc_with("sticky_disarm", "xy\n");
10134        d.caret = 0;
10135        d.toggle(InlineKind::Strong);
10136        d.move_right(false); // caret 0 → 1, disarms
10137        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10138        d.insert("A");
10139        assert_eq!(d.source, "xAy\n", "the mark must not follow the caret");
10140    }
10141
10142    #[test]
10143    fn stacked_sticky_marks_apply_together() {
10144        // ⌘b then ⌘i before typing: the text comes out both bold and italic.
10145        let mut d = doc_with("sticky_stack", "\n");
10146        d.caret = 0;
10147        d.toggle(InlineKind::Strong);
10148        d.toggle(InlineKind::Emph);
10149        d.insert("x");
10150        // Land the caret on the styled character and confirm both marks are live.
10151        d.anchor = Some(d.source.find('x').unwrap());
10152        d.caret = d.anchor.unwrap() + 1;
10153        let marks = d.active_inline_marks();
10154        assert!(marks.contains(InlineKind::Strong), "bold: {}", d.source);
10155        assert!(marks.contains(InlineKind::Emph), "italic: {}", d.source);
10156    }
10157
10158    // ── the mark-edge rule (see `Doc::splice`) ───────────────────────────────
10159
10160    #[test]
10161    fn a_space_typed_in_a_bold_run_never_leaves_the_delimiters_showing() {
10162        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, "hey".
10163        // The space inside the run made `**bold **`, which is *not* bold — four
10164        // literal asterisks — so the rich view drew them, correctly and
10165        // uselessly, until the next character happened to close the run again.
10166        let mut d = wysiwyg_doc("edge_typing", "a \n");
10167        d.caret = 2;
10168        d.toggle(InlineKind::Strong);
10169        for c in "bold".chars() {
10170            d.insert(&c.to_string());
10171        }
10172        assert_eq!(d.source, "a **bold**\n");
10173        d.insert(" ");
10174        assert_eq!(
10175            d.source, "a **bold** \n",
10176            "the space belongs outside the run"
10177        );
10178        assert!(
10179            d.active_inline_marks().contains(InlineKind::Strong),
10180            "bold is still what's being typed, so the button stays lit"
10181        );
10182        // What the writer is looking at while all this happens: their words.
10183        d.build_visual(80);
10184        let drawn: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
10185        assert_eq!(drawn, "a bold ", "no delimiter ever surfaces: {}", d.source);
10186        for c in "hey".chars() {
10187            d.insert(&c.to_string());
10188        }
10189        assert_eq!(
10190            d.source, "a **bold hey**\n",
10191            "one bold phrase, not two runs"
10192        );
10193    }
10194
10195    #[test]
10196    fn typing_past_a_space_can_still_leave_the_bold_behind() {
10197        // The other half: the marks stay armed across the space, so ⌘b turns
10198        // them off again there and the next word is plain — the run isn't
10199        // rejoined by a caret that was told not to.
10200        let mut d = wysiwyg_doc("edge_shed", "\n");
10201        d.caret = 0;
10202        d.toggle(InlineKind::Strong);
10203        for c in "bold ".chars() {
10204            d.insert(&c.to_string());
10205        }
10206        assert_eq!(d.source, "**bold** \n");
10207        d.toggle(InlineKind::Strong);
10208        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
10209        d.insert("x");
10210        assert_eq!(d.source, "**bold** x\n");
10211    }
10212
10213    #[test]
10214    fn a_space_typed_first_of_all_still_leaves_the_mark_armed() {
10215        // ⌘b and then a space before any word: the space is not marked (nothing
10216        // is), and the word after it is.
10217        let mut d = wysiwyg_doc("edge_space_first", "a\n");
10218        d.caret = 1;
10219        d.toggle(InlineKind::Strong);
10220        d.insert(" ");
10221        assert_eq!(d.source, "a \n");
10222        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10223        d.insert("b");
10224        assert_eq!(d.source, "a **b**\n");
10225    }
10226
10227    #[test]
10228    fn a_space_typed_at_either_edge_of_an_existing_mark_steps_outside_it() {
10229        let mut d = wysiwyg_doc("edge_tail", "x **bold**\n");
10230        d.caret = 8; // the caret's home at the end of the run's text
10231        d.insert(" ");
10232        assert_eq!(
10233            d.source, "x **bold** \n",
10234            "the space lands past the delimiters"
10235        );
10236        assert_eq!(d.caret, 11, "and the caret stands past it, outside the run");
10237
10238        let mut d = wysiwyg_doc("edge_head", "x **bold** y\n");
10239        d.caret = 4; // in front of the "b"
10240        d.insert(" ");
10241        assert_eq!(d.source, "x  **bold** y\n");
10242        assert_eq!(d.caret, 3, "in front of the run, where the space was typed");
10243    }
10244
10245    #[test]
10246    fn a_delete_that_backs_a_space_onto_a_delimiter_moves_the_delimiter() {
10247        // Backspace over the last letter of a bold phrase.
10248        let mut d = wysiwyg_doc("edge_bksp", "a **bold h**\n");
10249        d.caret = 10; // past the "h"
10250        d.backspace();
10251        assert_eq!(d.source, "a **bold** \n");
10252        assert_eq!(d.caret, 11, "the caret keeps the place on screen it had");
10253        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10254        d.insert("x");
10255        assert_eq!(d.source, "a **bold x**\n", "and typing rejoins the run");
10256    }
10257
10258    #[test]
10259    fn deleting_the_last_of_a_run_takes_its_delimiters_with_it() {
10260        // `**b**` with the `b` gone is `****`: two delimiters with nothing to
10261        // mark, which is only text. The marks live on in the caret instead.
10262        let mut d = wysiwyg_doc("edge_empty", "a **b** c\n");
10263        d.caret = 5;
10264        d.backspace();
10265        assert_eq!(d.source, "a  c\n");
10266        assert!(d.active_inline_marks().contains(InlineKind::Strong));
10267        d.insert("x");
10268        assert_eq!(d.source, "a **x** c\n");
10269    }
10270
10271    #[test]
10272    fn typing_over_a_whole_bold_word_keeps_it_bold() {
10273        let mut d = wysiwyg_doc("edge_replace", "a **bold** c\n");
10274        d.anchor = Some(4);
10275        d.caret = 8; // the word, not its delimiters
10276        d.insert("x");
10277        assert_eq!(d.source, "a **x** c\n");
10278    }
10279
10280    #[test]
10281    fn a_code_span_keeps_the_space_it_is_given() {
10282        // Backticks are not whitespace-sensitive the way `**` is: `` `code ` ``
10283        // is still verbatim, so nothing is re-spelt. The repair asks the parser
10284        // rather than a table of kinds, and this is the answer it gets.
10285        let mut d = wysiwyg_doc("edge_code", "a `code` c\n");
10286        d.caret = 7;
10287        d.insert(" ");
10288        assert_eq!(d.source, "a `code ` c\n");
10289    }
10290
10291    #[test]
10292    fn a_delete_from_a_runs_outer_edge_reaches_into_the_run() {
10293        // A run's closing delimiter has a caret home on each side of it, one
10294        // column apart on screen — and a plain ← off the space after a bold word
10295        // lands on the outer one. The character drawn behind the caret there is
10296        // still the last letter of the phrase, so that is what Backspace takes;
10297        // the byte behind it is a `*` nobody can see.
10298        let mut d = wysiwyg_doc("edge_outer_close", "**bold** x\n");
10299        d.caret = 9;
10300        d.move_left(false);
10301        assert_eq!(d.caret, 8, "← rests past the delimiters, not inside them");
10302        d.backspace();
10303        assert_eq!(
10304            d.source, "**bol** x\n",
10305            "a letter of the phrase, not its `*`"
10306        );
10307        assert_eq!(d.caret, 5);
10308
10309        // And the mirror in front of the opening delimiter, where Delete's
10310        // character is the first letter of the run.
10311        let mut d = wysiwyg_doc("edge_outer_open", "x**bold**\n");
10312        d.caret = 1;
10313        d.delete_forward();
10314        assert_eq!(d.source, "x**old**\n");
10315        assert_eq!(d.caret, 3, "inside the run, in front of what is left of it");
10316    }
10317
10318    #[test]
10319    fn a_delete_at_a_run_edge_never_eats_a_delimiter() {
10320        // The byte beside the caret at either edge of a bold word is a `*` the
10321        // rich view draws nothing for. Taking it is not the character delete the
10322        // key was pressed for — it unspells the run and puts a literal asterisk
10323        // on screen (`a *bold** c`). The visible character is the one that goes.
10324        let mut d = wysiwyg_doc("edge_open_bksp", "a **bold** c\n");
10325        d.caret = 4; // in front of the "b"
10326        d.backspace();
10327        assert_eq!(d.source, "a**bold** c\n", "the space goes, the run stands");
10328
10329        let mut d = wysiwyg_doc("edge_close_del", "a **bold** c\n");
10330        d.caret = 8; // past the "d"
10331        d.delete_forward();
10332        assert_eq!(d.source, "a **bold**c\n");
10333        assert_eq!(d.caret, 8, "and the caret stays inside the run");
10334        d.insert("x");
10335        assert_eq!(d.source, "a **boldx**c\n");
10336
10337        // A code span's backticks are hidden the same way, so they are covered
10338        // by the same rule and not by a list of kinds.
10339        let mut d = wysiwyg_doc("edge_open_code", "a `code` c\n");
10340        d.caret = 3;
10341        d.backspace();
10342        assert_eq!(d.source, "a`code` c\n");
10343    }
10344
10345    #[test]
10346    fn the_source_view_deletes_the_delimiter_byte_it_is_shown() {
10347        // The asterisks are on the screen there and the caret can stand between
10348        // them, so a delete takes exactly the byte it is aimed at.
10349        let mut d = doc_with("edge_open_src", "a **bold** c\n");
10350        d.caret = 4;
10351        d.backspace();
10352        assert_eq!(d.source, "a *bold** c\n");
10353
10354        let mut d = doc_with("edge_close_src", "a **bold** c\n");
10355        d.caret = 8;
10356        d.delete_forward();
10357        assert_eq!(d.source, "a **bold* c\n");
10358    }
10359
10360    #[test]
10361    fn backspacing_the_space_out_of_a_bold_phrase_leaves_the_caret_in_it() {
10362        // The reported bug, keystroke for keystroke: ⌘b, "bold", space, Backspace.
10363        // The space had stepped outside the run (the mark-edge rule), taking the
10364        // caret with it, so the delete put it back down on the far side of the
10365        // closing `**` — one place on screen, and the wrong side of it. Typing
10366        // came out plain and the toolbar went dark, with nothing to see.
10367        let mut d = wysiwyg_doc("edge_bksp_space", "\n");
10368        d.caret = 0;
10369        d.toggle(InlineKind::Strong);
10370        for c in "bold".chars() {
10371            d.insert(&c.to_string());
10372        }
10373        d.insert(" ");
10374        assert_eq!(d.source, "**bold** \n");
10375        d.backspace();
10376        assert_eq!(
10377            d.source, "**bold**\n",
10378            "the space goes, the delimiters stay"
10379        );
10380        assert_eq!(d.caret, 6, "and the caret comes back inside the run");
10381        assert!(
10382            d.active_inline_marks().contains(InlineKind::Strong),
10383            "so the button is still lit"
10384        );
10385        d.insert("x");
10386        assert_eq!(
10387            d.source, "**boldx**\n",
10388            "and the next character is still bold"
10389        );
10390    }
10391
10392    #[test]
10393    fn a_second_backspace_there_deletes_a_letter_of_the_phrase() {
10394        // What the stranded caret did next: the byte behind it was the closing
10395        // `*`, so a second press took that instead of a letter — `**bold*`, the
10396        // styling gone and an asterisk on the screen where the word had been.
10397        let mut d = wysiwyg_doc("edge_bksp_twice", "\n");
10398        d.caret = 0;
10399        d.toggle(InlineKind::Strong);
10400        for c in "bold ".chars() {
10401            d.insert(&c.to_string());
10402        }
10403        assert_eq!(d.source, "**bold** \n");
10404        d.backspace();
10405        d.backspace();
10406        assert_eq!(d.source, "**bol**\n", "the delete lands inside the run");
10407        assert_eq!(d.caret, 5);
10408    }
10409
10410    #[test]
10411    fn a_delete_that_ends_at_a_nested_run_settles_inside_every_delimiter() {
10412        // `***both***` closes two runs with one stack of asterisks: the caret has
10413        // to walk in through all of them, or it lands between the emph and the
10414        // strong and types half-marked.
10415        let mut d = wysiwyg_doc("edge_bksp_nested", "***both*** \n");
10416        d.caret = 11;
10417        d.backspace();
10418        assert_eq!(d.source, "***both***\n");
10419        assert_eq!(d.caret, 7, "past the last letter, inside both runs");
10420        d.insert("x");
10421        assert_eq!(d.source, "***bothx***\n");
10422    }
10423
10424    #[test]
10425    fn a_delete_that_ends_mid_run_leaves_the_caret_where_it_fell() {
10426        // The settle only moves a caret a run actually closed over. Ordinary
10427        // deletes — inside a run, or in plain prose — are untouched.
10428        let mut d = wysiwyg_doc("edge_bksp_mid", "a **bold** c\n");
10429        d.caret = 8;
10430        d.backspace();
10431        assert_eq!(d.source, "a **bol** c\n");
10432        assert_eq!(d.caret, 7);
10433
10434        let mut d = wysiwyg_doc("edge_bksp_plain", "plain\n");
10435        d.caret = 5;
10436        d.backspace();
10437        assert_eq!(d.source, "plai\n");
10438        assert_eq!(d.caret, 4);
10439    }
10440
10441    #[test]
10442    fn the_source_view_leaves_a_delete_where_it_landed() {
10443        // The delimiters are on the screen there, so the offset past them is a
10444        // place the caret can be seen to be — nothing to settle.
10445        let mut d = doc_with("edge_bksp_src", "**bold** \n");
10446        d.caret = 9;
10447        d.backspace();
10448        assert_eq!(d.source, "**bold**\n");
10449        assert_eq!(d.caret, 8);
10450    }
10451
10452    #[test]
10453    fn the_mark_edge_rule_clears_every_delimiter_of_a_nested_run() {
10454        // `***both***` closes two runs with one stack of asterisks; a space that
10455        // clears only the inner one lands against the outer's and breaks that
10456        // instead.
10457        let mut d = wysiwyg_doc("edge_nested", "a ***both***\n");
10458        d.caret = 9;
10459        d.insert(" ");
10460        assert_eq!(d.source, "a ***both*** \n");
10461        assert_eq!(d.caret, 13);
10462        d.insert("x");
10463        assert_eq!(d.source, "a ***both x***\n");
10464    }
10465
10466    #[test]
10467    fn the_mark_edge_repair_undoes_with_the_keystroke_that_caused_it() {
10468        // The delimiter shuffle is not an edit the writer made, so it is not a
10469        // step they have to undo past.
10470        let mut d = wysiwyg_doc("edge_undo", "a **bold**\n");
10471        d.caret = 8;
10472        d.insert(" ");
10473        assert_eq!(d.source, "a **bold** \n");
10474        d.undo();
10475        assert_eq!(d.source, "a **bold**\n");
10476    }
10477
10478    #[test]
10479    fn the_source_view_types_the_space_where_it_was_asked_to() {
10480        // The rule is a rich-view courtesy. In the source view the delimiters are
10481        // on the screen and the user is editing the bytes they can see.
10482        let mut d = doc_with("edge_src", "a **bold** c\n");
10483        d.caret = 8;
10484        d.insert(" ");
10485        assert_eq!(d.source, "a **bold ** c\n");
10486    }
10487
10488    #[test]
10489    fn toggling_a_mark_over_a_selection_leaves_its_edge_whitespace_out() {
10490        // Double-clicking a word takes the space after it; bolding that must not
10491        // spell `**word **`, which is not bold at all.
10492        let mut d = wysiwyg_doc("edge_sel", "a word b\n");
10493        d.anchor = Some(2);
10494        d.caret = 7; // "word "
10495        d.toggle(InlineKind::Strong);
10496        assert_eq!(d.source, "a **word** b\n");
10497        d.toggle(InlineKind::Strong);
10498        assert_eq!(d.source, "a word b\n");
10499        d.toggle(InlineKind::Strong);
10500        assert_eq!(
10501            d.source, "a **word** b\n",
10502            "reapplying the mark must not wrap stale delimiter offsets"
10503        );
10504        // And a selection of nothing but whitespace has no word to mark.
10505        let mut d = wysiwyg_doc("edge_sel_ws", "a word b\n");
10506        d.anchor = Some(6);
10507        d.caret = 7;
10508        d.toggle(InlineKind::Strong);
10509        assert_eq!(d.source, "a word b\n");
10510        assert!(d.status.is_some());
10511    }
10512
10513    #[test]
10514    fn set_block_turns_a_paragraph_into_a_heading_at_the_caret() {
10515        let mut d = doc_with("head_set", "hello\n");
10516        d.caret = 2; // caret inside the paragraph, no selection
10517        d.set_block(BlockKind::Heading(1));
10518        assert_eq!(d.source, "# hello\n");
10519    }
10520
10521    #[test]
10522    fn set_block_heading_works_in_wysiwyg_view() {
10523        // The app defaults to WYSIWYG; the caret is a source offset either way.
10524        let mut d = wysiwyg_doc("head_wys", "hello\n");
10525        d.caret = 2;
10526        d.set_block(BlockKind::Heading(1));
10527        assert_eq!(d.source, "# hello\n");
10528    }
10529
10530    #[test]
10531    fn toggle_heading_applies_switches_and_reverts() {
10532        let mut d = doc_with("head_toggle", "hello\n");
10533        d.caret = 2;
10534        d.toggle_heading(1);
10535        assert_eq!(d.source, "# hello\n"); // paragraph → H1
10536        d.toggle_heading(2);
10537        assert_eq!(d.source, "## hello\n"); // H1 → H2 (different level switches)
10538        d.toggle_heading(2);
10539        assert_eq!(d.source, "hello\n"); // same level reverts to paragraph
10540    }
10541
10542    #[test]
10543    fn preserve_enter_at_a_line_end_lands_the_caret_on_the_new_blank_line() {
10544        // Regression: Enter at the end of a soft-break line (mid-paragraph) opened
10545        // the blank line but the caret rendered on the *next* line, because the
10546        // separator was a non-navigable decoration row. In Preserve flow that
10547        // blank line is a real caret home — the caret must resolve onto it, and
10548        // typing there makes the soft break that continues the paragraph.
10549        let src = "line one:\nsecond line\n";
10550        let mut d = wysiwyg_doc("pre_enter_lineend", src);
10551        d.set_line_flow(LineFlow::Preserve);
10552        d.build_visual_unwrapped(); // the GUI path (pixel-wrapped)
10553        d.caret = 9; // the visual end of row 0, at the soft-break '\n'
10554        d.newline();
10555        d.build_visual_unwrapped();
10556        assert_eq!(d.source, "line one:\n\nsecond line\n");
10557        assert_eq!(
10558            d.caret, 10,
10559            "caret sits on the new blank line, not the next line"
10560        );
10561        // The blank line is row 1, and the caret resolves onto it — not row 2.
10562        assert_eq!(
10563            d.vmap.pos_of_offset(10),
10564            (1, 0),
10565            "caret renders on the blank row"
10566        );
10567        assert!(
10568            !d.vmap.rows[1].decoration,
10569            "the blank line is navigable in Preserve"
10570        );
10571        // Typing there makes a soft break: one paragraph, three lines.
10572        d.insert("new clause,");
10573        assert_eq!(d.source, "line one:\nnew clause,\nsecond line\n");
10574    }
10575
10576    #[test]
10577    fn preserve_enter_makes_a_soft_break_not_a_paragraph() {
10578        // Mid-paragraph: Enter splits the line with a single `\n`, a soft break
10579        // that keeps it one paragraph — where Fold would open a second paragraph.
10580        let mut d = wysiwyg_doc("pre_enter_mid", "abcdef\n");
10581        d.set_line_flow(LineFlow::Preserve);
10582        d.caret = 3;
10583        d.newline();
10584        assert_eq!(d.source, "abc\ndef\n", "mid-line Enter is a soft break");
10585
10586        // End-of-paragraph: Enter then typing continues the same paragraph on a
10587        // new line (a soft break), not a fresh paragraph.
10588        let mut d = wysiwyg_doc("pre_enter_end", "abc\n");
10589        d.set_line_flow(LineFlow::Preserve);
10590        d.caret = 3;
10591        d.newline();
10592        d.insert("def");
10593        assert_eq!(
10594            d.source, "abc\ndef\n",
10595            "end-of-line Enter + typing is a soft break"
10596        );
10597    }
10598
10599    #[test]
10600    fn preserve_double_enter_still_makes_a_paragraph() {
10601        // Two Enters in a row promote to a real paragraph break: the second lands
10602        // on the blank line the first opened and takes the empty-line branch.
10603        let mut d = wysiwyg_doc("pre_enter_dbl", "abc\n");
10604        d.set_line_flow(LineFlow::Preserve);
10605        d.caret = 3;
10606        d.newline();
10607        d.newline();
10608        d.insert("def");
10609        assert_eq!(
10610            d.source, "abc\n\ndef\n",
10611            "double Enter is a paragraph break"
10612        );
10613    }
10614
10615    #[test]
10616    fn preserve_backspace_joins_across_a_soft_break() {
10617        // Backspace is the symmetric undo of a Preserve Enter: over the `\n` of a
10618        // soft break it deletes the single newline and joins the two lines.
10619        let mut d = wysiwyg_doc("pre_bs", "abc\ndef\n");
10620        d.set_line_flow(LineFlow::Preserve);
10621        d.build_visual(80);
10622        d.caret = 4; // start of "def", just past the soft break
10623        d.backspace();
10624        assert_eq!(
10625            d.source, "abcdef\n",
10626            "Backspace joins across the soft break"
10627        );
10628        assert_eq!(d.caret, 3, "caret lands where the lines meet");
10629    }
10630
10631    #[test]
10632    fn fold_enter_still_starts_a_new_paragraph() {
10633        // The default flow is unchanged: a lone `\n` would render as an invisible
10634        // space, so Enter keeps opening the paragraph break that actually shows.
10635        let mut d = wysiwyg_doc("fold_enter", "abcdef\n");
10636        d.caret = 3;
10637        d.newline();
10638        assert_eq!(
10639            d.source, "abc\n\ndef\n",
10640            "Fold mid-line Enter is a paragraph break"
10641        );
10642    }
10643
10644    #[test]
10645    fn wysiwyg_one_enter_starts_a_new_paragraph() {
10646        // Regression: one Enter left the caret between the two newlines, so typing
10647        // made a soft break (one paragraph) and you needed a second Enter.
10648        let mut d = wysiwyg_doc("wys_enter", "abc\n");
10649        d.caret = 3;
10650        d.newline();
10651        d.insert("def");
10652        assert_eq!(d.source, "abc\n\ndef\n"); // two paragraphs, not "abc\ndef\n"
10653    }
10654
10655    #[test]
10656    fn enter_at_the_end_of_a_bold_run_keeps_its_closing_delimiter_attached() {
10657        // Regression: Enter at the caret's natural End-of-line resting place
10658        // after a bold run with nothing following it (on screen: right after
10659        // "bold", before the hidden closing "**") spliced the paragraph break
10660        // at that very byte offset — which sits *before* the closing "**" in
10661        // the source, since the delimiter is hidden and emits no glyph of its
10662        // own for `push_row`'s "end of row" fallback to count. That severed the
10663        // mark: "**bold**\n" became "**bold\n\n**\n", stranding the closing
10664        // "**" alone on the new line instead of leaving "**bold**" intact with
10665        // a fresh empty paragraph after it.
10666        let mut d = wysiwyg_doc("bold_eol_enter", "**bold**\n");
10667        d.move_end(false); // the WYSIWYG End key, from caret 0
10668        assert_eq!(
10669            d.caret, 6,
10670            "caret rests right after \"bold\", before the hidden \"**\""
10671        );
10672        d.newline();
10673        assert!(
10674            d.source.starts_with("**bold**"),
10675            "the closing ** must stay attached to \"bold\": got {:?}",
10676            d.source
10677        );
10678        assert_eq!(
10679            d.source, "**bold**\n\n\n",
10680            "a fresh empty paragraph follows the still-intact bold run"
10681        );
10682    }
10683
10684    #[test]
10685    fn source_view_enter_is_a_single_newline() {
10686        let mut d = doc_with("src_enter", "abc\n");
10687        d.caret = 3;
10688        d.newline();
10689        assert_eq!(d.source, "abc\n\n");
10690    }
10691
10692    #[test]
10693    fn heading_applies_at_the_end_of_a_paragraph() {
10694        // The caret at a line end sits at the doc level; set_block must still find
10695        // the block on that line.
10696        let mut d = doc_with("head_end", "abc\n");
10697        d.caret = 3; // end of "abc"
10698        d.toggle_heading(1);
10699        assert_eq!(d.source, "# abc\n");
10700    }
10701
10702    #[test]
10703    fn heading_on_an_empty_new_paragraph_creates_one() {
10704        let mut d = wysiwyg_doc("head_empty", "abc\n");
10705        d.caret = 3;
10706        d.newline(); // caret now on a fresh, empty paragraph
10707        d.toggle_heading(1);
10708        d.insert("Title");
10709        assert!(d.source.contains("# Title"), "got {:?}", d.source);
10710    }
10711
10712    #[test]
10713    fn a_heading_typed_on_a_blank_line_keeps_the_caret_on_its_own_row() {
10714        // The reported bug, end to end: click a blank line with another one under
10715        // it, press H1, type. The text landed in the heading and the caret's
10716        // offset was right (the source view drew it there), but the rich view
10717        // drew it two rows lower, on the trailing blank line — the empty `# `
10718        // heading had left every row below it short by the marker's two bytes,
10719        // and the blank line ended up claiming the heading's own end offset.
10720        let mut d = wysiwyg_doc("head_blank", "one\n\ntwo\n\n\n\n");
10721        d.build_visual_unwrapped();
10722        d.caret = d.vmap.offset_of_pos(4, 0); // the first of the two blank lines
10723        d.toggle_heading(1);
10724        for c in "title".chars() {
10725            d.insert(&c.to_string());
10726            d.build_visual_unwrapped(); // as a frontend does, one frame per key
10727        }
10728        assert_eq!(d.source, "one\n\ntwo\n\n# title\n\n");
10729        assert_eq!(
10730            d.caret_pos(),
10731            (4, 5),
10732            "the caret draws at the end of the heading"
10733        );
10734    }
10735
10736    #[test]
10737    fn clicking_an_empty_heading_types_after_its_marker() {
10738        // The same anchor from the other side: the empty heading's row is its own
10739        // caret home, so a click on it must land past the hidden `# `. Landing in
10740        // front of the hashes made the first keystroke un-heading the line.
10741        let mut d = wysiwyg_doc("head_click", "# \n");
10742        d.build_visual_unwrapped();
10743        d.caret = d.vmap.offset_of_pos(0, 0);
10744        d.insert("x");
10745        assert_eq!(d.source, "# x\n");
10746    }
10747
10748    #[test]
10749    fn wysiwyg_enter_after_a_heading_makes_a_paragraph() {
10750        let mut d = wysiwyg_doc("head_enter", "# Title\n");
10751        d.caret = 7; // end of the heading
10752        d.newline();
10753        d.insert("body");
10754        assert_eq!(d.source, "# Title\n\nbody\n");
10755    }
10756
10757    #[test]
10758    fn wysiwyg_enter_continues_a_bullet_list() {
10759        let mut d = wysiwyg_doc("wys_bullet", "- item\n");
10760        d.caret = 6; // end of "item"
10761        d.newline();
10762        d.insert("two");
10763        assert_eq!(d.source, "- item\n- two\n");
10764    }
10765
10766    #[test]
10767    fn wysiwyg_enter_increments_an_ordered_list() {
10768        let mut d = wysiwyg_doc("wys_ol", "1. one\n");
10769        d.caret = 6; // end of "one"
10770        d.newline();
10771        d.insert("two");
10772        assert_eq!(d.source, "1. one\n2. two\n");
10773    }
10774
10775    #[test]
10776    fn wysiwyg_backspace_after_leaving_a_list_collapses_the_gap_cleanly() {
10777        // Regression for the "extra newline" left between a list and the paragraph
10778        // below it. Enter, Enter leaves the list on a fresh empty paragraph
10779        // (`- item\n\n\n\nnext`, a navigable blank between the two blocks); one
10780        // Backspace should then take the caret cleanly back to the end of the list
10781        // item, `- item\n\nnext`, not delete a single newline and strand it on the
10782        // odd `- item\n\n\nnext` — a blank line the eye reads as one separator but
10783        // no caret can land on. The map is rebuilt between keystrokes exactly as a
10784        // frontend does, since Backspace reads the stop table to place the delete.
10785        let mut d = wysiwyg_doc("wys_exit_bksp", "- item\n\nnext\n");
10786        d.caret = 6; // end of "item"
10787        d.newline();
10788        d.build_visual(80);
10789        d.newline(); // leave the list onto a fresh empty paragraph
10790        d.build_visual(80);
10791        assert_eq!(
10792            d.source, "- item\n\n\n\nnext\n",
10793            "double-Enter opens the empty paragraph"
10794        );
10795        d.backspace();
10796        assert_eq!(
10797            d.source, "- item\n\nnext\n",
10798            "one Backspace collapses the whole gap"
10799        );
10800        assert_eq!(
10801            d.caret, 6,
10802            "and lands the caret back at the end of the list item"
10803        );
10804    }
10805
10806    #[test]
10807    fn wysiwyg_backspace_on_stacked_blank_lines_still_removes_just_one() {
10808        // The stop-wise delete must not over-reach when there is no block boundary
10809        // to cross: two blank lines in a row are one caret stop apart, so pressing
10810        // Enter on an empty line and then Backspace removes exactly the one newline
10811        // it added — the lone-Enter / lone-Backspace symmetry, preserved.
10812        let mut d = wysiwyg_doc("wys_stack", "abc\n\n\n");
10813        d.caret = 5; // the empty paragraph the first Enter already opened
10814        d.build_visual(80);
10815        d.newline();
10816        d.build_visual(80);
10817        assert_eq!(
10818            d.source, "abc\n\n\n\n",
10819            "Enter on the blank line adds one newline"
10820        );
10821        d.backspace();
10822        assert_eq!(
10823            d.source, "abc\n\n\n",
10824            "Backspace takes back exactly that one newline"
10825        );
10826    }
10827
10828    #[test]
10829    fn wysiwyg_enter_on_an_empty_list_item_exits_the_list() {
10830        let mut d = wysiwyg_doc("wys_exit", "- a\n- \n");
10831        d.caret = 6; // end of the empty "- " item
10832        d.newline();
10833        d.insert("p");
10834        assert_eq!(d.source, "- a\n\np\n");
10835    }
10836
10837    #[test]
10838    fn wysiwyg_enter_does_not_mistake_a_setext_underline_for_a_list() {
10839        // `text\n- \n` is a setext heading — the `- ` is its underline, not a
10840        // list item, though it reads as a `- ` marker byte-for-byte. Enter must
10841        // not take the list-exit path (which would splice the `- ` away as if
10842        // leaving an empty item); the AST guard sends it to a normal break and
10843        // leaves the underline intact.
10844        let mut d = wysiwyg_doc("wys_setext", "text\n- \n");
10845        assert!(
10846            d.nodes().iter().any(|n| n.kind == Kind::Heading),
10847            "precondition: twig parses this as a heading, not a list",
10848        );
10849        d.caret = 7; // on the `- ` underline line
10850        d.newline();
10851        assert!(
10852            d.source.contains("- "),
10853            "the setext underline survives, not spliced away as a list item: {:?}",
10854            d.source,
10855        );
10856    }
10857
10858    #[test]
10859    fn wysiwyg_enter_in_a_code_block_is_a_literal_newline() {
10860        let mut d = wysiwyg_doc("wys_code", "```\nabc\n```\n");
10861        d.caret = 7; // end of "abc" inside the fence
10862        d.newline();
10863        d.insert("def");
10864        assert_eq!(d.source, "```\nabc\ndef\n```\n");
10865    }
10866
10867    #[test]
10868    fn wysiwyg_enter_continues_a_block_quote() {
10869        // Enter opens a new *paragraph* inside the quote, not a second line of
10870        // the same one. `> quote\n> more` is a soft break, which under
10871        // `LineFlow::Fold` renders as a space — the keystroke would look like it
10872        // did nothing. The quoted blank line is what makes the break visible, and
10873        // it's the same thing Enter does in running prose.
10874        let mut d = wysiwyg_doc("wys_quote", "> quote\n");
10875        d.caret = 7; // end of "quote"
10876        d.newline();
10877        d.insert("more");
10878        assert_eq!(d.source, "> quote\n>\n> more\n");
10879        // Still one quote, now holding two paragraphs — not a quote and a stray
10880        // line that fell out of it.
10881        let quotes = d
10882            .nodes()
10883            .iter()
10884            .filter(|n| n.kind == Kind::BlockQuote)
10885            .count();
10886        assert_eq!(quotes, 1);
10887    }
10888
10889    #[test]
10890    fn set_block_makes_a_heading_at_the_caret() {
10891        let mut d = doc_with("head", "Title\n\nbody\n");
10892        d.caret = 0;
10893        d.set_block(BlockKind::Heading(2));
10894        assert_eq!(d.source, "## Title\n\nbody\n");
10895        d.set_block(BlockKind::Paragraph);
10896        assert_eq!(d.source, "Title\n\nbody\n");
10897    }
10898
10899    // ── block containers (quote / list) ──────────────────────────────────────
10900
10901    #[test]
10902    fn toggle_blockquote_wraps_the_block_at_the_caret_and_reverses() {
10903        let g = |m, f: fn(&mut Doc)| golden("quote", m, f);
10904        assert_eq!(g("hel|lo\n", |d| d.toggle_blockquote()), "> hel|lo\n");
10905        assert_eq!(g("> hel|lo\n", |d| d.toggle_blockquote()), "hel|lo\n");
10906        // A caret at a line end sits at the doc level; the block is still found.
10907        assert_eq!(g("hello|\n", |d| d.toggle_blockquote()), "> hello|\n");
10908    }
10909
10910    #[test]
10911    fn toggle_blockquote_keeps_the_caret_in_a_hard_wrapped_paragraph() {
10912        // Every source line of the paragraph gets its own `> `, so a caret left
10913        // on its old byte offset falls one prefix per line above it too far
10914        // back — inside the markup it just asked for rather than in its word.
10915        assert_eq!(
10916            golden("quote_wrap", "aaa\nb|bb\nccc\n", |d| d.toggle_blockquote()),
10917            "> aaa\n> b|bb\n> ccc\n"
10918        );
10919    }
10920
10921    #[test]
10922    fn toggle_blockquote_works_in_wysiwyg_view() {
10923        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
10924        assert_eq!(
10925            g("q_wys", "hel|lo\n", |d| d.toggle_blockquote()),
10926            "> hel|lo\n"
10927        );
10928        assert_eq!(
10929            g("q_wys2", "> hel|lo\n", |d| d.toggle_blockquote()),
10930            "hel|lo\n"
10931        );
10932    }
10933
10934    #[test]
10935    fn toggle_list_makes_a_list_and_converts_between_the_kinds() {
10936        let g = |m, f: fn(&mut Doc)| golden("list", m, f);
10937        assert_eq!(g("hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
10938        assert_eq!(g("hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
10939        // The *other* kind converts in place instead of nesting, which is what
10940        // makes the two buttons one three-state control.
10941        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(true)), "1. hel|lo\n");
10942        assert_eq!(g("1. hel|lo\n", |d| d.toggle_list(false)), "- hel|lo\n");
10943        // Its own kind, over the only item the list holds, takes it off.
10944        assert_eq!(g("- hel|lo\n", |d| d.toggle_list(false)), "hel|lo\n");
10945    }
10946
10947    #[test]
10948    fn toggle_list_works_in_wysiwyg_view() {
10949        let g = |n, m, f: fn(&mut Doc)| golden_in(View::Wysiwyg, n, m, f);
10950        assert_eq!(
10951            g("l_wys", "hel|lo\n", |d| d.toggle_list(true)),
10952            "1. hel|lo\n"
10953        );
10954        assert_eq!(
10955            g("l_wys2", "1. hel|lo\n", |d| d.toggle_list(false)),
10956            "- hel|lo\n"
10957        );
10958        assert_eq!(
10959            g("l_wys3", "- hel|lo\n", |d| d.toggle_list(false)),
10960            "hel|lo\n"
10961        );
10962    }
10963
10964    #[test]
10965    fn a_list_over_a_selection_numbers_each_block_and_stays_selected() {
10966        // The selection has to grow with the markup: twig takes a container off
10967        // only a range covering every block it holds, so the second press can
10968        // reverse the first only if the result is what's selected.
10969        let mut d = doc_with("list_sel", "abc\n\ndef\n");
10970        d.select_all();
10971        d.toggle_list(true);
10972        assert_eq!(d.source, "1. abc\n\n2. def\n");
10973        assert_eq!(d.selection(), Some((0, d.source.len())));
10974        d.toggle_list(true);
10975        assert_eq!(d.source, "abc\n\ndef\n");
10976    }
10977
10978    #[test]
10979    fn toggle_blockquote_nests_a_partly_covered_quote() {
10980        // twig's rule: covering only some of a container's blocks nests, because
10981        // taking the quote off would drag its uncovered siblings out with it.
10982        let mut d = doc_with("quote_nest", "> a\n>\n> b\n");
10983        d.caret = 2; // in the first quoted paragraph only
10984        d.toggle_blockquote();
10985        assert_eq!(d.source, "> > a\n>\n> b\n");
10986    }
10987
10988    #[test]
10989    fn a_container_toggle_opens_an_empty_one_on_a_blank_line() {
10990        // A blank line used to be no block for twig to wrap —
10991        // `toggle_block_container` answered `NotFound` — so Quote and the list
10992        // buttons did nothing on the very line the H1 button works on, and leaf
10993        // lent twig a scratch paragraph to wrap and took it back out again.
10994        // twig 3.2.0 opens an empty container there itself, so what is left here
10995        // is where the caret lands: inside the marker that was just written.
10996        let mut d = doc_with("quote_blank", "\nabc\n");
10997        d.caret = 0;
10998        d.toggle_blockquote();
10999        assert_eq!(d.source, "> \nabc\n");
11000        assert_eq!(
11001            d.caret, 2,
11002            "the caret belongs inside the quote it just opened"
11003        );
11004        assert!(d.status.is_none(), "{:?}", d.status);
11005        assert!(d.dirty);
11006
11007        // And the paragraph below is still its own block: an empty container one
11008        // soft break from `abc` would take that paragraph into the quote with it.
11009        let mut d = wysiwyg_doc("quote_blank_rows", "\nabc\n");
11010        d.caret = 0;
11011        d.toggle_blockquote();
11012        d.build_visual(80);
11013        assert_eq!(drawn_rows(&d), ["│ ", "", "abc"]);
11014
11015        // The same from the other side: a blank line directly under a paragraph
11016        // earns the blank line an empty block needs, rather than being read as a
11017        // soft break inside that paragraph.
11018        let mut d = doc_with("list_blank_below", "abc\n");
11019        d.caret = 4;
11020        d.toggle_list(false);
11021        assert_eq!(d.source, "abc\n\n- ");
11022        assert_eq!(d.caret, 7);
11023    }
11024
11025    #[test]
11026    fn enter_at_the_end_of_a_quote_stays_in_the_quote() {
11027        // The gesture the rendering fix is for. `newline` inside a quote already
11028        // wrote the right source — `> a\n` becomes `> a\n>\n> \n`, twig's own
11029        // spelling — but the two marker lines it adds belonged to no node until
11030        // twig 3.2.0, so the gutter stopped at `a` and the line the writer had
11031        // just made drew as plain prose under the quote.
11032        let mut d = wysiwyg_doc("quote_enter", "> a\n");
11033        d.caret = 3; // past `a`, at the end of the quoted line
11034        d.newline();
11035        assert_eq!(d.source, "> a\n>\n> \n");
11036        d.build_visual(80);
11037        assert_eq!(drawn_rows(&d), ["│ a", "│ ", "│ "]);
11038        // And the caret is on the new line, not stranded on the old one.
11039        assert_eq!(d.caret, 8);
11040    }
11041
11042    #[test]
11043    fn opening_a_container_on_a_blank_line_is_one_undo_step() {
11044        // It was three edits — scratch, wrap, unscratch — coalesced into one, and
11045        // now it is twig's single edit. Either way one ⌘z has to put the blank
11046        // line back rather than undoing into a half-built document.
11047        for open in [
11048            &(|d: &mut Doc| d.toggle_blockquote()) as &dyn Fn(&mut Doc),
11049            &|d: &mut Doc| d.toggle_list(false),
11050            &|d: &mut Doc| d.toggle_list(true),
11051        ] {
11052            let mut d = doc_with("container_blank_undo", "a\n\n\n\nb\n");
11053            d.caret = 3;
11054            open(&mut d);
11055            assert_ne!(d.source, "a\n\n\n\nb\n");
11056            d.undo();
11057            assert_eq!(d.source, "a\n\n\n\nb\n");
11058        }
11059    }
11060
11061    #[test]
11062    fn a_container_toggle_is_one_undo_step() {
11063        let mut d = doc_with("quote_undo", "hello\n");
11064        d.caret = 3;
11065        d.insert("X"); // a typing run the structural edit must not fold into
11066        d.toggle_blockquote();
11067        assert_eq!(d.source, "> helXlo\n");
11068        d.undo();
11069        assert_eq!(d.source, "helXlo\n");
11070    }
11071
11072    // ── links ────────────────────────────────────────────────────────────────
11073
11074    #[test]
11075    fn insert_link_wraps_the_selection_and_leaves_its_text_selected() {
11076        let mut d = doc_with("link_sel", "word here\n");
11077        d.anchor = Some(0);
11078        d.caret = 4;
11079        d.insert_link("http://x.dev");
11080        assert_eq!(d.source, "[word](http://x.dev) here\n");
11081        // The text, not the destination — so a second press re-points the link
11082        // the first one made rather than nesting one inside it.
11083        assert_eq!(d.selected_text(), Some("word"));
11084        d.insert_link("http://y.dev");
11085        assert_eq!(d.source, "[word](http://y.dev) here\n");
11086        assert_eq!(d.selected_text(), Some("word"));
11087    }
11088
11089    #[test]
11090    fn insert_image_at_the_caret_spells_the_markup_and_lands_past_it() {
11091        let mut d = doc_with("img_caret", "before after\n");
11092        d.caret = 7; // between "before " and "after"
11093        d.insert_image("cat.png", "a cat");
11094        assert_eq!(d.source, "before ![a cat](cat.png)after\n");
11095        // The caret sits just past the inserted image, nothing selected.
11096        assert_eq!(d.selection(), None);
11097        assert_eq!(d.caret, 7 + "![a cat](cat.png)".len());
11098    }
11099
11100    /// The bug a real vault hit: a filename with spaces in it. Markdown ends a
11101    /// destination at the first space, so the `format!` this used to be wrote
11102    /// something that was not an image at all — and the reader saw the markup as
11103    /// text. twig owns the spelling now, and moves it into the angle form.
11104    #[test]
11105    fn insert_image_spells_a_destination_with_spaces_so_it_stays_an_image() {
11106        let mut d = doc_with("img_space", "x\n");
11107        d.caret = 0;
11108        d.insert_image("Jesus Commands the Apostles to Rest.jpg", "");
11109        assert_eq!(
11110            d.source,
11111            "![](<Jesus Commands the Apostles to Rest.jpg>)x\n"
11112        );
11113        // And it reads back as an image pointing at the unescaped path — the angle
11114        // brackets are spelling, not part of the destination.
11115        d.caret = 2;
11116        assert_eq!(
11117            d.image_destination_at_caret(),
11118            Some("Jesus Commands the Apostles to Rest.jpg".to_string())
11119        );
11120    }
11121
11122    /// A `)` in a caption or a filename must not close the image early.
11123    #[test]
11124    fn insert_image_escapes_a_paren_in_either_half() {
11125        let mut d = doc_with("img_paren", "x\n");
11126        d.caret = 0;
11127        d.insert_image("a)b.png", "");
11128        assert_eq!(d.source, "![](a\\)b.png)x\n");
11129        d.caret = 2;
11130        assert_eq!(d.image_destination_at_caret(), Some("a)b.png".to_string()));
11131    }
11132
11133    #[test]
11134    fn insert_image_uses_the_selection_as_alt_text() {
11135        let mut d = doc_with("img_sel", "caption here\n");
11136        d.anchor = Some(0);
11137        d.caret = 7; // "caption"
11138        d.insert_image("p.png", "ignored fallback");
11139        assert_eq!(d.source, "![caption](p.png) here\n");
11140    }
11141
11142    #[test]
11143    fn insert_image_with_no_alt_leaves_empty_brackets() {
11144        let mut d = doc_with("img_noalt", "\n");
11145        d.caret = 0;
11146        d.insert_image("logo.svg", "");
11147        assert_eq!(d.source, "![](logo.svg)\n");
11148    }
11149
11150    // ── move_block ─────────────────────────────────────────────────────────────
11151
11152    /// A move, then its undo: one step takes the whole thing back.
11153    fn moved(name: &str, body: &str, from: usize, to: usize) -> (String, Doc) {
11154        let mut d = doc_with(name, body);
11155        d.caret = from;
11156        let steps = d.undo_steps;
11157        d.move_block(from, to);
11158        let after = d.source.clone();
11159        assert_eq!(d.undo_steps, steps + 1, "one undo step");
11160        assert!(d.dirty);
11161        d.undo();
11162        assert_eq!(d.source, body, "one undo restores the original");
11163        (after, d)
11164    }
11165
11166    #[test]
11167    fn move_block_carries_a_paragraph_between_two_paragraphs_and_to_the_end() {
11168        let body = "a\n\nb\n\nc\n";
11169        assert_eq!(moved("mv_p1", body, 6, 3).0, "a\n\nc\n\nb\n");
11170        assert_eq!(moved("mv_p2", body, 0, body.len()).0, "b\n\nc\n\na\n");
11171        assert_eq!(moved("mv_p3", body, 3, 0).0, "b\n\na\n\nc\n");
11172    }
11173
11174    #[test]
11175    fn move_block_carries_an_image_block() {
11176        let body = "a\n\n![p](x.png)\n\nc\n";
11177        assert_eq!(moved("mv_img1", body, 4, 0).0, "![p](x.png)\n\na\n\nc\n");
11178        assert_eq!(
11179            moved("mv_img2", body, 4, body.len()).0,
11180            "a\n\nc\n\n![p](x.png)\n"
11181        );
11182    }
11183
11184    #[test]
11185    fn move_block_carries_a_table() {
11186        let body = "a\n\n| h |\n|---|\n| c |\n\nc\n";
11187        assert_eq!(
11188            moved("mv_tbl1", body, 5, 0).0,
11189            "| h |\n|---|\n| c |\n\na\n\nc\n"
11190        );
11191        assert_eq!(
11192            moved("mv_tbl2", body, 5, body.len()).0,
11193            "a\n\nc\n\n| h |\n|---|\n| c |\n"
11194        );
11195    }
11196
11197    #[test]
11198    fn move_block_carries_a_code_block() {
11199        let body = "a\n\n```rs\nx\n```\n\nc\n";
11200        assert_eq!(moved("mv_code1", body, 8, 0).0, "```rs\nx\n```\n\na\n\nc\n");
11201        assert_eq!(
11202            moved("mv_code2", body, 8, body.len()).0,
11203            "a\n\nc\n\n```rs\nx\n```\n"
11204        );
11205    }
11206
11207    #[test]
11208    fn move_block_onto_its_own_boundary_is_a_quiet_no_op() {
11209        let mut d = doc_with("mv_noop", "a\n\nb\n");
11210        let steps = d.undo_steps;
11211        d.move_block(0, 0);
11212        d.move_block(0, 3);
11213        assert_eq!(d.source, "a\n\nb\n");
11214        assert_eq!(d.undo_steps, steps);
11215        assert_eq!(d.status, None);
11216        assert!(!d.dirty);
11217    }
11218
11219    #[test]
11220    fn move_block_into_a_fence_is_refused_with_a_status() {
11221        let mut d = doc_with("mv_fence", "a\n\n```\nx\ny\n```\n");
11222        d.move_block(0, 7);
11223        assert_eq!(d.source, "a\n\n```\nx\ny\n```\n");
11224        assert!(
11225            d.status
11226                .as_deref()
11227                .is_some_and(|s| s.starts_with("move block"))
11228        );
11229    }
11230
11231    #[test]
11232    fn move_block_rides_the_caret_with_the_block() {
11233        // Down: "second" is line 0 of its block, caret 3 bytes from its end.
11234        let mut d = doc_with("mv_caret1", "first\n\nsecond\n\nthird\n");
11235        d.caret = 10; // "sec|ond"
11236        d.move_block(10, d.source.len());
11237        assert_eq!(d.source, "first\n\nthird\n\nsecond\n");
11238        assert_eq!(&d.source[d.caret..], "ond\n");
11239        // Up, across a wrapped paragraph's second line.
11240        let mut d = doc_with("mv_caret2", "first\n\nsecond\nline two\n");
11241        d.caret = 16; // "li|ne two"
11242        d.move_block(16, 0);
11243        assert_eq!(d.source, "second\nline two\n\nfirst\n");
11244        assert_eq!(&d.source[d.caret..], "ne two\n\nfirst\n");
11245        assert_eq!(d.selection(), None);
11246    }
11247
11248    #[test]
11249    fn move_block_keeps_the_caret_on_its_line_through_a_quotes_prefix() {
11250        let mut d = doc_with("mv_quote_caret", "para\n\n> a\n");
11251        d.caret = 2; // "pa|ra"
11252        d.move_block(2, 9); // after a, inside the quote
11253        assert_eq!(d.source, "> a\n>\n> para\n");
11254        assert_eq!(&d.source[d.caret..], "ra\n");
11255    }
11256
11257    #[test]
11258    fn move_block_up_and_down_step_over_siblings() {
11259        let mut d = doc_with("mv_updown", "a\n\nb\n\nc\n");
11260        d.caret = 3;
11261        d.move_block_down();
11262        assert_eq!(d.source, "a\n\nc\n\nb\n");
11263        assert_eq!(&d.source[d.caret..], "b\n");
11264        d.move_block_down();
11265        assert_eq!(d.source, "a\n\nc\n\nb\n", "nothing below the last block");
11266        assert_eq!(d.status.as_deref(), Some("move block: nothing below"));
11267        d.move_block_up();
11268        d.move_block_up();
11269        assert_eq!(d.source, "b\n\na\n\nc\n");
11270        assert_eq!(&d.source[d.caret..], "b\n\na\n\nc\n");
11271        d.move_block_up();
11272        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11273    }
11274
11275    #[test]
11276    fn move_block_up_and_down_reorder_list_items_with_their_children() {
11277        let mut d = doc_with("mv_items", "- a\n  - x\n- b\n- c\n");
11278        d.caret = 12; // in "b"
11279        d.move_block_up();
11280        assert_eq!(d.source, "- b\n- a\n  - x\n- c\n");
11281        assert_eq!(&d.source[d.caret..], "b\n- a\n  - x\n- c\n");
11282        d.caret = 6; // in "a"
11283        d.move_block_down();
11284        assert_eq!(d.source, "- b\n- c\n- a\n  - x\n");
11285        assert_eq!(&d.source[d.caret..], "a\n  - x\n");
11286        // A nested item leaves its list upward, as an item of the outer one.
11287        d.caret = 16; // in "x"
11288        d.move_block_up();
11289        assert_eq!(d.source, "- b\n- c\n- x\n- a\n");
11290    }
11291
11292    #[test]
11293    fn move_block_on_a_lone_item_that_stays_a_bullet_is_no_step() {
11294        let mut d = doc_with("mv_lone_item", "x\n\n- b\n\ny\n");
11295        d.caret = 5;
11296        let steps = d.undo_steps;
11297        d.move_block_up();
11298        assert_eq!(d.source, "x\n\n- b\n\ny\n");
11299        assert_eq!(
11300            d.undo_steps, steps,
11301            "a move that rewrote nothing is no undo step"
11302        );
11303        assert_eq!(d.status.as_deref(), Some("move block: nothing above"));
11304    }
11305
11306    #[test]
11307    fn move_block_up_leaves_a_container_at_its_first_block_and_down_at_its_last() {
11308        let mut d = doc_with("mv_leave", "x\n\n> a\n>\n> b\n\ny\n");
11309        d.caret = 5; // "a"
11310        d.move_block_up();
11311        assert_eq!(d.source, "x\n\na\n\n> b\n\ny\n");
11312        d.caret = 8; // "b"
11313        d.move_block_down();
11314        assert_eq!(d.source, "x\n\na\n\nb\n\ny\n");
11315        // A tail block leaves its item into the next item's tail, then the list.
11316        let mut d = doc_with("mv_tail", "- a\n\n  t\n- b\n");
11317        d.caret = 7;
11318        d.move_block_down();
11319        assert_eq!(d.source, "- a\n- b\n\n  t\n");
11320        d.move_block_down();
11321        assert_eq!(d.source, "- a\n- b\n\nt\n");
11322        // And a paragraph after a quote steps over the whole quote, not into it.
11323        let mut d = doc_with("mv_over", "x\n\n> a\n>\n> b\n\ny\n");
11324        d.caret = 14;
11325        d.move_block_up();
11326        assert_eq!(d.source, "x\n\ny\n\n> a\n>\n> b\n");
11327        assert_eq!(d.caret, 3);
11328        d.move_block_down();
11329        assert_eq!(d.status, None);
11330        assert_eq!(d.source, "x\n\n> a\n>\n> b\n\ny\n");
11331        // Above a quote that opens the document is offset 0 — before the
11332        // quote, not inside it.
11333        let mut d = doc_with("mv_over_top", "> a\n\ny\n");
11334        d.caret = 5;
11335        d.move_block_up();
11336        assert_eq!(d.source, "y\n\n> a\n");
11337        assert_eq!(d.caret, 0);
11338    }
11339
11340    #[test]
11341    fn move_block_up_from_the_first_block_of_a_quote_that_opens_the_document_leaves_it() {
11342        let mut d = doc_with("mv_top_quote", "> a\n>\n> b\n");
11343        d.caret = 2;
11344        d.move_block_up();
11345        assert_eq!(d.source, "a\n\n> b\n");
11346        assert_eq!(d.caret, 0);
11347        assert_eq!(d.status, None);
11348    }
11349
11350    #[test]
11351    fn move_block_on_a_blank_line_or_read_only_does_nothing() {
11352        let mut d = doc_with("mv_blank", "a\n\nb\n");
11353        d.caret = 2;
11354        d.move_block_down();
11355        assert_eq!(d.source, "a\n\nb\n");
11356        assert_eq!(d.status.as_deref(), Some("move block: no block here"));
11357        d.read_only = true;
11358        d.caret = 0;
11359        d.move_block_down();
11360        d.move_block(0, 5);
11361        assert_eq!(d.source, "a\n\nb\n");
11362    }
11363
11364    #[test]
11365    fn move_block_never_lands_above_hidden_frontmatter() {
11366        let mut d = wysiwyg_doc("mv_fm", "---\nt: x\n---\n\na\n\nb\n");
11367        let b = d.source.find('b').unwrap();
11368        d.move_block(b, 0);
11369        assert_eq!(d.source, "---\nt: x\n---\n\nb\n\na\n");
11370    }
11371
11372    #[test]
11373    fn block_range_at_is_the_block_a_move_picks_up() {
11374        let mut d = doc_with("mv_range", "a\n\n- b\n  - c\n\nd\n");
11375        assert_eq!(d.block_range_at(0), Some(0..1));
11376        assert_eq!(d.block_range_at(5), Some(3..12), "the item with its child");
11377        assert_eq!(d.block_range_at(10), Some(7..12), "the nested item alone");
11378        assert_eq!(d.block_range_at(2), None, "a blank line");
11379    }
11380
11381    #[test]
11382    fn drop_target_at_splits_a_block_at_its_middle_row_and_ends_below_everything() {
11383        let long = "two ".repeat(40).trim_end().to_string(); // wraps to three rows at 80
11384        let mut d = wysiwyg_doc("drop", &format!("one\n\n{long} four\n\nfive\n"));
11385        let rows = d.vmap.rows.len();
11386        assert_eq!(rows, 7, "one, gap, three wrapped rows, gap, five");
11387        assert_eq!(d.drop_target_at(0), Some(DropTarget { offset: 0, row: 0 }));
11388        let two = d.source.find("two").unwrap();
11389        assert_eq!(
11390            d.drop_target_at(1),
11391            Some(DropTarget {
11392                offset: two,
11393                row: 2
11394            }),
11395            "the gap resolves to the block under it"
11396        );
11397        assert_eq!(
11398            d.drop_target_at(2),
11399            Some(DropTarget {
11400                offset: two,
11401                row: 2
11402            })
11403        );
11404        assert_eq!(
11405            d.drop_target_at(3),
11406            Some(DropTarget {
11407                offset: two,
11408                row: 2
11409            })
11410        );
11411        let four_end = d.source.find("four").unwrap() + 4;
11412        assert_eq!(
11413            d.drop_target_at(4),
11414            Some(DropTarget {
11415                offset: four_end,
11416                row: 5
11417            })
11418        );
11419        assert_eq!(
11420            d.drop_target_at(rows + 3),
11421            Some(DropTarget {
11422                offset: d.source.len(),
11423                row: rows
11424            })
11425        );
11426        // And the offsets are ones move_block takes.
11427        let five = d.source.find("five").unwrap();
11428        let t = d.drop_target_at(2).unwrap();
11429        d.move_block(five, t.offset);
11430        assert_eq!(d.source, format!("one\n\nfive\n\n{long} four\n"));
11431    }
11432
11433    #[test]
11434    fn append_media_lands_at_the_end_as_its_own_block() {
11435        let mut d = doc_with("append_mid", "first word and more\n");
11436        d.caret = 0; // an editor nobody has tapped: the caret is at the start
11437        d.append_media(MediaKind::Image, "cat.png", "");
11438        assert_eq!(d.source, "first word and more\n\n![](cat.png)");
11439        assert_eq!(d.selection(), None);
11440        assert_eq!(d.caret, "first word and more\n\n![](cat.png)".len());
11441    }
11442
11443    #[test]
11444    fn append_media_needs_no_separator_after_a_blank_line_or_in_an_empty_document() {
11445        let mut d = doc_with("append_blank", "para\n\n");
11446        d.append_media(MediaKind::Image, "a.png", "");
11447        assert_eq!(d.source, "para\n\n![](a.png)");
11448
11449        let mut e = doc_with("append_empty", "");
11450        e.append_media(MediaKind::Image, "b.png", "");
11451        assert_eq!(e.source, "![](b.png)");
11452
11453        let mut f = doc_with("append_noeol", "no newline at end");
11454        f.anchor = Some(0);
11455        f.caret = 2; // a selection, which the verb ignores
11456        f.append_media(MediaKind::Video, "clip.mp4", "");
11457        assert_eq!(
11458            f.source,
11459            "no newline at end\n\n<video src=\"clip.mp4\" controls></video>"
11460        );
11461    }
11462
11463    #[test]
11464    fn insert_media_spells_a_video_as_html_and_reads_it_back_as_a_block() {
11465        // The round trip is the point: it's no use writing markup the reader
11466        // can't pick up again. This is the pair that only holds from twig 2.5.1
11467        // on — before it, the one-line form went in fine and came back as a
11468        // paragraph of raw tags, publishing no media at all.
11469        let mut d = doc_with("vid_rt", "\n");
11470        d.caret = 0;
11471        d.insert_media(MediaKind::Video, "clip.mp4", "a clip");
11472        assert_eq!(
11473            d.source,
11474            "<video src=\"clip.mp4\" controls>a clip</video>\n"
11475        );
11476
11477        d.build_visual(80);
11478        assert_eq!(d.vmap.media.len(), 1, "reads back as one block media");
11479        assert_eq!(d.vmap.media[0].kind, MediaKind::Video);
11480        assert_eq!(d.vmap.media[0].destination, "clip.mp4");
11481        assert_eq!(d.vmap.media[0].alt, "a clip");
11482    }
11483
11484    #[test]
11485    fn insert_media_spells_audio_with_its_own_tag() {
11486        let mut d = doc_with("aud_rt", "\n");
11487        d.caret = 0;
11488        d.insert_media(MediaKind::Audio, "take.mp3", "");
11489        assert_eq!(d.source, "<audio src=\"take.mp3\" controls></audio>\n");
11490        d.build_visual(80);
11491        assert_eq!(d.vmap.media[0].kind, MediaKind::Audio);
11492    }
11493
11494    #[test]
11495    fn insert_media_uses_the_selection_as_fallback_text() {
11496        // The same courtesy `insert_image` does with alt: select a caption,
11497        // insert, and the caption labels the thing rather than being replaced.
11498        let mut d = doc_with("vid_sel", "the talk here\n");
11499        d.anchor = Some(0);
11500        d.caret = 8; // "the talk"
11501        d.insert_media(MediaKind::Video, "talk.mp4", "ignored fallback");
11502        assert_eq!(
11503            d.source,
11504            "<video src=\"talk.mp4\" controls>the talk</video> here\n"
11505        );
11506    }
11507
11508    #[test]
11509    fn insert_media_with_an_image_kind_is_just_insert_image() {
11510        let mut d = doc_with("img_via_media", "\n");
11511        d.caret = 0;
11512        d.insert_media(MediaKind::Image, "logo.svg", "x");
11513        assert_eq!(d.source, "![x](logo.svg)\n");
11514    }
11515
11516    // ── thematic breaks ─────────────────────────────────────────────────────
11517
11518    /// The node the source parses as at `caret` — what confirms an inserted
11519    /// `---` actually reads back as a rule, not stray text or a setext heading.
11520    ///
11521    /// The *narrowest* node covering the offset. Every ancestor covers it too,
11522    /// and since twig 2.8 that includes the `doc` root, which now carries a real
11523    /// span (it reported none before, so taking the first match used to land on
11524    /// the block by luck and now always answers `"doc"`).
11525    fn kind_at(d: &mut Doc, caret: usize) -> Option<Kind> {
11526        d.nodes()
11527            .into_iter()
11528            .filter(|n| n.span.start <= caret && caret < n.span.end)
11529            .min_by_key(|n| n.span.end - n.span.start)
11530            .map(|n| n.kind)
11531    }
11532
11533    #[test]
11534    fn a_task_box_toggles_at_the_caret_and_reads_back() {
11535        let mut d = doc_with("task_toggle", "- [ ] todo\n- [x] done\n");
11536        d.caret = 8; // inside "todo"
11537        assert_eq!(d.task_checked_at_caret(), Some(false));
11538        d.toggle_task_checked();
11539        assert_eq!(d.source, "- [x] todo\n- [x] done\n");
11540        assert_eq!(d.task_checked_at_caret(), Some(true));
11541        d.toggle_task_checked();
11542        assert_eq!(d.source, "- [ ] todo\n- [x] done\n");
11543    }
11544
11545    #[test]
11546    fn a_click_toggles_a_box_without_taking_the_caret_with_it() {
11547        // The whole reason `toggle_task_at` exists apart from the caret form:
11548        // ticking a box elsewhere must not move the cursor out of what's being
11549        // typed.
11550        let mut d = doc_with("task_click", "- [ ] first\n- [ ] second\n");
11551        d.caret = 8; // inside "first"
11552        let second = d.source.find("second").unwrap();
11553        d.toggle_task_at(second);
11554        assert_eq!(d.source, "- [ ] first\n- [x] second\n");
11555        assert_eq!(d.caret, 8, "the caret stayed in the first item");
11556    }
11557
11558    #[test]
11559    fn a_paragraph_becomes_a_task_item_in_one_undo_step() {
11560        let mut d = doc_with("task_para", "first\n\nplain para\n");
11561        d.caret = d.source.find("para").unwrap();
11562        d.toggle_task_item();
11563        assert_eq!(d.source, "first\n\n- [ ] plain para\n");
11564        assert_eq!(d.task_checked_at_caret(), Some(false));
11565        assert_eq!(d.status, None);
11566        d.undo();
11567        assert_eq!(
11568            d.source, "first\n\nplain para\n",
11569            "one step takes both back"
11570        );
11571    }
11572
11573    #[test]
11574    fn a_blank_line_becomes_an_empty_task_item() {
11575        let mut d = doc_with("task_blank", "first\n\n");
11576        d.caret = d.source.len();
11577        d.toggle_task_item();
11578        assert_eq!(d.task_checked_at_caret(), Some(false), "{:?}", d.source);
11579        assert_eq!(d.status, None);
11580    }
11581
11582    #[test]
11583    fn a_plain_item_gains_and_loses_a_box() {
11584        let mut d = doc_with("task_mint", "- plain\n");
11585        d.caret = 4;
11586        assert_eq!(d.task_checked_at_caret(), None);
11587        d.toggle_task_item();
11588        assert_eq!(d.source, "- [ ] plain\n");
11589        assert_eq!(
11590            d.task_checked_at_caret(),
11591            Some(false),
11592            "a new box arrives unticked"
11593        );
11594        d.toggle_task_item();
11595        assert_eq!(d.source, "- plain\n");
11596    }
11597
11598    #[test]
11599    fn ticking_a_box_that_isnt_there_reports_rather_than_minting_one() {
11600        // `set checked` must not silently convert a bullet into a task — that is
11601        // `toggle_task_item`'s job, and twig refuses it here.
11602        let mut d = doc_with("task_none", "- plain\n");
11603        d.caret = 4;
11604        d.toggle_task_checked();
11605        assert_eq!(d.source, "- plain\n", "nothing written");
11606        assert!(
11607            d.status.is_some(),
11608            "the refusal should reach the status line"
11609        );
11610    }
11611
11612    #[test]
11613    fn a_task_item_in_a_quote_is_found_past_the_quote_marker() {
11614        let mut d = doc_with("task_quote", "> - [ ] nested\n");
11615        d.caret = d.source.find("nested").unwrap();
11616        assert_eq!(d.task_checked_at_caret(), Some(false));
11617        d.toggle_task_checked();
11618        assert_eq!(d.source, "> - [x] nested\n");
11619    }
11620
11621    #[test]
11622    fn insert_thematic_break_parts_the_paragraph_around_the_caret() {
11623        // A rule is a block, so twig's `insert_thematic_break` alone lands it
11624        // after the whole paragraph. `split_block` parts the paragraph first and
11625        // the rule is aimed at the *first* half, which is what a rule button is
11626        // understood to do — and what leaf spelled by hand until twig grew both
11627        // halves of the gesture.
11628        let mut d = doc_with("hr_mid", "before after\n");
11629        d.caret = 7; // between "before " and "after"
11630        d.insert_thematic_break();
11631        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11632        assert_eq!(d.selection(), None);
11633        assert_eq!(
11634            kind_at(&mut d, "before \n\n".len()),
11635            Some(Kind::ThematicBreak)
11636        );
11637    }
11638
11639    #[test]
11640    fn insert_thematic_break_at_a_paragraph_s_end_splits_nothing() {
11641        // At the end there is nothing to part, and a split there writes the
11642        // separator anyway — a blank line and the empty slot the next paragraph
11643        // would fill — which the rule then landed above: `para\n\n* * *\n\n\n`,
11644        // two blank lines nothing fills. Now the rule lands after the paragraph,
11645        // where the split-and-aim was sending it regardless. Both formats, and
11646        // both shapes of a last line — terminated, and still being typed —
11647        // because the two reach the split through different doors: Markdown's
11648        // paragraph span stops before its newline, so `para\n` at 4 never split
11649        // there, but `para` at 4 did.
11650        //
11651        // What stands under the rule is the line the caret goes on to, not a
11652        // slot: nothing above the rule but the one blank line, and the caret on
11653        // the line beneath it.
11654        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11655            for src in ["para\n", "para"] {
11656                let mut d = Doc::from_source(src.into(), fmt).unwrap();
11657                d.caret = 4;
11658                d.insert_thematic_break();
11659                assert_eq!(d.source, format!("para\n\n{rule}\n\n"), "{fmt:?} {src:?}");
11660                assert_eq!(d.caret, d.source.len());
11661            }
11662            // Mid-document the slot sat between the rule and the next block;
11663            // the caret's line does now, a blank line either side of it.
11664            let mut d = Doc::from_source("para\n\nnext\n".into(), fmt).unwrap();
11665            d.caret = 4;
11666            d.insert_thematic_break();
11667            assert_eq!(d.source, format!("para\n\n{rule}\n\n\n\nnext\n"), "{fmt:?}");
11668            // Trailing whitespace is nothing to part either.
11669            let mut d = Doc::from_source("para  \n".into(), fmt).unwrap();
11670            d.caret = 4;
11671            d.insert_thematic_break();
11672            assert_eq!(d.source, format!("para  \n\n{rule}\n\n"), "{fmt:?}");
11673        }
11674    }
11675
11676    #[test]
11677    fn insert_thematic_break_at_a_paragraph_s_start_lands_before_it() {
11678        // The split at the start parts nothing, but it is kept on purpose:
11679        // `|para` becomes `\npara` with the caret on a blank line, and twig
11680        // (3.5.2) writes a rule aimed at a blank line ON that line — the only
11681        // way "before the paragraph" is reachable through a gesture that only
11682        // places after. Before 3.5.2 this came out as `\n\n---\n\npara`.
11683        for (fmt, rule) in [(Format::Markdown, "---"), (Format::Djot, "* * *")] {
11684            let mut d = Doc::from_source("para\n".into(), fmt).unwrap();
11685            d.caret = 0;
11686            d.insert_thematic_break();
11687            assert_eq!(d.source, format!("{rule}\n\npara\n"), "{fmt:?}");
11688            let mut d = Doc::from_source("prev\n\npara\n".into(), fmt).unwrap();
11689            d.caret = 6;
11690            d.insert_thematic_break();
11691            assert_eq!(d.source, format!("prev\n\n{rule}\n\npara\n"), "{fmt:?}");
11692        }
11693    }
11694
11695    #[test]
11696    fn insert_thematic_break_on_a_blank_line_takes_that_line() {
11697        // The gap between two blocks is where a click lands the caret; the
11698        // rule goes on the blank, one blank each side, and the caret on the
11699        // line opened under it.
11700        let mut d = doc_with("hr_gap", "a\n\nb\n");
11701        d.caret = 2;
11702        d.insert_thematic_break();
11703        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11704        assert_eq!(d.caret, "a\n\n---\n\n".len());
11705    }
11706
11707    #[test]
11708    fn insert_thematic_break_leaves_the_caret_on_a_line_under_the_rule() {
11709        // The caret used to be left where twig's splice ended, the home past
11710        // the rule, which is drawn on the rule's own row: the writer saw the
11711        // caret beside the rule, and mid-document what they typed next ran
11712        // into the block below. Now it goes on to an empty row under the
11713        // rule's gap from every place a rule is asked for — the end of a
11714        // paragraph, the empty paragraph Enter opened, a list and the line
11715        // Enter leaves a list for, closing the document and before another
11716        // block — and what is typed there is a paragraph of its own.
11717        for (body, caret, typed) in [
11718            ("para\n", 4, "para\n\n---\n\nX"),
11719            ("para\n\n\n", 6, "para\n\n---\n\nX"),
11720            ("- one\n- two\n", 11, "- one\n- two\n\n---\n\nX"),
11721            ("- one\n- two\n\n\n", 13, "- one\n- two\n\n---\n\nX"),
11722            ("a\n\nb\n", 1, "a\n\n---\n\nX\n\nb\n"),
11723            ("a\n\n\n\nb\n", 3, "a\n\n---\n\nX\n\nb\n"),
11724        ] {
11725            let mut d = wysiwyg_doc("hr_caret", body);
11726            d.build_visual(80);
11727            d.caret = caret;
11728            d.insert_thematic_break();
11729            d.build_visual(80);
11730            let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11731            let (row, col) = d.vmap.pos_of_offset(d.caret);
11732            assert_eq!((row, col), (rule + 2, 0), "{body:?} → {:?}", d.source);
11733            assert!(d.vmap.rows[rule + 1].decoration, "the gap under the rule");
11734            assert!(d.vmap.rows[row].glyphs.is_empty(), "an empty line");
11735            d.insert("X");
11736            assert_eq!(d.source, typed, "{body:?}");
11737            let rule_at = d.source.find("---").unwrap();
11738            assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
11739        }
11740        // djot's rule takes in its newline; the line under it is the same.
11741        let mut d = Doc::from_source("a\n\nb\n".into(), Format::Djot).unwrap();
11742        d.view = View::Wysiwyg;
11743        d.caret = 1;
11744        d.insert_thematic_break();
11745        d.build_visual(80);
11746        assert_eq!(d.source, "a\n\n* * *\n\n\n\nb\n");
11747        assert_eq!(d.vmap.pos_of_offset(d.caret), (4, 0));
11748    }
11749
11750    #[test]
11751    fn a_rule_parting_a_paragraph_leaves_the_caret_before_its_second_half() {
11752        // The line under the rule is the paragraph's second half, so that is
11753        // where the caret goes: the text it was standing in front of is still
11754        // in front of it.
11755        let mut d = wysiwyg_doc("hr_parted", "before after\n");
11756        d.caret = 7;
11757        d.insert_thematic_break();
11758        assert_eq!(d.source, "before \n\n---\n\nafter\n");
11759        assert_eq!(d.caret, d.source.find("after").unwrap());
11760        // At the start of a paragraph too, the rule landing above it.
11761        let mut d = wysiwyg_doc("hr_parted_start", "prev\n\npara\n");
11762        d.caret = 6;
11763        d.insert_thematic_break();
11764        assert_eq!(d.caret, d.source.find("para").unwrap());
11765    }
11766
11767    #[test]
11768    fn the_line_under_a_new_rule_is_one_undo_step_with_it() {
11769        let mut d = wysiwyg_doc("hr_undo", "a\n\nb\n");
11770        d.caret = 1;
11771        d.insert_thematic_break();
11772        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11773        d.undo();
11774        assert_eq!(d.source, "a\n\nb\n");
11775        assert!(!d.can_undo());
11776        d.redo();
11777        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
11778    }
11779
11780    #[test]
11781    fn a_rule_in_preserve_flow_leaves_the_caret_on_the_first_line_under_it() {
11782        // Preserve draws every blank line as somewhere to type, the first under
11783        // the rule included, so that is the caret's line and the one written.
11784        let mut d = wysiwyg_doc("hr_preserve", "para\n");
11785        d.set_line_flow(LineFlow::Preserve);
11786        d.caret = 4;
11787        d.insert_thematic_break();
11788        assert_eq!(d.source, "para\n\n---\n\n");
11789        assert_eq!(d.caret, "para\n\n---\n".len());
11790        d.build_visual(80);
11791        let rule = d.vmap.pos_of_offset(d.source.find("---").unwrap()).0;
11792        assert_eq!(d.vmap.pos_of_offset(d.caret), (rule + 1, 0));
11793        // Before another block, one blank line more keeps it off that block.
11794        let mut d = wysiwyg_doc("hr_preserve_mid", "a\n\nb\n");
11795        d.set_line_flow(LineFlow::Preserve);
11796        d.caret = 1;
11797        d.insert_thematic_break();
11798        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
11799        assert_eq!(d.caret, "a\n\n---\n".len());
11800    }
11801
11802    #[test]
11803    fn insert_page_break_leaves_the_caret_on_a_line_under_it() {
11804        // The rule button's placement, for the other block the toolbar writes:
11805        // the caret was left at the end of twig's splice, beside the break at
11806        // the end of the document and on the next block's first letter before
11807        // one. djot spells the break as a fence of two lines; the line under
11808        // it is under the closing `:::`.
11809        for (fmt, body, want, typed) in [
11810            (
11811                Format::Markdown,
11812                "a\n\nb\n",
11813                "a\n\n::page-break\n\n\n\nb\n",
11814                "a\n\n::page-break\n\nX\n\nb\n",
11815            ),
11816            (
11817                Format::Markdown,
11818                "a\n",
11819                "a\n\n::page-break\n\n",
11820                "a\n\n::page-break\n\nX",
11821            ),
11822            (
11823                Format::Djot,
11824                "a\n\nb\n",
11825                "a\n\n::: page-break\n:::\n\n\n\nb\n",
11826                "a\n\n::: page-break\n:::\n\nX\n\nb\n",
11827            ),
11828        ] {
11829            let mut d = Doc::from_source(body.into(), fmt).unwrap();
11830            d.view = View::Wysiwyg;
11831            d.caret = 1;
11832            d.insert_page_break();
11833            assert_eq!(d.source, want, "{fmt:?}");
11834            d.build_visual(80);
11835            let (row, col) = d.vmap.pos_of_offset(d.caret);
11836            assert_eq!(col, 0);
11837            assert!(d.vmap.rows[row].glyphs.is_empty(), "{fmt:?}: an empty line");
11838            assert!(
11839                d.vmap.rows[row - 2].leaf_directive.is_some(),
11840                "{fmt:?}: under the break"
11841            );
11842            d.insert("X");
11843            assert_eq!(d.source, typed, "{fmt:?}");
11844            d.undo();
11845            d.undo();
11846            assert_eq!(
11847                d.source, body,
11848                "{fmt:?}: the break and its line are one step"
11849            );
11850        }
11851    }
11852
11853    #[test]
11854    fn a_block_parting_a_paragraph_is_one_undo_step() {
11855        // The split went to twig without leaf counting it, so the first Undo
11856        // took back the block, left the paragraph parted, and reported nothing
11857        // more to undo.
11858        let mut rule = wysiwyg_doc("part_undo_rule", "before after\n");
11859        rule.caret = 7;
11860        rule.insert_thematic_break();
11861        let mut table = wysiwyg_doc("part_undo_table", "before after\n");
11862        table.caret = 7;
11863        table.insert_table(1, 1);
11864        let mut page = wysiwyg_doc("part_undo_page", "before after\n");
11865        page.caret = 7;
11866        page.insert_page_break();
11867        for (name, d) in [
11868            ("rule", &mut rule),
11869            ("table", &mut table),
11870            ("page break", &mut page),
11871        ] {
11872            assert_ne!(d.source, "before after\n", "{name}");
11873            d.undo();
11874            assert_eq!(d.source, "before after\n", "{name}: one Undo");
11875            assert_eq!(d.caret, 7, "{name}: the caret back where it was");
11876            assert!(!d.can_undo(), "{name}");
11877            assert!(d.can_redo(), "{name}");
11878            d.redo();
11879            assert!(!d.source.starts_with("before after"), "{name}: one Redo");
11880            assert!(!d.can_redo(), "{name}");
11881        }
11882        // A table twig would refuse parts nothing: the refusal comes first.
11883        let mut d = wysiwyg_doc("part_undo_zero", "before after\n");
11884        d.caret = 7;
11885        d.insert_table(0, 1);
11886        assert_eq!(d.source, "before after\n");
11887        assert!(!d.can_undo());
11888    }
11889
11890    #[test]
11891    fn enter_at_a_paragraph_s_start_opens_an_empty_paragraph_above_it() {
11892        // twig's split at a paragraph's start writes one newline ahead of it,
11893        // which Fold draws as one more gap, so the first Enter showed nothing.
11894        // A paragraph break opens a line above, the caret staying before the
11895        // text. Past a mark's opening delimiters — where a tap before the
11896        // first letter lands — the split used to cut the mark in two
11897        // (`**\n\nb**`); the break goes in front of them, as it goes in
11898        // front of a heading's `#`, where the heading's own Enter left an
11899        // empty heading over its text as a paragraph. A paragraph that
11900        // opens a div gets its line outside the div, where it draws.
11901        for (body, caret, want, want_caret) in [
11902            ("a\n\nb\n", 3, "a\n\n\n\nb\n", 5),
11903            ("# H\n\nb\n", 5, "# H\n\n\n\nb\n", 7),
11904            ("a\n\n# H\n", 5, "a\n\n\n\n# H\n", 7),
11905            ("a\n\n**b** c\n", 3, "a\n\n\n\n**b** c\n", 5),
11906            ("a\n\n**b** c\n", 5, "a\n\n\n\n**b** c\n", 7),
11907            (
11908                "a\n\n<span data-color=\"orange\">b</span>\n",
11909                29,
11910                "a\n\n\n\n<span data-color=\"orange\">b</span>\n",
11911                31,
11912            ),
11913            (
11914                "a\n\n<div class=\"center\">\n\nb\n\n</div>\n",
11915                25,
11916                "a\n\n\n\n<div class=\"center\">\n\nb\n\n</div>\n",
11917                27,
11918            ),
11919        ] {
11920            let mut d = wysiwyg_doc("enter_para_start", body);
11921            d.build_visual(80);
11922            d.caret = caret;
11923            d.newline();
11924            assert_eq!(d.source, want, "{body:?}");
11925            assert_eq!(d.caret, want_caret, "{body:?}");
11926            d.build_visual(80);
11927            let (row, _) = d.vmap.pos_of_offset(d.caret);
11928            assert!(
11929                d.vmap.rows[row - 2].glyphs.is_empty(),
11930                "{body:?}: an empty line above"
11931            );
11932            assert!(
11933                !d.vmap.rows[row - 2].decoration,
11934                "{body:?}: one the caret can stand on"
11935            );
11936        }
11937        // Past the first letter it is an ordinary split.
11938        let mut d = wysiwyg_doc("enter_para_mid", "a\n\n**b** c\n");
11939        d.caret = 8;
11940        d.newline();
11941        assert_eq!(d.source, "a\n\n**b**\n\nc\n");
11942    }
11943
11944    #[test]
11945    fn enter_again_at_a_paragraph_s_start_opens_one_more_line() {
11946        // The first Enter's paragraph break leaves a gap either side of the
11947        // empty line. A second break drew two lines more; a newline draws one.
11948        let mut d = wysiwyg_doc("enter_para_again", "a\n\nb\n");
11949        d.build_visual(80);
11950        d.caret = 3;
11951        for (want, lines) in [("a\n\n\n\nb\n", 1), ("a\n\n\n\n\nb\n", 2)] {
11952            d.newline();
11953            assert_eq!(d.source, want);
11954            assert_eq!(&d.source[d.caret..], "b\n");
11955            d.build_visual(80);
11956            let empty = d
11957                .vmap
11958                .rows
11959                .iter()
11960                .filter(|r| r.glyphs.is_empty() && !r.decoration)
11961                .count();
11962            assert_eq!(empty, lines, "{want:?}");
11963        }
11964    }
11965
11966    #[test]
11967    fn enter_at_the_first_block_s_start_pushes_it_down() {
11968        // No row was drawn for a blank line above the first block, so Enter
11969        // there wrote a line and the text stayed where it was. Each Enter now
11970        // draws one empty line above it, the caret staying with the text;
11971        // past frontmatter, the line conventionally under it still draws
11972        // nothing until Enter adds to it.
11973        for (body, caret, wants) in [
11974            ("b\n", 0, ["\n\nb\n", "\n\n\nb\n"]),
11975            ("**b** c\n", 2, ["\n\n**b** c\n", "\n\n\n**b** c\n"]),
11976            ("# H\n", 2, ["\n\n# H\n", "\n\n\n# H\n"]),
11977            (
11978                "---\nt: x\n---\n\nb\n",
11979                14,
11980                ["---\nt: x\n---\n\n\nb\n", "---\nt: x\n---\n\n\n\nb\n"],
11981            ),
11982        ] {
11983            let mut d = wysiwyg_doc("enter_first_block", body);
11984            d.build_visual(80);
11985            let empty = |d: &Doc| {
11986                d.vmap
11987                    .rows
11988                    .iter()
11989                    .filter(|r| r.glyphs.is_empty() && !r.decoration)
11990                    .count()
11991            };
11992            assert_eq!(empty(&d), 0, "{body:?}: nothing above the text yet");
11993            d.caret = caret;
11994            for (lines, want) in wants.into_iter().enumerate() {
11995                d.newline();
11996                assert_eq!(d.source, want, "{body:?}");
11997                assert!(d.source[d.caret..].starts_with(&body[caret..]), "{body:?}");
11998                d.build_visual(80);
11999                assert_eq!(empty(&d), lines + 1, "{want:?}");
12000            }
12001            // The caret can go up onto the lines it opened.
12002            d.move_up(false);
12003            let (row, _) = d.vmap.pos_of_offset(d.caret);
12004            assert!(d.vmap.rows[row].glyphs.is_empty(), "{body:?}");
12005            assert!(!d.vmap.rows[row].decoration, "{body:?}");
12006        }
12007    }
12008
12009    /// What a reader sees of a map: each row's text, whether it is a gap,
12010    /// and the presentation it is drawn with. Offsets are left out, since an
12011    /// edit shifts them without anything on screen changing.
12012    fn drawn(d: &Doc) -> Vec<String> {
12013        d.vmap
12014            .rows
12015            .iter()
12016            .map(|r| {
12017                let text: String = r.glyphs.iter().map(|g| g.ch).collect();
12018                format!(
12019                    "{}{text:?} h={:?} lh={:?} a={:?}",
12020                    if r.decoration { "~" } else { "" },
12021                    r.heading,
12022                    r.line_height,
12023                    r.align
12024                )
12025            })
12026            .collect()
12027    }
12028
12029    #[test]
12030    fn enter_and_backspace_anywhere_show_what_they_write_and_undo_in_one_step() {
12031        // Enter that writes what the view does not draw looks like a key that
12032        // did nothing, so it gets pressed again, and the lines pile up unseen
12033        // until something redraws them all at once. The rule, the page break,
12034        // a paragraph's start, the first block's start and the blank page
12035        // were each that bug once. So: at every place the caret can stand, in
12036        // both flows, Enter either changes what is drawn or writes nothing,
12037        // and one Undo takes back whatever it wrote. Enter and Backspace both
12038        // leave the view a fresh open of the text would draw, so nothing
12039        // moves when the view is next rebuilt from scratch.
12040        let cases: &[(Format, &str)] = &[
12041            (
12042                Format::Markdown,
12043                "I talk to myself\n\nI laugh\n\nI cry\n\nknees to nose\n\nlet me go\n",
12044            ),
12045            (Format::Markdown, "I talk to myself\nI laugh\nI cry\n"),
12046            (
12047                Format::Markdown,
12048                "<div data-line-height=\"1.5\">\n\nI laugh\n\nI cry\n\nknees to nose\n\n</div>\n",
12049            ),
12050            (
12051                Format::Markdown,
12052                "<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",
12053            ),
12054            (
12055                Format::Markdown,
12056                "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n",
12057            ),
12058            (
12059                Format::Markdown,
12060                "---\ntitle: x\n---\n\n# Title\n\nbody **bold** and <span data-color=\"red\">red</span>\n",
12061            ),
12062            (Format::Markdown, "\n\n\nafter blank lines\n\n\n\nmid\n\n\n"),
12063            (
12064                Format::Markdown,
12065                "- one\n- two\n\n1. a\n2. b\n\n- [ ] task\n",
12066            ),
12067            (Format::Markdown, "> quoted\n> more\n\n> - in a quote\n"),
12068            (Format::Markdown, "a\n\n---\n\nb\n\n::page-break\n\nc\n"),
12069            (Format::Markdown, "Title\n=====\n\nSub\n---\n\ntext\n"),
12070            (
12071                Format::Markdown,
12072                "```\ncode\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n",
12073            ),
12074            (Format::Djot, "I laugh\n\nI cry\n\nknees to nose\n"),
12075            (
12076                Format::Djot,
12077                "{data-line-height=\"2\"}\nI cry\n\n{data-line-height=\"2\"}\nknees to nose\n",
12078            ),
12079            (Format::Djot, "# Title\n\na\n\n* * *\n\nb\n"),
12080            // HTML is not here: Enter writes blank lines there, which the
12081            // view draws and HTML does not keep. See
12082            // docs/tasks/enter-in-html-writes-whitespace.md.
12083        ];
12084        let mut failures = Vec::new();
12085        for &(format, body) in cases {
12086            for flow in [LineFlow::Fold, LineFlow::Preserve] {
12087                let open = || {
12088                    let mut d = Doc::from_source(body.into(), format).unwrap();
12089                    d.view = View::Wysiwyg;
12090                    d.set_line_flow(flow);
12091                    d.build_visual_unwrapped();
12092                    d
12093                };
12094                // The map a fresh open of the same text would draw. The
12095                // edited map differing from it is a view that changes on the
12096                // next full rebuild, seconds after the key, with no key.
12097                let fresh = |source: &str| {
12098                    let mut ed =
12099                        twig::Editor::new_ext(source.as_bytes(), format, parse_extensions())
12100                            .unwrap();
12101                    let nodes = ed.nodes().unwrap();
12102                    crate::wysiwyg::build(
12103                        &nodes,
12104                        source,
12105                        None,
12106                        flow == LineFlow::Preserve,
12107                        &wysiwyg::Surface::default(),
12108                        None,
12109                    )
12110                };
12111                let probe = open();
12112                let stops: Vec<usize> = (0..=body.len())
12113                    .filter(|&o| probe.vmap.is_stop(o))
12114                    .collect();
12115                for at in stops {
12116                    for enter in [true, false] {
12117                        let mut d = open();
12118                        d.caret = at;
12119                        d.anchor = None;
12120                        let before = drawn(&d);
12121                        if enter {
12122                            d.newline();
12123                        } else {
12124                            d.backspace();
12125                        }
12126                        d.build_visual_unwrapped();
12127                        let key = if enter { "enter" } else { "backspace" };
12128                        let what = format!(
12129                            "{key} {format:?} {flow:?} caret {at} in {body:?} -> {:?}",
12130                            d.source
12131                        );
12132                        if maps_differ(&d.vmap, &fresh(&d.source)) {
12133                            failures.push(format!("redraws differently: {what}"));
12134                        }
12135                        if d.source == body {
12136                            continue;
12137                        }
12138                        if enter && drawn(&d) == before {
12139                            failures.push(format!("drew nothing: {what}"));
12140                        }
12141                        d.undo();
12142                        if d.source != body {
12143                            failures.push(format!("undo left {:?}: {what}", d.source));
12144                        }
12145                    }
12146                }
12147            }
12148        }
12149        assert!(
12150            failures.is_empty(),
12151            "{} failures:\n{}",
12152            failures.len(),
12153            failures.join("\n")
12154        );
12155    }
12156
12157    #[test]
12158    fn enter_opens_a_line_that_draws_inside_a_div_a_quote_and_preserve_flow() {
12159        // Each of these wrote a line the view did not draw, so Enter looked
12160        // dead and every press left one more.
12161        let enter = |format, flow, body: &str, at: usize| {
12162            let mut d = Doc::from_source(body.into(), format).unwrap();
12163            d.view = View::Wysiwyg;
12164            d.set_line_flow(flow);
12165            d.build_visual(80);
12166            d.caret = at;
12167            d.newline();
12168            d.build_visual(80);
12169            d
12170        };
12171        let div = "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n</div>\n";
12172        let end = div.find("knees").unwrap() + "knees".len();
12173
12174        // At the end of a div's last paragraph, the empty paragraph opens
12175        // inside the div, drawn with its line height, and what is typed
12176        // there stays in it.
12177        let mut d = enter(Format::Markdown, LineFlow::Fold, div, end);
12178        let (row, _) = d.vmap.pos_of_offset(d.caret);
12179        let r = &d.vmap.rows[row];
12180        assert!(r.glyphs.is_empty() && !r.decoration, "{:?}", drawn(&d));
12181        assert!(
12182            r.line_height.is_some(),
12183            "the new line keeps the div's spacing"
12184        );
12185        d.insert("x");
12186        assert_eq!(
12187            d.source,
12188            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\nx\n\n</div>\n"
12189        );
12190        // Preserve flow's soft line there draws too.
12191        let d = enter(Format::Markdown, LineFlow::Preserve, div, end);
12192        assert_eq!(
12193            d.source,
12194            "<div data-line-height=\"1.5\">\n\nI cry\n\nknees\n\n\n</div>\n"
12195        );
12196        assert_eq!(d.vmap.rows.len(), 4, "{:?}", drawn(&d));
12197        // Between two of the div's paragraphs, the empty line takes its
12198        // spacing as well.
12199        let d = enter(
12200            Format::Markdown,
12201            LineFlow::Fold,
12202            div,
12203            div.find("knees").unwrap(),
12204        );
12205        let (row, _) = d.vmap.pos_of_offset(d.caret);
12206        assert!(
12207            d.vmap.rows[row - 2].line_height.is_some(),
12208            "{:?}",
12209            drawn(&d)
12210        );
12211
12212        // Under `</div>` the blank line is the one Markdown needs to end the
12213        // div. Preserve flow drew it as a line to type on, and Backspace
12214        // there glued the next paragraph to the tag (`</div>after`).
12215        let below = "<div class=\"center\">\n\nmiddle\n\n</div>\n\nafter\n";
12216        let mut d = Doc::from_source(below.into(), Format::Markdown).unwrap();
12217        d.view = View::Wysiwyg;
12218        d.set_line_flow(LineFlow::Preserve);
12219        d.build_visual(80);
12220        assert_eq!(d.vmap.rows.len(), 2, "{:?}", drawn(&d));
12221        d.caret = below.find("after").unwrap();
12222        d.backspace();
12223        assert!(!d.source.contains("</div>after"), "{:?}", d.source);
12224
12225        // At a quote's first line, the line opens above the quote; twig's
12226        // split wrote a quoted blank line above the text, which drew nothing.
12227        let d = enter(
12228            Format::Markdown,
12229            LineFlow::Fold,
12230            "a\n\n> quoted\n> more\n",
12231            5,
12232        );
12233        assert_eq!(d.source, "a\n\n\n\n> quoted\n> more\n");
12234        assert_eq!(&d.source[d.caret..], "quoted\n> more\n");
12235
12236        // Preserve flow at a paragraph's start: past a mark's delimiters its
12237        // newline cut the mark (`**\nb**`), and in djot a heading ran on
12238        // over it unseen.
12239        let d = enter(Format::Markdown, LineFlow::Preserve, "a\n\n**b** c\n", 5);
12240        assert_eq!(d.source, "a\n\n\n**b** c\n");
12241        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 5);
12242        assert_eq!(d.source, "a\n\n\n# Title\n");
12243        // Inside a heading it parts the heading, as in Fold flow.
12244        let d = enter(Format::Djot, LineFlow::Preserve, "a\n\n# Title\n", 7);
12245        assert_eq!(d.source, "a\n\n# Ti\n\ntle\n");
12246    }
12247
12248    #[test]
12249    fn enter_on_a_blank_page_writes_nothing() {
12250        // With no block to push down, Fold flow draws no line for Enter to
12251        // open, and the newline it wrote was an edit and an undo step that
12252        // showed nothing. Preserve flow draws every line, so there it writes.
12253        for body in ["", "\n", "\n\n  \n", "---\nt: x\n---\n"] {
12254            let mut d = wysiwyg_doc("enter_blank_page", body);
12255            d.build_visual(80);
12256            d.caret = d.source.len();
12257            d.newline();
12258            assert_eq!(d.source, body);
12259            assert!(!d.can_undo(), "{body:?}");
12260            assert!(!d.dirty, "{body:?}");
12261        }
12262        let mut d = wysiwyg_doc("enter_blank_page_preserve", "");
12263        d.set_line_flow(LineFlow::Preserve);
12264        d.build_visual(80);
12265        d.newline();
12266        assert_eq!(d.source, "\n");
12267    }
12268
12269    #[test]
12270    fn enter_beside_a_rule_opens_a_line_under_it() {
12271        // Beside a rule the caret stands at the home past it, which in source is
12272        // the start of the blank line under the rule, and Enter took it for an
12273        // empty paragraph: a lone newline, drawn as one more gap, and the caret
12274        // put on the next block's first line — where typing joined that block.
12275        // It goes on under the rule instead, as the rule button leaves it.
12276        let mut d = wysiwyg_doc("enter_rule", "a\n\n---\n\nb\n");
12277        d.build_visual(80);
12278        d.caret = "a\n\n---\n".len();
12279        d.newline();
12280        assert_eq!(d.source, "a\n\n---\n\n\n\nb\n");
12281        assert_eq!(d.caret, "a\n\n---\n\n".len());
12282        d.insert("X");
12283        assert_eq!(d.source, "a\n\n---\n\nX\n\nb\n");
12284
12285        // Closing the document.
12286        let mut d = wysiwyg_doc("enter_rule_end", "a\n\n---\n");
12287        d.caret = d.source.len();
12288        d.newline();
12289        assert_eq!(d.source, "a\n\n---\n\n");
12290        assert_eq!(d.caret, d.source.len());
12291
12292        // In a quote, where the lines it writes keep the quote's prefix.
12293        let mut d = wysiwyg_doc("enter_rule_quote", "> a\n>\n> ---\n>\n> b\n");
12294        d.caret = "> a\n>\n> ---\n".len();
12295        d.newline();
12296        assert_eq!(d.source, "> a\n>\n> ---\n>\n> \n>\n> b\n");
12297        d.insert("X");
12298        assert_eq!(d.source, "> a\n>\n> ---\n>\n> X\n>\n> b\n");
12299
12300        // Preserve draws the blank line under a rule as a line, and the caret
12301        // on it: Enter there is a blank line's, one line down.
12302        let mut d = wysiwyg_doc("enter_rule_preserve", "a\n\n---\n\nb\n");
12303        d.set_line_flow(LineFlow::Preserve);
12304        d.caret = "a\n\n---\n".len();
12305        d.newline();
12306        assert_eq!(d.source, "a\n\n---\n\n\nb\n");
12307        assert_eq!(d.caret, "a\n\n---\n\n".len());
12308    }
12309
12310    #[test]
12311    fn insert_table_at_a_paragraph_s_end_splits_nothing() {
12312        // The same door as the rule's, through the placement they share.
12313        let mut d = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12314        d.caret = 4;
12315        d.insert_table(1, 1);
12316        assert_eq!(d.source, "para\n\n|  |\n|---|\n|  |\n");
12317        let mut d = doc_with("table_end_typed", "para");
12318        d.caret = 4;
12319        d.insert_table(1, 1);
12320        assert_eq!(d.source, "para\n\n|  |\n| --- |\n|  |\n");
12321        assert!(d.caret_in_table());
12322    }
12323
12324    #[test]
12325    fn insert_thematic_break_spells_the_rule_the_format_s_own_way() {
12326        // The whole point of delegating: `---` is Markdown's, `* * *` is djot's,
12327        // and leaf wrote the first into both until twig started spelling it.
12328        let mut md = doc_with("hr_md", "para\n");
12329        md.caret = 2;
12330        md.insert_thematic_break();
12331        assert_eq!(md.source, "pa\n\n---\n\nra\n");
12332
12333        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12334        dj.caret = 2;
12335        dj.insert_thematic_break();
12336        assert_eq!(dj.source, "pa\n\n* * *\n\nra\n");
12337    }
12338
12339    #[test]
12340    fn insert_table_parts_the_paragraph_and_lands_in_the_first_header_cell() {
12341        // The table goes *at* the caret the way the rule does: the paragraph is
12342        // parted first, and twig writes the grid after its first half. The
12343        // caret then sits in the first header cell — selected, as Tab would
12344        // leave it — so the next keystroke is the heading.
12345        let mut d = doc_with("table_mid", "before after\n");
12346        d.caret = 7;
12347        d.insert_table(2, 3);
12348        assert_eq!(
12349            d.source,
12350            "before \n\n|  |  |  |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |\n\nafter\n"
12351        );
12352        assert!(d.caret_in_table());
12353        let first_bar = d.source.find('|').unwrap();
12354        assert!(
12355            d.caret > first_bar && d.caret < d.source.find("| ---").unwrap(),
12356            "caret {} is not in the header row",
12357            d.caret
12358        );
12359        d.insert("Name");
12360        assert!(d.source.starts_with("before \n\n| Name |  |  |\n"));
12361        // And the grid the table was written into is one the table keys walk
12362        // (over the map a frontend rebuilds after every edit).
12363        d.build_visual(80);
12364        assert!(d.cell_tab(true));
12365        d.insert("Qty");
12366        assert!(d.source.starts_with("before \n\n| Name | Qty |  |\n"));
12367    }
12368
12369    #[test]
12370    fn insert_table_spells_the_grid_the_format_s_own_way() {
12371        // Djot's delimiter row is unpadded, and leaf never has to know that.
12372        let mut dj = Doc::from_source("para\n".into(), Format::Djot).unwrap();
12373        dj.caret = 2;
12374        dj.insert_table(1, 2);
12375        assert_eq!(dj.source, "pa\n\n|  |  |\n|---|---|\n|  |  |\n\nra\n");
12376        assert!(dj.caret_in_table());
12377    }
12378
12379    #[test]
12380    fn insert_table_refuses_where_the_format_spells_no_table() {
12381        let mut d = Doc::from_source("<p>ab</p>\n".into(), Format::Html).unwrap();
12382        d.caret = 4;
12383        d.insert_table(1, 1);
12384        assert_eq!(d.source, "<p>ab</p>\n");
12385        assert!(d.status.as_deref().unwrap_or("").contains("not supported"));
12386        assert!(!d.capabilities().table);
12387    }
12388
12389    #[test]
12390    fn insert_table_reports_a_zero_shape_and_writes_nothing() {
12391        let mut d = doc_with("table_zero", "para\n");
12392        d.caret = 2;
12393        d.insert_table(0, 2);
12394        assert_eq!(d.source, "para\n");
12395        assert!(d.status.as_deref().unwrap_or("").starts_with("table:"));
12396    }
12397
12398    #[test]
12399    fn clicking_below_a_final_thematic_break_can_type_after_it() {
12400        let mut d = wysiwyg_doc("hr_final_click", "---\n");
12401        d.build_visual(80);
12402        d.click(d.vmap.num_rows() + 2, 0, false);
12403        assert_eq!(d.caret, d.source.len(), "the caret belongs after the rule");
12404        d.insert("after");
12405        assert_eq!(d.source, "---\nafter");
12406    }
12407
12408    #[test]
12409    fn enter_in_a_nested_list_item_keeps_the_new_item_nested() {
12410        // The same bytes are two documents. In Markdown `  - b` is a nested item
12411        // and the next one belongs beside it, at its indent. In Djot a list
12412        // marker can't interrupt a paragraph, so those bytes are literal text in
12413        // item `a` and there is only one item — writing `  - ` under it would add
12414        // no item at all, just more text, and the new sibling has to go to
12415        // column zero. Both spellings come out of the *enclosing item's* line.
12416        let mut md = wysiwyg_doc("enter_nested_md", "- a\n  - b\n");
12417        md.caret = "- a\n  - b".len();
12418        md.newline();
12419        assert_eq!(md.source, "- a\n  - b\n  - \n");
12420        assert_eq!(list_items(&mut md), 3);
12421
12422        let mut dj = Doc::from_source("- a\n  - b\n".into(), Format::Djot).unwrap();
12423        dj.view = View::Wysiwyg;
12424        dj.build_visual(80);
12425        dj.caret = "- a\n  - b".len();
12426        dj.newline();
12427        assert_eq!(dj.source, "- a\n  - b\n- \n");
12428        assert_eq!(list_items(&mut dj), 2);
12429
12430        // Where Djot's nesting is real — opened by a blank line — the indent is
12431        // reproduced there too, and the two formats agree again.
12432        let mut dj = Doc::from_source("- a\n\n  - b\n".into(), Format::Djot).unwrap();
12433        dj.view = View::Wysiwyg;
12434        dj.build_visual(80);
12435        dj.caret = "- a\n\n  - b".len();
12436        dj.newline();
12437        assert_eq!(dj.source, "- a\n\n  - b\n  - \n");
12438        assert_eq!(list_items(&mut dj), 3);
12439    }
12440
12441    #[test]
12442    fn tab_nests_an_item_at_the_column_its_own_marker_asks_for() {
12443        // Tab replaces the line's whole prefix with the one twig spells, so the
12444        // quote markers, the parent's indent and an ordered marker's extra
12445        // column are all its answer rather than leaf's arithmetic.
12446        for (name, body, caret, want) in [
12447            ("bullet", "- a\n- b\n", 6, "- a\n  - b\n"),
12448            ("ordered", "1. a\n2. b\n", 8, "1. a\n   1. b\n"),
12449            ("quoted", "> - a\n> - b\n", 10, "> - a\n>   - b\n"),
12450            // A checkbox is markup the item's own text wraps past, but a nested
12451            // list may only open at the *list* marker's column — four in from
12452            // there is a paragraph continuation, and `- [ ] a\n      - [ ] b`
12453            // parses as one item, not two.
12454            ("task", "- [ ] a\n- [ ] b\n", 14, "- [ ] a\n  - [ ] b\n"),
12455            (
12456                "quoted task",
12457                "> - [ ] a\n> - [ ] b\n",
12458                18,
12459                "> - [ ] a\n>   - [ ] b\n",
12460            ),
12461        ] {
12462            let mut doc = wysiwyg_doc(name, body);
12463            doc.caret = caret;
12464            doc.indent();
12465            assert_eq!(doc.source, want, "{name}");
12466            // The nesting is real, not just indented text.
12467            assert_eq!(list_items(&mut doc), 2, "{name}");
12468        }
12469    }
12470
12471    #[test]
12472    fn backspace_only_outdents_where_the_format_says_there_is_an_item() {
12473        // The same bytes, the two formats disagreeing, and a gesture that used
12474        // to read the bytes. `  - b` is a nested item in Markdown, so Backspace
12475        // at its marker outdents. In Djot a marker can't interrupt a paragraph,
12476        // so those bytes are literal text inside item `a` — there is nothing to
12477        // outdent, and treating them as a marker turned one item into two, a
12478        // structural edit from a keystroke that should delete one character.
12479        //
12480        // twig's `line_prefix` is what tells them apart: it reports the marker
12481        // on the Markdown line and nothing on the Djot one, which is a
12482        // continuation. No byte scan can reach that answer.
12483        let src = "- a\n  - b\n";
12484        let at = "- a\n  - ".len();
12485
12486        let mut md = Doc::from_source(src.into(), Format::Markdown).unwrap();
12487        md.view = View::Wysiwyg;
12488        md.build_visual(80);
12489        md.caret = at;
12490        md.backspace();
12491        assert_eq!(md.source, "- a\n- b\n");
12492        assert_eq!(list_items(&mut md), 2);
12493
12494        let mut dj = Doc::from_source(src.into(), Format::Djot).unwrap();
12495        dj.view = View::Wysiwyg;
12496        dj.build_visual(80);
12497        dj.caret = at;
12498        dj.backspace();
12499        assert_eq!(dj.source, "- a\n  -b\n"); // an ordinary character delete
12500        assert_eq!(list_items(&mut dj), 1); // and the structure is untouched
12501    }
12502
12503    #[test]
12504    fn enter_in_a_checklist_item_starts_another_unchecked_one() {
12505        // Leaf used to spell the next item from the marker bytes it scanned, and
12506        // its scanner stopped at the bullet — so Enter in a checklist wrote `- `
12507        // and dropped out of the checklist. twig reproduces the whole
12508        // continuation, and a fresh item is always unticked however the one above
12509        // it stands.
12510        for (name, body, want) in [
12511            ("unchecked", "- [ ] a\n", "- [ ] a\n- [ ] \n"),
12512            ("checked", "- [x] a\n", "- [x] a\n- [ ] \n"),
12513        ] {
12514            let mut doc = wysiwyg_doc(name, body);
12515            doc.caret = body.trim_end_matches('\n').len();
12516            doc.newline();
12517            assert_eq!(doc.source, want, "{name}");
12518            // Both items are checklist items — the new one is a box, not the
12519            // plain bullet the old marker scan left behind — and it is unticked
12520            // whichever way the one above it faces.
12521            let boxes: Vec<Option<bool>> = doc
12522                .nodes()
12523                .iter()
12524                .filter(|n| n.kind == Kind::TaskListItem)
12525                .map(|n| n.checked)
12526                .collect();
12527            assert_eq!(boxes.len(), 2, "{name}");
12528            assert_eq!(boxes[1], Some(false), "{name}");
12529        }
12530    }
12531
12532    #[test]
12533    fn a_split_takes_the_space_the_caret_was_in_front_of() {
12534        // Splicing a break at the caret strands the space the words were parted
12535        // at on the head of the second block, where it reads as an indent nobody
12536        // typed. twig's split consumes it.
12537        for (name, body, caret, want) in [
12538            ("para", "one two\n", 3, "one\n\ntwo\n"),
12539            ("item", "- one two\n", 5, "- one\n- two\n"),
12540            ("quote", "> one two\n", 5, "> one\n>\n> two\n"),
12541            // A heading takes leaf's own path, which has to match.
12542            ("heading", "# one two\n", 5, "# one\n\ntwo\n"),
12543        ] {
12544            let mut doc = wysiwyg_doc(name, body);
12545            doc.caret = caret;
12546            doc.newline();
12547            assert_eq!(doc.source, want, "{name}");
12548        }
12549    }
12550
12551    #[test]
12552    fn enter_at_the_end_of_a_heading_opens_a_paragraph() {
12553        // The one place leaf keeps its own break: `split_block` repeats the `#`,
12554        // and Enter after a title is how the body under it is asked for.
12555        let mut doc = wysiwyg_doc("head_enter", "# Title\n");
12556        doc.caret = "# Title".len();
12557        doc.newline();
12558        doc.insert("body");
12559        assert_eq!(doc.source, "# Title\n\nbody\n");
12560        assert_eq!(
12561            doc.nodes()
12562                .iter()
12563                .filter(|n| n.kind == Kind::Heading)
12564                .count(),
12565            1
12566        );
12567    }
12568
12569    #[test]
12570    fn enter_in_a_quoted_list_item_starts_the_next_quoted_item() {
12571        // A quoted item's marker doesn't open its line, so a scan that starts at
12572        // column zero finds a `>` where it wanted a bullet, calls the line "not a
12573        // list" and hands Enter to the plain-quote branch — which writes `> ` and
12574        // drops the list. The next item has to carry the whole prefix.
12575        for (name, body, want) in [
12576            ("flat", "> - a\n", "> - a\n> - \n"),
12577            ("sibling", "> - a\n> - b\n", "> - a\n> - b\n> - \n"),
12578            ("nested", "> - a\n>   - b\n", "> - a\n>   - b\n>   - \n"),
12579            ("ordered", "> 1. a\n> 2. b\n", "> 1. a\n> 2. b\n> 3. \n"),
12580            ("twice quoted", "> > - a\n", "> > - a\n> > - \n"),
12581        ] {
12582            let mut doc = wysiwyg_doc(name, body);
12583            doc.caret = body.trim_end_matches('\n').len();
12584            doc.newline();
12585            assert_eq!(doc.source, want, "{name}");
12586            // The marker isn't just spelled right, it parses as an item.
12587            assert_eq!(list_items(&mut doc), body.lines().count() + 1, "{name}");
12588        }
12589    }
12590
12591    #[test]
12592    fn an_empty_quoted_item_leaves_the_list_and_stays_in_the_quote() {
12593        // Double-Enter exits the list. Unquoted that means a blank line, but a
12594        // *bare* blank line would end the quote too and drop the caret out of it,
12595        // so the separator keeps its `>` and the caret's line keeps its `> `.
12596        let mut doc = wysiwyg_doc("quoted_exit", "> - a\n> - \n");
12597        doc.caret = "> - a\n> - ".len();
12598        doc.newline();
12599        assert_eq!(doc.source, "> - a\n>\n> \n");
12600        assert_eq!(list_items(&mut doc), 1);
12601        // What "still in the quote" means for the next keystroke: the caret sits
12602        // behind the prefix, and what's typed there lands inside the quote as a
12603        // paragraph of its own — not as more of item `a`.
12604        doc.insert("x");
12605        assert_eq!(doc.source, "> - a\n>\n> x\n");
12606        assert!(
12607            doc.editor
12608                .ancestors_at(doc.caret - 1)
12609                .is_ok_and(|c| c.into_iter().any(|m| m.kind == Kind::BlockQuote))
12610        );
12611    }
12612
12613    #[test]
12614    fn backspace_at_a_quoted_marker_takes_the_marker_and_leaves_the_quote() {
12615        // The marker is hidden block markup, so Backspace over it is structural —
12616        // but only the marker is the list's. Splicing from the line start would
12617        // take the `>` with it and silently unquote the line.
12618        let mut doc = wysiwyg_doc("quoted_bksp", "> - a\n");
12619        doc.caret = "> - ".len();
12620        doc.backspace();
12621        assert_eq!(doc.source, "> a\n");
12622        assert_eq!(list_items(&mut doc), 0);
12623
12624        // A nested one outdents instead, moving the bullet within the quote
12625        // rather than moving the quote.
12626        let mut doc = wysiwyg_doc("quoted_outdent", "> - a\n>   - b\n");
12627        doc.caret = "> - a\n>   - ".len();
12628        doc.backspace();
12629        assert_eq!(doc.source, "> - a\n> - b\n");
12630        assert_eq!(list_items(&mut doc), 2);
12631    }
12632
12633    #[test]
12634    fn only_a_bare_paragraph_is_parted_around_the_caret() {
12635        // The split is deliberately narrow. Parting a fenced block would leave
12636        // two fences with a rule between them, and parting a list item would
12637        // mint an item nobody asked for on the way to a rule that lands after
12638        // the list either way — so both keep the whole block intact and take the
12639        // rule after it. A caret in a quote is likewise left alone.
12640        for (name, body, caret, want) in [
12641            (
12642                "code",
12643                "```\nfn x() {}\n```\n",
12644                8,
12645                "```\nfn x() {}\n```\n\n---\n\n",
12646            ),
12647            ("list", "- one two\n", 6, "- one two\n\n---\n\n"),
12648            ("quote", "> one two\n", 6, "> one two\n>\n> ---\n>\n> \n"),
12649        ] {
12650            let mut d = doc_with(&format!("hr_narrow_{name}"), body);
12651            d.caret = caret;
12652            d.insert_thematic_break();
12653            assert_eq!(d.source, want, "{name}: the block should stay whole");
12654        }
12655    }
12656
12657    #[test]
12658    fn insert_thematic_break_replaces_the_selection() {
12659        // Now that the rule lands *at* the caret again, replacing the selection
12660        // is coherent once more: the text goes, and the rule takes its place.
12661        // The space the deletion left leading the second half is consumed by the
12662        // split rather than opening the new paragraph with it.
12663        let mut d = doc_with("hr_sel", "one two three\n");
12664        d.anchor = Some(4);
12665        d.caret = 7; // "two"
12666        d.insert_thematic_break();
12667        assert_eq!(d.source, "one \n\n---\n\nthree\n");
12668        assert_eq!(d.selection(), None);
12669    }
12670
12671    #[test]
12672    fn insert_thematic_break_clears_a_code_block_and_a_table_rather_than_refusing() {
12673        // Both are blocks the rule lands *after*. Leaf used to refuse a fence,
12674        // because writing `---` into one is code, not a rule — twig now walks out
12675        // to the block that owns the caret's line, so there is nothing to refuse.
12676        let mut code = doc_with("hr_code", "```\nfn x() {}\n```\n");
12677        code.caret = 5; // inside the fenced code
12678        code.insert_thematic_break();
12679        assert_eq!(code.source, "```\nfn x() {}\n```\n\n---\n\n");
12680        assert_eq!(code.status, None, "no refusal to report any more");
12681
12682        let mut table = doc_with("hr_table", "| a | b |\n|---|---|\n| 1 | 2 |\n");
12683        table.caret = 3; // in the header row
12684        table.insert_thematic_break();
12685        assert_eq!(table.source, "| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n\n");
12686    }
12687
12688    #[test]
12689    fn insert_thematic_break_in_a_list_item_ends_the_list() {
12690        // The un-indented rule cannot continue the list, so it closes the list
12691        // and lands at the top level rather than nested inside it.
12692        let mut d = doc_with("hr_list", "- one\n- two\n");
12693        d.caret = "- one\n- tw".len(); // mid "two"
12694        d.insert_thematic_break();
12695        d.build_visual(80);
12696        let rule_at = d.source.find("---").unwrap();
12697        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12698        assert!(
12699            !d.nodes().iter().any(|n| n.kind == Kind::BulletList
12700                && n.span.start <= rule_at
12701                && rule_at < n.span.end),
12702            "the rule must not be nested inside the list"
12703        );
12704    }
12705
12706    #[test]
12707    fn insert_thematic_break_in_a_blockquote_stays_in_the_quote() {
12708        // Leaf used to end the quote. twig gives the rule the quote's own prefix,
12709        // which is the document the gesture was actually asked for — and the
12710        // line the caret goes on to under it wears the prefix too, as the line
12711        // Enter opens in a quote does.
12712        let mut d = doc_with("hr_quote", "> hello\n");
12713        d.caret = 4; // inside the quoted text
12714        d.insert_thematic_break();
12715        assert_eq!(d.source, "> hello\n>\n> ---\n>\n> \n");
12716        assert_eq!(d.caret, "> hello\n>\n> ---\n>\n> ".len());
12717        d.build_visual(80);
12718        let rule_at = d.source.find("---").unwrap();
12719        assert_eq!(kind_at(&mut d, rule_at), Some(Kind::ThematicBreak));
12720        assert!(
12721            d.nodes().iter().any(|n| n.kind == Kind::BlockQuote
12722                && n.span.start <= rule_at
12723                && rule_at < n.span.end),
12724            "the rule belongs to the quote it was asked for"
12725        );
12726    }
12727
12728    // ── typing against a block picture ────────────────────────────────────────
12729
12730    /// A rendered-view document with the caret parked on one of the picture's two
12731    /// stops, and the map already built — the state a frontend is in between
12732    /// drawing a frame and the next keystroke.
12733    fn doc_at_picture(name: &str, src: &str, side: MediaStop) -> Doc {
12734        let mut d = doc_in(View::Wysiwyg, name, src);
12735        d.build_visual_unwrapped();
12736        let start = src.find("![").unwrap();
12737        d.caret = match side {
12738            MediaStop::Before => start,
12739            MediaStop::After => start + "![](p.png)".len(),
12740        };
12741        d
12742    }
12743
12744    /// The block media the map publishes, after rebuilding it — "is this still a
12745    /// picture, or has it become a line of text with an image in it?"
12746    fn media_count(d: &mut Doc) -> usize {
12747        d.build_visual_unwrapped();
12748        d.vmap.media.len()
12749    }
12750
12751    #[test]
12752    fn typing_past_a_block_picture_opens_a_paragraph_under_it() {
12753        // The accident this prevents: tap the blank page under a photo (which
12754        // lands on the picture's trailing stop), type, and `![](p.png)xy` is a
12755        // paragraph with an *inline* image — the photo stops being drawn.
12756        let mut d = doc_at_picture("pic_after", "hi\n\n![](p.png)\n", MediaStop::After);
12757        d.insert("xy");
12758        assert_eq!(d.source, "hi\n\n![](p.png)\n\nxy\n");
12759        assert_eq!(media_count(&mut d), 1, "still a picture");
12760    }
12761
12762    #[test]
12763    fn typing_in_front_of_a_block_picture_opens_a_paragraph_above_it() {
12764        let mut d = doc_at_picture("pic_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12765        d.insert("xy");
12766        assert_eq!(d.source, "hi\n\nxy\n\n![](p.png)\n");
12767        assert_eq!(media_count(&mut d), 1);
12768    }
12769
12770    #[test]
12771    fn a_picture_that_opens_the_document_still_takes_a_paragraph_above_it() {
12772        let mut d = doc_at_picture("pic_first", "![](p.png)\n", MediaStop::Before);
12773        d.insert("x");
12774        assert_eq!(d.source, "x\n\n![](p.png)\n");
12775        assert_eq!(media_count(&mut d), 1);
12776    }
12777
12778    #[test]
12779    fn one_undo_puts_the_picture_back_the_way_it_was_found() {
12780        // The opened paragraph is part of the keystroke, not an edit the writer
12781        // made — so it undoes with the character, not a step later.
12782        let mut d = doc_at_picture("pic_undo", "hi\n\n![](p.png)\n", MediaStop::After);
12783        d.insert("x");
12784        assert_eq!(d.source, "hi\n\n![](p.png)\n\nx\n");
12785        d.undo();
12786        assert_eq!(d.source, "hi\n\n![](p.png)\n");
12787    }
12788
12789    #[test]
12790    fn pasting_against_a_block_picture_opens_a_paragraph_too() {
12791        // ⌘V dissolves the picture exactly as a keystroke does.
12792        let mut d = doc_at_picture("pic_paste", "hi\n\n![](p.png)\n", MediaStop::After);
12793        d.paste("pasted");
12794        assert_eq!(d.source, "hi\n\n![](p.png)\n\npasted\n");
12795        assert_eq!(media_count(&mut d), 1);
12796    }
12797
12798    #[test]
12799    fn typing_beside_an_inline_image_is_ordinary_editing() {
12800        // An inline image has no placeholder row and no stops of its own. Opening
12801        // a paragraph mid-sentence would be the bug, not the fix.
12802        let mut d = doc_in(View::Wysiwyg, "pic_inline", "see ![](p.png) here\n");
12803        d.build_visual_unwrapped();
12804        d.caret = "see ![](p.png)".len();
12805        d.insert("!");
12806        assert_eq!(d.source, "see ![](p.png)! here\n");
12807    }
12808
12809    #[test]
12810    fn source_view_types_raw_markup_against_an_image_untouched() {
12811        // Source view is for writing the markup itself; a break inserted behind
12812        // the writer's back there would be the editor arguing with them.
12813        let mut d = doc_in(View::Source, "pic_src", "![](p.png)\n");
12814        d.caret = "![](p.png)".len();
12815        d.insert("x");
12816        assert_eq!(d.source, "![](p.png)x\n");
12817    }
12818
12819    #[test]
12820    fn typing_over_a_selection_that_starts_at_a_picture_stop_replaces_it() {
12821        // A selection is replaced, not joined into, so there is nothing to
12822        // protect: the range takes the picture with it.
12823        let mut d = doc_at_picture("pic_sel", "hi\n\n![](p.png)\n", MediaStop::Before);
12824        d.anchor = Some(d.caret);
12825        d.caret = d.source.find("![").unwrap() + "![](p.png)".len();
12826        d.insert("x");
12827        assert_eq!(d.source, "hi\n\nx\n");
12828    }
12829
12830    #[test]
12831    fn backspace_past_a_block_picture_deletes_the_picture_not_its_last_byte() {
12832        // What this actually cost: a real vault's photo, to one stray Backspace.
12833        // The caret past `![](p.png)` was deleting the closing paren — invisible
12834        // in the rendered view — and the photo became the text `![](p.png`.
12835        let mut d = doc_at_picture("pic_bs", "hi\n\n![](p.png)\n", MediaStop::After);
12836        d.backspace();
12837        assert_eq!(d.source, "hi\n");
12838        assert_eq!(media_count(&mut d), 0, "the picture went, in one piece");
12839        d.undo();
12840        assert_eq!(
12841            d.source, "hi\n\n![](p.png)\n",
12842            "and comes back in one piece"
12843        );
12844    }
12845
12846    #[test]
12847    fn backspace_in_front_of_a_block_picture_steps_out_instead_of_merging_it() {
12848        // Deleting the break here would join the picture to the paragraph above,
12849        // where it is an *inline* image and stops being drawn. Step over the
12850        // boundary; the next press deletes in the paragraph the caret reached.
12851        let mut d = doc_at_picture("pic_bs_before", "hi\n\n![](p.png)\n", MediaStop::Before);
12852        d.backspace();
12853        assert_eq!(d.source, "hi\n\n![](p.png)\n", "nothing deleted");
12854        assert_eq!(d.caret, 2, "the caret stepped up to the end of `hi`");
12855        d.backspace();
12856        assert_eq!(d.source, "h\n\n![](p.png)\n", "and now it deletes there");
12857        assert_eq!(media_count(&mut d), 1, "the picture was never at risk");
12858    }
12859
12860    #[test]
12861    fn forward_delete_in_front_of_a_block_picture_deletes_the_picture() {
12862        // The mirror. A byte-step here eats the `!` and leaves a link.
12863        let mut d = doc_at_picture("pic_del", "hi\n\n![](p.png)\n\nbye\n", MediaStop::Before);
12864        d.delete_forward();
12865        assert_eq!(d.source, "hi\n\nbye\n");
12866        assert_eq!(media_count(&mut d), 0);
12867    }
12868
12869    #[test]
12870    fn forward_delete_past_a_block_picture_steps_over_the_boundary() {
12871        let mut d = doc_at_picture(
12872            "pic_del_after",
12873            "hi\n\n![](p.png)\n\nbye\n",
12874            MediaStop::After,
12875        );
12876        d.delete_forward();
12877        assert_eq!(d.source, "hi\n\n![](p.png)\n\nbye\n", "nothing deleted");
12878        assert_eq!(
12879            d.caret,
12880            d.source.find("bye").unwrap(),
12881            "the caret stepped down to `bye`"
12882        );
12883    }
12884
12885    #[test]
12886    fn a_picture_that_is_the_whole_document_still_deletes_cleanly() {
12887        let mut d = doc_at_picture("pic_only", "![](p.png)\n", MediaStop::After);
12888        d.backspace();
12889        assert_eq!(d.source, "\n");
12890        assert_eq!(media_count(&mut d), 0);
12891    }
12892
12893    #[test]
12894    fn a_word_delete_takes_the_picture_whole_or_steps_out_of_it() {
12895        // ⌥⌫ past a picture would otherwise eat a "word" of its markup.
12896        let mut d = doc_at_picture("pic_wordbs", "hi there\n\n![](p.png)\n", MediaStop::After);
12897        d.delete_word_back();
12898        assert_eq!(d.source, "hi there\n");
12899
12900        // And in front of one it runs *through* the paragraph break into the
12901        // prose above, which merges the picture inline — so it steps out first,
12902        // and the second press deletes the word it was aimed at.
12903        let mut d = doc_at_picture("pic_wordbs2", "hi there\n\n![](p.png)\n", MediaStop::Before);
12904        d.delete_word_back();
12905        assert_eq!(d.source, "hi there\n\n![](p.png)\n");
12906        d.delete_word_back();
12907        assert_eq!(
12908            d.source, "hi \n\n![](p.png)\n",
12909            "the word above went, the picture stayed"
12910        );
12911        assert_eq!(media_count(&mut d), 1);
12912    }
12913
12914    #[test]
12915    fn source_view_deletes_raw_markup_against_an_image_untouched() {
12916        let mut d = doc_in(View::Source, "pic_src_del", "![](p.png)\n");
12917        d.caret = "![](p.png)".len();
12918        d.backspace();
12919        assert_eq!(d.source, "![](p.png\n", "raw editing, byte by byte");
12920    }
12921
12922    #[test]
12923    fn image_destination_at_caret_reads_the_image_under_the_caret() {
12924        let mut d = doc_with("img_read", "![a cat](cat.png)\n");
12925        d.caret = 3; // inside the image markup
12926        assert_eq!(d.image_destination_at_caret(), Some("cat.png".to_string()));
12927        // Past the image, the caret is in no image.
12928        d.caret = "![a cat](cat.png)".len();
12929        assert_eq!(d.image_destination_at_caret(), None);
12930    }
12931
12932    #[test]
12933    fn set_media_rows_reserves_blank_filler_rows_the_frontend_paints_over() {
12934        // The image is one placeholder row by default, and `set_media_rows` grows
12935        // it to the height the frontend measured: the label row plus blank
12936        // `decoration` fillers that hold the vertical space a raster is drawn into.
12937        let mut d = wysiwyg_doc("img_rows", "intro\n\n![a cat](cat.png)\n\nend\n");
12938        assert_eq!(d.vmap.media.len(), 1);
12939        let img_row = d.vmap.media[0].rows_span.start;
12940        assert_eq!(
12941            d.vmap.media[0].rows_span,
12942            img_row..img_row + 1,
12943            "default is one row"
12944        );
12945
12946        d.set_media_rows(HashMap::from([("cat.png".to_string(), 4)]));
12947        d.build_visual(80);
12948        assert_eq!(d.vmap.media.len(), 1, "still one image, now taller");
12949        let span = d.vmap.media[0].rows_span.clone();
12950        assert_eq!(span.end - span.start, 4, "reserves the four rows asked for");
12951        // The label row carries the mark and its glyphs; the three below are blank
12952        // decoration — drawn, but no caret and no text.
12953        assert!(
12954            d.vmap.rows[span.start].media.is_some(),
12955            "mark rides the first row"
12956        );
12957        for r in (span.start + 1)..span.end {
12958            assert!(d.vmap.rows[r].decoration, "filler row {r} is decoration");
12959            assert!(d.vmap.rows[r].glyphs.is_empty(), "filler row {r} is blank");
12960            assert!(
12961                d.vmap.rows[r].media.is_none(),
12962                "only the first row is marked"
12963            );
12964        }
12965    }
12966
12967    #[test]
12968    fn a_taller_image_adds_no_caret_stops_and_motion_steps_over_its_fillers() {
12969        // The extra rows are pure spacers: the caret's only homes stay the stop in
12970        // front of the image and the one just past it, so walking the document top
12971        // to bottom visits the same offsets whether the image is 1 row or 5.
12972        let body = "ab\n\n![x](p.png)\n\ncd\n";
12973        let stops_at = |rows: usize| -> Vec<usize> {
12974            let mut d = wysiwyg_doc("img_stops", body);
12975            if rows > 1 {
12976                d.set_media_rows(HashMap::from([("p.png".to_string(), rows)]));
12977                d.build_visual(80);
12978            }
12979            d.caret = 0;
12980            let mut seen = vec![d.caret];
12981            loop {
12982                d.move_right(false);
12983                if *seen.last().unwrap() == d.caret {
12984                    break;
12985                }
12986                seen.push(d.caret);
12987            }
12988            seen
12989        };
12990        assert_eq!(
12991            stops_at(1),
12992            stops_at(5),
12993            "reserving rows must not add stops"
12994        );
12995    }
12996
12997    #[test]
12998    fn insert_link_repoints_the_link_at_a_bare_caret() {
12999        let mut d = doc_with("link_repoint", "[word](http://x.dev)\n");
13000        d.caret = 3; // in the link's text, nothing selected
13001        d.insert_link("http://y.dev");
13002        assert_eq!(d.source, "[word](http://y.dev)\n");
13003        assert_eq!(d.selected_text(), Some("word"));
13004    }
13005
13006    #[test]
13007    fn insert_link_on_an_empty_range_autolinks_a_url() {
13008        // A link with no text of its own is an autolink, and twig spells it —
13009        // `<…>` is the canonical form and needs no text typed into it, so the
13010        // caret lands after it rather than selecting a finished link.
13011        let mut d = doc_with("link_empty", "\n");
13012        d.caret = 0;
13013        d.insert_link("http://x.dev");
13014        assert_eq!(d.source, "<http://x.dev>\n");
13015        assert_eq!(d.selection(), None);
13016        assert_eq!(d.caret, 14);
13017    }
13018
13019    #[test]
13020    fn insert_link_on_an_empty_range_falls_back_for_a_non_url() {
13021        // `<./notes.md>` is literal text in both formats and `<foo>` is raw HTML
13022        // in Markdown, so a destination that can't autolink doubles as the text
13023        // instead — which is then selected, ready to be typed over.
13024        let mut d = doc_with("link_rel", "\n");
13025        d.caret = 0;
13026        d.insert_link("./notes.md");
13027        assert_eq!(d.source, "[./notes.md](./notes.md)\n");
13028        assert_eq!(d.selection(), Some((1, 11)));
13029        d.insert("Notes");
13030        assert_eq!(d.source, "[Notes](./notes.md)\n");
13031    }
13032
13033    #[test]
13034    fn insert_link_repoints_the_autolink_the_caret_stands_in() {
13035        // The autolink's text is its URL, so re-pointing replaces the whole
13036        // node — the caret must not splice a second link inside the first.
13037        let mut d = doc_with("link_repoint_auto", "see <https://x.dev> ok\n");
13038        d.caret = 10;
13039        d.insert_link("https://y.dev");
13040        assert_eq!(d.source, "see <https://y.dev> ok\n");
13041    }
13042
13043    #[test]
13044    fn code_language_reads_and_edits_through_the_fence() {
13045        let mut d = doc_with("code_lang", "```rust\nlet x = 1;\n```\n");
13046        d.caret = 10; // inside the code body
13047        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13048        assert!(d.caret_in_fenced_code());
13049
13050        d.set_code_language("python");
13051        assert!(
13052            d.source.starts_with("```python\n"),
13053            "source: {:?}",
13054            d.source
13055        );
13056        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13057
13058        // Clearing it leaves a bare fence and no label.
13059        d.set_code_language("");
13060        assert!(d.source.starts_with("```\n"), "source: {:?}", d.source);
13061        assert_eq!(d.code_language_at_caret(), None);
13062
13063        // A caret outside any code block edits nothing.
13064        let mut p = doc_with("code_lang_none", "just prose\n");
13065        assert!(!p.caret_in_fenced_code());
13066        p.set_code_language("rust");
13067        assert_eq!(p.source, "just prose\n");
13068    }
13069
13070    #[test]
13071    fn code_language_reads_and_edits_through_a_quoted_fence() {
13072        let mut d = doc_with("code_lang_quote", "> ```rust\n> let x = 1;\n> ```\n");
13073        d.caret = d.source.find("let").unwrap();
13074        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13075        assert!(d.caret_in_fenced_code());
13076        d.set_code_language("python");
13077        assert!(
13078            d.source.starts_with("> ```python\n"),
13079            "source: {:?}",
13080            d.source
13081        );
13082        assert_eq!(d.code_language_at_caret().as_deref(), Some("python"));
13083    }
13084
13085    #[test]
13086    fn a_language_the_fence_cannot_carry_is_refused_not_written() {
13087        // Markdown's info string ends at whitespace, so `two words` would write
13088        // a fence that reads back with a different language than the one asked
13089        // for. twig refuses it; leaf reports that and leaves the source alone.
13090        // The old splice trimmed the ends and wrote whatever was left.
13091        let mut d = doc_with("code_lang_bad", "```rust\nx\n```\n");
13092        d.caret = 10;
13093        d.set_code_language("two words");
13094        assert_eq!(d.source, "```rust\nx\n```\n", "source should be untouched");
13095        assert!(d.status.is_some(), "the refusal should be reported");
13096        assert_eq!(d.code_language_at_caret().as_deref(), Some("rust"));
13097    }
13098
13099    #[test]
13100    fn link_destination_at_caret_reads_both_spellings() {
13101        let mut d = doc_with("link_dest", "see [t](https://x.dev) ok\n");
13102        d.caret = 5;
13103        assert_eq!(
13104            d.link_destination_at_caret().as_deref(),
13105            Some("https://x.dev")
13106        );
13107        d.caret = 0;
13108        assert_eq!(d.link_destination_at_caret(), None);
13109
13110        // An autolink has no `destination`; its text is the URL.
13111        let mut a = doc_with("link_dest_auto", "see <https://x.dev> ok\n");
13112        a.caret = 10;
13113        assert_eq!(
13114            a.link_destination_at_caret().as_deref(),
13115            Some("https://x.dev")
13116        );
13117        a.caret = 21;
13118        assert_eq!(a.link_destination_at_caret(), None);
13119    }
13120
13121    #[test]
13122    fn heading_at_caret_is_the_nearest_heading_above() {
13123        let src = "intro\n\n# Title\n\n## The *Second* Part\n\nbody here\n";
13124        let mut d = doc_with("heading_at", src);
13125        // Under no heading at all.
13126        d.caret = 2;
13127        assert_eq!(d.heading_at_caret(), None);
13128        // In a paragraph under a level-2 heading: that heading, its markup
13129        // stripped for the slug, and its own span.
13130        d.caret = src.find("body").unwrap() + 2;
13131        let h = d.heading_at_caret().expect("under `## The Second Part`");
13132        assert_eq!(h.text, "The Second Part");
13133        assert_eq!(h.level, 2);
13134        assert_eq!(&src[h.span.clone()].trim_end(), &"## The *Second* Part");
13135        // Standing in a heading answers with that heading.
13136        let h = d.heading_at(src.find("Title").unwrap()).unwrap();
13137        assert_eq!((h.text.as_str(), h.level), ("Title", 1));
13138        // And the text is what `locate` lands a slug of.
13139        let landing = d.locate("the-second-part").unwrap();
13140        assert_eq!(landing.start, d.heading_at_caret().unwrap().span.start);
13141    }
13142
13143    #[test]
13144    fn locate_finds_the_block_a_declared_id_names() {
13145        // The Book of Mormon shape: one document per chapter, one `{#v…}` per
13146        // verse. The locator has to land on the *verse*, which is the whole
13147        // reason a link carries one.
13148        let src = "{#v1}\nI, Nephi, having been born of goodly parents.\n\n\
13149                   {#v2}\nYea, I make a record in the language of my father.\n";
13150        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13151        let v2 = d.locate("v2").expect("the document declares `{#v2}`");
13152        assert_eq!(
13153            d.source[v2.start..v2.end].trim_end(),
13154            "Yea, I make a record in the language of my father."
13155        );
13156        // The attribute line is not part of it: `start` is a place to put a
13157        // caret, and `{#v2}` is markup the caret has no business landing in.
13158        assert!(d.source[..v2.start].ends_with("{#v2}\n"));
13159        assert_eq!(d.locate("v99"), None);
13160    }
13161
13162    #[test]
13163    fn locate_reads_a_heading_by_its_words_when_the_format_mints_no_ids() {
13164        // Markdown has no ids at all — twig mints none, and `{#custom}` in a
13165        // Markdown heading is literal text. So `#the-second-part` can only be
13166        // the heading's own words, which is the rule every Markdown renderer
13167        // already follows and therefore the one a link was authored against.
13168        let src = "# Title\n\nintro\n\n## The Second Part\n\nbody\n\n## Third\n\nmore\n";
13169        let mut d = doc_with("locate_md", src);
13170        let hit = d.locate("the-second-part").expect("the heading's slug");
13171        assert!(d.source[hit.start..].starts_with("## The Second Part"));
13172        // Bounded by the next heading that isn't under it, so a peek shows the
13173        // section rather than only its title.
13174        assert_eq!(
13175            &d.source[hit.start..hit.end],
13176            "## The Second Part\n\nbody\n\n"
13177        );
13178
13179        // A subsection does not end its parent: `# Title` runs to `## Third`'s
13180        // sibling only because there is no other `#`, so it covers the lot.
13181        let title = d.locate("title").expect("the top heading");
13182        assert_eq!(title.end, d.source.len());
13183    }
13184
13185    #[test]
13186    fn locate_reads_a_djot_auto_id_however_the_link_spelled_it() {
13187        // djot mints `Some-Heading-Here`; a link to it is written
13188        // `#some-heading-here` by nearly everything that writes links. Both
13189        // spellings are one question.
13190        let src = "## Some Heading Here\n\nbody\n";
13191        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13192        let exact = d.locate("Some-Heading-Here").expect("djot's own spelling");
13193        let slugged = d.locate("some-heading-here").expect("the link's spelling");
13194        assert_eq!(exact, slugged);
13195        // The section, not the heading line — there is more to show than a title.
13196        assert_eq!(&d.source[exact.start..exact.end], src);
13197    }
13198
13199    #[test]
13200    fn locate_ignores_an_empty_locator_and_one_that_slugs_to_nothing() {
13201        let mut d = doc_with("locate_empty", "# Title\n\nbody\n");
13202        assert_eq!(d.locate(""), None);
13203        assert_eq!(d.locate("   "), None);
13204        // All punctuation: it names nothing, and must not be read as "match the
13205        // first heading whose slug is also empty".
13206        assert_eq!(d.locate("!!!"), None);
13207    }
13208
13209    #[test]
13210    fn locate_gives_a_duplicated_id_to_the_first_block_that_claims_it() {
13211        // The document's mistake, and the answer every other anchor
13212        // implementation gives — the alternative is for a link to mean whichever
13213        // of the two a walk happened to reach first.
13214        let src = "{#dup}\nfirst.\n\n{#dup}\nsecond.\n";
13215        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13216        let hit = d.locate("dup").expect("the first `{#dup}`");
13217        assert_eq!(d.source[hit.start..hit.end].trim_end(), "first.");
13218    }
13219
13220    #[test]
13221    fn insert_footnote_writes_both_halves_and_lands_the_caret_in_the_note() {
13222        // The button's whole job: a reference where the caret was, a definition
13223        // to give it meaning, and the caret waiting in the empty note so the
13224        // next keystroke is the note's first word.
13225        let mut d = doc_with("fn_insert", "A claim and more.\n");
13226        d.caret = 7; // just past "A claim"
13227        d.insert_footnote();
13228        assert!(
13229            d.source.starts_with("A claim[^1] and more."),
13230            "{:?}",
13231            d.source
13232        );
13233        assert!(
13234            d.source.contains("[^1]:"),
13235            "the definition too: {:?}",
13236            d.source
13237        );
13238        assert_eq!(d.status, None);
13239
13240        let reference = d.source.find("[^1]").unwrap();
13241        let note = d
13242            .footnote_at(reference + 2)
13243            .expect("the reference just written");
13244        assert_eq!(note.label, "1");
13245        assert_eq!(note.text.as_deref(), Some(""), "the note starts empty");
13246        assert_eq!(Some(d.caret), note.offset, "the caret waits in the note");
13247        // …and typing there is typing into the note, not near it.
13248        d.insert("the note");
13249        assert_eq!(
13250            d.footnote_at(reference + 2).and_then(|f| f.text),
13251            Some("the note".to_string())
13252        );
13253    }
13254
13255    #[test]
13256    fn insert_footnote_numbers_past_the_notes_already_written() {
13257        // A second press must not hand back a label somebody else is using: twig
13258        // reuses a defined label rather than appending a rival definition, so a
13259        // repeat of `1` would quietly point the new reference at the old note.
13260        let mut d = doc_with("fn_insert_number", "One[^1] two.\n\n[^1]: first\n");
13261        d.caret = 7; // past `[^1]`, before " two."
13262        d.insert_footnote();
13263        assert!(d.source.starts_with("One[^1][^2] two."), "{:?}", d.source);
13264        assert_eq!(d.source.matches("[^2]:").count(), 1);
13265    }
13266
13267    #[test]
13268    fn insert_footnote_counts_a_dangling_reference_and_ignores_a_named_one() {
13269        // `[^2]` with no definition is still a 2 that means something to whoever
13270        // wrote it — stepping over it would mint a note for their reference. A
13271        // word label takes no number, so it blocks none.
13272        let mut d = doc_with("fn_insert_dangling", "a[^2] b[^why] c\n\n[^why]: named\n");
13273        d.caret = d.source.find(" c").unwrap();
13274        d.insert_footnote();
13275        assert!(d.source.contains("[^1]:"), "1 is free: {:?}", d.source);
13276        assert!(
13277            d.source.starts_with("a[^2] b[^why][^1] c"),
13278            "{:?}",
13279            d.source
13280        );
13281    }
13282
13283    #[test]
13284    fn insert_footnote_marks_the_selection_rather_than_replacing_it() {
13285        // A reference annotates the words before it. Consuming the selection —
13286        // which is what an insert normally does — would delete the very claim
13287        // the author selected in order to footnote.
13288        let mut d = doc_with("fn_insert_sel", "A claim and more.\n");
13289        d.anchor = Some(2);
13290        d.caret = 7; // "claim" selected
13291        d.insert_footnote();
13292        assert!(
13293            d.source.starts_with("A claim[^1] and more."),
13294            "{:?}",
13295            d.source
13296        );
13297    }
13298
13299    #[test]
13300    fn a_note_just_written_still_knows_where_its_reference_is() {
13301        // The authoring loop in one test: press the button, type the note, ask to
13302        // go back. The caret ends at the note's last byte — which is the *end* of
13303        // the definition's span, the one offset the query used to exclude — so
13304        // this is where the round trip either works or doesn't.
13305        let mut d = doc_with("fn_insert_return", "A claim and more.\n");
13306        d.caret = 7;
13307        d.insert_footnote();
13308        d.insert("the note");
13309        assert_eq!(d.source, "A claim[^1] and more.\n\n[^1]: the note\n");
13310        let back = d
13311            .footnote_definition_at_caret()
13312            .expect("still in the note we just typed");
13313        assert_eq!(back.label, "1");
13314        // …and following it lands on the reference's label, where a reader's
13315        // return leg lands.
13316        assert_eq!(back.offset, Some(9));
13317        assert_eq!(&d.source[9..10], "1");
13318    }
13319
13320    #[test]
13321    fn insert_footnote_takes_one_undo_for_both_halves() {
13322        // twig writes the pair as a single edit; the point of that is here.
13323        let before = "A claim and more.\n";
13324        let mut d = doc_with("fn_insert_undo", before);
13325        d.caret = 7;
13326        d.insert_footnote();
13327        assert_ne!(d.source, before);
13328        d.undo();
13329        assert_eq!(d.source, before, "one undo takes back both halves");
13330    }
13331
13332    #[test]
13333    fn insert_footnote_refuses_a_format_that_cannot_spell_one() {
13334        // HTML is authorable — it spells the inline marks — and has no footnote.
13335        // The refusal says so rather than writing brackets that would render as
13336        // brackets.
13337        let src = "<p>A claim.</p>\n";
13338        let mut d = Doc::from_source(src.to_string(), Format::Html).unwrap();
13339        assert!(!Capabilities::of(Format::Html).footnote);
13340        d.caret = 5;
13341        d.insert_footnote();
13342        assert_eq!(d.source, src, "nothing written");
13343        assert!(d.status.is_some_and(|s| s.starts_with("footnote:")));
13344    }
13345
13346    #[test]
13347    fn insert_footnote_leaves_the_caret_on_a_real_stop_in_the_rich_view() {
13348        // The empty body is the one place this could go wrong: the definition
13349        // renders as a `[1] ` marker the caret cannot occupy, so a caret aimed a
13350        // byte early would draw up in the paragraph above the note it belongs to.
13351        let mut d = doc_in(View::Wysiwyg, "fn_insert_stop", "A claim and more.\n");
13352        d.place_caret(7, false);
13353        d.insert_footnote();
13354        d.build_visual(80); // the frame a frontend draws after the edit
13355        assert_eq!(
13356            d.vmap.snap_to_stop(d.caret),
13357            d.caret,
13358            "the caret sits on a stop"
13359        );
13360        let (row, _) = d.caret_pos();
13361        assert!(
13362            drawn_rows(&d)[row].contains("[1]"),
13363            "the caret is on the note's row, not above it: {:?}",
13364            drawn_rows(&d)
13365        );
13366    }
13367
13368    #[test]
13369    fn footnote_at_caret_resolves_a_reference_to_its_note() {
13370        // `[^1]` spans 7..11; its label byte is at 9. The definition follows a
13371        // blank line, as one has to.
13372        let mut d = doc_with("fn_at_caret", "A claim[^1] and more.\n\n[^1]: the note\n");
13373        d.caret = 9;
13374        let f = d
13375            .footnote_at_caret()
13376            .expect("the caret stands in a reference");
13377        assert_eq!(f.label, "1");
13378        assert_eq!(f.text.as_deref(), Some("the note"));
13379        // The offset points at the note's first word, not at the definition's
13380        // `[` — the marker is decoration with no caret stop on it.
13381        assert_eq!(f.offset, Some(29));
13382        assert_eq!(&d.source[29..37], "the note");
13383        // …and `end` closes the range, so a frontend can ask which rendered rows
13384        // the note occupies rather than re-deriving them from the text.
13385        assert_eq!(f.end, Some(37));
13386        assert_eq!(&d.source[f.offset.unwrap()..f.end.unwrap()], "the note");
13387    }
13388
13389    /// Two definitions in a row: each is its own note, and neither reaches into
13390    /// the other.
13391    ///
13392    /// A djot definition's span used to run past the blank line into the first
13393    /// byte of whatever followed, so this answered `"first note.\n\n["` — and the
13394    /// offsets named the *next* note's rows too, showing a reader two footnotes
13395    /// when they had asked about one. twig 3.1 ends the span after the block's
13396    /// own last line; the test outlives the workaround leaf carried for it.
13397    #[test]
13398    fn footnote_at_stops_a_note_at_the_definition_after_it() {
13399        let src = "Claim[^2a] and [^2b].\n\n[^2a]: first note.\n\n[^2b]: second note.\n";
13400        for format in [Format::Markdown, Format::Djot] {
13401            let mut d = Doc::from_source(src.to_string(), format).unwrap();
13402            d.caret = 7;
13403            let f = d.footnote_at_caret().expect("a reference");
13404            assert_eq!(f.text.as_deref(), Some("first note."), "in {format:?}");
13405            assert_eq!(
13406                &src[f.offset.unwrap()..f.end.unwrap()],
13407                "first note.",
13408                "in {format:?}"
13409            );
13410        }
13411    }
13412
13413    /// The other side of that boundary: a blank line *inside* a definition is
13414    /// interior to it, and the note keeps its second paragraph.
13415    ///
13416    /// This is what the old body scan cost. It stopped at the first line not
13417    /// indented under the note — a blank line is not — so a two-paragraph note
13418    /// came back as its first paragraph, and "go to note" framed half of it.
13419    /// Reading the span twig gives is both simpler and right.
13420    #[test]
13421    fn footnote_at_keeps_a_notes_second_paragraph() {
13422        let src = "Claim[^1].\n\n[^1]: first para.\n\n    second para.\n\nAfter.\n";
13423        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
13424        d.caret = 7;
13425        let f = d.footnote_at_caret().expect("a reference");
13426        assert_eq!(f.text.as_deref(), Some("first para.\n\n    second para."));
13427        // And it stops there — `After.` is the next block, not more note.
13428        assert_eq!(
13429            &src[f.offset.unwrap()..f.end.unwrap()],
13430            f.text.as_deref().unwrap()
13431        );
13432        assert!(!f.text.as_deref().unwrap().contains("After"));
13433    }
13434
13435    #[test]
13436    fn footnote_at_bounds_a_note_whose_body_is_empty() {
13437        // `[^1]:` with nothing after it. The range is empty rather than
13438        // inverted, and still points inside the definition — which is what keeps
13439        // a frontend's row lookup from walking off into the block above.
13440        let src = "A claim[^1].\n\n[^1]:\n";
13441        let mut d = doc_with("fn_empty_body", src);
13442        d.caret = 9;
13443        let f = d.footnote_at_caret().expect("a reference");
13444        assert_eq!(f.text.as_deref(), Some(""));
13445        assert_eq!(f.offset, f.end, "an empty note is an empty range");
13446        assert!(f.offset.unwrap() >= src.find("[^1]:").unwrap());
13447    }
13448
13449    #[test]
13450    fn footnote_at_caret_ignores_a_caret_that_stands_in_no_reference() {
13451        let mut d = doc_with(
13452            "fn_at_caret_none",
13453            "A claim[^1] and more.\n\n[^1]: the note\n",
13454        );
13455        d.caret = 2; // in the prose
13456        assert_eq!(d.footnote_at_caret(), None);
13457    }
13458
13459    #[test]
13460    fn footnote_at_caret_is_not_a_link_query_and_vice_versa() {
13461        // The two are deliberately separate: a reference names a note in this
13462        // document, a link names somewhere to leave for, and answering one with
13463        // the other is what made a reference click do nothing at all.
13464        let mut d = doc_with("fn_vs_link", "a[^1] b [t](https://x.dev)\n\n[^1]: note\n");
13465        d.caret = 3; // the `1` of `[^1]`
13466        assert!(d.footnote_at_caret().is_some());
13467        assert_eq!(
13468            d.link_destination_at_caret(),
13469            None,
13470            "a reference is not a link"
13471        );
13472
13473        d.caret = 10; // inside the link's label
13474        assert_eq!(d.footnote_at_caret(), None, "a link is not a reference");
13475        assert_eq!(
13476            d.link_destination_at_caret().as_deref(),
13477            Some("https://x.dev")
13478        );
13479    }
13480
13481    #[test]
13482    fn footnote_at_caret_reports_an_undefined_reference_rather_than_nothing() {
13483        // A `[^99]` the document never defines is a real state — a note deleted
13484        // out from under its reference — and the label is what lets a frontend
13485        // say so. `None` here would be indistinguishable from "not on a
13486        // reference", which is the wrong thing to tell a reader.
13487        let mut d = doc_with("fn_undefined", "A claim[^99] and more.\n");
13488        d.caret = 9;
13489        let f = d
13490            .footnote_at_caret()
13491            .expect("the reference is still a reference");
13492        assert_eq!(f.label, "99");
13493        assert_eq!(f.text, None);
13494        assert_eq!(f.offset, None);
13495    }
13496
13497    #[test]
13498    fn footnote_at_caret_reads_a_word_label_and_a_multiline_note() {
13499        // Labels are not always numbers, and a note's body runs past its first
13500        // line — the indented continuation belongs to the note, so it comes back
13501        // with it (source bytes, verbatim, as documented).
13502        let src = "see[^note] here\n\n[^note]: first line\n    second line\n";
13503        let mut d = doc_with("fn_word_label", src);
13504        d.caret = 6;
13505        let f = d
13506            .footnote_at_caret()
13507            .expect("the caret stands in a reference");
13508        assert_eq!(f.label, "note");
13509        assert_eq!(f.text.as_deref(), Some("first line\n    second line"));
13510    }
13511
13512    #[test]
13513    fn footnote_at_answers_for_an_offset_the_caret_is_nowhere_near() {
13514        // The point of the offset form: a pointer hovering a reference asks what
13515        // note it names, and must not drag the caret along to ask.
13516        let mut d = doc_with("fn_at_off", "A claim[^1] and more.\n\n[^1]: the note\n");
13517        d.caret = 0;
13518        let f = d.footnote_at(9).expect("offset 9 stands in the reference");
13519        assert_eq!(f.label, "1");
13520        assert_eq!(f.text.as_deref(), Some("the note"));
13521        assert_eq!(d.caret, 0, "asking must not move the caret");
13522        assert_eq!(d.footnote_at(2), None, "offset 2 is prose");
13523    }
13524
13525    #[test]
13526    fn footnote_definition_at_caret_points_back_at_the_reference() {
13527        // The return leg. `[^1]` spans 7..11, so its label — the only byte of it
13528        // the caret can rest on — is at 9.
13529        let mut d = doc_with("fn_def", "A claim[^1] and more.\n\n[^1]: the note\n");
13530        d.caret = 30; // inside the note's body
13531        let f = d
13532            .footnote_definition_at_caret()
13533            .expect("the caret stands in a definition");
13534        assert_eq!(f.label, "1");
13535        assert_eq!(f.offset, Some(9));
13536        assert_eq!(&d.source[7..11], "[^1]");
13537    }
13538
13539    #[test]
13540    fn footnote_definition_at_covers_where_a_go_to_note_actually_lands() {
13541        // The two legs have to meet: wherever `footnote_at` sends the caret, the
13542        // definition query must answer for — otherwise arriving at a note leaves
13543        // the reader somewhere the way back isn't offered.
13544        let src = "A claim[^1] and more.\n\n[^1]: the note\n";
13545        let mut d = doc_with("fn_def_marker", src);
13546        let landed = d.footnote_at(9).unwrap().offset.unwrap();
13547        assert_eq!(
13548            d.footnote_definition_at(landed).and_then(|f| f.offset),
13549            Some(9),
13550            "the note a reference sends you to offers the way back"
13551        );
13552    }
13553
13554    #[test]
13555    fn footnote_definition_at_caret_ignores_prose_and_the_reference_itself() {
13556        // The two queries answer for disjoint places, which is what lets one
13557        // gesture mean "down to the note" in one and "back up" in the other
13558        // without either having to remember which way the reader is going.
13559        let mut d = doc_with("fn_def_none", "A claim[^1] and more.\n\n[^1]: the note\n");
13560        d.caret = 2; // prose
13561        assert_eq!(d.footnote_definition_at_caret(), None);
13562        d.caret = 9; // the reference
13563        assert_eq!(d.footnote_definition_at_caret(), None);
13564        assert!(
13565            d.footnote_at_caret().is_some(),
13566            "which is the reference's own query"
13567        );
13568    }
13569
13570    #[test]
13571    fn footnote_definition_at_caret_reports_an_orphan_note_rather_than_nothing() {
13572        // Nothing cites `[^2]`. Answering `None` would say "you are not in a
13573        // note", which is false and leaves a frontend unable to explain why the
13574        // way back is missing.
13575        let src = "A claim[^1].\n\n[^1]: cited\n\n[^2]: orphan\n";
13576        let mut d = doc_with("fn_def_orphan", src);
13577        d.caret = src.find("orphan").unwrap();
13578        let f = d
13579            .footnote_definition_at_caret()
13580            .expect("an orphan is still a definition");
13581        assert_eq!(f.label, "2");
13582        assert_eq!(f.offset, None);
13583    }
13584
13585    #[test]
13586    fn footnote_definition_at_caret_returns_to_the_first_of_repeated_references() {
13587        // One label, cited twice. The first is where the reader most likely came
13588        // from, and the only answer that doesn't depend on how they got here.
13589        let src = "One[^a] and two[^a].\n\n[^a]: the note\n";
13590        let mut d = doc_with("fn_def_repeat", src);
13591        d.caret = src.find("the note").unwrap();
13592        let f = d.footnote_definition_at_caret().expect("a definition");
13593        assert_eq!(
13594            f.offset,
13595            Some(5),
13596            "the first `[^a]`'s label, not the second's"
13597        );
13598        assert_eq!(&src[3..7], "[^a]");
13599    }
13600
13601    #[test]
13602    fn footnote_navigation_is_a_round_trip_through_placed_carets() {
13603        // Down and back up, each leg found from the document rather than from a
13604        // memory of the other — so it still works for a reader who scrolled to
13605        // the notes instead of jumping there.
13606        //
13607        // `place_caret` rather than assigning `caret`, because that is what a
13608        // frontend calls: it snaps to a real caret stop, and a jump that lands
13609        // on a byte the caret can't rest on would arrive somewhere the return
13610        // leg no longer answers for. `build_map` first, since snapping is a
13611        // no-op until the map exists — which is exactly how this went unnoticed
13612        // when the offsets pointed at the `[^` markers.
13613        let mut d = doc_with("fn_round", "A claim[^1] and more.\n\n[^1]: the note\n");
13614        d.build_map(None);
13615        d.place_caret(9, false);
13616        let down = d
13617            .footnote_at_caret()
13618            .expect("a reference")
13619            .offset
13620            .expect("a note");
13621        d.place_caret(down, false);
13622        let up = d
13623            .footnote_definition_at_caret()
13624            .expect("a definition")
13625            .offset
13626            .expect("a reference");
13627        d.place_caret(up, false);
13628        assert_eq!(d.caret, up, "the way back is a stop the caret can occupy");
13629        assert_eq!(
13630            d.footnote_at_caret().expect("back on the reference").label,
13631            "1"
13632        );
13633    }
13634
13635    #[test]
13636    fn insert_link_hands_the_destination_to_twig_raw() {
13637        // Escaping is twig's, and format-specific: Markdown ends a destination
13638        // at the first space and needs the `<…>` form, where djot would read
13639        // those angle brackets as part of the URL.
13640        let mut d = doc_with("link_space", "word\n");
13641        d.anchor = Some(0);
13642        d.caret = 4;
13643        d.insert_link("a b");
13644        assert_eq!(d.source, "[word](<a b>)\n");
13645    }
13646
13647    #[test]
13648    fn insert_link_reports_a_destination_no_format_can_carry() {
13649        let mut d = doc_with("link_bad", "word\n");
13650        d.anchor = Some(0);
13651        d.caret = 4;
13652        d.insert_link("a\nb");
13653        assert_eq!(d.source, "word\n"); // untouched, not quietly rewritten
13654        assert!(
13655            d.status.is_some(),
13656            "InvalidArgument should reach the status line"
13657        );
13658        assert!(!d.dirty);
13659    }
13660
13661    #[test]
13662    fn insert_link_works_in_wysiwyg_view() {
13663        let mut d = wysiwyg_doc("link_wys", "word here\n");
13664        d.anchor = Some(0);
13665        d.caret = 4;
13666        d.insert_link("http://x.dev");
13667        assert_eq!(d.source, "[word](http://x.dev) here\n");
13668        assert_eq!(d.selected_text(), Some("word"));
13669        // The map the caret has to keep riding is rebuilt each frame; motion
13670        // over the fresh one must still land on a real stop (the debug_assert).
13671        d.build_visual(80);
13672        d.move_right(false);
13673        d.move_left(false);
13674    }
13675
13676    #[test]
13677    fn click_maps_a_row_col_to_a_byte_offset() {
13678        let mut d = doc_with("click", "ab\ncd\n");
13679        d.click(1, 1, false); // row 1 ("cd"), col 1 -> the 'd'
13680        assert_eq!(d.caret, 4);
13681    }
13682
13683    // A pixel-hit-test placement (the GUI's `place_caret`) must land on a caret
13684    // stop just as the `(row, col)` click path does, so the caret can never come
13685    // to rest in the blank gap between two paragraphs — where it would draw in one
13686    // place and type in another.
13687    #[test]
13688    fn place_caret_snaps_out_of_the_blank_gap_between_paragraphs() {
13689        // "A\n\nB": offset 2 is the gap the paragraph break is drawn with, not a
13690        // caret stop (stops are 0,1,3,4).
13691        let mut d = wysiwyg_doc("place_gap", "A\n\nB");
13692        assert!(!d.vmap.is_stop(2), "offset 2 should be an unreachable gap");
13693        d.place_caret(2, false);
13694        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13695        assert_eq!(d.caret, 1, "should snap to the end of the paragraph above");
13696    }
13697
13698    #[test]
13699    fn place_caret_dragging_through_the_gap_keeps_selection_on_stops() {
13700        let mut d = wysiwyg_doc("place_gap_drag", "A\n\nB");
13701        d.place_caret(0, false); // anchor at the start of "A"
13702        d.place_caret(2, true); // drag into the gap
13703        assert!(d.vmap.is_stop(d.caret), "caret {} is not a stop", d.caret);
13704        let (s, e) = d.selection().expect("a selection");
13705        assert!(
13706            d.vmap.is_stop(s) && d.vmap.is_stop(e),
13707            "selection {s}..{e} off a stop"
13708        );
13709    }
13710
13711    #[test]
13712    fn place_caret_on_a_real_stop_is_left_untouched() {
13713        let mut d = wysiwyg_doc("place_stop", "A\n\nB");
13714        d.place_caret(3, false); // the start of "B" — a genuine stop
13715        assert_eq!(d.caret, 3);
13716    }
13717
13718    // An *empty paragraph* (two blank lines, an intentional blank line the user
13719    // opened) is a real caret stop, unlike the gap — a click into it must stay.
13720    #[test]
13721    fn place_caret_rests_in_an_empty_paragraph() {
13722        let mut d = wysiwyg_doc("place_empty_para", "A\n\n\n\nB");
13723        let empty = 3; // the navigable empty row's offset (stops: 0,1,3,5,6)
13724        assert!(d.vmap.is_stop(empty));
13725        d.place_caret(empty, false);
13726        assert_eq!(d.caret, empty);
13727    }
13728
13729    // The content end of a hidden mark is a home too (`VisualMap::mark_ends`):
13730    // a drag over the word `bold` ends there, and a caret placed there stays.
13731    #[test]
13732    fn place_caret_rests_at_the_end_of_a_hidden_marks_content() {
13733        let src = "| A | B |\n| --- | --- |\n| **bold** | other |\n";
13734        let mut d = wysiwyg_doc("place_mark_end", src);
13735        let start = src.find("bold").unwrap();
13736        d.place_caret(start, false);
13737        d.place_caret(start + 4, true);
13738        assert_eq!(d.selection(), Some((start, start + 4)), "the whole word");
13739        d.toggle(InlineKind::Strong);
13740        assert_eq!(d.source, src.replace("**bold**", "bold"));
13741    }
13742
13743    #[test]
13744    fn right_steps_onto_the_end_of_a_mark_and_then_past_its_delimiter() {
13745        let mut d = wysiwyg_doc("right_mark_end", "a **bold** b");
13746        d.caret = 7; // before the `d`
13747        d.move_right(false);
13748        assert_eq!(d.caret, 8, "onto the end of the bold");
13749        assert!(d.active_inline_marks().contains(InlineKind::Strong));
13750        d.move_right(false);
13751        assert_eq!(d.caret, 10, "past the closing `**`");
13752        assert!(!d.active_inline_marks().contains(InlineKind::Strong));
13753        d.move_left(false);
13754        assert_eq!(d.caret, 8);
13755        d.move_left(false);
13756        assert_eq!(d.caret, 7);
13757        // Typing at the inner home extends the bold.
13758        d.caret = 8;
13759        d.insert("!");
13760        assert_eq!(d.source, "a **bold!** b");
13761    }
13762
13763    #[test]
13764    fn a_marks_end_home_follows_an_edit_through_the_incremental_map() {
13765        // The splice path shifts the home with the block it is in, and the
13766        // re-rendered block finds its own again.
13767        let mut d = wysiwyg_doc("mark_end_splice", "x\n\na **bold** b\n\ny\n");
13768        d.build_visual_unwrapped();
13769        d.edit(0, 0, "zz");
13770        d.build_visual_unwrapped();
13771        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a shift");
13772        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13773        let at = d.source.find("bold").unwrap();
13774        d.edit(at, at, "very ");
13775        d.build_visual_unwrapped();
13776        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after a re-render");
13777        assert!(d.vmap.is_stop(d.source.find("bold").unwrap() + 4));
13778    }
13779
13780    fn wysiwyg_doc(name: &str, body: &str) -> Doc {
13781        doc_in(View::Wysiwyg, name, body)
13782    }
13783
13784    /// How many list items the source actually parses into — the check that a
13785    /// marker Leaf wrote is a marker the format agrees is one.
13786    fn list_items(doc: &mut Doc) -> usize {
13787        doc.editor
13788            .nodes()
13789            .unwrap()
13790            .iter()
13791            .filter(|n| n.kind == Kind::ListItem || n.kind == Kind::TaskListItem)
13792            .count()
13793    }
13794
13795    /// A from-scratch, cache-free WYSIWYG map for `source` — the ground truth the
13796    /// incremental (`build_spliced` / `build_cached`) path must always match.
13797    fn reference_map(source: &str) -> crate::wysiwyg::VisualMap {
13798        reference_map_revealing(source, None)
13799    }
13800
13801    /// [`reference_map`] with a reveal line — the ground truth for the
13802    /// `MarkupMode::Full` builds, where the map is a function of the caret's
13803    /// line as well as the text.
13804    fn reference_map_revealing(source: &str, reveal: Option<Reveal>) -> crate::wysiwyg::VisualMap {
13805        // The same parse `Doc` uses. With twig's plain defaults instead, the two
13806        // sides disagree on what the *document* is before the renderer is even
13807        // reached — a bare `:word` is a text directive to one and prose to the
13808        // other — and the mismatch reads as a splice bug that isn't one.
13809        let mut ed =
13810            twig::Editor::new_ext(source.as_bytes(), Format::Markdown, parse_extensions()).unwrap();
13811        let nodes = ed.nodes().unwrap();
13812        crate::wysiwyg::build(
13813            &nodes,
13814            source,
13815            None,
13816            false,
13817            &wysiwyg::Surface::default(),
13818            reveal,
13819        )
13820    }
13821
13822    fn maps_differ(a: &crate::wysiwyg::VisualMap, b: &crate::wysiwyg::VisualMap) -> bool {
13823        if a.rows.len() != b.rows.len() {
13824            return true;
13825        }
13826        for (ra, rb) in a.rows.iter().zip(&b.rows) {
13827            if ra.end_src != rb.end_src || ra.glyphs.len() != rb.glyphs.len() {
13828                return true;
13829            }
13830            for (ga, gb) in ra.glyphs.iter().zip(&rb.glyphs) {
13831                if ga.ch != gb.ch || ga.src != gb.src {
13832                    return true;
13833                }
13834            }
13835        }
13836        false
13837    }
13838
13839    #[test]
13840    fn incremental_build_matches_a_fresh_build_across_edits() {
13841        // Every `Doc` edit rebuilds through `build_spliced` (the single-block
13842        // fast path, gated on twig's `dirty_range`) or falls back to
13843        // `build_cached`. After each edit the map must be byte-identical to a
13844        // from-scratch build — this is the correctness net under the splice.
13845        let docs = [
13846            "# Title\n\nThe quick brown fox jumps.\n\nAnother paragraph here.\n\n- a\n- b\n",
13847            "para one\n\n> quote **bold** text\n> continued line\n\ntail paragraph\n",
13848            "alpha\n\nbeta\n\ngamma\n\ndelta\n\nepsilon\n\nzeta\n",
13849            // A footnote definition is a root beside `doc`, merged back into the
13850            // top-level list by `wysiwyg::top_blocks`. The random edits below
13851            // make and unmake definitions as they go (a deleted `:` turns one
13852            // back into a paragraph, and vice versa), which is exactly the
13853            // structural churn the splice path has to notice and bail out of.
13854            "text[^1] here\n\n[^1]: the note\n\nmore text[^b]\n\n[^b]: second\n",
13855            // A comment is a top-level block that draws no rows — a layout entry
13856            // at zero rows either side of blocks that do. The edits below type
13857            // into the blocks around it (a splice past a hidden block), and
13858            // break the comment open into prose and back (a structural change).
13859            "intro\n\n<!-- exec -->\n```\ncode\n```\n\nafter the comment\n\n<!-- trail -->\n",
13860            // Link reference definitions: a hidden block that an edit can turn
13861            // into a paragraph (a deleted `:`) and back, and whose own bytes an
13862            // edit can land in.
13863            "see [a] and [b]\n\n[a]: /a\n\nmid text\n\n[b]: /b\n",
13864            // Blank lines above the first block draw as rows, counted as its
13865            // separator; above it past frontmatter and past a comment too.
13866            "\n\nfirst pushed down\n\nsecond\n",
13867            "---\ntitle: x\n---\n\n\nafter frontmatter\n\nmore\n",
13868            "<!-- lead -->\n\n\nafter a comment\n\nmore\n",
13869            // No `<div>` here yet: an edit that takes the blank line under
13870            // `</div>` leaves a map no fresh build draws. See
13871            // docs/tasks/text-glued-under-a-closing-div.md.
13872        ];
13873        // A deterministic mix: mostly single characters (which stay inside one
13874        // block → splice), plus edits that reshape structure (a paragraph break,
13875        // a heading marker, a code fence → fallback), so both paths are exercised.
13876        let inserts = ["x", "y", "\n\n", "#", "`", " ", "z"];
13877        for src in docs {
13878            let mut d = wysiwyg_doc("diff", src);
13879            d.build_visual_unwrapped();
13880            wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "initial");
13881
13882            for step in 0..60usize {
13883                let len = d.source.len();
13884                let raw = (step * 13 + 5) % (len + 1);
13885                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
13886                let pre = d.source.clone();
13887                let action;
13888                if step % 3 == 0 && pos < len {
13889                    let end = (pos + 1..=len)
13890                        .find(|&i| d.source.is_char_boundary(i))
13891                        .unwrap();
13892                    action = format!("delete [{pos},{end})");
13893                    d.edit(pos, end, "");
13894                } else {
13895                    let ins = inserts[step % inserts.len()];
13896                    action = format!("insert {ins:?} @ {pos}");
13897                    d.edit(pos, pos, ins);
13898                }
13899                d.build_visual_unwrapped();
13900                if maps_differ(&d.vmap, &reference_map(&d.source)) {
13901                    panic!(
13902                        "FIRST MISMATCH at step {step}: {action}\n  pre  = {pre:?}\n  post = {:?}",
13903                        d.source
13904                    );
13905                }
13906            }
13907        }
13908    }
13909
13910    /// A frontend is handed [`Doc::vmap`] and may present it differently:
13911    /// leaf-ratatui splices blank filler rows under an oversized heading so the
13912    /// raster it paints there has somewhere to stand, and leaves them in the map
13913    /// because the caret and the mouse both read it between frames. The splice
13914    /// path addresses that map by *row index*, against the block layout the last
13915    /// build recorded — so handed a map with rows in it that no block owns, it
13916    /// laid the re-rendered block over one of the fillers and carried the rows
13917    /// the block really occupied into the suffix. One stranded copy of the
13918    /// edited line, and everything below it a row further down, per keystroke.
13919    ///
13920    /// A map that isn't the one the layout describes is a map this path can't
13921    /// patch, whoever changed it and for whatever reason. It rebuilds instead.
13922    #[test]
13923    fn an_edit_over_a_map_a_frontend_reshaped_rebuilds_it_whole() {
13924        let mut d = wysiwyg_doc("reshaped", "# Title\n\nThe quick brown fox jumps.\n");
13925        d.build_visual_unwrapped();
13926
13927        // Stand in for the heading filler rows: two blank rows past the heading
13928        // that no block accounts for. Cloning a real row keeps every field
13929        // plausible — it is the row *count* the splice can't survive.
13930        let filler = d.vmap.rows[0].clone();
13931        d.vmap.rows.insert(1, filler.clone());
13932        d.vmap.rows.insert(1, filler);
13933
13934        // An edit inside the last block: the single-block case the splice path
13935        // is for, and the one the frontend hits on every keystroke.
13936        let at = d.source.len() - 1;
13937        d.edit(at, at, "!");
13938        d.build_visual_unwrapped();
13939
13940        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the edit");
13941    }
13942
13943    /// A glyph's [`FaceId`] has to mean the same thing however its row was
13944    /// built. A row comes three ways — a fresh walk, a [`BlockCache`] hit
13945    /// cloned at a shifted offset, and a previous map's rows a splice kept
13946    /// untouched — and only the first of those walks a `data-font` at all. An
13947    /// index into a per-build table would have had the same glyph naming two
13948    /// families the moment a second one appeared; the id is the name's own
13949    /// hash, so nothing is remapped and the table is merged rather than rebuilt.
13950    ///
13951    /// Two families, because one cannot tell a wrong id from a right one.
13952    ///
13953    /// [`FaceId`]: crate::style::FaceId
13954    /// [`BlockCache`]: crate::wysiwyg::BlockCache
13955    #[test]
13956    fn a_spliced_rebuild_still_says_which_family_each_glyph_is_set_in() {
13957        use crate::style::{FaceId, FaceRef};
13958        let garamond = FaceId::of("Garamond");
13959        let futura = FaceId::of("Futura");
13960        let mut d = wysiwyg_doc(
13961            "two_faces",
13962            "x <span data-font=\"Garamond\">alpha</span>\n\ny <span data-font=\"Futura\">beta</span>\n",
13963        );
13964        d.build_visual_unwrapped();
13965
13966        // What the map has to keep saying, whichever path built it.
13967        let check = |d: &Doc, ctx: &str| {
13968            let face_of = |ch: char| {
13969                d.vmap
13970                    .rows
13971                    .iter()
13972                    .flat_map(|r| r.glyphs.iter())
13973                    .find(|g| g.ch == ch)
13974                    .map(|g| g.style.font)
13975            };
13976            assert_eq!(face_of('a'), Some(Some(FaceRef::Named(garamond))), "{ctx}");
13977            assert_eq!(face_of('b'), Some(Some(FaceRef::Named(futura))), "{ctx}");
13978            assert_eq!(d.vmap.face_name(garamond), Some("Garamond"), "{ctx}");
13979            assert_eq!(d.vmap.face_name(futura), Some("Futura"), "{ctx}");
13980            assert_eq!(d.vmap.face_name(FaceId::of("Bodoni")), None, "{ctx}");
13981        };
13982        check(&d, "fresh");
13983
13984        // An edit inside the second block: the single-block case the splice
13985        // path is for. The first block's rows are carried over untouched, so
13986        // its glyphs' ids are the previous build's and the table has to be too.
13987        let at = d.source.find("beta").unwrap();
13988        d.edit(at, at, "z");
13989        d.build_visual_unwrapped();
13990        check(&d, "after an edit in the second block");
13991        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced");
13992
13993        // And the other way round, so the block that was kept is the one that
13994        // is now re-rendered.
13995        let at = d.source.find("alpha").unwrap();
13996        d.edit(at, at, "z");
13997        d.build_visual_unwrapped();
13998        check(&d, "after an edit in the first block");
13999        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "spliced again");
14000
14001        // A structural edit is one the splice bails out of, so the map is
14002        // reassembled by `build_cached` — where an untouched block is a *cache
14003        // hit* and its rows are cloned without a `data-font` being walked
14004        // again. The names the entry stored are what keeps the table honest
14005        // there.
14006        let at = d.source.find("\n\ny ").unwrap();
14007        d.edit(at, at, "\n\nmiddle");
14008        d.build_visual_unwrapped();
14009        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached");
14010        // Twice, because that first `build_cached` is what stores the entries:
14011        // this one is the build where the Garamond block is a *hit*, its rows
14012        // cloned with their ids and no attribute walked to explain them.
14013        let at = d.source.len() - 1;
14014        d.edit(at, at, "\n\ntail");
14015        d.build_visual_unwrapped();
14016        check(&d, "after a structural edit, through the block cache");
14017        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "cached again");
14018
14019        // A family the edit took the last glyph of leaves the glyphs with no
14020        // face and the table with a name nothing asks for — harmless, and the
14021        // price of not walking the rows the splice exists to avoid walking.
14022        let span = d.source.find("<span data-font=\"Futura\">").unwrap();
14023        let end = d.source.rfind("</span>").unwrap() + "</span>".len();
14024        d.edit(span, end, "beta");
14025        d.build_visual_unwrapped();
14026        assert!(!d.source.contains("Futura"), "{:?}", d.source);
14027        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "the face removed");
14028    }
14029
14030    #[test]
14031    fn incremental_build_matches_a_fresh_build_under_full_reveal() {
14032        // The same correctness net as `incremental_build_matches_a_fresh_build_
14033        // across_edits`, under `MarkupMode::Full` — where the map depends on
14034        // the caret's *line* as well as the text, so the two caches have a new
14035        // way to be wrong. Both are exercised: the block cache can hand back
14036        // rows built for a line that is no longer the revealed one, and the
14037        // splice path can reuse a suffix that still has yesterday's line raw.
14038        //
14039        // Caret motion is interleaved with the edits deliberately, because a
14040        // caret that only ever moved with the edit would never cross a line
14041        // without also dirtying it — the case where a stale reveal survives.
14042        let docs = [
14043            "# Title\n\n*one* and **two**\n\n[lk](http://x) and `code`\n\n- a *b*\n",
14044            "para *em* one\n\n> quote **bold** text\n\ntail ~~del~~ paragraph\n",
14045        ];
14046        let inserts = ["x", "*", "\n\n", "#", "`", " ", "_"];
14047        for src in docs {
14048            let mut d = wysiwyg_doc("reveal_diff", src);
14049            d.set_markup_mode(MarkupMode::Full);
14050
14051            for step in 0..60usize {
14052                let len = d.source.len();
14053                let raw = (step * 13 + 5) % (len + 1);
14054                let pos = (raw..=len).find(|&i| d.source.is_char_boundary(i)).unwrap();
14055                let pre = d.source.clone();
14056                let action;
14057                if step % 3 == 0 && pos < len {
14058                    let end = (pos + 1..=len)
14059                        .find(|&i| d.source.is_char_boundary(i))
14060                        .unwrap();
14061                    action = format!("delete [{pos},{end})");
14062                    d.edit(pos, end, "");
14063                } else {
14064                    let ins = inserts[step % inserts.len()];
14065                    action = format!("insert {ins:?} @ {pos}");
14066                    d.edit(pos, pos, ins);
14067                }
14068                // Walk the caret somewhere else in the document, independently
14069                // of where the edit landed.
14070                let want = (step * 29 + 11) % (d.source.len() + 1);
14071                d.caret = (want..=d.source.len())
14072                    .find(|&i| d.source.is_char_boundary(i))
14073                    .unwrap();
14074                d.build_visual_unwrapped();
14075
14076                let want = reference_map_revealing(&d.source, d.reveal_line());
14077                if maps_differ(&d.vmap, &want) {
14078                    panic!(
14079                        "FIRST MISMATCH at step {step}: {action}, caret {}\n  pre  = {pre:?}\n  post = {:?}",
14080                        d.caret, d.source
14081                    );
14082                }
14083            }
14084        }
14085    }
14086
14087    #[test]
14088    fn caret_motion_across_lines_rebuilds_only_under_full() {
14089        // The cache-key change has to earn its keep in both directions: `Full`
14090        // must rebuild when the caret changes line (or the reveal would never
14091        // move), and the hidden modes must *not* (or every arrow key would pay
14092        // for a feature they don't use). The existing `cache_motion` test pins
14093        // the second for the default mode; this pins the pair against a mode
14094        // change alone.
14095        let body = "*one* here\n\n*two* there\n";
14096
14097        let mut full = doc_in(View::Wysiwyg, "motion_full", body);
14098        full.set_markup_mode(MarkupMode::Full);
14099        caret_at(&mut full, "one");
14100        let before = full.revision();
14101        caret_at(&mut full, "two");
14102        assert_eq!(full.revision(), before, "motion is not an edit");
14103        assert!(
14104            drawn_rows(&full).iter().any(|r| r == "*two* there"),
14105            "the map followed the caret: {:?}",
14106            drawn_rows(&full)
14107        );
14108
14109        let mut hidden = doc_in(View::Wysiwyg, "motion_hidden", body);
14110        caret_at(&mut hidden, "one");
14111        let key = hidden.vmap_key.clone();
14112        caret_at(&mut hidden, "two");
14113        assert_eq!(
14114            hidden.vmap_key, key,
14115            "a hidden mode rebuilds nothing on motion"
14116        );
14117    }
14118
14119    #[test]
14120    fn wysiwyg_down_crosses_a_paragraph_boundary() {
14121        // Regression: the blank separator row used to share the previous
14122        // paragraph's end offset, so Down got pinned at the boundary (while Up
14123        // still crossed). Both directions must step through it symmetrically.
14124        //
14125        // It's now stepped *over* rather than onto: the blank line between two
14126        // paragraphs is the boundary being drawn, not a line of the document, so
14127        // one press of Down crosses it. The goal column survives the crossing —
14128        // col 3 at the end of "abc" is col 3 at the end of "def".
14129        let mut d = wysiwyg_doc("wys_down", "abc\n\ndef\n");
14130        d.caret = 3; // end of "abc" (row 0)
14131        d.move_down(false);
14132        assert_eq!(d.caret_pos().0, 2, "Down should reach the second paragraph");
14133        assert_eq!(d.caret, 8); // end of "def", col 3 kept
14134        d.move_up(false);
14135        assert_eq!(d.caret_pos().0, 0, "Up should come back symmetrically");
14136        assert_eq!(d.caret, 3);
14137    }
14138
14139    #[test]
14140    fn wysiwyg_up_and_down_are_inverse_across_paragraphs() {
14141        // The second Up and the second Down here run off the ends of the
14142        // document, which is no longer a place a press is swallowed: they carry
14143        // the caret to the start and the end of the text. The claim in the
14144        // middle — that a Down retraces the Up that crossed the paragraph gap —
14145        // is the one this test is for, and it is asserted where it is made.
14146        let mut d = wysiwyg_doc("wys_updown", "abc\n\ndef\n");
14147        d.caret = 5; // start of "def"
14148        let start = d.caret_pos();
14149        d.move_up(false);
14150        assert_eq!(d.caret_pos().0, 0, "Up reaches the first paragraph");
14151        d.move_up(false);
14152        assert_eq!(d.caret, 0, "a second Up runs on to the document's start");
14153        d.move_down(false);
14154        assert_eq!(d.caret_pos(), start, "Down retraces Up exactly");
14155        d.move_down(false);
14156        assert_eq!(d.caret, 8, "a second Down runs on to the document's end");
14157    }
14158
14159    #[test]
14160    fn wysiwyg_new_paragraph_shows_before_typing() {
14161        // Regression: two Enters at the end of a paragraph produced trailing
14162        // newlines with no AST node, so the caret appeared stuck on the old line
14163        // until a character was typed. It must ride down onto the new line now.
14164        let mut d = doc_with("wys_newpara", "abc\n");
14165        d.view = View::Wysiwyg;
14166        d.caret = 3;
14167        d.insert("\n");
14168        d.insert("\n"); // source is now "abc\n\n\n", caret at 5
14169        assert_eq!(d.source, "abc\n\n\n");
14170        d.build_visual(80);
14171        let (row, _) = d.caret_pos();
14172        assert!(
14173            row >= 2,
14174            "caret should have moved down to the new line, got row {row}"
14175        );
14176        assert!(
14177            d.vmap.num_rows() >= 3,
14178            "the blank lines should render as rows"
14179        );
14180    }
14181
14182    #[test]
14183    fn wysiwyg_enter_between_paragraphs_lands_on_an_empty_line() {
14184        // The reported bug: Enter at the end of a paragraph that has another
14185        // paragraph below put the caret at the *start of the next paragraph* —
14186        // the empty paragraph it opened had no row, so the caret snapped onto
14187        // "World". It must now sit on its own empty line, with a blank spacer
14188        // above it (the paragraph gap).
14189        let mut d = wysiwyg_doc("wys_gap_mid", "Hello\n\nWorld\n");
14190        d.caret = 5; // end of "Hello"
14191        d.newline();
14192        d.build_visual(80);
14193        let (row, col) = d.caret_pos();
14194        assert_eq!(col, 0, "caret should start an empty line, not sit in text");
14195        assert_eq!(
14196            d.vmap.row_width(row),
14197            0,
14198            "caret's row must be empty, not 'World'"
14199        );
14200        assert!(
14201            row >= 2,
14202            "a blank spacer row should sit above the caret, got row {row}"
14203        );
14204        // The row above the caret is a real (empty) gap, and "Hello" stays put.
14205        assert_eq!(
14206            d.vmap.row_width(row - 1),
14207            0,
14208            "the row above the caret is a gap"
14209        );
14210        let row0: String = d.vmap.rows[0].glyphs.iter().map(|g| g.ch).collect();
14211        assert_eq!(row0, "Hello", "the paragraph above the caret must not move");
14212    }
14213
14214    #[test]
14215    fn wysiwyg_enter_at_eof_shows_a_gap_before_typing() {
14216        // At the document end a single Enter must also show the paragraph gap —
14217        // a blank spacer row above the caret — so the layout already matches how
14218        // it will look once the new paragraph has text.
14219        let mut d = wysiwyg_doc("wys_gap_eof", "Hello");
14220        d.caret = 5; // end of "Hello", no trailing newline
14221        d.newline(); // source becomes "Hello\n\n"
14222        d.build_visual(80);
14223        let (row, col) = d.caret_pos();
14224        assert_eq!(col, 0);
14225        assert!(
14226            row >= 2,
14227            "caret should sit below a blank spacer, got row {row}"
14228        );
14229        assert_eq!(
14230            d.vmap.row_width(row - 1),
14231            0,
14232            "the row above the caret is a gap"
14233        );
14234    }
14235
14236    #[test]
14237    fn wysiwyg_typing_after_enter_does_not_shift_the_caret_row() {
14238        // The spacer is view-only: typing the new paragraph must not reflow the
14239        // caret onto a different row — the transient view already matched the
14240        // settled one.
14241        let mut d = wysiwyg_doc("wys_no_reflow", "Hello\n\nWorld\n");
14242        d.caret = 5;
14243        d.newline();
14244        d.build_visual(80);
14245        let before = d.caret_pos();
14246        d.insert("New");
14247        d.build_visual(80);
14248        let after = d.caret_pos();
14249        assert_eq!(
14250            after.0, before.0,
14251            "typing must not move the caret to another row ({before:?} -> {after:?})"
14252        );
14253    }
14254
14255    #[test]
14256    fn wysiwyg_return_on_the_last_code_line_keeps_the_caret_in_the_block() {
14257        // Return at the end of the block's last line writes an empty line the
14258        // map used to drop, so the caret landed on `after` and the next
14259        // keystroke went into the paragraph below instead of into the code.
14260        let mut d = wysiwyg_doc("code_return", "prose\n\n```\nalpha\nbeta\n```\n\nafter\n");
14261        d.caret = d.source.find("beta").unwrap() + "beta".len();
14262        d.build_visual(80);
14263        let before = d.caret_pos().0;
14264
14265        d.newline();
14266        d.build_visual(80);
14267        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\n\n```\n\nafter\n");
14268
14269        let (row, col) = d.caret_pos();
14270        assert_eq!(row, before + 1, "the caret moves down one row");
14271        assert_eq!(col, 0, "onto the head of the empty line");
14272        let span = d.vmap.code_blocks[0].rows_span.clone();
14273        assert!(
14274            span.contains(&row),
14275            "caret row {row} is outside the block's rows {span:?}"
14276        );
14277
14278        // The whole point: what is typed next is code.
14279        d.insert("gamma");
14280        assert_eq!(d.source, "prose\n\n```\nalpha\nbeta\ngamma\n```\n\nafter\n");
14281    }
14282
14283    #[test]
14284    fn wysiwyg_hides_frontmatter_from_the_caret_and_copy() {
14285        let fm = "---\ntitle: hi\n---\n";
14286        let body = format!("{fm}# leaf\n\nbody\n");
14287        let mut d = wysiwyg_doc("wys_fm", &body);
14288        // Opening lifts the caret out of the now-hidden frontmatter.
14289        assert_eq!(
14290            d.caret,
14291            fm.len(),
14292            "caret should start at the first real block"
14293        );
14294        // Left at the content start can't step back into frontmatter.
14295        d.move_left(false);
14296        assert_eq!(d.caret, fm.len(), "left must not enter frontmatter");
14297        // Doc-start lands on the content floor, not offset 0.
14298        d.move_doc_start(false);
14299        assert_eq!(d.caret, fm.len());
14300        // Select-all + copy never include the frontmatter bytes.
14301        d.select_all();
14302        let sel = d.selected_text().unwrap().to_string();
14303        assert!(!sel.contains("title"), "copy leaked frontmatter: {sel:?}");
14304        assert!(
14305            sel.starts_with("# leaf"),
14306            "selection should begin at content: {sel:?}"
14307        );
14308    }
14309
14310    #[test]
14311    fn typing_in_a_frontmatter_only_document_lands_after_the_frontmatter() {
14312        // A fresh note is frontmatter and nothing else. With no rendered block
14313        // to floor the caret it opened at offset 0 — before the opening `---` —
14314        // so the first keystroke wrote itself in front of the metadata and the
14315        // file came out as `This---\ntitle: …`.
14316        let fm = "---\ntitle: 2026-08-29\nid: f8s32cd\n---\n";
14317        let mut d = wysiwyg_doc("wys_fm_only", fm);
14318        assert_eq!(d.caret, fm.len(), "caret must open past the frontmatter");
14319        // Nothing is rendered, so the caret draws at the origin of an empty view
14320        // — the same place an empty document puts it.
14321        assert_eq!(d.caret_pos(), (0, 0));
14322        d.insert("This");
14323        assert_eq!(d.source, format!("{fm}This"));
14324    }
14325
14326    /// `select_range` is the verb for a range a host already knows the bytes of,
14327    /// so it must not snap — and must still hold every invariant `place_caret`
14328    /// holds, the frontmatter floor above all.
14329    #[test]
14330    fn select_range_takes_the_range_as_given_but_still_floors_it() {
14331        let fm = "---\ntitle: foo\n---\n\n";
14332        let body = format!("{fm}body foo here\n");
14333        let mut d = wysiwyg_doc("wys_select_range", &body);
14334
14335        // The `foo` in the body: taken exactly, not snapped to a caret stop.
14336        let at = body.rfind("foo").unwrap();
14337        d.select_range(at, at + 3);
14338        assert_eq!(d.selection(), Some((at, at + 3)));
14339        assert_eq!(d.selected_text(), Some("foo"));
14340
14341        // The `foo` in the hidden frontmatter: below the floor, so both ends
14342        // come up to it rather than parking the caret in the metadata, where a
14343        // later keystroke would rewrite `title:`.
14344        let hidden = body.find("foo").unwrap();
14345        assert!(hidden < d.vmap.content_start);
14346        d.select_range(hidden, hidden + 3);
14347        assert!(
14348            d.caret >= d.vmap.content_start && d.anchor.unwrap() >= d.vmap.content_start,
14349            "a range under the floor must not leave the caret in the frontmatter"
14350        );
14351
14352        // Past the end, and mid-character, are both brought back to something
14353        // sliceable rather than panicking the next reader of the range.
14354        let multi = wysiwyg_doc("wys_select_range_utf8", "héllo\n");
14355        let mut d = multi;
14356        d.select_range(2, 9_999);
14357        assert_eq!(d.caret, d.source.len());
14358        assert!(d.source.is_char_boundary(d.anchor.unwrap()));
14359        assert!(d.source.is_char_boundary(d.caret));
14360    }
14361
14362    /// The bug `select_range` exists for: a match butting up against a hidden
14363    /// delimiter. `place_caret` snaps to the nearest *visible* stop, which is
14364    /// the one before the `**`.
14365    #[test]
14366    fn select_range_does_not_snap_off_a_hidden_delimiter() {
14367        let mut d = wysiwyg_doc("wys_select_range_bold", "a **needle** in it\n");
14368        let at = d.source.find("needle").unwrap();
14369        d.select_range(at, at + 6);
14370        assert_eq!(d.selected_text(), Some("needle"), "not \"needl\"");
14371    }
14372
14373    #[test]
14374    fn wysiwyg_backspace_at_content_start_leaves_frontmatter_intact() {
14375        // Backspace deletes `prev_boundary..caret` directly; at the first real
14376        // block that boundary is inside the hidden frontmatter, so it must be a
14377        // no-op rather than eating the closing `---`.
14378        let fm = "---\ntitle: hi\n---\n";
14379        let body = format!("{fm}leaf\n");
14380        let mut d = wysiwyg_doc("wys_fm_bs", &body);
14381        assert_eq!(d.caret, fm.len());
14382        d.backspace();
14383        assert_eq!(d.source, body, "backspace must not touch frontmatter");
14384        d.delete_word_back();
14385        assert_eq!(
14386            d.source, body,
14387            "word-delete must not touch frontmatter either"
14388        );
14389    }
14390
14391    #[test]
14392    fn wysiwyg_edits_inside_a_vis_directive_block_without_disturbing_its_fences() {
14393        // diaryx's `:::vis{.audience}` visibility block — any `:::name{.class}`
14394        // fenced div, really, since core parses these on for every document
14395        // now (`parse_extensions`). The container is a `directive` node, an
14396        // `is_block_container` kind like `block_quote`, so the caret works
14397        // inside its child paragraph exactly as it would inside a quote: typing
14398        // edits the paragraph, and the `:::vis{...}` / `:::` fences round-trip
14399        // untouched.
14400        let body = ":::vis{.public .family}\nhello\n:::\nafter\n";
14401        let mut d = wysiwyg_doc("wys_vis", body);
14402        d.caret = body.find("hello").unwrap() + "hello".len();
14403        d.insert("!");
14404        assert_eq!(
14405            d.source, ":::vis{.public .family}\nhello!\n:::\nafter\n",
14406            "typing inside the block edits its content in place"
14407        );
14408        assert!(
14409            d.source.contains(":::vis{.public .family}"),
14410            "opening fence survives"
14411        );
14412        assert!(d.source.contains(":::\nafter"), "closing fence survives");
14413    }
14414
14415    #[test]
14416    fn source_view_still_reaches_frontmatter() {
14417        // The metadata is only *hidden*, never lost: the source view edits and
14418        // selects it in full, and it's always preserved on save.
14419        let fm = "---\ntitle: hi\n---\n";
14420        let body = format!("{fm}# leaf\n");
14421        let mut d = doc_with("src_fm", &body);
14422        d.select_all();
14423        let sel = d.selected_text().unwrap();
14424        assert!(
14425            sel.contains("title"),
14426            "source view should select everything"
14427        );
14428        d.move_doc_start(false);
14429        assert_eq!(d.caret, 0, "source view can reach offset 0");
14430    }
14431
14432    const TABLE: &str = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n| Fig | 12 |\n";
14433
14434    #[test]
14435    fn wysiwyg_right_crosses_a_cell_border_without_stalling() {
14436        // The border and padding between two cells all share one source offset,
14437        // so a column-stepping caret would sit on `│` and then stall there
14438        // forever. Right must step: end of "Name" -> start of "Qty".
14439        let mut d = wysiwyg_doc("tbl_right", TABLE);
14440        d.caret = TABLE.find("Name").unwrap() + 4; // just after "Name"
14441        d.move_right(false);
14442        assert_eq!(
14443            d.caret,
14444            TABLE.find("Qty").unwrap(),
14445            "should land in the next cell"
14446        );
14447        let (r, c) = d.caret_pos();
14448        assert_eq!(d.vmap.rows[r].glyphs[c].ch, 'Q');
14449    }
14450
14451    #[test]
14452    fn wysiwyg_left_crosses_back_to_the_previous_cell() {
14453        let mut d = wysiwyg_doc("tbl_left", TABLE);
14454        d.caret = TABLE.find("Qty").unwrap();
14455        d.move_left(false);
14456        assert_eq!(
14457            d.caret,
14458            TABLE.find("Name").unwrap() + 4,
14459            "end of the previous cell"
14460        );
14461    }
14462
14463    #[test]
14464    fn wysiwyg_down_steps_over_a_table_rule() {
14465        // Between the header and the first body row sits a `├───┼───┤` rule.
14466        // It's drawn but holds no caret, so one Down must reach "Pear".
14467        let mut d = wysiwyg_doc("tbl_down", TABLE);
14468        d.caret = TABLE.find("Name").unwrap();
14469        d.move_down(false);
14470        assert_eq!(
14471            d.caret,
14472            TABLE.find("Pear").unwrap(),
14473            "one Down reaches the body row"
14474        );
14475        d.move_down(false);
14476        assert_eq!(d.caret, TABLE.find("Fig").unwrap());
14477    }
14478
14479    #[test]
14480    fn wysiwyg_tab_walks_the_cells_and_shift_tab_walks_back() {
14481        let mut d = wysiwyg_doc("tbl_tab", TABLE);
14482        d.caret = TABLE.find("Name").unwrap();
14483        // A hop lands with the destination cell's whole content selected, the
14484        // caret at its end — so typing replaces the cell like a form field.
14485        assert!(d.cell_hop(true));
14486        assert_eq!(
14487            d.selected_text(),
14488            Some("Qty"),
14489            "the target cell comes up selected"
14490        );
14491        assert_eq!(d.caret, TABLE.find("Qty").unwrap() + "Qty".len());
14492        assert!(d.cell_hop(true), "Tab wraps onto the next row's first cell");
14493        assert_eq!(d.selected_text(), Some("Pear"));
14494        assert!(d.cell_hop(false));
14495        assert_eq!(d.selected_text(), Some("Qty"));
14496    }
14497
14498    #[test]
14499    fn tab_outside_a_table_is_not_a_cell_hop() {
14500        // `cell_hop` reports false so the frontend can indent as usual.
14501        let mut d = wysiwyg_doc("tbl_none", "just a paragraph\n");
14502        d.caret = 4;
14503        assert!(!d.cell_hop(true));
14504        assert_eq!(d.caret, 4, "a refused hop leaves the caret alone");
14505    }
14506
14507    #[test]
14508    fn tab_at_the_last_cell_declines_rather_than_leaving_the_table() {
14509        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14510        d.caret = TABLE.rfind("12").unwrap(); // the final cell
14511        assert!(!d.cell_hop(true), "no cell after the last one");
14512        d.caret = TABLE.find("Name").unwrap();
14513        assert!(!d.cell_hop(false), "no cell before the first one");
14514    }
14515
14516    #[test]
14517    fn wysiwyg_vertical_cell_motion_holds_the_column() {
14518        // Down/Up step to the cell above/below in the *same column*, not back to
14519        // the top-left the way a naive row/col motion over the picture would.
14520        let mut d = wysiwyg_doc("tbl_vert", TABLE);
14521        d.caret = TABLE.find("Qty").unwrap();
14522        // Each vertical hop selects the destination cell, holding the column.
14523        assert!(d.cell_move_vertical(true));
14524        assert_eq!(d.selected_text(), Some("3"), "Down holds column 1");
14525        assert!(d.cell_move_vertical(true));
14526        assert_eq!(d.selected_text(), Some("12"), "Down again, still column 1");
14527        assert!(!d.cell_move_vertical(true), "no row below the last");
14528        assert!(d.cell_move_vertical(false));
14529        assert_eq!(d.selected_text(), Some("3"), "Up holds column 1");
14530        assert!(d.cell_move_vertical(false));
14531        assert_eq!(d.selected_text(), Some("Qty"), "Up onto the header");
14532        assert!(!d.cell_move_vertical(false), "no row above the header");
14533    }
14534
14535    #[test]
14536    fn tab_off_the_last_cell_grows_a_row_and_enters_it() {
14537        let mut d = wysiwyg_doc("tbl_grow", TABLE);
14538        d.caret = TABLE.rfind("12").unwrap();
14539        let rows_before = d.source.matches('\n').count();
14540        assert!(d.cell_tab(true), "acts as a table key");
14541        assert_eq!(
14542            d.source.matches('\n').count(),
14543            rows_before + 1,
14544            "a fresh row was appended"
14545        );
14546        assert!(d.caret_in_table(), "the caret entered the new row");
14547        // The caret sits in the new row's first cell — past the old last cell.
14548        assert!(d.caret > TABLE.rfind("12").unwrap());
14549    }
14550
14551    #[test]
14552    fn return_in_a_table_drops_a_cell_and_grows_a_row_at_the_bottom() {
14553        let mut d = wysiwyg_doc("tbl_ret", TABLE);
14554        d.caret = TABLE.find("Name").unwrap();
14555        assert!(d.cell_return(), "acts as a table key");
14556        assert_eq!(
14557            d.selected_text(),
14558            Some("Pear"),
14559            "Return drops one cell, selecting it"
14560        );
14561        // From the last row, Return appends a row and enters it.
14562        d.caret = TABLE.rfind("Fig").unwrap();
14563        let rows_before = d.source.matches('\n').count();
14564        assert!(d.cell_return());
14565        assert_eq!(d.source.matches('\n').count(), rows_before + 1);
14566        assert!(d.caret_in_table());
14567    }
14568
14569    #[test]
14570    fn return_and_tab_outside_a_table_decline() {
14571        let mut d = wysiwyg_doc("tbl_decline", "just a paragraph\n");
14572        d.caret = 4;
14573        assert!(!d.cell_return(), "no table: the frontend inserts a newline");
14574        assert!(!d.cell_tab(true), "no table: the frontend indents");
14575        assert!(
14576            !d.cell_line_break(),
14577            "no table: the frontend breaks the line"
14578        );
14579    }
14580
14581    #[test]
14582    fn a_click_under_a_trailing_table_lands_past_it_and_enter_opens_a_line() {
14583        // A document that ends in a table used to end *inside* it: nothing
14584        // past the last cell was a caret stop, so a click in the blank space
14585        // under the grid snapped back into the table and there was no way to
14586        // write a line after it. The bottom border's end is that stop now.
14587        let mut d = wysiwyg_doc("tbl_trail", TABLE);
14588        let rows = d.vmap.num_rows();
14589        d.click(rows + 3, 0, false);
14590        let end = TABLE.trim_end_matches('\n').len();
14591        assert_eq!(d.caret, end, "the caret stands just past the table");
14592        assert!(!d.caret_in_table(), "past the table is outside it");
14593        assert!(!d.cell_return(), "Return there is the frontend's newline");
14594        d.newline();
14595        d.insert("after");
14596        assert_eq!(
14597            d.source,
14598            format!("{TABLE}\nafter\n"),
14599            "Enter opens a paragraph under the table"
14600        );
14601    }
14602
14603    #[test]
14604    fn typing_at_a_table_s_trailing_stop_opens_a_paragraph_first() {
14605        // The stop sits at the end of the table's last source line, and a
14606        // line glued under a table is a row of it — `| Fig | 12 |x` would be a
14607        // three-cell row. So the text gets a paragraph of its own, as it does
14608        // beside a block picture.
14609        let mut d = wysiwyg_doc("tbl_type", TABLE);
14610        d.caret = TABLE.trim_end_matches('\n').len();
14611        d.insert("x");
14612        assert_eq!(d.source, format!("{TABLE}\nx\n"));
14613        assert_eq!(d.caret, TABLE.len() + 2, "the caret follows the text");
14614        // And a paste, which joins the block exactly as typing would.
14615        let mut d = wysiwyg_doc("tbl_paste", TABLE);
14616        d.caret = TABLE.trim_end_matches('\n').len();
14617        d.paste("pasted");
14618        assert_eq!(d.source, format!("{TABLE}\npasted\n"));
14619    }
14620
14621    #[test]
14622    fn right_leaves_a_table_by_its_trailing_stop_and_backspace_steps_back_in() {
14623        let mut d = wysiwyg_doc("tbl_edge", TABLE);
14624        let last_cell_end = TABLE.rfind("12").unwrap() + 2;
14625        let end = TABLE.trim_end_matches('\n').len();
14626        d.caret = last_cell_end;
14627        d.move_right(false);
14628        assert_eq!(d.caret, end, "Right from the last cell leaves the table");
14629        // Backspace there takes no byte: the one behind the caret is the row's
14630        // closing `|`, which the rich view never drew. It steps back instead.
14631        d.backspace();
14632        assert_eq!(d.source, TABLE, "nothing deleted");
14633        assert_eq!(d.caret, last_cell_end, "back into the last cell");
14634        // Down from the last row lands on the same stop, and Up returns.
14635        d.move_down(false);
14636        assert_eq!(d.caret, end, "Down from the last row leaves the table");
14637        d.move_up(false);
14638        assert_eq!(d.caret, last_cell_end);
14639    }
14640
14641    #[test]
14642    fn a_table_s_trailing_stop_sits_between_it_and_the_text_below() {
14643        // With prose under the table, the stop is one hop between the last
14644        // cell and the paragraph — the shape a block picture's second stop has.
14645        let src = format!("{TABLE}\nafter\n");
14646        let mut d = wysiwyg_doc("tbl_mid", &src);
14647        d.caret = TABLE.rfind("12").unwrap() + 2;
14648        d.move_right(false);
14649        assert_eq!(d.caret, TABLE.trim_end_matches('\n').len());
14650        d.move_right(false);
14651        assert_eq!(d.caret, src.find("after").unwrap());
14652        // Typing at the stop still opens a paragraph, and the text below keeps
14653        // its own.
14654        d.move_left(false);
14655        d.insert("x");
14656        assert_eq!(d.source, format!("{TABLE}\nx\n\nafter\n"));
14657    }
14658
14659    #[test]
14660    fn shift_return_inserts_an_in_cell_break_the_renderer_reads_as_a_line() {
14661        let mut d = wysiwyg_doc("tbl_break", TABLE);
14662        d.caret = TABLE.find("Pear").unwrap() + 4; // just after "Pear"
14663        assert!(d.cell_line_break(), "acts as a table key");
14664        assert!(
14665            d.source.contains("Pear<br>"),
14666            "spelled as an inline <br>: {}",
14667            d.source
14668        );
14669        assert!(d.caret_in_table(), "still in the cell, past the break");
14670        // The break renders as a real line: the "Pear" cell now draws two lines,
14671        // so the table's picture is one row taller than a single-line table.
14672        d.build_visual(80);
14673        let table = &d.vmap.tables[0];
14674        let cell = &table.grid[1].cells[0]; // first body row, first column
14675        assert!(
14676            cell.glyphs.iter().any(|g| g.ch == '\n'),
14677            "the cell carries the break as a newline glyph for the frontend to split"
14678        );
14679    }
14680
14681    #[test]
14682    fn shift_return_in_a_markdown_cell_leaves_a_semantic_hard_break_not_raw_html() {
14683        // twig promotes the in-cell `<br>` to a `hard_break`, so the break reads
14684        // back as structure — the whole point of routing through insert_line_break
14685        // instead of splicing raw `<br>` bytes.
14686        let mut d = wysiwyg_doc("tbl_break_semantic", TABLE);
14687        d.caret = TABLE.find("Pear").unwrap() + 4;
14688        assert!(d.cell_line_break());
14689        let kinds: Vec<Kind> = d
14690            .editor
14691            .nodes()
14692            .unwrap()
14693            .iter()
14694            .map(|n| n.kind.clone())
14695            .collect();
14696        assert!(kinds.contains(&Kind::HardBreak), "got {kinds:?}");
14697        assert!(
14698            !kinds.contains(&Kind::RawInline),
14699            "still raw HTML: {kinds:?}"
14700        );
14701    }
14702
14703    #[test]
14704    fn backspace_over_an_in_cell_break_deletes_the_whole_br_not_a_byte() {
14705        // The `<br>` draws as one newline glyph, so Backspace over it must take
14706        // all four bytes — a one-byte delete would strand a visible `<br` in the
14707        // cell (the reported bug).
14708        let mut d = wysiwyg_doc("tbl_break_bs", TABLE);
14709        d.caret = TABLE.find("Pear").unwrap() + 4;
14710        assert!(d.cell_line_break());
14711        assert!(d.source.contains("Pear<br>"), "precondition: {}", d.source);
14712        d.backspace(); // caret sits just past the break
14713        assert!(
14714            !d.source.contains("<br"),
14715            "no half-deleted <br left: {}",
14716            d.source
14717        );
14718        assert!(
14719            d.source.contains("| Pear |"),
14720            "the cell is back to one line: {}",
14721            d.source
14722        );
14723    }
14724
14725    #[test]
14726    fn backspace_at_a_cell_start_is_a_wall() {
14727        // The task's repro: two presses used to take the padding and then the
14728        // `|`, merging `d` into `c`'s cell and leaving the row a column short.
14729        let src = "| a | b |\n| - | - |\n| c | d |\n";
14730        let mut d = wysiwyg_doc("tbl_wall_bs", src);
14731        d.place_caret(src.find("d |").unwrap(), false);
14732        for _ in 0..3 {
14733            d.backspace();
14734        }
14735        assert_eq!(d.source, src);
14736        // Inside the padding too — right after the `|`, before the space. Set
14737        // directly: `place_caret` would snap it onto the stop past the space.
14738        d.caret = src.find("| d").unwrap() + 1;
14739        d.backspace();
14740        assert_eq!(d.source, src);
14741        // The row's first cell, and an empty one, are walls the same.
14742        d.place_caret(src.find("c |").unwrap(), false);
14743        d.backspace();
14744        assert_eq!(d.source, src);
14745        // A cell that opens on hidden markup: the wall is the first letter
14746        // drawn, not the `**` in front of it.
14747        let bold = "| a | b |\n| - | - |\n| c | **d** |\n";
14748        let mut d = wysiwyg_doc("tbl_wall_bs_bold", bold);
14749        d.place_caret(bold.find("d**").unwrap(), false);
14750        d.backspace();
14751        assert_eq!(d.source, bold);
14752        let empty = "| a | b |\n| - | - |\n| c |   |\n";
14753        let mut d = wysiwyg_doc("tbl_wall_bs_empty", empty);
14754        d.place_caret(empty.find("|   |").unwrap() + 2, false);
14755        d.backspace();
14756        assert_eq!(d.source, empty);
14757    }
14758
14759    #[test]
14760    fn backspace_inside_a_cell_still_deletes_a_character() {
14761        let src = "| a | b |\n| - | - |\n| c | de |\n";
14762        let mut d = wysiwyg_doc("tbl_wall_bs_mid", src);
14763        d.place_caret(src.find("e |").unwrap(), false);
14764        d.backspace();
14765        assert_eq!(d.source, "| a | b |\n| - | - |\n| c | e |\n");
14766    }
14767
14768    #[test]
14769    fn delete_at_a_cell_end_is_a_wall() {
14770        // The mirror: Delete at `c`'s end would take the padding, then the `|`.
14771        let src = "| a | b |\n| - | - |\n| c | d |\n";
14772        let mut d = wysiwyg_doc("tbl_wall_del", src);
14773        d.place_caret(src.find("c |").unwrap() + 1, false);
14774        for _ in 0..3 {
14775            d.delete_forward();
14776        }
14777        assert_eq!(d.source, src);
14778        // And inside the trailing padding, set directly past the snap.
14779        d.caret = src.find("c |").unwrap() + 2;
14780        d.delete_forward();
14781        assert_eq!(d.source, src);
14782        // The row's last cell is a wall on its closing `|` as well.
14783        d.place_caret(src.find("d |").unwrap() + 1, false);
14784        d.delete_forward();
14785        assert_eq!(d.source, src);
14786        // Mid-cell Delete is untouched.
14787        d.place_caret(src.find("c |").unwrap(), false);
14788        d.delete_forward();
14789        assert_eq!(d.source, "| a | b |\n| - | - |\n|  | d |\n");
14790    }
14791
14792    #[test]
14793    fn delete_forward_over_an_in_cell_break_deletes_the_whole_br() {
14794        let mut d = wysiwyg_doc("tbl_break_del", TABLE);
14795        d.caret = TABLE.find("Pear").unwrap() + 4;
14796        assert!(d.cell_line_break());
14797        d.caret = TABLE.find("Pear").unwrap() + 4; // back onto the break's start
14798        d.delete_forward();
14799        assert!(
14800            !d.source.contains("<br"),
14801            "no half-deleted <br: {}",
14802            d.source
14803        );
14804        assert!(
14805            d.source.contains("| Pear |"),
14806            "cell back to one line: {}",
14807            d.source
14808        );
14809    }
14810
14811    #[test]
14812    fn shift_return_in_a_djot_cell_is_swallowed_and_leaves_the_row_intact() {
14813        // Djot has no idiomatic in-cell break, so twig refuses it. The gesture is
14814        // still consumed (a real newline would split the one-line row), but the
14815        // cell must be left exactly as it was — no non-idiomatic `<br>` spliced in.
14816        let src = "| Name | Qty |\n|:-----|----:|\n| Pear | 3 |\n";
14817        let mut d = Doc::from_source(src.to_string(), Format::Djot).unwrap();
14818        d.caret = src.find("Pear").unwrap() + 4;
14819        assert!(d.caret_in_table(), "caret should be inside the djot table");
14820        assert!(
14821            d.cell_line_break(),
14822            "the key is consumed, not passed to the frontend"
14823        );
14824        assert_eq!(d.source, src, "the djot cell is left untouched");
14825        assert!(
14826            !d.source.contains("<br>"),
14827            "no non-idiomatic <br> spliced into djot"
14828        );
14829        assert!(
14830            d.status.is_some(),
14831            "the refusal is surfaced on the status line"
14832        );
14833    }
14834
14835    #[test]
14836    fn typing_in_a_cell_edits_that_cell() {
14837        // Editing comes free once offsets map correctly: the caret is a source
14838        // offset, so a normal splice lands inside the pipe table.
14839        let mut d = wysiwyg_doc("tbl_type", TABLE);
14840        d.caret = TABLE.find("Pear").unwrap() + 4;
14841        d.insert("s");
14842        assert!(d.source.contains("| Pears | 3 |"), "got {:?}", d.source);
14843    }
14844
14845    #[test]
14846    fn motion_and_delete_treat_an_emoji_as_one_character() {
14847        // 👨‍👩‍👧 is a single grapheme built from three emoji joined by ZWJ — 18
14848        // bytes, several codepoints. Right-arrow must clear it in one step, and
14849        // backspace must remove the whole cluster, not a stray joiner.
14850        let family = "👨‍👩‍👧";
14851        let mut d = doc_with("emoji", &format!("a{family}b\n"));
14852        d.caret = 1; // just after 'a', before the emoji
14853        d.move_right(false);
14854        assert_eq!(
14855            d.caret,
14856            1 + family.len(),
14857            "one step clears the whole cluster"
14858        );
14859        assert_eq!(&d.source[d.caret..d.caret + 1], "b");
14860
14861        d.backspace(); // delete the emoji as a unit
14862        assert_eq!(d.source, "ab\n");
14863        assert_eq!(d.caret, 1);
14864    }
14865
14866    #[test]
14867    fn motion_handles_a_combining_accent_as_one_character() {
14868        // "e" + U+0301 (combining acute) renders as one é.
14869        let mut d = doc_with("combining", "e\u{0301}x\n");
14870        d.caret = 0;
14871        d.move_right(false);
14872        assert_eq!(
14873            d.caret,
14874            "e\u{0301}".len(),
14875            "steps past base + combining mark"
14876        );
14877    }
14878
14879    #[test]
14880    fn undo_then_redo_round_trips_an_edit() {
14881        let mut d = doc_with("undo", "hello\n");
14882        d.caret = 5;
14883        d.insert("!");
14884        assert_eq!(d.source, "hello!\n");
14885        d.undo();
14886        assert_eq!(d.source, "hello\n");
14887        assert_eq!(d.caret, 5, "undo restores the caret");
14888        d.redo();
14889        assert_eq!(d.source, "hello!\n");
14890    }
14891
14892    #[test]
14893    fn a_run_of_typing_undoes_as_one_step() {
14894        let mut d = doc_with("coalesce", "\n");
14895        d.caret = 0;
14896        d.insert("a");
14897        d.insert("b");
14898        d.insert("c");
14899        assert_eq!(d.source, "abc\n");
14900        d.undo(); // the whole typed run, not just "c"
14901        assert_eq!(d.source, "\n");
14902        d.undo(); // nothing left — the run was one step
14903        assert_eq!(d.source, "\n");
14904        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
14905    }
14906
14907    // ── IME composition ──────────────────────────────────────────────────────
14908
14909    #[test]
14910    fn a_composition_run_undoes_as_one_step() {
14911        let mut d = doc_with("compose", "\n");
14912        d.caret = 0;
14913        // What an IME does: each step replaces the last one's provisional bytes.
14914        d.edit_composing(0, 0, "k");
14915        d.edit_composing(0, 1, "か");
14916        d.edit_composing(0, 3, "かん");
14917        d.edit_composing(0, 6, "感"); // the commit
14918        d.end_composition();
14919        assert_eq!(d.source, "感\n");
14920        d.undo(); // the whole composition, not its last keystroke
14921        assert_eq!(d.source, "\n");
14922        assert_eq!(d.status.as_deref(), None, "the run was a single step");
14923    }
14924
14925    /// A Replace All the way a host does one: every match, last to first so
14926    /// the offsets still to go stay put, each a selection replaced by an
14927    /// insert, inside one undo group. `select_range` rather than the host's
14928    /// snapping `place_caret`, which would snap against a map these tests do
14929    /// not rebuild between edits.
14930    fn replace_all_in(d: &mut Doc, needle: &str, with: &str) {
14931        let hits: Vec<usize> = d.source.match_indices(needle).map(|(i, _)| i).collect();
14932        d.begin_undo_group();
14933        for at in hits.into_iter().rev() {
14934            d.select_range(at, at + needle.len());
14935            d.insert(with);
14936        }
14937        d.end_undo_group();
14938    }
14939
14940    #[test]
14941    fn a_replace_all_undoes_and_redoes_as_one_step() {
14942        let mut d = wysiwyg_doc("group", "a cat, a **cat**, a cat\n");
14943        d.caret = 0;
14944        d.insert("x");
14945        replace_all_in(&mut d, "cat", "dog");
14946        assert_eq!(d.source, "xa dog, a **dog**, a dog\n");
14947        assert!(d.undo(), "one undo");
14948        assert_eq!(
14949            d.source, "xa cat, a **cat**, a cat\n",
14950            "puts back every match"
14951        );
14952        assert!(d.redo(), "one redo");
14953        assert_eq!(
14954            d.source, "xa dog, a **dog**, a dog\n",
14955            "replaces them all again"
14956        );
14957        assert!(d.undo());
14958        assert!(d.undo(), "the typing before is its own step");
14959        assert_eq!(d.source, "a cat, a **cat**, a cat\n");
14960        assert!(!d.can_undo());
14961    }
14962
14963    #[test]
14964    fn typing_after_a_group_is_a_step_of_its_own() {
14965        // A one-character replacement is an insert like a keystroke, and a
14966        // keystroke after it would coalesce with it outside a group.
14967        let mut d = wysiwyg_doc("group", "a b a\n");
14968        replace_all_in(&mut d, "a", "c");
14969        d.caret = d.source.len() - 1;
14970        d.insert("d");
14971        assert_eq!(d.source, "c b cd\n");
14972        assert!(d.undo());
14973        assert_eq!(d.source, "c b c\n", "the typing alone");
14974        assert!(d.undo());
14975        assert_eq!(d.source, "a b a\n", "then the replacement, whole");
14976    }
14977
14978    #[test]
14979    fn a_group_of_more_edits_than_the_history_holds_is_still_one_step() {
14980        // twig keeps 200 steps; a group folds as it goes, so it never holds
14981        // more than one of them.
14982        let src = format!("start\n{}\n", "x ".repeat(300));
14983        let mut d = wysiwyg_doc("group", &src);
14984        d.caret = 5;
14985        d.insert("!");
14986        replace_all_in(&mut d, "x", "yy");
14987        assert_eq!(d.undo_steps, 2);
14988        assert!(d.undo());
14989        assert_eq!(d.source, src.replacen("start", "start!", 1));
14990        assert!(d.undo());
14991        assert_eq!(d.source, src);
14992        assert!(!d.can_undo());
14993    }
14994
14995    #[test]
14996    fn an_undo_closes_an_open_group() {
14997        let mut d = wysiwyg_doc("group", "one\n");
14998        d.caret = 3;
14999        d.begin_undo_group();
15000        d.begin_undo_group();
15001        d.insert("x");
15002        assert!(d.in_undo_group());
15003        assert!(d.undo());
15004        assert!(
15005            !d.in_undo_group(),
15006            "the history moved, so the group is over"
15007        );
15008        d.end_undo_group();
15009        d.end_undo_group();
15010        assert_eq!(d.source, "one\n");
15011        assert!(d.redo());
15012        assert_eq!(d.source, "onex\n");
15013    }
15014
15015    #[test]
15016    fn a_substitution_behind_the_caret_leaves_the_caret_and_is_its_own_step() {
15017        let mut d = wysiwyg_doc("substitute", "\n");
15018        d.caret = 0;
15019        for c in ["I", " ", "s", "a", "w", " ", "t", "e", "h", " "] {
15020            d.insert(c);
15021        }
15022        assert_eq!(d.source, "I saw teh \n");
15023        let at = d.source.find("teh").unwrap();
15024        assert!(d.substitute(at, at + 3, "the"));
15025        assert_eq!(d.source, "I saw the \n");
15026        assert_eq!(d.caret, 10, "still after the space");
15027        assert!(d.selection().is_none());
15028        d.insert("c");
15029        assert_eq!(d.source, "I saw the c\n");
15030        assert!(d.undo(), "the typing after it is a step of its own");
15031        assert_eq!(d.source, "I saw the \n");
15032        assert!(d.undo(), "the correction is one step");
15033        assert_eq!(d.source, "I saw teh \n", "what was typed");
15034        assert_eq!(d.caret, 10, "with the caret where it stood");
15035        assert!(d.redo());
15036        assert_eq!(d.source, "I saw the \n");
15037        assert!(d.undo());
15038        assert!(d.undo(), "and the typing before it is its own");
15039        assert_eq!(d.source, "\n");
15040        assert!(!d.can_undo());
15041    }
15042
15043    #[test]
15044    fn a_substitution_keeps_the_markup_it_stands_beside() {
15045        // A quote typed just past a bold run: only its own byte changes.
15046        let mut d = wysiwyg_doc("substitute", "A **bold** word\n");
15047        let at = d.source.find(" word").unwrap();
15048        d.caret = at;
15049        d.insert("\"");
15050        assert_eq!(d.source, "A **bold**\" word\n");
15051        assert!(d.substitute(at, at + 1, "\u{201d}"));
15052        assert_eq!(d.source, "A **bold**\u{201d} word\n");
15053        assert_eq!(d.caret, at + "\u{201d}".len());
15054        assert!(
15055            d.marks_at(d.source.find("bold").unwrap())
15056                .iter()
15057                .any(|(k, _)| *k == InlineKind::Strong)
15058        );
15059        // A range that is not one is refused, and changes nothing.
15060        let src = d.source.clone();
15061        assert!(!d.substitute(3, 2, "x"));
15062        assert!(!d.substitute(0, src.len() + 1, "x"));
15063        assert!(!d.substitute(d.source.find('\u{201d}').unwrap() + 1, d.source.len(), "x"));
15064        assert_eq!(d.source, src);
15065    }
15066
15067    #[test]
15068    fn a_substitution_that_half_lands_takes_back_only_its_own_deletion() {
15069        // The deletion lands and twig refuses the literal text: the deleted
15070        // bytes go back, and nothing else moves — not an earlier substitution
15071        // of the same keystroke, not the group it is in, and no redo is left
15072        // to delete them again.
15073        let mut d = wysiwyg_doc("substitute", "\n");
15074        d.set_markup_mode(MarkupMode::None);
15075        d.caret = 0;
15076        for c in ["a", "\"", "b", " ", "\""] {
15077            d.insert(c);
15078        }
15079        assert_eq!(d.source, "a\"b \"\n");
15080
15081        d.refuse_next_literal = true;
15082        assert!(!d.substitute(1, 2, "\u{201c}"));
15083        assert_eq!(d.source, "a\"b \"\n");
15084        assert_eq!(d.caret, 5, "the caret where it stood");
15085        assert!(!d.can_redo(), "no redo step left behind");
15086
15087        d.begin_undo_group();
15088        assert!(d.substitute(4, 5, "\u{201d}"));
15089        d.refuse_next_literal = true;
15090        assert!(!d.substitute(1, 2, "\u{201c}"));
15091        assert!(d.in_undo_group(), "the group is still open");
15092        assert_eq!(d.source, "a\"b \u{201d}\n", "the first substitution stands");
15093        d.end_undo_group();
15094        assert!(!d.can_redo());
15095        assert!(d.undo());
15096        assert_eq!(d.source, "a\"b \"\n", "one step takes the group back");
15097        assert!(d.undo());
15098        assert_eq!(d.source, "\n", "and the typing is still one step");
15099        assert!(!d.can_undo());
15100
15101        // A group whose first edit is the one that half lands has no step.
15102        let mut d = wysiwyg_doc("substitute", "\n");
15103        d.set_markup_mode(MarkupMode::None);
15104        d.caret = 0;
15105        d.insert("\"");
15106        d.begin_undo_group();
15107        d.refuse_next_literal = true;
15108        assert!(!d.substitute(0, 1, "\u{201c}"));
15109        assert!(d.substitute(0, 1, "\u{201c}"));
15110        d.end_undo_group();
15111        assert!(d.undo());
15112        assert_eq!(
15113            d.source, "\"\n",
15114            "the substitution that landed is the group's step"
15115        );
15116        assert!(d.undo());
15117        assert_eq!(d.source, "\n");
15118    }
15119
15120    #[test]
15121    fn a_substitution_is_written_the_way_typing_writes() {
15122        // Where typing is literal, so is a replacement's text.
15123        let mut d = wysiwyg_doc("substitute", "say hi\n");
15124        d.set_markup_mode(MarkupMode::None);
15125        assert!(d.substitute(4, 6, "*hi*"));
15126        assert_eq!(d.source, "say \\*hi\\*\n");
15127        assert!(d.undo());
15128        assert_eq!(d.source, "say hi\n", "one step, escapes and all");
15129    }
15130
15131    #[test]
15132    fn can_undo_is_false_once_a_coalesced_run_is_undone() {
15133        // The task's repro: five characters typed are one twig step, and the
15134        // counter used to say five.
15135        let mut d = wysiwyg_doc("undo_truth", "\n");
15136        d.caret = 0;
15137        for c in ["h", "e", "l", "l", "o"] {
15138            d.insert(c);
15139        }
15140        assert!(d.can_undo());
15141        assert!(d.undo(), "the run undoes");
15142        assert_eq!(d.source, "\n");
15143        assert!(!d.can_undo(), "and nothing is left behind it");
15144        let rev = d.revision();
15145        assert!(!d.undo(), "an undo that does not move says so");
15146        assert_eq!(d.revision(), rev);
15147        assert!(d.can_redo());
15148        assert!(d.redo());
15149        assert_eq!(d.source, "hello\n");
15150        assert!(!d.can_redo());
15151        assert!(!d.redo());
15152    }
15153
15154    #[test]
15155    fn can_undo_is_exact_across_the_gestures_that_coalesce() {
15156        // Each gesture below folds, or may fold, one twig step into another.
15157        // After it, the mirror must name exactly the number of undos twig
15158        // takes — and the same number of redos back.
15159        type Gesture = fn(&mut Doc);
15160        let cases: &[(&str, &str, Gesture)] = &[
15161            ("typing", "\n", |d| {
15162                d.caret = 0;
15163                d.insert("ab");
15164                d.insert("c");
15165                d.move_left(false);
15166                d.insert("x");
15167            }),
15168            ("backspaces", "abcdef\n", |d| {
15169                d.caret = 6;
15170                d.backspace();
15171                d.backspace();
15172                d.insert("z");
15173                d.backspace();
15174            }),
15175            ("ordered list item", "1. one\n2. two\n", |d| {
15176                d.caret = 6;
15177                d.newline();
15178                d.insert("x");
15179            }),
15180            ("list indent", "- one\n- two\n", |d| {
15181                d.caret = d.source.find("two").unwrap();
15182                d.indent();
15183                d.outdent();
15184            }),
15185            ("bold then type", "one two\n", |d| {
15186                d.select_range(0, 3);
15187                d.toggle(InlineKind::Strong);
15188                d.caret = d.source.len() - 1;
15189                d.insert("!");
15190            }),
15191            ("highlight", "one two\n", |d| {
15192                d.select_range(0, 3);
15193                d.highlight(None);
15194                d.highlight(Some(MarkColor::Green));
15195            }),
15196            ("heading and quote", "one\n", |d| {
15197                d.caret = 1;
15198                d.toggle_heading(2);
15199                d.toggle_blockquote();
15200            }),
15201            ("footnote", "one\n", |d| {
15202                d.caret = 3;
15203                d.insert_footnote();
15204                d.insert("note");
15205            }),
15206            ("blocks", "one\n\ntwo\n\nthree\n", |d| {
15207                d.caret = 1;
15208                d.move_block_down();
15209                d.toggle_list(true);
15210                d.set_alignment(Some(Align::Center));
15211                d.insert_page_break();
15212                d.insert_table(2, 2);
15213            }),
15214            ("paste and compose", "\n", |d| {
15215                d.caret = 0;
15216                d.paste("one two");
15217                d.delete_word_back();
15218                d.edit_composing(d.caret, d.caret, "か");
15219                d.edit_composing(d.caret - 3, d.caret, "蚊");
15220                d.end_composition();
15221                d.insert("z");
15222            }),
15223            ("table", "| a | b |\n| - | - |\n| c | d |\n", |d| {
15224                d.place_caret(d.source.find("d |").unwrap(), false);
15225                d.cell_tab(true);
15226                d.insert("e");
15227                d.cell_return();
15228            }),
15229            ("replace all", "cat cat cat\n", |d| {
15230                d.caret = 0;
15231                d.insert("a ");
15232                replace_all_in(d, "cat", "dog");
15233                d.insert("!");
15234            }),
15235            ("nested group", "one\n\ntwo\n", |d| {
15236                d.begin_undo_group();
15237                d.caret = 3;
15238                d.insert("x");
15239                d.begin_undo_group();
15240                d.toggle_heading(1);
15241                d.end_undo_group();
15242                d.insert("y");
15243                d.end_undo_group();
15244                d.backspace();
15245            }),
15246            ("group around a list", "1. one\n2. two\n", |d| {
15247                d.begin_undo_group();
15248                d.caret = 6;
15249                d.newline();
15250                d.insert("x");
15251                d.end_undo_group();
15252            }),
15253            ("substitution", "\n", |d| {
15254                d.caret = 0;
15255                d.insert("t");
15256                d.insert("e");
15257                d.insert("h");
15258                d.insert(" ");
15259                d.substitute(0, 3, "the");
15260                d.insert("c");
15261            }),
15262            ("empty group", "one\n", |d| {
15263                d.caret = 3;
15264                d.insert("x");
15265                d.begin_undo_group();
15266                d.end_undo_group();
15267                d.insert("y");
15268            }),
15269            ("undo inside a group", "one\n", |d| {
15270                d.caret = 3;
15271                d.begin_undo_group();
15272                d.insert("x");
15273                d.undo();
15274                d.insert("y");
15275                d.insert("z");
15276                d.end_undo_group();
15277            }),
15278        ];
15279        for (name, src, gesture) in cases {
15280            let mut d = wysiwyg_doc("undo_exact", src);
15281            gesture(&mut d);
15282            let (steps, after) = (d.undo_steps, d.source.clone());
15283            let mut undone = 0;
15284            while d.can_undo() {
15285                assert!(d.undo(), "{name}: can_undo said yes, undo moved nothing");
15286                undone += 1;
15287            }
15288            assert!(!d.undo(), "{name}: can_undo said no, undo moved");
15289            assert_eq!(undone, steps, "{name}");
15290            assert_eq!(d.source, *src, "{name}: back to the start");
15291            let mut redone = 0;
15292            while d.can_redo() {
15293                assert!(d.redo(), "{name}: can_redo said yes, redo moved nothing");
15294                redone += 1;
15295            }
15296            assert!(!d.redo(), "{name}: can_redo said no, redo moved");
15297            assert_eq!(redone, steps, "{name}");
15298            assert_eq!(d.source, after, "{name}: forward to the end");
15299        }
15300    }
15301
15302    #[test]
15303    fn two_compositions_are_two_undo_steps() {
15304        let mut d = doc_with("compose_two", "\n");
15305        d.caret = 0;
15306        d.edit_composing(0, 0, "か");
15307        d.edit_composing(0, 3, "蚊");
15308        d.end_composition();
15309        d.edit_composing(3, 3, "き");
15310        d.edit_composing(3, 6, "木");
15311        d.end_composition();
15312        assert_eq!(d.source, "蚊木\n");
15313        d.undo();
15314        assert_eq!(d.source, "蚊\n", "only the second composition");
15315        d.undo();
15316        assert_eq!(d.source, "\n");
15317    }
15318
15319    #[test]
15320    fn a_composition_does_not_fold_into_the_typing_around_it() {
15321        let mut d = doc_with("compose_typing", "\n");
15322        d.caret = 0;
15323        d.insert("a");
15324        d.insert("b");
15325        d.edit_composing(2, 2, "か");
15326        d.edit_composing(2, 5, "蚊");
15327        d.end_composition();
15328        d.insert("c");
15329        assert_eq!(d.source, "ab蚊c\n");
15330        d.undo();
15331        assert_eq!(d.source, "ab蚊\n");
15332        d.undo();
15333        assert_eq!(d.source, "ab\n");
15334        d.undo();
15335        assert_eq!(d.source, "\n");
15336    }
15337
15338    #[test]
15339    fn ending_a_composition_that_never_began_leaves_a_typing_run_alone() {
15340        let mut d = doc_with("compose_spurious", "\n");
15341        d.caret = 0;
15342        d.insert("a");
15343        d.end_composition(); // an IME unmarking unprompted
15344        d.insert("b");
15345        assert_eq!(d.source, "ab\n");
15346        d.undo();
15347        assert_eq!(d.source, "\n", "still one typed run");
15348    }
15349
15350    // ── the clipboard's rich flavor ──────────────────────────────────────────
15351
15352    #[test]
15353    fn an_inline_selection_publishes_html_without_a_paragraph_wrapper() {
15354        let mut d = doc_with("sel_inline", "a **bold** c\n");
15355        d.anchor = Some(2);
15356        d.caret = 10; // `**bold**`, inside the paragraph
15357        assert_eq!(d.selection_html().as_deref(), Some("<strong>bold</strong>"));
15358    }
15359
15360    #[test]
15361    fn a_whole_block_selection_keeps_its_paragraph() {
15362        let mut d = doc_with("sel_block", "a **bold** c\n");
15363        d.anchor = Some(0);
15364        d.caret = 12; // the entire paragraph
15365        assert_eq!(
15366            d.selection_html().as_deref(),
15367            Some("<p>a <strong>bold</strong> c</p>")
15368        );
15369    }
15370
15371    #[test]
15372    fn a_multi_block_selection_keeps_its_structure() {
15373        let mut d = doc_with("sel_multi", "para\n\n- one\n- two\n");
15374        d.select_all();
15375        let html = d.selection_html().expect("renders");
15376        assert!(html.contains("<p>para</p>"), "{html:?}");
15377        assert!(html.contains("<li>one</li>"), "{html:?}");
15378    }
15379
15380    #[test]
15381    fn a_word_inside_a_heading_publishes_as_text_not_a_heading() {
15382        // The fragment `Head` is a paragraph standalone; the *document* says it
15383        // sits inside one block, so the wrapper is an artifact either way.
15384        let mut d = doc_with("sel_heading", "# Head line\n");
15385        d.anchor = Some(2);
15386        d.caret = 6;
15387        assert_eq!(d.selection_html().as_deref(), Some("Head"));
15388    }
15389
15390    #[test]
15391    fn no_selection_publishes_no_html() {
15392        let mut d = doc_with("sel_none", "a b\n");
15393        d.caret = 1;
15394        assert_eq!(d.selection_html(), None);
15395    }
15396
15397    #[test]
15398    fn pasting_html_converts_it_and_is_one_undo_step() {
15399        let mut d = doc_with("paste_html", "x\n");
15400        d.caret = 1;
15401        assert!(d.paste_html("<p>a <strong>b</strong> c</p>"));
15402        assert_eq!(d.source, "xa **b** c\n");
15403        d.undo();
15404        assert_eq!(d.source, "x\n", "the whole paste, in one step");
15405    }
15406
15407    #[test]
15408    fn pasting_html_replaces_the_selection() {
15409        let mut d = doc_with("paste_html_sel", "keep drop\n");
15410        d.anchor = Some(5);
15411        d.caret = 9;
15412        assert!(d.paste_html("<em>new</em>"));
15413        assert_eq!(d.source, "keep *new*\n");
15414    }
15415
15416    #[test]
15417    fn html_that_would_paste_garbage_declines_so_the_caller_falls_back() {
15418        let mut d = doc_with("paste_html_bad", "x\n");
15419        d.caret = 1;
15420        // twig builds no table from HTML; raw `<table>` in prose is worse than
15421        // the plain flavor the caller still holds.
15422        assert!(!d.paste_html("<table><tr><td>a</td></tr></table>"));
15423        assert_eq!(d.source, "x\n", "declined edits nothing");
15424    }
15425
15426    #[test]
15427    fn copy_then_paste_round_trips_through_the_html_flavor() {
15428        let mut d = doc_with("clip_round", "a **b** and [l](https://x.dev)\n");
15429        d.select_all();
15430        let html = d.selection_html().expect("renders");
15431        let mut into = doc_with("clip_round_dst", "\n");
15432        into.caret = 0;
15433        assert!(into.paste_html(&html));
15434        assert_eq!(into.source, "a **b** and [l](https://x.dev)\n");
15435    }
15436
15437    #[test]
15438    fn moving_the_caret_starts_a_new_undo_group() {
15439        let mut d = doc_with("break", "\n");
15440        d.caret = 0;
15441        d.insert("a");
15442        d.insert("b"); // "ab\n", caret at 2
15443        d.move_left(false); // breaks the run
15444        d.insert("X"); // "aXb\n"
15445        assert_eq!(d.source, "aXb\n");
15446        d.undo();
15447        assert_eq!(
15448            d.source, "ab\n",
15449            "first undo removes only the post-move insert"
15450        );
15451        d.undo();
15452        assert_eq!(d.source, "\n", "second undo removes the earlier run");
15453    }
15454
15455    #[test]
15456    fn undo_reverses_a_format_toggle() {
15457        let mut d = doc_with("fmt_undo", "a word b\n");
15458        d.anchor = Some(2);
15459        d.caret = 6;
15460        d.toggle(InlineKind::Strong);
15461        assert_eq!(d.source, "a **word** b\n");
15462        d.undo();
15463        assert_eq!(d.source, "a word b\n");
15464    }
15465
15466    #[test]
15467    fn undo_back_to_the_saved_state_clears_dirty() {
15468        let mut d = doc_with("dirty_undo", "hello\n");
15469        assert!(!d.dirty);
15470        d.caret = 5;
15471        d.insert("!");
15472        assert!(d.dirty);
15473        d.undo();
15474        assert!(
15475            !d.dirty,
15476            "undoing to the saved source is not a modification"
15477        );
15478    }
15479
15480    #[test]
15481    fn marking_saved_as_what_was_written_keeps_later_typing_dirty() {
15482        let mut d = doc_with("saved_as", "Does this\n");
15483        d.caret = 9;
15484        d.insert(" ");
15485        // The host reads the source, and its write takes a while…
15486        let written = d.source.clone();
15487        // …during which the rest of the sentence is typed.
15488        d.insert("work?");
15489        d.mark_saved_as(&written);
15490        assert!(d.dirty, "what was typed during the write is not saved");
15491        d.undo();
15492        assert!(!d.dirty, "undoing to what was written is the saved state");
15493
15494        d.redo();
15495        let written = d.source.clone();
15496        d.mark_saved_as(&written);
15497        assert!(!d.dirty, "nothing typed meanwhile: saved");
15498    }
15499
15500    #[test]
15501    fn a_new_edit_invalidates_redo() {
15502        let mut d = doc_with("redo_inv", "\n");
15503        d.caret = 0;
15504        d.insert("a");
15505        d.undo();
15506        d.insert("b"); // diverges — the redo of "a" is now gone
15507        d.redo();
15508        assert_eq!(d.source, "b\n");
15509    }
15510
15511    #[test]
15512    fn can_undo_and_can_redo_follow_the_history_a_menu_would_enable_by() {
15513        let mut d = doc_with("can_undo", "hello\n");
15514        assert!(
15515            !d.can_undo() && !d.can_redo(),
15516            "a fresh document has no history"
15517        );
15518        d.caret = 5;
15519        d.insert("!");
15520        assert!(
15521            d.can_undo() && !d.can_redo(),
15522            "an edit is a step to take back"
15523        );
15524        d.undo();
15525        assert!(!d.can_undo() && d.can_redo(), "undone: only redo remains");
15526        d.redo();
15527        assert!(d.can_undo() && !d.can_redo(), "redone: back to undoable");
15528        d.undo();
15529        d.insert("?");
15530        assert!(
15531            d.can_undo() && !d.can_redo(),
15532            "a fresh edit ends the redo chain"
15533        );
15534        // A coalesced run over-counts steps — the bound is what a menu needs,
15535        // and it reconciles the moment twig reports the history empty.
15536        d.insert("a");
15537        d.insert("b");
15538        while d.can_undo() {
15539            d.undo();
15540        }
15541        assert_eq!(d.source, "hello\n");
15542        assert!(!d.can_undo());
15543        // A reading surface has nothing to undo, whatever the history holds.
15544        d.redo();
15545        d.set_read_only(true);
15546        assert!(!d.can_undo() && !d.can_redo());
15547    }
15548
15549    #[test]
15550    fn undo_on_empty_history_is_a_no_op() {
15551        let mut d = doc_with("undo_empty", "hi\n");
15552        d.undo();
15553        assert_eq!(d.source, "hi\n");
15554        assert_eq!(d.status.as_deref(), Some("nothing to undo"));
15555    }
15556
15557    #[test]
15558    fn a_one_character_paste_is_its_own_undo_step() {
15559        for view in [View::Source, View::Wysiwyg] {
15560            let mut d = doc_in(view, "paste_step", "ab\n");
15561            d.caret = 0;
15562            d.insert("x");
15563            d.insert("y"); // a run of typing
15564            d.paste("z"); // one character, but pasted — not part of that run
15565            assert_eq!(d.source, "xyzab\n");
15566            d.undo();
15567            assert_eq!(d.source, "xyab\n", "the paste undoes on its own");
15568            assert_eq!(d.caret, 2, "and hands back the caret it found");
15569            d.undo();
15570            assert_eq!(d.source, "ab\n", "the typed run is still one step under it");
15571        }
15572    }
15573
15574    #[test]
15575    fn the_same_character_typed_still_joins_the_run() {
15576        // The other half of the pair: `z` is a keystroke here and a paste above,
15577        // and the two undo differently. Nothing about the *string* says which —
15578        // which is why provenance has to come from the door the caller uses.
15579        for view in [View::Source, View::Wysiwyg] {
15580            let mut d = doc_in(view, "typed_run", "ab\n");
15581            d.caret = 0;
15582            d.insert("x");
15583            d.insert("y");
15584            d.insert("z");
15585            d.undo();
15586            assert_eq!(d.source, "ab\n", "one run, one step");
15587        }
15588    }
15589
15590    #[test]
15591    fn undo_restores_the_caret_to_where_it_was_not_to_the_edit_site() {
15592        for view in [View::Source, View::Wysiwyg] {
15593            let mut d = doc_in(view, "undo_caret", "hello world\n");
15594            d.caret = 11; // standing at the end of "world", away from the edit
15595            d.edit(0, 5, "goodbye");
15596            assert_eq!(d.source, "goodbye world\n");
15597            d.undo();
15598            assert_eq!(d.source, "hello world\n");
15599            // The undone edit ends at offset 5; the user was at 11.
15600            assert_eq!(d.caret, 11, "the caret comes back with the bytes");
15601        }
15602    }
15603
15604    #[test]
15605    fn undo_restores_the_selection_the_edit_replaced() {
15606        for view in [View::Source, View::Wysiwyg] {
15607            let mut d = doc_in(view, "undo_sel", "a word b\n");
15608            d.anchor = Some(2);
15609            d.caret = 6; // "word" selected
15610            d.insert("X");
15611            assert_eq!(d.source, "a X b\n");
15612            d.undo();
15613            assert_eq!(d.source, "a word b\n");
15614            assert_eq!(d.selection(), Some((2, 6)), "the selection comes back too");
15615        }
15616    }
15617
15618    #[test]
15619    fn redo_restores_the_caret_the_edit_left_behind() {
15620        for view in [View::Source, View::Wysiwyg] {
15621            let mut d = doc_in(view, "redo_caret", "hello world\n");
15622            d.caret = 11;
15623            d.edit(0, 5, "goodbye");
15624            assert_eq!(d.caret, 7, "the edit left the caret after its new text");
15625            d.undo();
15626            d.redo();
15627            assert_eq!(d.source, "goodbye world\n");
15628            assert_eq!(d.caret, 7, "redo puts it back where the edit had it");
15629        }
15630    }
15631
15632    #[test]
15633    fn undoing_a_typed_run_restores_the_caret_from_before_the_whole_run() {
15634        for view in [View::Source, View::Wysiwyg] {
15635            let mut d = doc_in(view, "run_caret", "hi\n");
15636            d.caret = 2;
15637            d.insert("a");
15638            d.insert("b");
15639            d.insert("c");
15640            assert_eq!(d.source, "hiabc\n");
15641            d.undo();
15642            assert_eq!(d.source, "hi\n");
15643            assert_eq!(d.caret, 2, "before the run, not before its last keystroke");
15644            d.redo();
15645            assert_eq!(d.caret, 5, "and redo restores the end of the whole run");
15646        }
15647    }
15648
15649    #[test]
15650    fn undo_restores_the_caret_across_a_format_toggle() {
15651        // A toggle reaches twig without going through `splice`, so it has to
15652        // record its own step — miss it and every stack depth below it is off by
15653        // one, and undo starts handing back another edit's caret.
15654        for view in [View::Source, View::Wysiwyg] {
15655            let mut d = doc_in(view, "fmt_caret", "a word b\n");
15656            d.caret = 8;
15657            d.anchor = Some(2);
15658            d.caret = 6;
15659            d.toggle(InlineKind::Strong);
15660            assert_eq!(d.source, "a **word** b\n");
15661            d.undo();
15662            assert_eq!(d.source, "a word b\n");
15663            assert_eq!(
15664                d.selection(),
15665                Some((2, 6)),
15666                "the toggled selection comes back"
15667            );
15668        }
15669    }
15670
15671    #[test]
15672    fn an_edit_after_an_undo_truncates_the_caret_history_with_twigs() {
15673        // The drift that would never announce itself: twig drops its redo stack
15674        // on any fresh edit, so a leaf redo entry that outlives it would restore
15675        // a caret from the timeline that edit abandoned.
15676        for view in [View::Source, View::Wysiwyg] {
15677            let mut d = doc_in(view, "redo_trunc", "hello world\n");
15678            d.caret = 11;
15679            d.edit(0, 5, "goodbye"); // step A, caret 11 → 7
15680            d.undo();
15681            assert_eq!(d.caret, 11);
15682            d.caret = 0;
15683            d.insert("X"); // diverges: A's redo is gone from twig
15684            assert_eq!(d.source, "Xhello world\n");
15685
15686            d.redo();
15687            assert_eq!(d.source, "Xhello world\n", "nothing to redo onto");
15688            assert_eq!(d.status.as_deref(), Some("nothing to redo"));
15689            d.undo();
15690            assert_eq!(d.source, "hello world\n");
15691            assert_eq!(
15692                d.caret, 0,
15693                "the surviving step's caret, not the dropped one"
15694            );
15695        }
15696    }
15697
15698    #[test]
15699    fn indent_and_outdent_move_the_caret_line_with_its_text() {
15700        for view in [View::Source, View::Wysiwyg] {
15701            let g = |m, f: fn(&mut Doc)| golden_in(view, "indent_line", m, f);
15702            assert_eq!(g("he|llo\n", |d| d.indent()), "  he|llo\n");
15703            assert_eq!(g("  he|llo\n", |d| d.outdent()), "he|llo\n");
15704            // Indentation the caret is standing *in* collapses to the line start
15705            // rather than dragging the caret into the text.
15706            assert_eq!(g("| hello\n", |d| d.outdent()), "|hello\n");
15707            // A line with none to give back is left exactly as it was.
15708            assert_eq!(g("he|llo\n", |d| d.outdent()), "he|llo\n");
15709            // Less than a full level gives back what it has.
15710            assert_eq!(g(" he|llo\n", |d| d.outdent()), "he|llo\n");
15711            // A tab is one level however many spaces it isn't.
15712            assert_eq!(g("\the|llo\n", |d| d.outdent()), "he|llo\n");
15713        }
15714    }
15715
15716    #[test]
15717    fn one_indent_level_leaves_a_paragraph_a_paragraph() {
15718        // Why the level is two spaces and not the four both frontends type
15719        // today. Four is markdown's indented-code-block marker, so a Tab on a
15720        // paragraph would silently restyle it as code — a width that changes
15721        // what the document *means* isn't an indent. Pinned because the number
15722        // is the kind of thing a later list-aware pass would reach for.
15723        let mut d = doc_with("indent_kind", "hello\n");
15724        d.caret = 2;
15725        d.indent();
15726        assert_eq!(d.source, "  hello\n");
15727        assert!(
15728            d.nodes().iter().any(|n| n.kind == Kind::Para),
15729            "still prose after a Tab"
15730        );
15731        assert!(!d.nodes().iter().any(|n| n.kind == Kind::CodeBlock));
15732
15733        // The four-space level this replaces, for contrast: same text, and twig
15734        // reparses the paragraph into a code block.
15735        let mut wide = doc_with("indent_kind_4", "    hello\n");
15736        wide.build_visual(80);
15737        assert!(
15738            wide.nodes().iter().any(|n| n.kind == Kind::CodeBlock),
15739            "four spaces is a code block, not an indented paragraph"
15740        );
15741    }
15742
15743    #[test]
15744    fn indent_nests_a_list_item_under_its_parent() {
15745        // Tab indents a list item by its own marker width, landing its marker at
15746        // the parent's content column so twig reparses it as a nested list.
15747        for view in [View::Source, View::Wysiwyg] {
15748            let mut d = doc_in(view, "indent_nest", "- a\n- b\n");
15749            d.caret = 6; // on the second item
15750            d.indent();
15751            assert_eq!(d.source, "- a\n  - b\n");
15752            let lists = d
15753                .nodes()
15754                .iter()
15755                .filter(|n| n.kind == Kind::BulletList)
15756                .count();
15757            assert_eq!(lists, 2, "the indented item is a nested list");
15758        }
15759    }
15760
15761    #[test]
15762    fn indent_nests_an_ordered_item_at_its_marker_width() {
15763        // An ordered marker `1. ` is three columns wide, so a two-space step
15764        // (which nests a bullet) leaves it flat. Regression: Tab must use the
15765        // marker width, three, so the item actually nests — and the source
15766        // renumbers so the sub-list restarts at 1 and the outer list resumes.
15767        for view in [View::Source, View::Wysiwyg] {
15768            let mut d = doc_in(view, "indent_ord", "1. a\n2. b\n3. c\n");
15769            d.caret = d.source.find('b').unwrap();
15770            d.indent();
15771            assert_eq!(d.source, "1. a\n   1. b\n2. c\n");
15772            let lists = d
15773                .nodes()
15774                .iter()
15775                .filter(|n| n.kind == Kind::OrderedList)
15776                .count();
15777            assert_eq!(lists, 2, "the indented item is a nested ordered list");
15778        }
15779    }
15780
15781    #[test]
15782    fn indent_leaves_a_lists_first_item_put() {
15783        // The first item of a list has no sibling above it to nest under, so Tab
15784        // is a no-op there — the marker stays at column zero rather than being
15785        // shoved into indentation twig can't read as a sub-list.
15786        for view in [View::Source, View::Wysiwyg] {
15787            let mut d = doc_in(view, "indent_first", "- a\n- b\n");
15788            d.caret = 1; // on the FIRST item
15789            d.indent();
15790            assert_eq!(d.source, "- a\n- b\n", "the first item doesn't nest");
15791            // The sibling below still nests, proving the guard is per-item.
15792            d.caret = d.source.find('b').unwrap();
15793            d.indent();
15794            assert_eq!(d.source, "- a\n  - b\n");
15795        }
15796    }
15797
15798    #[test]
15799    fn hidden_mode_keeps_typed_markup_literal() {
15800        // The Diaryx default: typing `*hi*` gives the characters, not emphasis —
15801        // twig escapes what would open markup, so the source is `\*hi\*` and the
15802        // AST is a plain string. Formatting is the commands' job in this mode.
15803        let mut d = doc_in(View::Wysiwyg, "hidden_literal", "");
15804        d.insert("*hi*");
15805        assert_eq!(d.source, "\\*hi\\*");
15806        assert!(
15807            d.nodes()
15808                .iter()
15809                .all(|n| n.kind != Kind::Emph && n.kind != Kind::Strong)
15810        );
15811    }
15812
15813    #[test]
15814    fn hidden_mode_escapes_a_line_start_block_marker() {
15815        // A `#`/`-`/`>` at a line start would open a block, so Hidden mode keeps
15816        // it literal too — a Diaryx user's "# 1 idea" stays prose, not a heading.
15817        let mut d = doc_in(View::Wysiwyg, "hidden_block", "");
15818        d.insert("# hi");
15819        assert_eq!(d.source, "\\# hi");
15820        assert!(d.nodes().iter().all(|n| n.kind != Kind::Heading));
15821    }
15822
15823    #[test]
15824    fn authoring_modes_keep_typed_markup_live() {
15825        // Both authoring rungs of the ladder: typing `*hi*` really is emphasis
15826        // (no escape), the same as source view — escaping is `None`'s alone, and
15827        // it's the axis, not the reveal, that decides.
15828        for (view, mode) in [
15829            (View::Wysiwyg, MarkupMode::Shortcuts),
15830            (View::Wysiwyg, MarkupMode::Full),
15831            (View::Source, MarkupMode::None),
15832        ] {
15833            let mut d = doc_in(view, "live_markup", "");
15834            d.set_markup_mode(mode);
15835            d.insert("*hi*");
15836            assert_eq!(d.source, "*hi*", "{mode:?} in {view:?} types raw markup");
15837        }
15838    }
15839
15840    #[test]
15841    fn hidden_mode_overwrite_undoes_in_one_step() {
15842        // Typing over a selection escapes the replacement *and* stays a single
15843        // undo — the selection-delete and the literal insert fold together, so
15844        // one undo brings the whole selection back, like a plain overwrite.
15845        let mut d = doc_in(View::Wysiwyg, "hidden_overwrite", "a word b\n");
15846        d.anchor = Some(2);
15847        d.caret = 6; // "word"
15848        d.insert("*");
15849        assert_eq!(d.source, "a \\* b\n", "the replacement is escaped");
15850        d.undo();
15851        assert_eq!(d.source, "a word b\n");
15852        assert_eq!(d.selection(), Some((2, 6)), "one undo, selection restored");
15853    }
15854
15855    #[test]
15856    fn backspace_over_an_escaped_char_takes_the_hidden_backslash_too() {
15857        // Type `*` in Hidden mode → `\*` (drawn as one `*`); one Backspace clears
15858        // the whole visual character, never stranding the hidden `\`.
15859        let mut d = doc_in(View::Wysiwyg, "bsp_escape", "");
15860        d.insert("*");
15861        assert_eq!(d.source, "\\*");
15862        d.backspace();
15863        assert_eq!(d.source, "", "the escape backslash went with the *");
15864        // A *literal* backslash (source view, no escape) is an ordinary char.
15865        let mut s = doc_in(View::Source, "bsp_lit", "a\\b\n");
15866        s.caret = 3; // after `b`
15867        s.backspace();
15868        assert_eq!(s.source, "a\\\n", "only the b is deleted, the \\ stays");
15869    }
15870
15871    #[test]
15872    fn hidden_mode_leaves_structural_markup_alone() {
15873        // Enter continues a bullet list by writing a real `- ` marker (an
15874        // `insert_raw`, not the typing path), so Hidden mode's escaping never
15875        // touches it — the list keeps working.
15876        let mut d = doc_in(View::Wysiwyg, "hidden_struct", "- item\n");
15877        d.caret = 6;
15878        d.newline();
15879        d.insert("two");
15880        assert_eq!(d.source, "- item\n- two\n");
15881    }
15882
15883    #[test]
15884    fn markup_mode_defaults_to_none_and_round_trips() {
15885        // Diaryx's default is the clean `None` surface; a markup-fluent
15886        // frontend can climb the ladder, and the choice sticks.
15887        let mut d = doc_in(View::Wysiwyg, "markup_mode", "hi\n");
15888        assert_eq!(d.markup_mode(), MarkupMode::None, "None by default");
15889        for mode in [MarkupMode::Shortcuts, MarkupMode::Full, MarkupMode::None] {
15890            d.set_markup_mode(mode);
15891            assert_eq!(d.markup_mode(), mode);
15892        }
15893    }
15894
15895    #[test]
15896    fn full_mode_reveals_only_the_caret_line() {
15897        // The mode's whole claim: the caret's line shows its raw delimiters and
15898        // every other line stays resolved. Two paragraphs with identical markup
15899        // so the only difference between the rows is where the caret is.
15900        let mut d = doc_in(
15901            View::Wysiwyg,
15902            "reveal_caret_line",
15903            "*one* here\n\n*two* there\n",
15904        );
15905        d.set_markup_mode(MarkupMode::Full);
15906
15907        caret_at(&mut d, "one");
15908        let rows = drawn_rows(&d);
15909        assert!(
15910            rows.iter().any(|r| r == "*one* here"),
15911            "caret's line raw: {rows:?}"
15912        );
15913        assert!(
15914            rows.iter().any(|r| r == "two there"),
15915            "other line resolved: {rows:?}"
15916        );
15917
15918        // Move to the other paragraph: the reveal follows, and the line just
15919        // left goes back to being resolved.
15920        caret_at(&mut d, "two");
15921        let rows = drawn_rows(&d);
15922        assert!(
15923            rows.iter().any(|r| r == "*two* there"),
15924            "caret's line raw: {rows:?}"
15925        );
15926        assert!(
15927            rows.iter().any(|r| r == "one here"),
15928            "left line resolved: {rows:?}"
15929        );
15930    }
15931
15932    #[test]
15933    fn revealing_a_coloured_highlight_shows_the_emoji_that_spelled_it() {
15934        // The emoji is a delimiter, not content — so `MarkupMode::Full` owes it
15935        // the same treatment as an emphasis's `*`: hidden while the caret is
15936        // elsewhere, shown in full where the caret lands. That falls out of
15937        // `delims` reading the bytes between the mark's span and its content
15938        // span, which is exactly `==🔴 ` and `==`, rather than from a table
15939        // of spellings — so the no-space form `==🟢green==` reveals right too.
15940        let mut d = doc_in(
15941            View::Wysiwyg,
15942            "reveal_coloured_mark",
15943            "a ==🔴 red== one\n\nb ==plain== two\n",
15944        );
15945        d.set_markup_mode(MarkupMode::Full);
15946
15947        caret_at(&mut d, "red");
15948        let rows = drawn_rows(&d);
15949        assert!(
15950            rows.iter().any(|r| r == "a ==🔴 red== one"),
15951            "the caret's line shows the colour it was written with: {rows:?}"
15952        );
15953        assert!(
15954            rows.iter().any(|r| r == "b plain two"),
15955            "and every other line stays resolved: {rows:?}"
15956        );
15957
15958        // Away from it, the emoji goes back to being markup — the reader sees
15959        // the words and the wash.
15960        caret_at(&mut d, "two");
15961        let rows = drawn_rows(&d);
15962        assert!(
15963            rows.iter().any(|r| r == "a red one"),
15964            "resolved again: {rows:?}"
15965        );
15966    }
15967
15968    #[test]
15969    fn hidden_modes_never_reveal_wherever_the_caret_is() {
15970        // The two rungs below `Full` share a rendering: delimiters stay hidden
15971        // even under the caret. `Shortcuts` differing from `None` only in what
15972        // typing does is exactly the point of splitting the axes.
15973        for mode in [MarkupMode::None, MarkupMode::Shortcuts] {
15974            let mut d = doc_in(View::Wysiwyg, "reveal_hidden", "*one* here\n");
15975            d.set_markup_mode(mode);
15976            caret_at(&mut d, "one");
15977            let rows = drawn_rows(&d);
15978            assert!(
15979                rows.iter().any(|r| r == "one here"),
15980                "{mode:?} hides: {rows:?}"
15981            );
15982            assert!(
15983                !rows.iter().any(|r| r.contains('*')),
15984                "{mode:?} shows no `*`: {rows:?}"
15985            );
15986        }
15987    }
15988
15989    #[test]
15990    fn revealed_delimiters_are_the_authors_own_spelling() {
15991        // Delimiters are re-read from the source rather than synthesized per
15992        // kind, so a line comes back spelled the way it was written: `_em_` does
15993        // not turn into `*em*`, and a two-backtick fence keeps both backticks.
15994        let body = "_em_ and __st__ and ``lit ` tick`` and [lk](http://x) and ~~del~~\n";
15995        let mut d = doc_in(View::Wysiwyg, "reveal_spelling", body);
15996        d.set_markup_mode(MarkupMode::Full);
15997        caret_at(&mut d, "em");
15998        let rows = drawn_rows(&d);
15999        assert!(
16000            rows.iter().any(|r| r == body.trim_end()),
16001            "the revealed line is its own source: {rows:?}"
16002        );
16003    }
16004
16005    #[test]
16006    fn revealed_heading_shows_its_hashes() {
16007        // The `# ` marker is a block-level prefix, not an inline delimiter, so
16008        // it takes its own path — but it reveals on the same rule.
16009        let mut d = doc_in(View::Wysiwyg, "reveal_heading", "# Title\n\nbody\n");
16010        d.set_markup_mode(MarkupMode::Full);
16011
16012        caret_at(&mut d, "Title");
16013        assert!(
16014            drawn_rows(&d).iter().any(|r| r == "# Title"),
16015            "{:?}",
16016            drawn_rows(&d)
16017        );
16018
16019        caret_at(&mut d, "body");
16020        let rows = drawn_rows(&d);
16021        assert!(
16022            rows.iter().any(|r| r == "Title"),
16023            "hashes hidden again: {rows:?}"
16024        );
16025    }
16026
16027    #[test]
16028    fn revealed_delimiters_are_caret_stops() {
16029        // A delimiter that is drawn but can't be reached is worse than one
16030        // that's hidden: the mode exists so the markup can be *edited*. Every
16031        // revealed byte must be somewhere the caret can stand.
16032        let mut d = doc_in(View::Wysiwyg, "reveal_stops", "*em* x\n");
16033        d.set_markup_mode(MarkupMode::Full);
16034        caret_at(&mut d, "em");
16035        let opener = d.source.find('*').unwrap();
16036        assert!(d.vmap.is_stop(opener), "the opening `*` is a caret stop");
16037        assert!(
16038            d.vmap.is_stop(opener + 3),
16039            "the closing `*` is a caret stop"
16040        );
16041    }
16042
16043    #[test]
16044    fn setext_heading_reveals_nothing_across_its_newline() {
16045        // A setext heading's underline is on another line, so it is not the
16046        // caret line's to reveal — and emitting it would inject a `\n` glyph
16047        // that splits the row where the author wrote no break.
16048        let mut d = doc_in(View::Wysiwyg, "reveal_setext", "Title\n=====\n\nbody\n");
16049        d.set_markup_mode(MarkupMode::Full);
16050        caret_at(&mut d, "Title");
16051        let rows = drawn_rows(&d);
16052        assert!(
16053            rows.iter().any(|r| r == "Title"),
16054            "title renders alone: {rows:?}"
16055        );
16056        assert!(
16057            !rows.iter().any(|r| r.contains('=')),
16058            "no underline leaks in: {rows:?}"
16059        );
16060    }
16061
16062    #[test]
16063    fn markup_mode_axes_split_the_ladder() {
16064        // The two behaviours the ladder spells: `Shortcuts` is the middle rung
16065        // that authors markup but still hides it, and it's the only rung where
16066        // the two axes disagree.
16067        assert!(!MarkupMode::None.authors());
16068        assert!(!MarkupMode::None.reveals_caret_line());
16069        assert!(MarkupMode::Shortcuts.authors());
16070        assert!(!MarkupMode::Shortcuts.reveals_caret_line());
16071        assert!(MarkupMode::Full.authors());
16072        assert!(MarkupMode::Full.reveals_caret_line());
16073    }
16074
16075    #[test]
16076    fn indenting_an_empty_dash_item_under_text_dodges_the_setext_collapse() {
16077        // Tabbing an empty `- ` under a text line would spell `- hello\n  - `,
16078        // which twig (correctly, per CommonMark — pandoc agrees) reparses as a
16079        // setext H2. leaf swaps the dash for a `*` so the item stays an empty
16080        // nested bullet and `hello` stays prose: the file round-trips instead of
16081        // hiding a heading the user never asked for.
16082        for view in [View::Source, View::Wysiwyg] {
16083            let mut d = doc_in(view, "setext_guard", "- hello\n- \n");
16084            d.caret = d.source.find("- \n").unwrap() + 2; // after the empty marker
16085            d.indent();
16086            assert_eq!(d.source, "- hello\n  * \n");
16087            assert!(
16088                d.nodes().iter().all(|n| n.kind != Kind::Heading),
16089                "no heading"
16090            );
16091            // And it's genuinely a nested list, not a flat one.
16092            assert_eq!(
16093                d.nodes()
16094                    .iter()
16095                    .filter(|n| n.kind == Kind::BulletList)
16096                    .count(),
16097                2
16098            );
16099        }
16100    }
16101
16102    #[test]
16103    fn indenting_a_dash_item_with_content_keeps_its_dash() {
16104        // With content, `- x` can't be a setext underline, so there's nothing to
16105        // dodge: the marker stays a dash and nests as an ordinary sub-bullet.
16106        let mut d = doc_in(View::Wysiwyg, "setext_ok", "- hello\n- x\n");
16107        d.caret = d.source.find('x').unwrap();
16108        d.indent();
16109        assert_eq!(d.source, "- hello\n  - x\n");
16110    }
16111
16112    #[test]
16113    fn the_setext_swap_undoes_as_one_step_with_the_indent() {
16114        // The dash→`*` repair coalesces into the Tab, so a single undo restores
16115        // the whole pre-Tab state rather than stranding a half-collapsed doc.
16116        let mut d = doc_in(View::Wysiwyg, "setext_undo", "- hello\n- \n");
16117        d.caret = d.source.find("- \n").unwrap() + 2;
16118        d.indent();
16119        assert_eq!(d.source, "- hello\n  * \n");
16120        d.undo();
16121        assert_eq!(d.source, "- hello\n- \n", "one undo, not two");
16122    }
16123
16124    #[test]
16125    fn indent_leaves_a_nested_lists_first_item_put_too() {
16126        // The guard is about siblings, not depth: the first item of an *inner*
16127        // list (already nested under `a`) still has nothing before it at its own
16128        // level, so Tab can't take it deeper.
16129        let mut d = doc_in(View::Wysiwyg, "indent_first_nested", "- a\n  - b\n  - c\n");
16130        d.caret = d.source.find('b').unwrap();
16131        d.indent();
16132        assert_eq!(d.source, "- a\n  - b\n  - c\n", "inner first item holds");
16133        // But `c` (a sibling of `b`) nests under `b`.
16134        d.caret = d.source.find('c').unwrap();
16135        d.indent();
16136        assert_eq!(d.source, "- a\n  - b\n    - c\n");
16137    }
16138
16139    #[test]
16140    fn backspace_at_a_nested_item_start_outdents_it() {
16141        // Backspace with the caret right after a nested item's marker gives back
16142        // one level of nesting, the mirror of Tab — and renumbers the flattened
16143        // ordered list back to a clean run.
16144        let mut d = doc_in(View::Wysiwyg, "bsp_outdent", "1. a\n   1. b\n2. c\n");
16145        d.caret = d.source.find('b').unwrap(); // start of the nested item's content
16146        d.backspace();
16147        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16148    }
16149
16150    #[test]
16151    fn backspace_at_a_top_level_item_start_strips_the_marker() {
16152        // At the outermost level there's no nesting left to give back, so the same
16153        // keystroke drops the bullet and leaves a plain paragraph.
16154        let mut d = doc_in(View::Wysiwyg, "bsp_strip", "- a\n- b\n");
16155        d.caret = d.source.find('b').unwrap(); // right after `- `
16156        d.backspace();
16157        assert_eq!(d.source, "- a\nb\n", "the marker is gone, the text stays");
16158    }
16159
16160    #[test]
16161    fn backspace_mid_item_still_deletes_a_character() {
16162        // The list behaviour is armed only at the item's content start; anywhere
16163        // else Backspace is the ordinary character delete.
16164        let mut d = doc_in(View::Wysiwyg, "bsp_mid", "- ab\n");
16165        d.caret = d.source.find('b').unwrap(); // between `a` and `b`
16166        d.backspace();
16167        assert_eq!(d.source, "- b\n");
16168    }
16169
16170    #[test]
16171    fn backspace_at_a_heading_start_strips_the_marker() {
16172        // The `# ` is markup the rich view hides, so Backspace over it takes the
16173        // whole marker and leaves a paragraph. Deleting a byte of it instead left
16174        // `#Title` — no longer a heading, with the hash now literal text the user
16175        // never typed and has to delete again.
16176        let mut d = doc_in(View::Wysiwyg, "bsp_head", "## Title\n");
16177        d.caret = d.source.find('T').unwrap(); // right after `## `
16178        d.backspace();
16179        assert_eq!(d.source, "Title\n");
16180        assert_eq!(
16181            d.caret, 0,
16182            "the caret stays with the text it was in front of"
16183        );
16184    }
16185
16186    #[test]
16187    fn backspace_at_a_heading_start_keeps_the_block_around_it() {
16188        // Only the heading's own marker goes — the quote (or list) it sits in is
16189        // untouched, exactly as un-heading it should be.
16190        let mut d = doc_in(View::Wysiwyg, "bsp_head_quote", "> # Title\n");
16191        d.caret = d.source.find('T').unwrap();
16192        d.backspace();
16193        assert_eq!(d.source, "> Title\n");
16194    }
16195
16196    #[test]
16197    fn backspace_at_a_heading_start_takes_its_closing_sequence_too() {
16198        // `# Title #`'s trailing hashes are hidden at the other end; leaving them
16199        // behind would surface the same stray hash the marker delete just avoided.
16200        let mut d = doc_in(View::Wysiwyg, "bsp_head_closed", "# Title #\n");
16201        d.caret = d.source.find('T').unwrap();
16202        d.backspace();
16203        assert_eq!(d.source, "Title\n");
16204        // And it's one edit: a single undo puts the whole heading back.
16205        d.undo();
16206        assert_eq!(d.source, "# Title #\n");
16207    }
16208
16209    #[test]
16210    fn backspace_mid_heading_still_deletes_a_character() {
16211        // The heading behaviour is armed only at the content's start; anywhere
16212        // else Backspace is the ordinary character delete.
16213        let mut d = doc_in(View::Wysiwyg, "bsp_head_mid", "# ab\n");
16214        d.caret = d.source.find('b').unwrap();
16215        d.backspace();
16216        assert_eq!(d.source, "# b\n");
16217    }
16218
16219    #[test]
16220    fn source_view_backspace_still_edits_the_heading_marker_literally() {
16221        // In source view the `# ` is text on the screen the user is deleting a
16222        // byte of, so it keeps its literal meaning — the same split the list
16223        // ladder and Enter draw between the two views.
16224        let mut d = doc_with("bsp_head_src", "# Title\n");
16225        d.caret = d.source.find('T').unwrap();
16226        d.backspace();
16227        assert_eq!(d.source, "#Title\n");
16228    }
16229
16230    #[test]
16231    fn outdent_unnests_an_ordered_item_in_one_press() {
16232        // Shift+Tab gives back exactly the marker width the indent added, so a
16233        // nested ordered item unnests in a single press, and the flattened list
16234        // renumbers back to a clean 1, 2, 3.
16235        let mut d = doc_with("outdent_ord", "1. a\n   2. b\n3. c\n");
16236        d.caret = d.source.find('b').unwrap();
16237        d.outdent();
16238        assert_eq!(d.source, "1. a\n2. b\n3. c\n");
16239        let lists = d
16240            .nodes()
16241            .iter()
16242            .filter(|n| n.kind == Kind::OrderedList)
16243            .count();
16244        assert_eq!(lists, 1, "back to one flat list");
16245    }
16246
16247    #[test]
16248    fn table_insert_row_adds_a_row_below_the_caret() {
16249        let mut d = doc_with("tbl_ins_row", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16250        d.caret = d.source.find('1').unwrap(); // in the body row
16251        d.table_insert_row(true);
16252        assert_eq!(d.source, "| a | b |\n| --- | --- |\n| 1 | 2 |\n|  |  |\n");
16253    }
16254
16255    #[test]
16256    fn table_insert_and_delete_column_at_the_caret() {
16257        let mut d = doc_with("tbl_col", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16258        d.caret = d.source.find('a').unwrap(); // column 0
16259        d.table_insert_column(true); // add a column to the right of `a`
16260        assert_eq!(
16261            d.source,
16262            "| a |  | b |\n| --- | --- | --- |\n| 1 |  | 2 |\n"
16263        );
16264        d.caret = d.source.find('b').unwrap(); // now the third column
16265        d.table_delete_column();
16266        assert_eq!(d.source, "| a |  |\n| --- | --- |\n| 1 |  |\n");
16267    }
16268
16269    // ── ragged formats ───────────────────────────────────────────────────────
16270    // No format spells every gesture. HTML writes the inline marks as a tag pair
16271    // and no heading, list, quote or link; Markdown spells five of the eight
16272    // marks — the highlight only because leaf parses with `highlight`, which is
16273    // why the question is asked with the extensions; djot spells all eight and
16274    // no in-cell break. leaf asks twig per
16275    // gesture (`Doc::supports`) and refuses at the door, rather than letting each
16276    // op discover the fact on its own — one of them didn't.
16277
16278    /// An HTML document in the rich view, ready for a gesture.
16279    fn html_doc(body: &str) -> Doc {
16280        let mut d = Doc::from_source(body.to_string(), Format::Html).unwrap();
16281        d.view = View::Wysiwyg;
16282        d.build_visual(80);
16283        d
16284    }
16285
16286    #[test]
16287    fn a_table_gesture_leaves_an_html_table_alone() {
16288        // The regression this guard exists for. twig's table editor consults no
16289        // `Syntax` table — it spells a grid, not a delimiter — so it rebuilt an
16290        // HTML `<table>` as a *pipe table* and reported success: the whole
16291        // element replaced by `| a | b |`, silently, on one press of a toolbar
16292        // button. Every grid op went the same way.
16293        let src = "<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>\n";
16294        // A table of named operations, which is what it looks like.
16295        #[allow(clippy::type_complexity)]
16296        let ops: [(&str, &dyn Fn(&mut Doc)); 7] = [
16297            ("insert row", &|d: &mut Doc| d.table_insert_row(true)),
16298            ("delete row", &|d: &mut Doc| d.table_delete_row()),
16299            ("insert column", &|d: &mut Doc| d.table_insert_column(true)),
16300            ("delete column", &|d: &mut Doc| d.table_delete_column()),
16301            ("align", &|d: &mut Doc| {
16302                d.table_set_alignment(Alignment::Right)
16303            }),
16304            ("move row", &|d: &mut Doc| d.table_move_row(true)),
16305            ("move column", &|d: &mut Doc| d.table_move_column(true)),
16306        ];
16307        for (name, op) in ops {
16308            let mut d = html_doc(src);
16309            d.caret = d.source.find('a').unwrap();
16310            assert!(d.caret_in_table(), "{name}: the caret really is in a table");
16311            op(&mut d);
16312            assert_eq!(d.source, src, "{name} rewrote an HTML table");
16313            assert!(
16314                !d.dirty,
16315                "{name} marked the document dirty without editing it"
16316            );
16317            assert!(d.status.is_some(), "{name} refused without saying why");
16318        }
16319    }
16320
16321    #[test]
16322    fn the_block_gestures_html_cannot_spell_are_refused_with_a_reason() {
16323        // A task box is a form control in HTML and a footnote has no native
16324        // spelling at all — the two gestures twig 3.5 still spells nothing
16325        // for, now that a quote, a list, a link and an image print through
16326        // its renderer (see the test below).
16327        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16328        // A table of named operations, which is what it looks like.
16329        #[allow(clippy::type_complexity)]
16330        let ops: [(&str, &dyn Fn(&mut Doc)); 3] = [
16331            ("task item", &|d: &mut Doc| d.toggle_task_item()),
16332            ("task tick", &|d: &mut Doc| d.toggle_task_checked()),
16333            ("footnote", &|d: &mut Doc| d.insert_footnote()),
16334        ];
16335        for (name, op) in ops {
16336            let mut d = html_doc(src);
16337            let at = d.source.find("Hello").unwrap();
16338            d.caret = at;
16339            d.anchor = Some(at + 5); // a selection, for the ops that want one
16340            op(&mut d);
16341            assert_eq!(d.source, src, "{name} edited an HTML document");
16342            assert!(
16343                !d.dirty,
16344                "{name} marked the document dirty without editing it"
16345            );
16346            let status = d.status.as_deref().unwrap_or("");
16347            assert!(
16348                status.contains("html"),
16349                "{name}: the refusal should name the format, got {status:?}"
16350            );
16351        }
16352    }
16353
16354    #[test]
16355    fn html_spells_a_quote_a_list_a_link_and_an_image_through_the_renderer() {
16356        // twig 3.5: where HTML has no marker alphabet it prints the fresh
16357        // node — a `<blockquote>` around the paragraph, a `<ul>`/`<ol>` with
16358        // the paragraph as its item, an `<a>` or `<img>` over the selection.
16359        // Until then every one of these was a refusal; now each is a real
16360        // edit, which is what the toolbar's capability flags say too.
16361        let src = "<h1>Title</h1>\n<p>Hello world</p>\n<ul><li>one</li></ul>\n";
16362        #[allow(clippy::type_complexity)]
16363        let ops: [(&str, &dyn Fn(&mut Doc), &str); 5] = [
16364            (
16365                "quote",
16366                &|d: &mut Doc| d.toggle_blockquote(),
16367                "<blockquote>",
16368            ),
16369            ("list", &|d: &mut Doc| d.toggle_list(false), "<ul>\n<li>"),
16370            (
16371                "ordered list",
16372                &|d: &mut Doc| d.toggle_list(true),
16373                "<ol>\n<li>",
16374            ),
16375            (
16376                "link",
16377                &|d: &mut Doc| d.insert_link("https://example.dev"),
16378                "<a href=\"https://example.dev\">Hello</a>",
16379            ),
16380            (
16381                "image",
16382                &|d: &mut Doc| d.insert_image("pic.png", "alt"),
16383                "<img alt=\"Hello\" src=\"pic.png\">",
16384            ),
16385        ];
16386        for (name, op, expect) in ops {
16387            let mut d = html_doc(src);
16388            let at = d.source.find("Hello").unwrap();
16389            d.caret = at;
16390            d.anchor = Some(at + 5);
16391            op(&mut d);
16392            assert!(d.source.contains(expect), "{name}: got {:?}", d.source);
16393            assert!(d.dirty, "{name}: a real edit");
16394            assert_eq!(
16395                d.status, None,
16396                "{name}: a supported gesture reports nothing"
16397            );
16398        }
16399    }
16400
16401    #[test]
16402    fn html_spells_a_heading_as_its_tag_pair() {
16403        // twig 3.4 rebuilds a heading or paragraph as its tag pair, attributes
16404        // along — the one block gesture whose HTML shape it can write. So ⌘2
16405        // in an HTML document is a real edit, and ⌘0 takes it back.
16406        let src = "<h1>Title</h1>\n<p>Hello world</p>\n";
16407        let mut d = html_doc(src);
16408        d.caret = d.source.find("Hello").unwrap();
16409        d.toggle_heading(2);
16410        assert_eq!(d.source, "<h1>Title</h1>\n<h2>Hello world</h2>\n");
16411        assert!(d.dirty);
16412        assert_eq!(d.status, None, "a supported gesture reports nothing");
16413        d.toggle_heading(2);
16414        assert_eq!(d.source, src, "the same level again is back to a paragraph");
16415    }
16416
16417    #[test]
16418    fn html_spells_the_inline_marks_and_the_rule() {
16419        // The other half, and why one per-document flag stopped being enough:
16420        // ⌘B in an HTML document writes `<strong>` — the tag the serializer
16421        // already emits and the parser reads straight back as the same mark —
16422        // and the rule button writes an `<hr>`. Refusing these on the old
16423        // "HTML is parse-only" reading would now be leaf's own limitation.
16424        let mut d = html_doc("<p>Hello world</p>\n");
16425        let at = d.source.find("world").unwrap();
16426        d.caret = at;
16427        d.anchor = Some(at + 5);
16428        d.toggle(InlineKind::Strong);
16429        assert_eq!(d.source, "<p>Hello <strong>world</strong></p>\n");
16430        assert!(d.dirty);
16431        assert_eq!(d.status, None, "a supported gesture reports nothing");
16432
16433        // And off again — the toggle reverses, which is the property that makes
16434        // authoring in HTML worth offering rather than a one-way trip.
16435        d.toggle(InlineKind::Strong);
16436        assert_eq!(d.source, "<p>Hello world</p>\n");
16437
16438        let mut d = html_doc("<p>Hello world</p>\n");
16439        d.caret = d.source.find("world").unwrap();
16440        d.insert_thematic_break();
16441        assert!(d.source.contains("<hr>"), "got {:?}", d.source);
16442    }
16443
16444    #[test]
16445    fn a_mark_the_format_cannot_spell_arms_nothing() {
16446        // `toggle` with a collapsed caret doesn't reach twig at all — it arms a
16447        // sticky mark for the next text typed. Guarding only the twig call
16448        // leaves that path live, promising a mark the gesture will not write and
16449        // then swallowing the error inside `insert`.
16450        //
16451        // Markdown carries this, on the superscript now rather than on the
16452        // highlight: `^x^` is text there in any configuration, whereas twig
16453        // 3.3.1 authors `==x==` for an editor holding the `highlight` extension,
16454        // which every leaf document does.
16455        let mut d = doc_with("mark", "Hello world\n");
16456        d.view = View::Wysiwyg;
16457        d.build_visual(80);
16458        d.caret = d.source.find("world").unwrap();
16459        d.toggle(InlineKind::Superscript);
16460        assert!(d.pending_marks.is_empty(), "no mark should be armed");
16461        assert!(d.status.as_deref().unwrap_or("").contains("markdown"));
16462        d.insert("X");
16463        assert_eq!(d.source, "Hello Xworld\n");
16464    }
16465
16466    #[test]
16467    fn markdown_authors_a_highlight_and_a_strikethrough() {
16468        // twig 3.3.1: the two marks Markdown reads and, until it, refused to
16469        // write. `==x==` is authorable because leaf's own `parse_extensions`
16470        // turns `highlight` on — twig will only mint bytes this editor's reparse
16471        // reads back — and `~~x~~` because GFM strikethrough is parsed by
16472        // default, so the refusal there was never right for any leaf document.
16473        // twig 3.10 adds the underline, spelled `<u>x</u>` and paired back into
16474        // an `insert` under the `html_elements` leaf parses with.
16475        for (kind, marked) in [
16476            (InlineKind::Mark, "a ==word== b\n"),
16477            (InlineKind::Delete, "a ~~word~~ b\n"),
16478            (InlineKind::Insert, "a <u>word</u> b\n"),
16479        ] {
16480            let mut d = doc_with("author_mark", "a word b\n");
16481            d.anchor = Some(2);
16482            d.caret = 6;
16483            d.toggle(kind);
16484            assert_eq!(d.source, marked, "{kind:?}");
16485            assert_eq!(d.status, None, "{kind:?}: a supported gesture is silent");
16486            assert!(d.dirty, "{kind:?}");
16487            // The region stays selected, so the second press reverses it — the
16488            // property that separates authoring from a one-way trip.
16489            d.toggle(kind);
16490            assert_eq!(d.source, "a word b\n", "{kind:?}");
16491        }
16492    }
16493
16494    #[test]
16495    fn an_authored_highlight_reads_back_as_a_mark() {
16496        // The round trip the extension gate exists to protect: what the toggle
16497        // writes, the reparse must read back as a `mark` rather than as two
16498        // literal `=` pairs. A `Role::Mark` glyph is that answer, taken from the
16499        // rebuilt map rather than from the source text.
16500        let mut d = doc_with("mark_roundtrip", "a word b\n");
16501        d.view = View::Wysiwyg;
16502        d.build_visual(80);
16503        d.anchor = Some(2);
16504        d.caret = 6;
16505        d.toggle(InlineKind::Mark);
16506        assert_eq!(d.source, "a ==word== b\n");
16507        d.build_visual(80);
16508        let w = d
16509            .vmap
16510            .rows
16511            .iter()
16512            .flat_map(|r| r.glyphs.iter())
16513            .find(|g| g.ch == 'w')
16514            .expect("the highlighted word");
16515        assert_eq!(w.style.role, crate::Role::Mark(None));
16516    }
16517
16518    #[test]
16519    fn an_authored_underline_reads_back_as_an_insert() {
16520        // The same round trip for `<u>…</u>`: under `html_elements` the tag pair
16521        // is one `insert`, so the word is underlined and the tags are markup the
16522        // caret-off line hides — not two `raw_inline` runs drawn as literal
16523        // HTML around plain text.
16524        let mut d = doc_with("underline_roundtrip", "a word b\nnext\n");
16525        d.view = View::Wysiwyg;
16526        d.build_visual(80);
16527        d.anchor = Some(2);
16528        d.caret = 6;
16529        d.toggle(InlineKind::Insert);
16530        assert_eq!(d.source, "a <u>word</u> b\nnext\n");
16531        d.anchor = None;
16532        d.caret = d.source.find("next").unwrap();
16533        d.build_visual(80);
16534        let glyphs: Vec<_> = d.vmap.rows.iter().flat_map(|r| r.glyphs.iter()).collect();
16535        let w = glyphs
16536            .iter()
16537            .find(|g| g.ch == 'w')
16538            .expect("the underlined word");
16539        assert!(w.style.underline);
16540        assert!(!glyphs.iter().any(|g| g.ch == '<'), "the tags are hidden");
16541    }
16542
16543    #[test]
16544    fn a_highlight_takes_a_colour_changes_it_and_gives_it_back() {
16545        // The three states of one gesture, in the order a palette is pressed:
16546        // an uncoloured highlight takes the prefix, a coloured one has it
16547        // replaced, and `None` takes it away with the space that was part of the
16548        // spelling.
16549        let mut d = doc_with("mark_colour", "a ==word== b\n");
16550        d.caret = d.source.find("word").unwrap();
16551        d.set_mark_color(Some(MarkColor::Red));
16552        assert_eq!(d.source, "a ==🔴 word== b\n");
16553        assert_eq!(d.status, None);
16554        assert!(d.dirty);
16555
16556        d.set_mark_color(Some(MarkColor::Blue));
16557        assert_eq!(d.source, "a ==🔵 word== b\n");
16558
16559        d.set_mark_color(None);
16560        assert_eq!(d.source, "a ==word== b\n");
16561    }
16562
16563    #[test]
16564    fn the_caret_keeps_its_place_in_the_text_across_a_colour() {
16565        // The prefix is written *before* the word, so an offset in the word has
16566        // to ride its width — a caret that stayed put would be a caret that
16567        // walked backwards through the text it was standing in.
16568        let mut d = doc_with("mark_colour_caret", "a ==word== b\n");
16569        let word = d.source.find("word").unwrap();
16570        d.caret = word + 2; // between `wo` and `rd`
16571        d.set_mark_color(Some(MarkColor::Red));
16572        assert_eq!(&d.source[d.caret..d.caret + 2], "rd", "still before `rd`");
16573
16574        // And back the other way when the prefix goes.
16575        d.set_mark_color(None);
16576        assert_eq!(&d.source[d.caret..d.caret + 2], "rd");
16577    }
16578
16579    #[test]
16580    fn the_colour_at_the_caret_is_what_the_palette_lights() {
16581        let mut d = doc_with("mark_colour_read", "a ==🔴 red== and ==plain== b\n");
16582        d.caret = d.source.find("red").unwrap();
16583        assert!(d.caret_in_mark());
16584        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Red));
16585
16586        d.caret = d.source.find("plain").unwrap();
16587        assert!(d.caret_in_mark(), "a highlight with no colour is still one");
16588        assert_eq!(d.mark_color_at_caret(), None);
16589
16590        d.caret = d.source.find(" and ").unwrap() + 2;
16591        assert!(!d.caret_in_mark());
16592        assert_eq!(d.mark_color_at_caret(), None);
16593    }
16594
16595    #[test]
16596    fn a_colour_without_a_highlight_says_so_and_writes_nothing() {
16597        // The gesture colours a highlight that exists; it does not make one.
16598        // Two presses is the price of a coloured highlight from bare text, and
16599        // the reason is undo — one press that spliced twice would take two
16600        // presses to take back.
16601        let mut d = doc_with("mark_colour_none", "a word b\n");
16602        d.caret = d.source.find("word").unwrap();
16603        d.set_mark_color(Some(MarkColor::Red));
16604        assert_eq!(d.source, "a word b\n");
16605        assert!(d.status.is_some(), "it should say why");
16606        assert!(!d.dirty);
16607
16608        // Clearing where there is nothing to clear is the same refusal, not a
16609        // quiet success — the caret is in no highlight either way.
16610        d.status = None;
16611        d.set_mark_color(None);
16612        assert_eq!(d.source, "a word b\n");
16613        assert!(d.status.is_some());
16614    }
16615
16616    #[test]
16617    fn clearing_an_uncoloured_highlight_is_a_quiet_no_op() {
16618        // twig answers this one *successfully* with a `Change` describing some
16619        // earlier edit, so a caller that trusted the change would jump the caret
16620        // to wherever that was. Core answers it before asking.
16621        let mut d = doc_with("mark_colour_noop", "a ==word== b\n");
16622        d.toggle(InlineKind::Strong); // an earlier edit for a stale change to name
16623        d.caret = d.source.find("word").unwrap();
16624        let (source, caret) = (d.source.clone(), d.caret);
16625        d.set_mark_color(None);
16626        assert_eq!(d.source, source);
16627        assert_eq!(
16628            d.caret, caret,
16629            "the caret must not ride a change that isn't one"
16630        );
16631        assert_eq!(d.status, None, "and it is not an error either");
16632    }
16633
16634    #[test]
16635    fn djot_spells_the_highlight_and_not_its_colour() {
16636        // The reason the palette is its own capability rather than the Highlight
16637        // button's: `{=word=}` is a highlight djot writes happily, and there is
16638        // no djot spelling for a colour on it.
16639        assert!(Capabilities::of(Format::Djot).mark);
16640        assert!(!Capabilities::of(Format::Djot).mark_color);
16641        assert!(Capabilities::of(Format::Markdown).mark_color);
16642
16643        let mut d = Doc::from_source("a {=word=} b\n".into(), Format::Djot).unwrap();
16644        d.caret = d.source.find("word").unwrap();
16645        assert!(
16646            d.caret_in_mark(),
16647            "the caret is in a highlight all the same"
16648        );
16649        d.set_mark_color(Some(MarkColor::Red));
16650        assert_eq!(d.source, "a {=word=} b\n");
16651        assert!(
16652            d.status.as_deref().unwrap_or("").contains("djot"),
16653            "and the refusal names the document's format: {:?}",
16654            d.status
16655        );
16656    }
16657
16658    #[test]
16659    fn a_coloured_highlight_is_one_undo_step_and_reads_back_as_its_colour() {
16660        // The round trip that matters for a palette: the bytes twig writes are
16661        // bytes its own reparse reads back as a colour, so the swatch that was
16662        // pressed is the swatch that lights afterwards.
16663        let mut d = doc_with("mark_colour_undo", "a word b\n");
16664        d.anchor = Some(2);
16665        d.caret = 6;
16666        d.toggle(InlineKind::Mark);
16667        d.caret = d.source.find("word").unwrap();
16668        d.set_mark_color(Some(MarkColor::Green));
16669        assert_eq!(d.source, "a ==🟢 word== b\n");
16670        assert_eq!(d.mark_color_at_caret(), Some(MarkColor::Green));
16671
16672        // One splice, one step: the colour comes off and the highlight stays.
16673        d.undo();
16674        assert_eq!(d.source, "a ==word== b\n");
16675        d.undo();
16676        assert_eq!(d.source, "a word b\n");
16677    }
16678
16679    #[test]
16680    fn every_colour_leaf_names_is_one_twig_writes() {
16681        // The two enums are one vocabulary, and this is what says so: each of
16682        // leaf's colours writes an emoji twig's reparse reads back as *that*
16683        // colour, so `twig_mark_color`'s table cannot quietly pair red with
16684        // orange.
16685        for color in MarkColor::ALL {
16686            let mut d = doc_with("mark_colour_all", "a ==word== b\n");
16687            d.caret = d.source.find("word").unwrap();
16688            d.set_mark_color(Some(color));
16689            assert_eq!(d.status, None, "{color:?}");
16690            assert_eq!(d.mark_color_at_caret(), Some(color), "{color:?}");
16691        }
16692    }
16693
16694    #[test]
16695    fn a_fresh_highlight_takes_a_colour_without_moving_the_caret_first() {
16696        // The two presses a coloured highlight is made of, in the state the
16697        // first one leaves: `toggle` selects the whole `==word==` and puts the
16698        // caret one past the closing `==`, which is *not* in the mark. Asking at
16699        // the caret alone would refuse to colour the highlight just written —
16700        // the selection's start is what answers.
16701        let mut d = doc_with("mark_colour_fresh", "a word b\n");
16702        d.anchor = Some(2);
16703        d.caret = 6;
16704        d.toggle(InlineKind::Mark);
16705        assert_eq!(d.source, "a ==word== b\n");
16706        assert_eq!(d.caret, 10, "the caret twig leaves, past the closing `==`");
16707
16708        assert!(d.caret_in_mark(), "the selected highlight is the one meant");
16709        d.set_mark_color(Some(MarkColor::Yellow));
16710        assert_eq!(d.source, "a ==🟡 word== b\n");
16711        assert_eq!(d.status, None);
16712    }
16713
16714    #[test]
16715    fn one_press_highlights_a_selection_and_colours_it() {
16716        // What a toolbar swatch means over a plain selection, and the undo it
16717        // has to have: one press, one step. Two steps would leave an uncoloured
16718        // highlight behind on the way back, which is a state the author never
16719        // asked for and never saw.
16720        let mut d = doc_with("highlight_one", "a word b\n");
16721        d.anchor = Some(2);
16722        d.caret = 6;
16723        d.highlight(Some(MarkColor::Purple));
16724        assert_eq!(d.source, "a ==\u{1F7E3} word== b\n");
16725        assert_eq!(d.status, None);
16726
16727        d.undo();
16728        assert_eq!(d.source, "a word b\n", "one press, one undo");
16729    }
16730
16731    #[test]
16732    fn one_press_on_an_existing_highlight_only_recolours_it() {
16733        // The other half: inside a highlight there is nothing to make, so the
16734        // compound is the plain gesture and the text is untouched.
16735        let mut d = doc_with("highlight_recolour", "a ==\u{1F534} word== b\n");
16736        d.caret = d.source.find("word").unwrap();
16737        d.highlight(Some(MarkColor::Blue));
16738        assert_eq!(d.source, "a ==\u{1F535} word== b\n");
16739        d.undo();
16740        assert_eq!(d.source, "a ==\u{1F534} word== b\n", "the highlight stays");
16741    }
16742
16743    #[test]
16744    fn one_press_with_no_colour_over_a_selection_just_highlights_it() {
16745        // `None` means "no colour", and over bare text that is the Highlight
16746        // button's own job. The fold must not happen here — there is no second
16747        // splice, and folding would take the *previous* edit into this one.
16748        let mut d = doc_with("highlight_none", "a word b and more\n");
16749        d.caret = d.source.find("more").unwrap() + 4; // after "more"
16750        d.insert("!"); // an earlier edit for a wrong fold to swallow
16751        d.anchor = Some(2);
16752        d.caret = 6;
16753        d.highlight(None);
16754        assert_eq!(d.source, "a ==word== b and more!\n");
16755
16756        d.undo();
16757        assert_eq!(
16758            d.source, "a word b and more!\n",
16759            "only the highlight came off"
16760        );
16761        d.undo();
16762        assert_eq!(
16763            d.source, "a word b and more\n",
16764            "and the edit before it survived"
16765        );
16766    }
16767
16768    #[test]
16769    fn one_press_at_a_bare_caret_in_no_highlight_writes_nothing() {
16770        // `toggle` at a collapsed caret arms a mark for text not yet typed, and
16771        // a colour cannot be armed with it — so the compound declines rather
16772        // than leaving half a promise.
16773        let mut d = doc_with("highlight_bare", "a word b\n");
16774        d.caret = 4;
16775        d.highlight(Some(MarkColor::Red));
16776        assert_eq!(d.source, "a word b\n");
16777        assert!(d.pending_marks.is_empty(), "and nothing armed");
16778        assert!(d.status.is_some());
16779    }
16780
16781    #[test]
16782    fn a_read_only_document_takes_no_colour() {
16783        let mut d = doc_with("mark_colour_ro", "a ==word== b\n");
16784        d.caret = d.source.find("word").unwrap();
16785        d.set_read_only(true);
16786        d.set_mark_color(Some(MarkColor::Red));
16787        assert_eq!(d.source, "a ==word== b\n");
16788    }
16789
16790    #[test]
16791    fn a_sticky_highlight_wraps_the_next_typed_text_in_markdown() {
16792        // The other door into `toggle`: no selection, so nothing reaches twig
16793        // until `insert` realises the armed mark. It is armed now — the guard
16794        // above asks `Doc::supports`, which asks with the extensions — and what
16795        // it writes is the same `==…==`.
16796        let mut d = doc_with("sticky_mark", "xy\n");
16797        d.caret = 1;
16798        d.toggle(InlineKind::Mark);
16799        assert!(d.pending_marks.contains(InlineKind::Mark));
16800        d.insert("Z");
16801        assert_eq!(d.source, "x==Z==y\n");
16802    }
16803
16804    #[test]
16805    fn html_documents_still_take_typed_text() {
16806        // The guard covers *markup* gestures and must not touch plain editing:
16807        // twig's splicer is language-neutral, and typing into an HTML document
16808        // is the thing that does work today.
16809        let mut d = html_doc("<p>Hello world</p>\n");
16810        d.caret = d.source.find("world").unwrap();
16811        d.insert("big ");
16812        assert_eq!(d.source, "<p>Hello big world</p>\n");
16813        assert!(d.dirty);
16814        d.backspace();
16815        assert_eq!(d.source, "<p>Hello bigworld</p>\n");
16816        d.undo();
16817        d.undo();
16818        assert_eq!(d.source, "<p>Hello world</p>\n");
16819    }
16820
16821    #[test]
16822    fn authorable_is_the_coarse_question_and_capabilities_the_useful_one() {
16823        // `authorable` only separates "there is a door in" from "there is not",
16824        // and HTML is on the near side of that line — which is exactly why a
16825        // toolbar must not be built from it.
16826        let html = Doc::from_source("<p>x</p>\n".into(), Format::Html).unwrap();
16827        assert!(html.authorable());
16828        assert!(
16829            !Doc::from_source("<r>x</r>".into(), Format::Xml)
16830                .unwrap()
16831                .authorable()
16832        );
16833
16834        let caps = html.capabilities();
16835        assert!(caps.bold && caps.italic && caps.code && caps.mark);
16836        assert!(caps.thematic_break && caps.cell_line_break);
16837        // A heading is a tag pair twig rebuilds (3.4), and since 3.5 so are a
16838        // quote, a list, a code block's language, a link and an image — each
16839        // printed as a fresh node where HTML has no marker to rewrite. A task
16840        // box is a form control and a footnote has no spelling, so those two
16841        // are what keeps the record ragged.
16842        assert!(caps.heading && caps.blockquote && caps.bullet_list);
16843        assert!(caps.link && caps.image && caps.code_language);
16844        assert!(!caps.task && !caps.footnote);
16845        // The one flag that isn't twig's answer: an HTML `<table>` is a grid
16846        // twig's table editor would happily re-emit as `| a | b |`.
16847        assert!(!caps.table);
16848
16849        // The two lightweight formats spell everything leaf offers — and still
16850        // differ from each other, which is the other half of why one boolean
16851        // can't serve.
16852        for fmt in [Format::Markdown, Format::Djot] {
16853            let caps = Capabilities::of(fmt);
16854            assert!(
16855                caps.heading && caps.blockquote && caps.ordered_list,
16856                "{fmt:?}"
16857            );
16858            assert!(
16859                caps.task && caps.link && caps.image && caps.table,
16860                "{fmt:?}"
16861            );
16862        }
16863        // Both spell the highlight, the strikethrough and the underline: djot
16864        // natively, and Markdown because `Capabilities` asks with
16865        // `parse_extensions` rather than with twig's defaults — `==x==` is text
16866        // under those, and a mark under the `highlight` leaf always parses
16867        // with; `<u>x</u>` likewise pairs into an `insert` only under
16868        // `html_elements`.
16869        for fmt in [Format::Markdown, Format::Djot] {
16870            let caps = Capabilities::of(fmt);
16871            assert!(caps.mark && caps.strike && caps.underline, "{fmt:?}");
16872        }
16873        // What still separates them, now that the highlight doesn't: djot has
16874        // no in-cell break, and Markdown spells neither of the scripts.
16875        assert!(Capabilities::of(Format::Djot).superscript);
16876        assert!(!Capabilities::of(Format::Markdown).superscript);
16877        assert!(Capabilities::of(Format::Markdown).cell_line_break);
16878        assert!(!Capabilities::of(Format::Djot).cell_line_break);
16879
16880        // A parse-only format answers no to every one of them, so the coarse
16881        // predicate and the record agree there.
16882        let caps = Capabilities::of(Format::Xml);
16883        assert!(!caps.bold && !caps.heading && !caps.table && !caps.thematic_break);
16884    }
16885
16886    #[test]
16887    fn a_refused_gesture_says_so_where_twig_would_have_said_it() {
16888        // The guard exists to name the *document's* format rather than twig's
16889        // internals, so the message has to survive being one leaf writes itself.
16890        // Checked against a gesture twig also refuses, since that is the pair
16891        // most at risk of drifting apart — the task box, once the code
16892        // language stopped being one (twig 3.5).
16893        let mut d = html_doc("<p>Hello</p>\n");
16894        d.caret = d.source.find("Hello").unwrap();
16895        d.toggle_task_item();
16896        assert_eq!(d.status.as_deref(), Some("task: not supported in html"));
16897        assert!(!d.dirty);
16898    }
16899
16900    #[test]
16901    fn table_set_alignment_respells_the_delimiter() {
16902        let mut d = doc_with("tbl_align", "| a | b |\n| --- | --- |\n| 1 | 2 |\n");
16903        d.caret = d.source.find('b').unwrap();
16904        d.table_set_alignment(Alignment::Right);
16905        assert_eq!(d.source, "| a | b |\n| --- | ---: |\n| 1 | 2 |\n");
16906    }
16907
16908    #[test]
16909    fn each_empty_table_cell_has_its_own_editable_home() {
16910        // Regression: an empty cell has no twig content_span, so both cells of a
16911        // `|  |  |` row collapsed onto the row's start (before the first `│`).
16912        // Typing there inserted *before* the table (`hello|  |  |`); nav couldn't
16913        // tell the cells apart. Each empty cell must now have a distinct home
16914        // inside it.
16915        let mut d = wysiwyg_doc("tbl_empty", "| a | b |\n| --- | --- |\n|  |  |\n");
16916        let (c0, c1) = {
16917            let cells = &d.vmap.tables[0].grid[1].cells;
16918            (cells[0].start, cells[1].start)
16919        };
16920        assert!(
16921            c0 < c1,
16922            "the two empty cells have distinct homes: {c0} < {c1}"
16923        );
16924        d.caret = c0;
16925        d.insert("x");
16926        assert_eq!(
16927            d.source, "| a | b |\n| --- | --- |\n| x |  |\n",
16928            "typed inside the cell"
16929        );
16930    }
16931
16932    #[test]
16933    fn arrows_step_into_each_empty_table_cell() {
16934        let mut d = wysiwyg_doc("tbl_empty_nav", "| a | b |\n| --- | --- |\n|  |  |\n");
16935        let (c0, c1) = {
16936            let cells = &d.vmap.tables[0].grid[1].cells;
16937            (cells[0].start, cells[1].start)
16938        };
16939        d.caret = d.source.find('b').unwrap(); // in the header's second cell
16940        let mut seen = std::collections::HashSet::new();
16941        for _ in 0..6 {
16942            d.move_right(false);
16943            seen.insert(d.caret);
16944        }
16945        assert!(
16946            seen.contains(&c0),
16947            "right arrow reaches the first empty cell"
16948        );
16949        assert!(
16950            seen.contains(&c1),
16951            "right arrow reaches the second empty cell"
16952        );
16953    }
16954
16955    #[test]
16956    fn table_op_off_a_table_is_a_no_op_with_a_status() {
16957        let mut d = doc_with("tbl_none", "just text\n");
16958        d.caret = 3;
16959        d.table_insert_row(true);
16960        assert_eq!(d.source, "just text\n", "nothing changed");
16961        assert!(d.status.is_some(), "a status explains why");
16962        assert!(!d.caret_in_table());
16963    }
16964
16965    #[test]
16966    fn enter_in_an_ordered_list_renumbers_the_following_items() {
16967        // Inserting an item mid-list left the source markers stale (`1. 2. 2. 3.`);
16968        // the renumber pass keeps them sequential, matching what the view draws.
16969        let mut d = wysiwyg_doc("enter_renumber", "1. a\n2. b\n3. c\n");
16970        d.caret = d.source.find('a').unwrap() + 1; // end of item a
16971        d.newline();
16972        d.insert("x");
16973        assert_eq!(d.source, "1. a\n2. x\n3. b\n4. c\n");
16974    }
16975
16976    #[test]
16977    fn outdent_with_nothing_to_give_back_records_no_undo_step() {
16978        for view in [View::Source, View::Wysiwyg] {
16979            let mut d = doc_in(view, "outdent_noop", "hello\n");
16980            d.caret = 2;
16981            d.outdent();
16982            assert_eq!(d.source, "hello\n");
16983            assert!(!d.dirty, "a no-op is not a modification");
16984            d.undo();
16985            assert_eq!(
16986                d.status.as_deref(),
16987                Some("nothing to undo"),
16988                "spends no undo step"
16989            );
16990            assert_eq!(d.source, "hello\n");
16991        }
16992    }
16993
16994    #[test]
16995    fn indent_shifts_every_selected_line_and_keeps_them_selected() {
16996        for view in [View::Source, View::Wysiwyg] {
16997            let mut d = doc_in(view, "indent_sel", "one\n\ntwo\n");
16998            d.anchor = Some(0);
16999            d.caret = 7; // through "two"
17000            d.indent();
17001            assert_eq!(
17002                d.source, "  one\n\n  two\n",
17003                "the blank line keeps no trailing pad"
17004            );
17005            // Selected, so a second Tab lands on the same lines rather than on
17006            // whatever the shifted offsets now cover.
17007            assert_eq!(d.selection(), Some((0, 12)));
17008            d.indent();
17009            assert_eq!(d.source, "    one\n\n    two\n");
17010        }
17011    }
17012
17013    #[test]
17014    fn outdent_takes_what_each_line_has_and_leaves_the_rest_alone() {
17015        for view in [View::Source, View::Wysiwyg] {
17016            let mut d = doc_in(view, "outdent_sel", "  two\n one\nnone\n");
17017            d.anchor = Some(0);
17018            d.caret = 15;
17019            d.outdent();
17020            assert_eq!(d.source, "two\none\nnone\n");
17021        }
17022    }
17023
17024    #[test]
17025    fn a_tab_undoes_as_one_step_however_many_lines_it_moved() {
17026        for view in [View::Source, View::Wysiwyg] {
17027            let mut d = doc_in(view, "indent_undo", "one\n\ntwo\n");
17028            d.anchor = Some(0);
17029            d.caret = 7;
17030            d.indent();
17031            assert_eq!(d.source, "  one\n\n  two\n");
17032            d.undo();
17033            assert_eq!(d.source, "one\n\ntwo\n", "one step, not one per line");
17034            assert_eq!(
17035                d.selection(),
17036                Some((0, 7)),
17037                "with the selection it was aimed at"
17038            );
17039            d.redo();
17040            assert_eq!(d.source, "  one\n\n  two\n");
17041            assert_eq!(
17042                d.selection(),
17043                Some((0, 12)),
17044                "redo replays the caret the indent placed, not the one splice left"
17045            );
17046        }
17047    }
17048
17049    #[test]
17050    fn vertical_motion_keeps_the_column() {
17051        let mut d = doc_with("move", "abcd\nef\n");
17052        d.caret = 3; // "abc|d" on row 0, col 3
17053        d.move_down(false); // row 1 "ef" only has cols 0..2 -> clamps to end
17054        assert_eq!(d.caret, 7); // just after "ef"
17055    }
17056
17057    // ── goal column ──────────────────────────────────────────────────────────
17058
17059    #[test]
17060    fn vertical_motion_goal_column_survives_a_short_line() {
17061        // Regression: re-deriving the column from the clamped position on
17062        // every step permanently forgets it once a short line clamps it.
17063        // Down through "xy" (2 cols) and into "ghijkl" must return to col 4.
17064        let g = |m, f: fn(&mut Doc)| golden("goalcol", m, f);
17065        assert_eq!(
17066            g("abcd|ef\nxy\nghijkl\n", |d| {
17067                d.move_down(false); // clamps to end of "xy"
17068                d.move_down(false); // restores col 4 on the long line
17069            }),
17070            "abcdef\nxy\nghij|kl\n"
17071        );
17072    }
17073
17074    #[test]
17075    fn goal_column_state_is_set_by_vertical_motion_and_cleared_by_horizontal() {
17076        let mut d = doc_with("goalcol_state", "abcdef\nxy\nghijkl\n");
17077        assert_eq!(d.goal_col, None);
17078        d.caret = 4; // row 0, col 4
17079        d.move_down(false); // clamps into "xy"; goal stays the original col
17080        assert_eq!(d.goal_col, Some(4));
17081        assert_eq!(d.caret_pos(), (1, 2));
17082
17083        // A horizontal motion drops the goal column...
17084        d.move_left(false);
17085        assert_eq!(d.goal_col, None);
17086
17087        // ...so the next vertical motion picks up the *new* column (1), not
17088        // the stale one (4).
17089        d.move_down(false);
17090        assert_eq!(d.goal_col, Some(1));
17091        assert_eq!(d.caret_pos(), (2, 1));
17092    }
17093
17094    #[test]
17095    fn editing_clears_the_goal_column() {
17096        let mut d = doc_with("goalcol_edit", "abcdef\nxy\nghijkl\n");
17097        d.caret = 4;
17098        d.move_down(false);
17099        assert_eq!(d.goal_col, Some(4));
17100        d.insert("Z");
17101        assert_eq!(d.goal_col, None);
17102    }
17103
17104    #[test]
17105    fn vertical_motion_on_an_empty_document_is_a_no_op() {
17106        let mut d = doc_with("empty_vert", "");
17107        d.move_down(false);
17108        assert_eq!(d.caret, 0);
17109        d.move_up(false);
17110        assert_eq!(d.caret, 0);
17111    }
17112
17113    // ── the document's edges ─────────────────────────────────────────────────
17114
17115    #[test]
17116    fn vertical_motion_at_the_document_edges_runs_to_them_in_both_views() {
17117        // The reproduction, and the disagreement: Down on the last line ran to
17118        // the end of the document in the source view — by accident, an
17119        // out-of-range row clamping to the end of the string — and did nothing
17120        // whatever in the view leaf opens in. One rule now, in both.
17121        for (view, tag) in VIEWS {
17122            let mut d = doc_in(view, &format!("edge_{tag}"), "abc");
17123            d.caret = 1;
17124            d.move_down(false);
17125            assert_eq!(d.caret, 3, "{tag}: Down on the last line runs to the end");
17126            d.move_up(false);
17127            assert_eq!(d.caret, 0, "{tag}: Up on the first line runs to the start");
17128        }
17129    }
17130
17131    #[test]
17132    fn vertical_motion_at_the_edges_carries_the_column_across_the_lines_between() {
17133        // Down off the bottom is a motion like any other, so it latches a goal
17134        // column — and Up comes back to the column the caret left, not to the
17135        // one the document's end happened to be in.
17136        for (view, tag) in VIEWS {
17137            let gap = if view == View::Source { "\n" } else { "\n\n" };
17138            let src = format!("abcdef{gap}ghijkl");
17139            let mut d = doc_in(view, &format!("edge_goal_{tag}"), &src);
17140            d.caret = 2; // row 0, col 2
17141            d.move_down(false);
17142            assert_eq!(d.caret_pos().1, 2, "{tag}: Down keeps the column");
17143            d.move_down(false);
17144            assert_eq!(
17145                d.caret,
17146                src.len(),
17147                "{tag}: Down off the bottom reaches the end"
17148            );
17149            d.move_up(false);
17150            assert_eq!(
17151                d.caret_pos().1,
17152                2,
17153                "{tag}: Up returns to the column Down left"
17154            );
17155        }
17156    }
17157
17158    #[test]
17159    fn vertical_motion_with_nowhere_to_go_latches_no_goal_column() {
17160        // `goal_col.get_or_insert` ran *before* the early return at row 0, so an
17161        // Up that did nothing still armed a goal column, and the next Down aimed
17162        // at a column the caret had never been in.
17163        for (view, tag) in VIEWS {
17164            let mut d = doc_in(view, &format!("noop_goal_{tag}"), "abc\n\ndef");
17165            d.caret = 0;
17166            d.move_up(false);
17167            assert_eq!(d.caret, 0, "{tag}: already at the start");
17168            assert_eq!(d.goal_col, None, "{tag}: a no-op Up latched a goal column");
17169
17170            d.caret = d.source.len();
17171            d.move_down(false);
17172            assert_eq!(d.caret, d.source.len(), "{tag}: already at the end");
17173            assert_eq!(
17174                d.goal_col, None,
17175                "{tag}: a no-op Down latched a goal column"
17176            );
17177        }
17178    }
17179
17180    // ── soft wrap ────────────────────────────────────────────────────────────
17181    // Every other test here builds the map at 80 columns, where no fixture is
17182    // long enough to fold. A wrap is where one offset belongs to two rows at
17183    // once, and it broke everything that asks the caret what row it is on.
17184
17185    /// The wrapped fixture these cases share, folded at 12 columns into
17186    /// `one two ` / `three four ` / `five six ` / `seven eight`.
17187    fn wrapped_doc(name: &str) -> Doc {
17188        let mut d = wysiwyg_doc(name, "one two three four five six seven eight");
17189        d.build_visual(12);
17190        d
17191    }
17192
17193    #[test]
17194    fn home_and_end_work_from_a_wrapped_row() {
17195        // The reproduction: offset 19 is the `f` of "five", the first character
17196        // of the third row — and also the offset the second row ends at. It
17197        // resolved to the *second* row, so End aimed at a place the caret was
17198        // already in and did nothing, while Home walked backwards onto a row the
17199        // caret had left.
17200        let mut d = wrapped_doc("wrap_home_end");
17201        d.caret = 19;
17202        assert_eq!(
17203            d.caret_pos(),
17204            (2, 0),
17205            "the wrap boundary opens the third row"
17206        );
17207        d.move_end(false);
17208        assert_eq!(d.caret, 27, "End stalled at the wrap boundary");
17209        d.move_home(false);
17210        assert_eq!(d.caret, 19, "Home left the row the caret was on");
17211    }
17212
17213    #[test]
17214    fn end_of_a_wrapped_row_stays_put_when_pressed_again() {
17215        // The row's end is the last offset that is only ever its own: the offset
17216        // past it opens the row below, and aiming there would send a second
17217        // press on to *that* row's end, and a third to the next — End walking
17218        // down the paragraph rather than sitting where it landed.
17219        let mut d = wrapped_doc("wrap_end_twice");
17220        d.caret = 12; // inside "three", on the second row
17221        d.move_end(false);
17222        assert_eq!(
17223            d.caret, 18,
17224            "the end of `three four`, before the space the wrap ate"
17225        );
17226        assert_eq!(d.caret_pos(), (1, 10), "drawn on the row it is the end of");
17227        d.move_end(false);
17228        assert_eq!(d.caret, 18, "a second End moved the caret");
17229        d.move_home(false);
17230        assert_eq!(d.caret, 8, "Home takes the row's own start");
17231    }
17232
17233    #[test]
17234    fn vertical_motion_crosses_a_soft_wrap() {
17235        // Down aimed at the row below's column 0, an offset that resolved *up*
17236        // to the row above's end — so it landed on the offset it already had and
17237        // the caret could never leave a paragraph's first row.
17238        let mut d = wrapped_doc("wrap_down");
17239        d.caret = 0;
17240        for (want, row) in [(8, 1), (19, 2), (28, 3), (39, 3)] {
17241            d.move_down(false);
17242            assert_eq!(d.caret, want, "Down stalled");
17243            assert_eq!(d.caret_pos().0, row, "Down landed on the wrong row");
17244        }
17245        d.move_down(false);
17246        assert_eq!(d.caret, 39, "the last row's Down runs to the end and stops");
17247
17248        // ...and back up, one row per press. The goal column is the end of the
17249        // last row, past every other row's width, so each press clamps to the
17250        // row's own last offset rather than to the one that opens the next.
17251        let mut d = wrapped_doc("wrap_up");
17252        d.caret = 39;
17253        for (want, pos) in [(27, (2, 8)), (18, (1, 10)), (7, (0, 7)), (0, (0, 0))] {
17254            d.move_up(false);
17255            assert_eq!(d.caret, want, "Up stalled");
17256            assert_eq!(d.caret_pos(), pos, "Up landed on the wrong row");
17257        }
17258    }
17259
17260    #[test]
17261    fn a_kill_on_a_wrapped_row_stops_at_the_row() {
17262        // The kills take the same line Home and End do, so in WYSIWYG they take
17263        // the visual row — and a soft wrap has no newline in it to delete, so
17264        // nothing is joined by reaching the end of one.
17265        let mut d = wrapped_doc("wrap_kill");
17266        d.caret = 19; // the `f` of "five", opening the third row
17267        d.delete_to_line_end();
17268        // The space the wrap ate goes with the row it was drawn on: sparing it
17269        // would leave "four  seven", two spaces where the row had been.
17270        assert_eq!(d.source, "one two three four seven eight");
17271
17272        // Backwards from the row's last caret position — which is *before* that
17273        // space, so this one survives, being on the far side of the caret.
17274        let mut d = wrapped_doc("wrap_kill_back");
17275        d.caret = 27;
17276        d.delete_to_line_start();
17277        assert_eq!(d.source, "one two three four  seven eight");
17278    }
17279
17280    // ── document start / end ────────────────────────────────────────────────
17281
17282    #[test]
17283    fn move_doc_start_and_end_jump_to_the_edges() {
17284        let g = |m, f: fn(&mut Doc)| golden("doc_edges", m, f);
17285        assert_eq!(
17286            g("hello\nwor|ld\n", |d| d.move_doc_start(false)),
17287            "|hello\nworld\n"
17288        );
17289        assert_eq!(
17290            g("hel|lo\nworld\n", |d| d.move_doc_end(false)),
17291            "hello\nworld\n|"
17292        );
17293        // Already at the edge: a no-op.
17294        assert_eq!(g("|hello\n", |d| d.move_doc_start(false)), "|hello\n");
17295        assert_eq!(g("hello|\n", |d| d.move_doc_end(false)), "hello\n|");
17296    }
17297
17298    #[test]
17299    fn move_doc_start_and_end_extend_the_selection() {
17300        assert_eq!(
17301            golden("doc_edges_ext_end", "hello wor|ld\n", |d| d
17302                .move_doc_end(true)),
17303            "hello wor[ld\n|]"
17304        );
17305        assert_eq!(
17306            golden("doc_edges_ext_start", "hello wor|ld\n", |d| d
17307                .move_doc_start(true)),
17308            "[|hello wor]ld\n"
17309        );
17310    }
17311
17312    #[test]
17313    fn move_doc_start_and_end_on_an_empty_document_are_a_no_op() {
17314        let mut d = doc_with("empty_edges", "");
17315        d.move_doc_end(false);
17316        assert_eq!(d.caret, 0);
17317        d.move_doc_start(false);
17318        assert_eq!(d.caret, 0);
17319    }
17320
17321    // ── arrow collapses an active selection ─────────────────────────────────
17322
17323    #[test]
17324    fn arrow_collapses_selection_to_its_near_edge() {
17325        let mut d = doc_with("collapse", "hello world\n");
17326
17327        // Forward selection (anchor before caret): Right -> end, Left -> start.
17328        d.anchor = Some(2);
17329        d.caret = 7;
17330        d.move_right(false);
17331        assert_eq!((d.caret, d.anchor), (7, None));
17332
17333        d.anchor = Some(2);
17334        d.caret = 7;
17335        d.move_left(false);
17336        assert_eq!((d.caret, d.anchor), (2, None));
17337
17338        // Backward selection (anchor after caret): edges are the same
17339        // regardless of which end the caret started on.
17340        d.anchor = Some(7);
17341        d.caret = 2;
17342        d.move_right(false);
17343        assert_eq!((d.caret, d.anchor), (7, None));
17344
17345        d.anchor = Some(7);
17346        d.caret = 2;
17347        d.move_left(false);
17348        assert_eq!((d.caret, d.anchor), (2, None));
17349    }
17350
17351    #[test]
17352    fn arrow_with_extend_keeps_growing_the_selection() {
17353        let mut d = doc_with("collapse_extend", "hello world\n");
17354        d.anchor = Some(2);
17355        d.caret = 7;
17356        d.move_right(true); // extend: no collapse, caret steps one further
17357        assert_eq!((d.caret, d.anchor), (8, Some(2)));
17358    }
17359
17360    #[test]
17361    fn arrow_without_a_selection_moves_one_character_as_before() {
17362        let mut d = doc_with("no_collapse", "hello\n");
17363        d.caret = 2;
17364        d.move_right(false);
17365        assert_eq!(d.caret, 3);
17366        d.move_left(false);
17367        assert_eq!(d.caret, 2);
17368    }
17369
17370    /// Press Right until it stops, collecting the offsets walked through. Every
17371    /// caret bug in the WYSIWYG view shows up here as a walk that ends early:
17372    /// two stops sharing one source offset can't be moved between, so the caret
17373    /// stalls on the first of them and the walk never reaches the rest.
17374    fn walk_right(d: &mut Doc) -> Vec<usize> {
17375        let mut seen = vec![d.caret];
17376        for _ in 0..2000 {
17377            let before = d.caret;
17378            d.move_right(false);
17379            if d.caret == before {
17380                break;
17381            }
17382            seen.push(d.caret);
17383        }
17384        seen
17385    }
17386
17387    #[test]
17388    fn the_caret_crosses_a_soft_break() {
17389        // A newline inside a paragraph is a `soft_break`, which twig gives no
17390        // span of its own — the space it renders as used to borrow the offset of
17391        // the character before it, and a caret can't move without changing
17392        // offset. Right must walk clean off the end of the first line.
17393        let mut d = wysiwyg_doc("soft_break_walk", "one two\nthree four\n");
17394        d.caret = 0;
17395        let seen = walk_right(&mut d);
17396        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17397    }
17398
17399    #[test]
17400    fn line_flow_preserve_resplits_the_map_and_defaults_to_fold() {
17401        // The paragraph holds one soft break. Folded (the default) it lays out as
17402        // a single reflowed row; Preserve re-lays it as a row per source line.
17403        // The setter must invalidate the cached map for the change to show, and
17404        // again on the way back — so a round trip returns to the folded layout.
17405        let mut d = wysiwyg_doc("line_flow", "one two\nthree four\n");
17406        assert_eq!(d.line_flow(), LineFlow::Fold, "fold is the default");
17407        d.build_visual(80);
17408        assert_eq!(d.vmap.num_rows(), 1, "fold: one flowing row");
17409
17410        d.set_line_flow(LineFlow::Preserve);
17411        d.build_visual(80);
17412        assert_eq!(d.vmap.num_rows(), 2, "preserve: a row per source line");
17413
17414        d.set_line_flow(LineFlow::Fold);
17415        d.build_visual(80);
17416        assert_eq!(d.vmap.num_rows(), 1, "fold again: back to one row");
17417    }
17418
17419    #[test]
17420    fn the_caret_still_crosses_a_preserved_soft_break() {
17421        // Preserve renders the soft break as a row boundary rather than a space,
17422        // but the caret must still reach every offset — the break's own offset is
17423        // the first row's end stop, so Right walks clean off the end of line one
17424        // onto line two, exactly as it does when the break is folded.
17425        let mut d = wysiwyg_doc("preserve_walk", "one two\nthree four\n");
17426        d.set_line_flow(LineFlow::Preserve);
17427        d.build_visual(80);
17428        d.caret = 0;
17429        let seen = walk_right(&mut d);
17430        assert_eq!(seen, (0..=18).collect::<Vec<_>>(), "walk stalled: {seen:?}");
17431    }
17432
17433    #[test]
17434    fn the_caret_walks_a_code_block() {
17435        // Every glyph of a code block used to map to the block's start, so the
17436        // whole block was a single offset and the caret couldn't move inside it.
17437        let src = "```rust\nlet x = 1;\nfn f() {}\n```\n";
17438        let mut d = wysiwyg_doc("code_walk", src);
17439        d.caret = 0;
17440        let seen = walk_right(&mut d);
17441        // The fences are markup: hidden, and no caret stop. The code between
17442        // them is reached a character at a time.
17443        let code = src.find("let").unwrap()..src.find("\n```").unwrap();
17444        for off in code.clone() {
17445            assert!(seen.contains(&off), "offset {off} unreachable: {seen:?}");
17446        }
17447        assert!(seen.contains(&code.end), "no stop after the last line");
17448    }
17449
17450    #[test]
17451    fn the_caret_walks_an_indented_code_block() {
17452        // An indented block's text has the four-space indent stripped, so it
17453        // isn't a verbatim slice and its lines have to be re-found. The caret
17454        // lands on the code, never in the indent.
17455        let src = "    indented\n    code\n";
17456        let mut d = wysiwyg_doc("indent_code_walk", src);
17457        d.caret = 0;
17458        let seen = walk_right(&mut d);
17459        assert!(seen.contains(&src.find("indented").unwrap()));
17460        assert!(seen.contains(&src.find("code").unwrap()));
17461        assert!(
17462            !seen.contains(&0) || seen[0] == 0,
17463            "the caret starts where it was put"
17464        );
17465        // Nothing in the stripped indent is a stop.
17466        for off in [1, 2, 3] {
17467            assert!(!seen.contains(&off), "landed in the indent at {off}");
17468        }
17469    }
17470
17471    #[test]
17472    fn the_caret_leaves_a_tight_heading() {
17473        // "# H" with text directly under it: the heading row's end and the
17474        // separator row's end are the same offset. Right used to find the
17475        // separator's copy, set the caret to where it already was, and stop.
17476        let mut d = wysiwyg_doc("tight_heading_walk", "# H\ntext\n");
17477        d.caret = 2; // the "H"
17478        let seen = walk_right(&mut d);
17479        assert!(
17480            seen.len() > 2,
17481            "Right stalled at the heading's end: {seen:?}"
17482        );
17483        assert!(
17484            seen.contains(&8),
17485            "never reached the end of \"text\": {seen:?}"
17486        );
17487    }
17488
17489    #[test]
17490    fn the_caret_skips_the_gap_between_two_paragraphs() {
17491        // The blank line between two paragraphs is the boundary itself. The
17492        // caret used to be able to sit on it, and typing there landed in the
17493        // previous paragraph — "A\n\nB" became "A\nx\nB", one paragraph with a
17494        // soft break, so the text visibly snapped back up.
17495        let mut d = wysiwyg_doc("gap_skip", "A\n\nB\n");
17496        d.caret = 1; // the end of "A"
17497        d.move_right(false);
17498        assert_eq!(d.caret, 3, "Right stopped in the gap");
17499        d.insert("x");
17500        assert_eq!(d.source, "A\n\nxB\n", "typing landed outside B");
17501    }
17502
17503    #[test]
17504    fn down_from_a_paragraph_lands_on_the_next_one() {
17505        let mut d = wysiwyg_doc("gap_down", "A\n\nB\n");
17506        d.caret = 0;
17507        d.move_down(false);
17508        assert_eq!(d.caret, 3, "Down stopped in the gap");
17509    }
17510
17511    #[test]
17512    fn clicking_the_gap_lands_on_real_text() {
17513        // A click can still *reach* the gap — it's drawn, so it's clickable.
17514        // It has to resolve to somewhere the caret can be.
17515        let mut d = wysiwyg_doc("gap_click", "A\n\nB\n");
17516        d.click(1, 0, false); // the gap row
17517        assert!(
17518            d.caret == 1 || d.caret == 3,
17519            "click left the caret in the gap at {}",
17520            d.caret
17521        );
17522        d.insert("x");
17523        // Either edge of the boundary is a fair place to land; inside it isn't.
17524        assert!(
17525            d.source == "Ax\n\nB\n" || d.source == "A\n\nxB\n",
17526            "click in the gap typed into the boundary: {:?}",
17527            d.source
17528        );
17529    }
17530
17531    #[test]
17532    fn enter_opens_an_empty_paragraph_the_caret_can_type_into() {
17533        // Enter inserts a paragraph break, which leaves a blank line spare on
17534        // either side of a new one. That middle line is a real empty paragraph:
17535        // the caret lands there, and typing makes a paragraph rather than
17536        // extending a neighbour.
17537        let mut d = wysiwyg_doc("gap_enter", "A\n\nB\n");
17538        d.caret = 1;
17539        d.newline();
17540        assert_eq!(d.source, "A\n\n\n\nB\n");
17541        d.build_visual(80);
17542        let (row, _) = d.caret_pos();
17543        assert!(
17544            d.vmap.row_is_navigable(row),
17545            "the caret landed on a gap row"
17546        );
17547        d.insert("x");
17548        assert_eq!(
17549            d.source, "A\n\nx\n\nB\n",
17550            "the new paragraph merged into a neighbour"
17551        );
17552    }
17553
17554    #[test]
17555    fn enter_at_the_end_of_the_document_opens_a_paragraph_too() {
17556        let mut d = wysiwyg_doc("gap_eof", "A\n");
17557        d.caret = 1;
17558        d.newline();
17559        d.build_visual(80);
17560        let (row, _) = d.caret_pos();
17561        assert!(
17562            d.vmap.row_is_navigable(row),
17563            "the caret landed on a gap row"
17564        );
17565        d.insert("x");
17566        assert!(
17567            d.source.starts_with("A\n\n") && d.source.contains('x'),
17568            "typing at the end merged into A: {:?}",
17569            d.source
17570        );
17571    }
17572
17573    // ── click_past_end ───────────────────────────────────────────────────────
17574
17575    /// [`Doc::click_past_end`] on `body`, and the source it left, with the caret
17576    /// rendered as `|`.
17577    fn past_end(name: &str, body: &str) -> (Doc, String) {
17578        let mut d = wysiwyg_doc(name, body);
17579        d.click_past_end();
17580        let out = render_caret(&d);
17581        (d, out)
17582    }
17583
17584    #[test]
17585    fn click_past_end_opens_an_empty_paragraph_under_the_last_block() {
17586        let (mut d, out) = past_end("pe_para", "A\n");
17587        assert_eq!(out, "A\n\n|");
17588        d.build_visual(80);
17589        let (row, _) = d.caret_pos();
17590        assert!(
17591            d.vmap.row_is_navigable(row),
17592            "the caret landed on a gap row"
17593        );
17594        d.insert("x");
17595        assert_eq!(d.source, "A\n\nx", "typing merged into A");
17596    }
17597
17598    #[test]
17599    fn click_past_end_writes_both_newlines_when_the_file_has_none() {
17600        assert_eq!(past_end("pe_bare", "A").1, "A\n\n|");
17601    }
17602
17603    #[test]
17604    fn click_past_end_is_only_a_caret_move_when_the_paragraph_is_already_there() {
17605        let (d, out) = past_end("pe_there", "A\n\n");
17606        assert_eq!(out, "A\n\n|");
17607        assert!(!d.dirty, "a click wrote to a document it did not need to");
17608        assert!(
17609            !d.can_undo(),
17610            "a click that changed nothing left an undo step"
17611        );
17612    }
17613
17614    #[test]
17615    fn click_past_end_leaves_a_closed_fence() {
17616        let (mut d, out) = past_end("pe_fence", "```\ncode\n```\n");
17617        assert_eq!(out, "```\ncode\n```\n\n|");
17618        d.build_visual(80);
17619        let (row, _) = d.caret_pos();
17620        assert!(!d.vmap.rows[row].code, "the caret is still on a code row");
17621        d.insert("x");
17622        assert_eq!(d.source, "```\ncode\n```\n\nx");
17623    }
17624
17625    #[test]
17626    fn click_past_end_closes_an_unclosed_fence_first() {
17627        assert_eq!(past_end("pe_open", "```\ncode\n").1, "```\ncode\n```\n\n|");
17628        assert_eq!(
17629            past_end("pe_open2", "````\ncode").1,
17630            "````\ncode\n````\n\n|"
17631        );
17632        assert_eq!(past_end("pe_tilde", "~~~\ncode\n").1, "~~~\ncode\n~~~\n\n|");
17633        assert_eq!(
17634            past_end("pe_quoted", "> ```\n> code\n").1,
17635            "> ```\n> code\n> ```\n\n|"
17636        );
17637    }
17638
17639    #[test]
17640    fn click_past_end_does_not_close_an_indented_block() {
17641        assert_eq!(past_end("pe_indent", "    code\n").1, "    code\n\n|");
17642    }
17643
17644    #[test]
17645    fn click_past_end_under_a_list_and_a_table_leaves_them() {
17646        let (mut d, out) = past_end("pe_list", "- a\n- b\n");
17647        assert_eq!(out, "- a\n- b\n\n|");
17648        d.insert("x");
17649        assert_eq!(d.source, "- a\n- b\n\nx", "typed into the list");
17650        assert_eq!(
17651            past_end("pe_table", "| a |\n|---|\n| b |\n").1,
17652            "| a |\n|---|\n| b |\n\n|"
17653        );
17654    }
17655
17656    #[test]
17657    fn click_past_end_on_an_empty_document_writes_nothing() {
17658        let (d, out) = past_end("pe_empty", "");
17659        assert_eq!(out, "|");
17660        assert!(!d.dirty);
17661    }
17662
17663    #[test]
17664    fn click_past_end_is_one_undo_step() {
17665        let (mut d, _) = past_end("pe_undo", "A\n");
17666        d.undo();
17667        assert_eq!(d.source, "A\n");
17668    }
17669
17670    #[test]
17671    fn click_past_end_in_the_source_view_only_moves_the_caret() {
17672        let mut d = doc_with("pe_source", "A\n");
17673        d.click_past_end();
17674        assert_eq!(render_caret(&d), "A\n|");
17675        assert!(!d.dirty);
17676    }
17677
17678    #[test]
17679    fn click_past_end_on_a_read_only_document_only_moves_the_caret() {
17680        let mut d = wysiwyg_doc("pe_ro", "A\n");
17681        d.set_read_only(true);
17682        d.click_past_end();
17683        assert_eq!(render_caret(&d), "A\n|");
17684    }
17685
17686    // ── toggle_code_block ────────────────────────────────────────────────────
17687
17688    #[test]
17689    fn toggle_code_block_fences_the_paragraph_at_the_caret_and_reverses() {
17690        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17691        assert_eq!(g("cb_on", "hel|lo\n"), "```\nhel|lo\n```\n");
17692        assert_eq!(g("cb_off", "```\nhel|lo\n```\n"), "hel|lo\n");
17693        assert_eq!(g("cb_end", "hello|\n"), "```\nhello|\n```\n");
17694        assert_eq!(
17695            g("cb_wrap", "aaa\nb|bb\nccc\n"),
17696            "```\naaa\nb|bb\nccc\n```\n"
17697        );
17698        assert_eq!(
17699            g("cb_unwrap", "```\naaa\nb|bb\nccc\n```\n"),
17700            "aaa\nb|bb\nccc\n"
17701        );
17702        // An indented block dedents, and the lines stay one-to-one.
17703        assert_eq!(g("cb_indent", "    co|de\n"), "co|de\n");
17704        // A quote's marker is kept on every line, the fence's included.
17705        assert_eq!(g("cb_quote", "> hel|lo\n"), "> ```\n> hel|lo\n> ```\n");
17706    }
17707
17708    #[test]
17709    fn toggle_code_block_on_a_blank_line_opens_an_empty_fence() {
17710        let g = |n, m| golden_in(View::Wysiwyg, n, m, |d| d.toggle_code_block());
17711        assert_eq!(g("cb_blank", "A\n\n|"), "A\n\n```\n|\n```");
17712        assert_eq!(
17713            g("cb_blank_mid", "A\n\n|\n\nB\n"),
17714            "A\n\n```\n|\n```\n\nB\n"
17715        );
17716        // Tight against a neighbour, a blank line goes in on that side.
17717        assert_eq!(g("cb_blank_tight", "A\n|\nB\n"), "A\n\n```\n|\n```\n\nB\n");
17718        // Inside a quote, on a quoted blank line.
17719        assert_eq!(
17720            g("cb_blank_quote", "> A\n>\n> |\n"),
17721            "> A\n>\n> ```\n> |\n> ```\n"
17722        );
17723    }
17724
17725    #[test]
17726    fn toggle_code_block_from_a_blank_line_is_a_block_the_caret_can_type_into() {
17727        let mut d = wysiwyg_doc("cb_type", "A\n\n");
17728        d.click_past_end();
17729        d.toggle_code_block();
17730        assert!(
17731            d.caret_in_code_block(),
17732            "the caret is not in the block it opened"
17733        );
17734        d.insert("let x = 1;");
17735        d.newline();
17736        d.insert("x");
17737        assert_eq!(d.source, "A\n\n```\nlet x = 1;\nx\n```");
17738        d.build_visual(80);
17739        let (row, _) = d.caret_pos();
17740        assert!(d.vmap.rows[row].code, "typed text is not on a code row");
17741        // And back out: the button reverses what it did, text kept.
17742        d.toggle_code_block();
17743        assert_eq!(d.source, "A\n\nlet x = 1;\nx\n");
17744        assert!(!d.caret_in_code_block());
17745    }
17746
17747    #[test]
17748    fn toggle_code_block_over_a_selection_fences_it_whole_and_keeps_it_selected() {
17749        let mut d = wysiwyg_doc("cb_sel", "one\n\ntwo\n\nthree\n");
17750        d.anchor = Some(1);
17751        d.caret = 7;
17752        d.toggle_code_block();
17753        assert_eq!(d.source, "```\none\n\ntwo\n```\n\nthree\n");
17754        assert!(d.selection().is_some(), "the block came back unselected");
17755        d.toggle_code_block();
17756        assert_eq!(
17757            d.source, "one\n\ntwo\n\nthree\n",
17758            "a second press did not reverse the first"
17759        );
17760    }
17761
17762    #[test]
17763    fn toggle_code_block_inside_a_list_item_fences_and_unfences_in_place() {
17764        for (name, before, fenced) in [
17765            ("cb_list", "- it|em\n", "- ```\n  it|em\n  ```\n"),
17766            ("cb_olist", "1. it|em\n", "1. ```\n   it|em\n   ```\n"),
17767            ("cb_task", "- [ ] it|em\n", "- [ ] ```\n  it|em\n  ```\n"),
17768            (
17769                "cb_nested",
17770                "- a\n  - it|em\n",
17771                "- a\n  - ```\n    it|em\n    ```\n",
17772            ),
17773        ] {
17774            let mut d = wysiwyg_doc(name, &before.replace('|', ""));
17775            d.caret = before.find('|').unwrap();
17776            d.toggle_code_block();
17777            assert_eq!(render_caret(&d), fenced, "{name}: fencing");
17778            assert!(
17779                d.caret_in_code_block(),
17780                "{name}: the caret is in the new block"
17781            );
17782            d.toggle_code_block();
17783            assert_eq!(
17784                render_caret(&d),
17785                before,
17786                "{name}: a second press reverses the first"
17787            );
17788        }
17789    }
17790
17791    #[test]
17792    fn toggle_code_block_in_a_list_item_is_one_undo_step() {
17793        let mut d = wysiwyg_doc("cb_list_undo", "- item\n");
17794        d.caret = 4;
17795        d.toggle_code_block();
17796        d.undo();
17797        assert_eq!(render_caret(&d), "- it|em\n");
17798    }
17799
17800    #[test]
17801    fn caret_in_code_block_reads_fenced_and_indented_blocks() {
17802        let mut d = wysiwyg_doc("cb_in", "para\n\n```\ncode\n```\n\n    more\n");
17803        d.caret = 2;
17804        assert!(!d.caret_in_code_block());
17805        d.caret = 11;
17806        assert!(d.caret_in_code_block());
17807        d.caret = 25;
17808        assert!(d.caret_in_code_block(), "an indented block is a code block");
17809    }
17810
17811    #[test]
17812    fn caret_in_blockquote_reads_every_line_of_a_quote_and_nothing_after() {
17813        let src = "para\n\n> # Head\n> body|\n\nafter\n";
17814        let mut d = wysiwyg_doc("bq_in", &src.replace('|', ""));
17815        let quote_start = src.find('>').unwrap();
17816        let body_end = src.find('|').unwrap();
17817        let after = src.find("after").unwrap() - 1;
17818        for (at, inside) in [
17819            (2, false),
17820            (quote_start + 4, true),
17821            (body_end - 2, true),
17822            (body_end, true),
17823            (after, false),
17824            (after + 2, false),
17825        ] {
17826            d.caret = at;
17827            assert_eq!(d.caret_in_blockquote(), inside, "caret at {at}");
17828        }
17829        // A heading in a quote is both: the quote is a layer over the style.
17830        d.caret = quote_start + 4;
17831        assert_eq!(d.current_heading_level(), Some(1));
17832    }
17833
17834    #[test]
17835    fn caret_in_blockquote_follows_the_toggle() {
17836        let mut d = wysiwyg_doc("bq_toggle", "hello\n");
17837        d.caret = 2;
17838        assert!(!d.caret_in_blockquote());
17839        d.toggle_blockquote();
17840        assert!(d.caret_in_blockquote());
17841        d.toggle_blockquote();
17842        assert!(!d.caret_in_blockquote());
17843    }
17844
17845    #[test]
17846    fn toggle_code_block_is_one_undo_step() {
17847        let mut d = wysiwyg_doc("cb_undo", "hello\n");
17848        d.caret = 2;
17849        d.toggle_code_block();
17850        d.undo();
17851        assert_eq!(render_caret(&d), "he|llo\n");
17852    }
17853
17854    #[test]
17855    fn triple_click_selects_a_paragraph_across_its_soft_breaks() {
17856        // A paragraph broken over two source lines is one paragraph. Selecting
17857        // it must not stop at the newline inside it — that newline is markup the
17858        // rich-text view exists to hide.
17859        let src = "one two\nthree four\n\nnext\n";
17860        let mut d = wysiwyg_doc("triple_para", src);
17861        d.select_block_at(2);
17862        assert_eq!(
17863            d.selected_text(),
17864            Some("one two\nthree four"),
17865            "stopped at the soft break"
17866        );
17867    }
17868
17869    #[test]
17870    fn the_wheel_can_scroll_away_from_a_caret_that_stays_put() {
17871        // The reader scrolls down past the caret's row. Nothing moved the
17872        // caret, so the view must stay where it was put — the old code revealed
17873        // the caret every frame, which dragged the view straight back and made
17874        // the document unscrollable past the caret.
17875        let mut d = wysiwyg_doc("scroll_free", "a\n\nb\n\nc\n\nd\n\ne\n");
17876        d.caret = 0;
17877        d.follow_caret(0, 3, 9); // first frame: the caret is at the top
17878        d.scroll = 4; // the wheel
17879        d.follow_caret(0, 3, 9);
17880        assert_eq!(
17881            d.scroll, 4,
17882            "the wheel was overruled by a caret that never moved"
17883        );
17884    }
17885
17886    #[test]
17887    fn moving_the_caret_brings_the_view_back_to_it() {
17888        let mut d = wysiwyg_doc("scroll_follow", "a\n\nb\n\nc\n\nd\n\ne\n");
17889        d.caret = 0;
17890        d.follow_caret(0, 3, 9);
17891        d.scroll = 6; // scrolled away
17892        d.move_right(false); // ...and now the caret moves
17893        let (row, _) = d.caret_pos();
17894        d.follow_caret(row, 3, 9);
17895        assert!(
17896            d.scroll <= row && row < d.scroll + 3,
17897            "caret row {row} off screen at scroll {}",
17898            d.scroll
17899        );
17900    }
17901
17902    #[test]
17903    fn scrolling_stops_at_the_last_row() {
17904        let mut d = wysiwyg_doc("scroll_clamp", "a\n\nb\n");
17905        d.caret = 0;
17906        d.follow_caret(0, 3, 3); // a first frame, so the caret isn't "new"
17907        d.scroll = 999; // the wheel, spun hard
17908        d.follow_caret(0, 3, 3);
17909        assert_eq!(d.scroll, 2, "scrolled into the void past the document");
17910    }
17911
17912    #[test]
17913    fn every_cell_of_a_wide_table_is_reachable() {
17914        // A table whose cells are far wider than the surface: the columns are
17915        // cut to fit and the text wraps inside them, so no cell hangs off the
17916        // right edge where the caret can never go.
17917        let src = "| Ingredient | Notes |\n|---|---|\n\
17918                   | flour milled coarse | sift it twice before folding it in |\n";
17919        let mut d = wysiwyg_doc("wide_table_walk", src);
17920        d.build_visual(30);
17921        d.caret = 0;
17922        let seen = walk_right(&mut d);
17923        for word in ["Ingredient", "Notes", "coarse", "folding"] {
17924            let at = src.find(word).unwrap();
17925            assert!(seen.contains(&at), "{word:?} at {at} unreachable: {seen:?}");
17926        }
17927    }
17928
17929    // ── view parity ──────────────────────────────────────────────────────────
17930    // `doc_with` pins the source view, so everything above tests a view users
17931    // never start in — `Doc::open` opens in WYSIWYG. These run the motion and
17932    // deletion golden cases through *both*, plus the WYSIWYG cases the two
17933    // can't share: where the source carries markup the rendered text is a
17934    // different string, and the views agreeing would itself be the bug.
17935
17936    const VIEWS: [(View, &str); 2] = [(View::Source, "source"), (View::Wysiwyg, "wysiwyg")];
17937
17938    /// Run `action` in both views on one `|`-marked fixture and assert they
17939    /// agree. Plain prose only: with no markup to hide, WYSIWYG renders the
17940    /// source verbatim, so the two views are looking at the same text and any
17941    /// disagreement is one of them having lost the plot.
17942    fn both_views(name: &str, marked: &str, action: fn(&mut Doc)) -> String {
17943        let (src, caret) = parse_caret(marked);
17944        let run = |view: View, tag: &str| {
17945            let mut d = doc_in(view, &format!("{name}_{tag}"), &src);
17946            d.caret = caret;
17947            action(&mut d);
17948            render_caret(&d)
17949        };
17950        let source = run(VIEWS[0].0, VIEWS[0].1);
17951        let wysiwyg = run(VIEWS[1].0, VIEWS[1].1);
17952        assert_eq!(source, wysiwyg, "the views disagree on {marked:?}");
17953        source
17954    }
17955
17956    #[test]
17957    fn word_motion_agrees_across_the_views_on_plain_prose() {
17958        let g = both_views;
17959        assert_eq!(
17960            g("par_wl", "hello wor|ld", |d| d.move_word_left(false)),
17961            "hello |world"
17962        );
17963        assert_eq!(
17964            g("par_wl2", "hello| world", |d| d.move_word_left(false)),
17965            "|hello world"
17966        );
17967        assert_eq!(
17968            g("par_wr", "hel|lo world", |d| d.move_word_right(false)),
17969            "hello| world"
17970        );
17971        assert_eq!(
17972            g("par_wr2", "hello| world", |d| d.move_word_right(false)),
17973            "hello world|"
17974        );
17975        assert_eq!(
17976            g("par_punct", "|foo.bar", |d| d.move_word_right(false)),
17977            "foo|.bar"
17978        );
17979        assert_eq!(
17980            g("par_ext", "hello |world", |d| d.move_word_right(true)),
17981            "hello [world|]"
17982        );
17983    }
17984
17985    #[test]
17986    fn word_deletion_agrees_across_the_views_on_plain_prose() {
17987        let g = both_views;
17988        assert_eq!(
17989            g("par_db", "hello world|", |d| d.delete_word_back()),
17990            "hello |"
17991        );
17992        assert_eq!(
17993            g("par_df", "hello |world", |d| d.delete_word_forward()),
17994            "hello |"
17995        );
17996        assert_eq!(
17997            g("par_db2", "foo |bar baz", |d| d.delete_word_back()),
17998            "|bar baz"
17999        );
18000        assert_eq!(g("par_utf8", "café |ok", |d| d.delete_word_back()), "|ok");
18001    }
18002
18003    #[test]
18004    fn character_motion_and_deletion_agree_across_the_views_on_plain_prose() {
18005        let g = both_views;
18006        assert_eq!(g("par_r", "he|llo", |d| d.move_right(false)), "hel|lo");
18007        assert_eq!(g("par_l", "he|llo", |d| d.move_left(false)), "h|ello");
18008        assert_eq!(g("par_bs", "hel|lo", |d| d.backspace()), "he|lo");
18009        assert_eq!(g("par_del", "hel|lo", |d| d.delete_forward()), "hel|o");
18010    }
18011
18012    #[test]
18013    fn wysiwyg_motion_steps_a_grapheme_cluster_the_way_the_source_view_does() {
18014        // The reproduction: the stop table was built one stop per `char`, so
18015        // Right parked the caret 4 bytes into a ZWJ sequence — a place the
18016        // source view, which steps by grapheme, can't reach and backspace can't
18017        // survive. The two views must land on the same offset.
18018        let family = "👨‍👩‍👧"; // three emoji strung together with joiners: one cluster
18019        for (view, tag) in VIEWS {
18020            let mut d = doc_in(view, &format!("cluster_{tag}"), &format!("a{family}b\n"));
18021            d.caret = 1;
18022            d.move_right(false);
18023            assert_eq!(d.caret, 1 + family.len(), "{tag} parked inside the cluster");
18024
18025            // ...and the edit that used to sever a joiner off the front of it.
18026            d.backspace();
18027            assert_eq!(d.source, "ab\n", "{tag} split the cluster");
18028            assert_eq!(d.caret, 1);
18029        }
18030    }
18031
18032    #[test]
18033    fn wysiwyg_motion_treats_a_combining_accent_as_one_character() {
18034        for (view, tag) in VIEWS {
18035            let mut d = doc_in(view, &format!("combining_{tag}"), "e\u{0301}x\n");
18036            d.caret = 0;
18037            d.move_right(false);
18038            assert_eq!(
18039                d.caret,
18040                "e\u{0301}".len(),
18041                "{tag} stopped on the combining mark"
18042            );
18043        }
18044    }
18045
18046    #[test]
18047    fn no_wysiwyg_motion_can_park_the_caret_inside_a_cluster() {
18048        // The general form: whatever route the caret takes through a document
18049        // full of clusters, it never lands between the codepoints of one — so no
18050        // motion-then-backspace sequence can leave a dangling joiner behind.
18051        use unicode_segmentation::UnicodeSegmentation;
18052
18053        let src = "a👨‍👩‍👧b e\u{0301}mo👨‍👩‍👧ji\n\nnext 👩‍🚀 line\n";
18054        let mut d = wysiwyg_doc("cluster_walk", src);
18055        d.caret = 0;
18056        let boundaries: Vec<usize> = src
18057            .grapheme_indices(true)
18058            .map(|(i, _)| i)
18059            .chain(std::iter::once(src.len()))
18060            .collect();
18061        for off in walk_right(&mut d) {
18062            assert!(
18063                boundaries.contains(&off),
18064                "Right stopped at {off}, inside a grapheme cluster"
18065            );
18066        }
18067    }
18068
18069    #[test]
18070    fn wysiwyg_word_motion_stays_out_of_hidden_delimiters() {
18071        // The reproduction: ⌥→ from inside the opening `**` computed its
18072        // boundary over the raw source and landed on byte 8 — inside the
18073        // *closing* `**`, which `caret_pos` draws at column 6, immediately after
18074        // "bold". The caret drew past the bold word and sat inside it.
18075        let mut d = wysiwyg_doc("wys_word_delim", "a **bold** c\n");
18076        d.caret = 2;
18077        d.move_word_right(false);
18078        assert!(
18079            d.vmap.is_stop(d.caret),
18080            "landed at {}, not a caret stop",
18081            d.caret
18082        );
18083        assert_eq!(d.caret, 10, "should land on the space after \"bold\"");
18084        // The rendered row is "a bold c": column 6 is the space just past "bold",
18085        // and now the caret is really there rather than only drawn there.
18086        assert_eq!(d.caret_pos(), (0, 6));
18087
18088        // ...and back again: ⌥← returns to the "b", not into the opening `**`.
18089        d.move_word_left(false);
18090        assert_eq!(d.caret, 4);
18091        assert_eq!(d.caret_pos(), (0, 2));
18092    }
18093
18094    #[test]
18095    fn wysiwyg_word_delete_takes_the_markup_with_the_word() {
18096        // The reproduction: ⌥⌫ from after "bold" walked the raw source, stopped
18097        // inside the closing `**`, and left "a ** c\n" — delimiters with no
18098        // opener. Glyph space covers the word alone, which would leave
18099        // "a **** c": markup wrapped around nothing. The word and the styling
18100        // that was only ever the word's go together.
18101        let mut d = wysiwyg_doc("wys_word_del_back", "a **bold** c\n");
18102        d.caret = 10;
18103        d.delete_word_back();
18104        assert_eq!(d.source, "a  c\n");
18105        assert_eq!(d.caret, 2);
18106
18107        let mut d = wysiwyg_doc("wys_word_del_fwd", "a **bold** c\n");
18108        d.caret = 4; // the "b"
18109        d.delete_word_forward();
18110        assert_eq!(d.source, "a  c\n");
18111    }
18112
18113    #[test]
18114    fn wysiwyg_word_delete_empties_a_nested_mark_and_a_code_span_too() {
18115        let src = "a ***bold*** c\n";
18116        let mut d = wysiwyg_doc("wys_word_del_nest", src);
18117        d.caret = src.find(" c").unwrap();
18118        d.delete_word_back();
18119        assert_eq!(
18120            d.source, "a  c\n",
18121            "the emph inside the strong empties it too"
18122        );
18123
18124        let src = "a `code` c\n";
18125        let mut d = wysiwyg_doc("wys_word_del_code", src);
18126        d.caret = src.find(" c").unwrap();
18127        d.delete_word_back();
18128        assert_eq!(d.source, "a  c\n");
18129    }
18130
18131    #[test]
18132    fn wysiwyg_word_delete_keeps_a_mark_that_still_has_text() {
18133        // Only an *emptied* node goes. Take one word of two and the `**` still
18134        // has a job to do — over the word that's left, with the space the delete
18135        // pushed against the opening delimiter moved out in front of it, or the
18136        // run would be no run at all (`** words**` is literal asterisks — see
18137        // the mark-edge rule on `splice`).
18138        let src = "a **two words** c\n";
18139        let mut d = wysiwyg_doc("wys_word_del_partial", src);
18140        d.caret = src.find(" words").unwrap();
18141        d.delete_word_back();
18142        assert_eq!(d.source, "a  **words** c\n");
18143    }
18144
18145    #[test]
18146    fn source_view_word_motion_still_walks_the_markup() {
18147        // The other half of the decision: in the source view the `**` are
18148        // characters like any other — they're on the screen, so word motion has
18149        // to stop at them and a word-delete has to leave them behind. Only
18150        // WYSIWYG hides them, so only WYSIWYG steps over them.
18151        let g = |n, m, f: fn(&mut Doc)| golden(n, m, f);
18152        assert_eq!(
18153            g("src_word_motion", "a |**bold** c\n", |d| d
18154                .move_word_right(false)),
18155            "a **bold|** c\n"
18156        );
18157        // The same caret as the WYSIWYG reproduction, and the opposite outcome:
18158        // here "a ** c\n" is right, because `bold**` is what's to the left of it.
18159        assert_eq!(
18160            g("src_word_del", "a **bold**| c\n", |d| d.delete_word_back()),
18161            "a **| c\n"
18162        );
18163    }
18164
18165    #[test]
18166    fn every_wysiwyg_motion_lands_on_a_caret_stop() {
18167        // The single invariant both bugs violated: the caret draws and edits at
18168        // the same place only when it's on a stop. `debug_assert_on_a_stop`
18169        // makes the same claim in-place; this pins it from the outside, over a
18170        // document with every kind of thing the map has to be careful about.
18171        // At two widths: the wide one every other test builds at, where no
18172        // fixture folds, and one narrow enough that they all do. A soft wrap is
18173        // where an offset stops being on exactly one row, and testing only the
18174        // width that never wraps is how the caret came to be pinned at the first
18175        // one Down reached.
18176        let src = "# Title\n\na **bold** e\u{0301}mo👨‍👩‍👧ji `x` c\n\n\
18177                   - item one\n\n| A | B |\n|---|---|\n| x | y |\n";
18178        // A table of named operations, which is what it looks like.
18179        #[allow(clippy::type_complexity)]
18180        let motions: [(&str, fn(&mut Doc)); 8] = [
18181            ("right", |d| d.move_right(false)),
18182            ("left", |d| d.move_left(false)),
18183            ("word_right", |d| d.move_word_right(false)),
18184            ("word_left", |d| d.move_word_left(false)),
18185            ("down", |d| d.move_down(false)),
18186            ("up", |d| d.move_up(false)),
18187            ("home", |d| d.move_home(false)),
18188            ("end", |d| d.move_end(false)),
18189        ];
18190        for width in [80, 12] {
18191            let mut d = wysiwyg_doc("stop_invariant", src);
18192            d.build_visual(width);
18193            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18194            assert!(stops.len() > 20, "fixture should have plenty of stops");
18195            for start in stops {
18196                for (name, motion) in &motions {
18197                    d.caret = start;
18198                    d.anchor = None;
18199                    motion(&mut d);
18200                    assert!(
18201                        d.vmap.is_stop(d.caret),
18202                        "{name} from {start} at width {width} landed at {} — not a caret stop",
18203                        d.caret
18204                    );
18205                }
18206            }
18207        }
18208    }
18209
18210    #[test]
18211    fn no_wysiwyg_motion_is_a_dead_end() {
18212        // Down held to the bottom of a document reaches the bottom, and Up held
18213        // to the top reaches the top — from anywhere, at a width that wraps. The
18214        // invariant above says a motion lands somewhere legal; this one says it
18215        // gets somewhere at all, which is what a caret pinned at a wrap boundary
18216        // was quietly failing to do while every assertion around it held.
18217        let src = "# Title\n\none two three four five six seven eight nine ten\n\n\
18218                   - item one two three four five\n\nlast\n";
18219        for width in [80, 12] {
18220            let mut d = wysiwyg_doc("no_dead_end", src);
18221            d.build_visual(width);
18222            let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18223            let (first, last) = (stops[0], stops[stops.len() - 1]);
18224            for &start in &stops {
18225                for (name, motion, want) in [
18226                    (
18227                        "down",
18228                        (|d: &mut Doc| d.move_down(false)) as fn(&mut Doc),
18229                        last,
18230                    ),
18231                    ("up", |d: &mut Doc| d.move_up(false), first),
18232                ] {
18233                    d.caret = start;
18234                    d.anchor = None;
18235                    d.goal_col = None;
18236                    // Every row, plus the presses the edges take, plus slack.
18237                    for _ in 0..d.vmap.num_rows() + 4 {
18238                        motion(&mut d);
18239                    }
18240                    assert_eq!(
18241                        d.caret, want,
18242                        "{name} held from {start} at width {width} never arrived"
18243                    );
18244                }
18245            }
18246        }
18247    }
18248    // ── display columns ──────────────────────────────────────────────────────
18249    // A `col` is a terminal cell, not a character. The two are the same number
18250    // for the ASCII the fixtures above are written in, which is how they came
18251    // apart in the first place: `你` is one character drawn in two cells, so a
18252    // column counted in characters names a cell the text isn't in — one earlier
18253    // for every wide character to its left.
18254
18255    #[test]
18256    fn a_wide_character_is_two_columns_wide() {
18257        // The reproduction: `你` is one char and two cells, so the caret just
18258        // past it drew at column 1 — inside the character it had already left.
18259        for (view, tag) in VIEWS {
18260            let mut d = doc_in(view, &format!("wide_col_{tag}"), "你好\n");
18261            d.caret = "你".len();
18262            assert_eq!(d.caret_pos(), (0, 2), "{tag}: caret drew inside 你");
18263            d.caret = "你好".len();
18264            assert_eq!(d.caret_pos(), (0, 4), "{tag}");
18265        }
18266    }
18267
18268    #[test]
18269    fn a_cluster_is_as_wide_as_it_is_drawn_not_as_its_codepoints_measure() {
18270        // `👨‍👩‍👧` is five codepoints — two-cell, joiner, two-cell, joiner,
18271        // two-cell — measuring six cells one at a time, but the character they
18272        // spell is drawn in two. Width belongs to the cluster, not the glyph,
18273        // and the frontends measure it the same way.
18274        let family = "👨‍👩‍👧";
18275        for (view, tag) in VIEWS {
18276            let src = format!("a{family}b\n");
18277            let mut d = doc_in(view, &format!("wide_cluster_{tag}"), &src);
18278            d.caret = 1 + family.len();
18279            assert_eq!(
18280                d.caret_pos(),
18281                (0, 3),
18282                "{tag}: 'a' is one cell, the family two"
18283            );
18284        }
18285    }
18286
18287    #[test]
18288    fn both_cells_of_a_wide_character_mean_the_character() {
18289        // Clicking the far half of `好` is still clicking `好`: half a character
18290        // is not a place the caret can be, so it comes to rest at the
18291        // character's start — the column it would have been drawn at anyway.
18292        for (view, tag) in VIEWS {
18293            let mut d = doc_in(view, &format!("wide_click_{tag}"), "你好\n");
18294            for col in [2, 3] {
18295                d.caret = 0;
18296                d.click(0, col, false);
18297                assert_eq!(d.caret, "你".len(), "{tag}: click at col {col}");
18298                assert_eq!(d.caret_pos(), (0, 2), "{tag}: click at col {col}");
18299            }
18300            // Past the last cell is the line's end, as it is for ASCII.
18301            d.click(0, 9, false);
18302            assert_eq!(d.caret, "你好".len(), "{tag}: click past the end");
18303        }
18304    }
18305
18306    #[test]
18307    fn every_offset_survives_the_trip_out_to_a_column_and_back() {
18308        // The mapping is only a mapping if it inverts: the cell the caret is
18309        // drawn in has to be the cell that brings it back to the same offset.
18310        // Over a fixture where a character may be one cell or two, and one
18311        // codepoint or five.
18312        use unicode_segmentation::UnicodeSegmentation;
18313
18314        let src = "ab 你好 c\n\n👨‍👩‍👧 e\u{0301}x 漢字\n\nplain ascii\n";
18315
18316        let mut d = doc_in(View::Source, "roundtrip_source", src);
18317        // Every offset the source view's caret can occupy: it steps by grapheme
18318        // cluster, so those are its boundaries.
18319        for (off, _) in src
18320            .grapheme_indices(true)
18321            .chain(std::iter::once((src.len(), "")))
18322        {
18323            d.caret = off;
18324            let (row, col) = d.caret_pos();
18325            d.click(row, col, false);
18326            assert_eq!(d.caret, off, "source: {off} → ({row}, {col}) → {}", d.caret);
18327        }
18328
18329        // And in WYSIWYG, where the offsets the caret can occupy are the map's
18330        // stops rather than every boundary.
18331        let mut d = doc_in(View::Wysiwyg, "roundtrip_wysiwyg", src);
18332        let stops: Vec<usize> = (0..=src.len()).filter(|&o| d.vmap.is_stop(o)).collect();
18333        assert!(stops.len() > 20, "fixture should have plenty of stops");
18334        for off in stops {
18335            d.caret = off;
18336            let (row, col) = d.caret_pos();
18337            d.click(row, col, false);
18338            assert_eq!(
18339                d.caret, off,
18340                "wysiwyg: {off} → ({row}, {col}) → {}",
18341                d.caret
18342            );
18343        }
18344    }
18345
18346    #[test]
18347    fn vertical_motion_aims_at_a_column_the_reader_can_see() {
18348        // Down from under `世` lands under the glyph in that cell, not two
18349        // characters further along the line. The goal is a column, so a line of
18350        // wide characters and a line of ASCII line up the way they're drawn.
18351        //
18352        // The gap differs by view: a bare newline inside a paragraph is a soft
18353        // break, which WYSIWYG draws as a space on a single row. The views share
18354        // a grid only where the source's lines are the renderer's rows too.
18355        for (view, tag) in VIEWS {
18356            let gap = if view == View::Source { "\n" } else { "\n\n" };
18357            let src = format!("你好世{gap}abcdef\n");
18358            let mut d = doc_in(view, &format!("goal_wide_{tag}"), &src);
18359            d.caret = "你好".len();
18360            assert_eq!(d.caret_pos().1, 4, "{tag}: `世` is drawn at column 4");
18361            d.move_down(false);
18362            assert_eq!(d.caret_pos().1, 4, "{tag}: goal column lost");
18363            assert!(
18364                d.source[d.caret..].starts_with('e'),
18365                "{tag}: landed on the wrong glyph"
18366            );
18367        }
18368    }
18369
18370    #[test]
18371    fn a_goal_column_landing_inside_a_wide_character_lands_on_it() {
18372        // Down from column 3 onto `你好`, whose characters start at columns 0
18373        // and 2: column 3 is the *second* cell of `好`. There is nowhere to be
18374        // between the cells of one character, so the caret rests on it — and on
18375        // its start, which is the only offset there that is a caret stop.
18376        for (view, tag) in VIEWS {
18377            let gap = if view == View::Source { "\n" } else { "\n\n" };
18378            let src = format!("abcdef{gap}你好\n");
18379            let mut d = doc_in(view, &format!("goal_inside_{tag}"), &src);
18380            let line = src.find('你').unwrap();
18381            d.caret = 3;
18382            d.move_down(false);
18383            assert_eq!(d.caret, line + "你".len(), "{tag}: landed off `好`'s start");
18384            assert_eq!(d.caret_pos().1, 2, "{tag}: drew between `好`'s cells");
18385        }
18386    }
18387
18388    #[test]
18389    fn a_caret_in_a_table_cell_of_wide_text_draws_where_the_text_is() {
18390        // The column the cell's text is laid out in is measured in cells, so the
18391        // caret walking that text has to be too — the two agreeing is the whole
18392        // point of the grid staying square.
18393        let mut d = wysiwyg_doc("table_wide", "| A | B |\n|---|---|\n| 你好 | y |\n");
18394        let at = d.source.find("你").unwrap();
18395        d.caret = at;
18396        let (row, col) = d.caret_pos();
18397        // `│ ` opens the row, so the cell's text starts at column 2; `好` is two
18398        // cells further along.
18399        assert_eq!(col, 2, "the cell's first character");
18400        d.move_right(false);
18401        assert_eq!(
18402            d.caret_pos(),
18403            (row, 4),
18404            "`好` is drawn past `你`'s two cells"
18405        );
18406        assert_eq!(d.caret, at + "你".len());
18407    }
18408
18409    // ── active inline marks ───────────────────────────────────────────────────
18410
18411    /// The marks at a `|`-marked fixture's caret, in `InlineMarks::iter` order.
18412    fn marks(view: View, name: &str, marked: &str) -> Vec<InlineKind> {
18413        let (src, caret) = parse_caret(marked);
18414        let mut d = doc_in(view, name, &src);
18415        d.caret = caret;
18416        d.active_inline_marks().iter().collect()
18417    }
18418
18419    /// The marks over the selection `[start, end)`.
18420    fn marks_over(view: View, name: &str, src: &str, start: usize, end: usize) -> Vec<InlineKind> {
18421        let mut d = doc_in(view, name, src);
18422        d.anchor = Some(start);
18423        d.caret = end;
18424        d.active_inline_marks().iter().collect()
18425    }
18426
18427    #[test]
18428    fn a_caret_in_a_mark_reports_it() {
18429        for (view, tag) in VIEWS {
18430            let m = |marked| marks(view, &format!("marks_in_{tag}"), marked);
18431            assert_eq!(m("a **bo|ld** b"), [InlineKind::Strong], "{tag}");
18432            assert_eq!(m("a *it|alic* b"), [InlineKind::Emph], "{tag}");
18433            assert_eq!(m("a `co|de` b"), [InlineKind::Verbatim], "{tag}");
18434            // Plain text under no mark lights nothing — the toolbar's resting state.
18435            assert_eq!(m("a| **bold** b"), [], "{tag}");
18436            assert!(m("plain t|ext").is_empty(), "{tag}");
18437        }
18438    }
18439
18440    #[test]
18441    fn nested_marks_all_report() {
18442        // Bold *and* italic: a toolbar lights both buttons, so the set has both —
18443        // the ancestor chain is a chain, and every mark on it is in force.
18444        for (view, tag) in VIEWS {
18445            assert_eq!(
18446                marks(
18447                    view,
18448                    &format!("marks_nested_{tag}"),
18449                    "**bold and *bo|th*** end"
18450                ),
18451                [InlineKind::Strong, InlineKind::Emph],
18452                "{tag}"
18453            );
18454        }
18455    }
18456
18457    #[test]
18458    fn the_caret_at_a_marks_edge_reports_it_where_typing_would_extend_it() {
18459        // The offsets a WYSIWYG caret actually reaches at a bold run's edges are
18460        // the first byte of its text and the byte after its last — both inside
18461        // the mark's span, both places typing lands inside the bold. The offset
18462        // past the closing delimiter is the next text, and reports nothing.
18463        let src = "a **bold** b";
18464        let inner_start = src.find("bold").unwrap(); // 4
18465        let inner_end = inner_start + "bold".len(); // 8, on the closing `**`
18466        for (view, tag) in VIEWS {
18467            let mut d = doc_in(view, &format!("marks_edge_{tag}"), src);
18468            for off in [2, 3, inner_start, inner_end, 9] {
18469                d.caret = off;
18470                assert!(
18471                    d.active_inline_marks().contains(InlineKind::Strong),
18472                    "{tag}: offset {off} is inside the strong span"
18473                );
18474            }
18475            for off in [0, 1, 10, 11, 12] {
18476                d.caret = off;
18477                assert!(
18478                    !d.active_inline_marks().contains(InlineKind::Strong),
18479                    "{tag}: offset {off} is outside the strong run"
18480                );
18481            }
18482        }
18483    }
18484
18485    #[test]
18486    fn a_mark_ends_the_same_way_at_the_end_of_the_buffer_as_in_the_middle() {
18487        // Regression: twig resolves an offset that is one node's end and the
18488        // next one's start to the node that *starts* there, so `**bold**|\n`
18489        // isn't bold. With nothing following there's no tie to break and the
18490        // chain still ended at the mark, which made a trailing `\n` — not the
18491        // text — decide whether the caret after a bold word reported bold. It's
18492        // the offset past the mark either way, and typing there is plain either
18493        // way. A blank document typed into is exactly this shape.
18494        for (view, tag) in VIEWS {
18495            let m = |name: String, marked| marks(view, &name, marked);
18496            assert_eq!(
18497                m(format!("marks_eob_{tag}"), "**bold**|"),
18498                [],
18499                "{tag}: no trailing newline"
18500            );
18501            assert_eq!(
18502                m(format!("marks_eol_{tag}"), "**bold**|\n"),
18503                [],
18504                "{tag}: with one"
18505            );
18506            // And the last offset that *is* in the mark still is.
18507            assert_eq!(
18508                m(format!("marks_eob_in_{tag}"), "**bold*|*"),
18509                [InlineKind::Strong],
18510                "{tag}"
18511            );
18512        }
18513    }
18514
18515    #[test]
18516    fn a_selection_reports_a_mark_only_when_it_covers_the_whole_thing() {
18517        let src = "a **bold** b";
18518        let (b, d_) = (src.find("bold").unwrap(), src.find("bold").unwrap() + 4);
18519        for (view, tag) in VIEWS {
18520            let m = |s, e| marks_over(view, &format!("marks_sel_{tag}"), src, s, e);
18521            // The whole bold word, and a slice of it.
18522            assert_eq!(m(b, d_), [InlineKind::Strong], "{tag}: the whole word");
18523            assert_eq!(m(b + 1, d_ - 1), [InlineKind::Strong], "{tag}: a slice");
18524            // Ending exactly at the closing delimiter's start is still all-bold:
18525            // an exclusive end sits *past* the last selected character, so the
18526            // question is asked of the character, not the boundary.
18527            assert_eq!(
18528                m(b, d_ + 2),
18529                [InlineKind::Strong],
18530                "{tag}: through the close"
18531            );
18532            // Half in, half out: Bold lit here would claim a press turns it off.
18533            assert_eq!(m(0, d_), [], "{tag}: leading plain text");
18534            assert_eq!(m(b, src.len()), [], "{tag}: trailing plain text");
18535        }
18536    }
18537
18538    #[test]
18539    fn a_selection_across_two_runs_of_the_same_mark_reports_nothing() {
18540        // Both ends are bold, but the space between them isn't — two runs are two
18541        // nodes, which is exactly what the node id catches and a kind-only
18542        // comparison would not.
18543        let src = "**one** **two**";
18544        for (view, tag) in VIEWS {
18545            let m = marks_over(view, &format!("marks_runs_{tag}"), src, 2, 13);
18546            assert_eq!(m, [], "{tag}: `one** **two` is not all bold");
18547        }
18548    }
18549
18550    #[test]
18551    fn marks_read_the_document_as_it_is_edited() {
18552        // The point of asking twig every frame instead of caching: the answer has
18553        // to follow the toggle that changed it.
18554        let mut d = wysiwyg_doc("marks_live", "one two\n");
18555        d.anchor = Some(0);
18556        d.caret = 3;
18557        assert!(d.active_inline_marks().is_empty(), "plain to start");
18558        d.toggle(InlineKind::Strong);
18559        assert_eq!(d.source, "**one** two\n");
18560        // `toggle` leaves the bolded text selected, so the button it lit stays lit.
18561        assert!(d.active_inline_marks().contains(InlineKind::Strong));
18562        d.toggle(InlineKind::Strong);
18563        assert!(d.active_inline_marks().is_empty(), "and off again");
18564    }
18565
18566    #[test]
18567    fn a_link_is_not_an_inline_mark() {
18568        // `link`/`str` are inline nodes, but nothing on the inline toolbar
18569        // toggles them — a set with a "link mark" in it would have no button.
18570        for (view, tag) in VIEWS {
18571            assert_eq!(
18572                marks(view, &format!("marks_link_{tag}"), "a [te|xt](u) b"),
18573                [],
18574                "{tag}"
18575            );
18576        }
18577    }
18578
18579    // ── blank documents ───────────────────────────────────────────────────────
18580
18581    #[test]
18582    fn a_blank_document_is_untitled_empty_and_markdown() {
18583        let mut d = Doc::blank().unwrap();
18584        assert!(d.is_untitled());
18585        assert_eq!(d.path, PathBuf::new());
18586        assert_eq!(
18587            d.file_name(),
18588            "untitled",
18589            "the header has to show something"
18590        );
18591        assert_eq!(d.format_name(), "markdown");
18592        assert_eq!(d.source, "");
18593        assert!(!d.dirty, "nothing typed yet is nothing to lose");
18594        assert_eq!(d.disk_state(), DiskState::Untitled);
18595        // And it's a document you can be in: the default view renders it.
18596        d.build_visual(80);
18597        assert_eq!(d.caret, 0);
18598    }
18599
18600    #[test]
18601    fn saving_an_untitled_document_asks_for_a_name_instead_of_writing() {
18602        let mut d = Doc::blank().unwrap();
18603        d.insert("hello");
18604        assert!(d.dirty);
18605        d.save();
18606        assert_eq!(d.status.as_deref(), Some("untitled — save as…"));
18607        assert!(d.dirty, "it must not come away believing it saved");
18608        assert!(d.is_untitled(), "and it still has no file");
18609    }
18610
18611    #[test]
18612    fn a_blank_document_becomes_a_real_one_at_the_first_save_as() {
18613        let p = temp_path("blank_save_as");
18614        let mut d = Doc::blank().unwrap();
18615        // Plain text — a blank doc opens in Hidden mode, where a typed `#` would
18616        // be kept literal (`\#`); this test is about save-as, not escaping (which
18617        // has its own test), so it types nothing that escaping would touch.
18618        d.insert("hi");
18619        d.save_as(p.clone());
18620        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi");
18621        assert!(!d.is_untitled());
18622        assert!(!d.dirty);
18623        assert_eq!(d.file_name(), p.file_name().unwrap().to_string_lossy());
18624        assert_eq!(
18625            d.disk_state(),
18626            DiskState::Unchanged,
18627            "the watermark is stamped"
18628        );
18629        // And ⌘S is a plain save from here on.
18630        d.insert("!");
18631        d.save();
18632        assert_eq!(std::fs::read_to_string(&p).unwrap(), "hi!");
18633        let _ = std::fs::remove_file(&p);
18634    }
18635
18636    // ── a file that isn't there yet ───────────────────────────────────────────
18637
18638    /// A unique path in the temp dir with the given extension, guaranteed not to
18639    /// exist — what `leaf notes.md` is handed when the file has never been made.
18640    fn missing_path(name: &str, ext: &str) -> PathBuf {
18641        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18642        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18643        let mut p = std::env::temp_dir();
18644        p.push(format!("leaf_test_new_{name}_{seq}.{ext}"));
18645        let _ = std::fs::remove_file(&p);
18646        p
18647    }
18648
18649    #[test]
18650    fn a_file_that_doesnt_exist_opens_as_an_empty_named_document() {
18651        let p = missing_path("named", "md");
18652        let mut d = Doc::open_or_create(p.clone()).unwrap();
18653
18654        assert_eq!(d.source, "", "nothing was read, so there's nothing in it");
18655        assert!(!d.dirty, "an untouched new buffer has nothing to lose");
18656        assert!(
18657            !d.is_untitled(),
18658            "it has the name the user asked for — ^S must not detour to Save As"
18659        );
18660        assert_eq!(d.file_name(), p.file_name().unwrap().to_str().unwrap());
18661        assert!(d.path.is_absolute(), "the same absolute path `open` stores");
18662        assert!(!p.exists(), "and opening it wrote nothing");
18663        // And it's a document you can be in.
18664        d.build_visual(80);
18665        assert_eq!(d.caret, 0);
18666    }
18667
18668    #[test]
18669    fn a_new_file_is_created_by_its_first_save() {
18670        let p = missing_path("first_save", "md");
18671        let mut d = Doc::open_or_create(p.clone()).unwrap();
18672        d.insert("hello\n");
18673        assert!(d.dirty);
18674        d.save();
18675
18676        assert_eq!(
18677            std::fs::read_to_string(&p).unwrap(),
18678            "hello\n",
18679            "a plain ^S wrote it — no Save As, no name to invent"
18680        );
18681        assert!(!d.dirty);
18682        assert_eq!(d.disk_state(), DiskState::Unchanged);
18683        let _ = std::fs::remove_file(&p);
18684    }
18685
18686    #[test]
18687    fn a_new_file_takes_its_format_from_the_extension() {
18688        // The one thing `blank` can't do: with no name it has to assume Markdown,
18689        // and typing djot into a Markdown parse is the wrong buffer.
18690        let dj = missing_path("format", "dj");
18691        assert_eq!(Doc::open_or_create(dj).unwrap().format_name(), "djot");
18692        let md = missing_path("format", "md");
18693        assert_eq!(Doc::open_or_create(md).unwrap().format_name(), "markdown");
18694    }
18695
18696    #[test]
18697    fn a_new_file_reports_itself_missing_until_it_is_saved() {
18698        // Not `Untitled` — that's the answer for a document with no path, and it
18699        // would tell a frontend there is nothing a save could collide with. Here
18700        // there is a path, and the file simply isn't at it yet.
18701        let p = missing_path("disk_state", "md");
18702        let mut d = Doc::open_or_create(p.clone()).unwrap();
18703        assert_eq!(d.disk_state(), DiskState::Missing);
18704
18705        // Somebody else creates it while the buffer is open: that's an overwrite
18706        // the frontend has to be able to prompt about, exactly as for an opened
18707        // file. Their bytes, not ours, so `Changed`.
18708        std::fs::write(&p, "theirs\n").unwrap();
18709        assert_eq!(d.disk_state(), DiskState::Changed);
18710
18711        // Saving makes the file ours and re-stamps the watermark.
18712        d.insert("ours\n");
18713        d.save();
18714        assert_eq!(d.disk_state(), DiskState::Unchanged);
18715        assert_eq!(std::fs::read_to_string(&p).unwrap(), "ours\n");
18716        let _ = std::fs::remove_file(&p);
18717    }
18718
18719    #[test]
18720    fn open_or_create_still_opens_a_file_that_is_there() {
18721        let d = doc_with("open_or_create_existing", "body\n");
18722        let reopened = Doc::open_or_create(d.path.clone()).unwrap();
18723        assert_eq!(reopened.source, "body\n");
18724        assert_eq!(reopened.disk_state(), DiskState::Unchanged);
18725    }
18726
18727    #[test]
18728    fn a_missing_file_with_no_readable_extension_is_still_an_error() {
18729        // A mistyped flag or a stray argument must not become a buffer promising
18730        // to save somewhere — the same refusal `open` gives a real file.
18731        let mut p = std::env::temp_dir();
18732        p.push("leaf_test_new_bad_ext.wat");
18733        assert!(Doc::open_or_create(p).is_err());
18734        let mut none = std::env::temp_dir();
18735        none.push("leaf_test_new_no_ext");
18736        assert!(Doc::open_or_create(none).is_err());
18737    }
18738
18739    #[test]
18740    fn a_new_file_in_a_directory_that_doesnt_exist_opens_but_wont_save() {
18741        // Opening reads nothing, so there is nothing to fail on yet; the write is
18742        // where it fails, and it says so rather than claiming a save.
18743        let p = std::env::temp_dir().join("leaf_test_no_such_dir_c41/doc.md");
18744        let mut d = Doc::open_or_create(p).unwrap();
18745        d.insert("x");
18746        d.save();
18747        assert!(
18748            d.status.as_deref().unwrap().starts_with("save failed:"),
18749            "got {:?}",
18750            d.status
18751        );
18752        assert!(d.dirty, "it must not come away believing it saved");
18753    }
18754
18755    // ── save as ───────────────────────────────────────────────────────────────
18756
18757    /// A unique path in the temp dir that no fixture wrote — a Save As target.
18758    fn temp_path(name: &str) -> PathBuf {
18759        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18760        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18761        let mut p = std::env::temp_dir();
18762        p.push(format!("leaf_test_target_{name}_{seq}.md"));
18763        let _ = std::fs::remove_file(&p);
18764        p
18765    }
18766
18767    #[test]
18768    fn save_as_moves_the_document_and_leaves_the_old_file_alone() {
18769        let mut d = doc_with("save_as_move", "original\n");
18770        let old = d.path.clone();
18771        let new = temp_path("save_as_move");
18772        d.insert("edited: ");
18773        d.save_as(new.clone());
18774
18775        assert_eq!(std::fs::read_to_string(&new).unwrap(), "edited: original\n");
18776        assert_eq!(
18777            std::fs::read_to_string(&old).unwrap(),
18778            "original\n",
18779            "Save As doesn't touch the file it came from"
18780        );
18781        assert_eq!(d.path, new, "the document moved");
18782        assert!(!d.dirty);
18783        assert_eq!(
18784            d.status.as_deref(),
18785            Some(&*format!("saved {}", d.file_name()))
18786        );
18787
18788        // Every later save follows it, which is the whole difference from a copy.
18789        d.caret = 0;
18790        d.insert("re-");
18791        d.save();
18792        assert_eq!(
18793            std::fs::read_to_string(&new).unwrap(),
18794            "re-edited: original\n"
18795        );
18796        assert_eq!(std::fs::read_to_string(&old).unwrap(), "original\n");
18797        let _ = std::fs::remove_file(&new);
18798    }
18799
18800    #[test]
18801    fn save_as_overwrites_an_existing_target() {
18802        // The picker already asked; asking again down here is the same question
18803        // twice, and the second one has no way to be answered.
18804        let new = temp_path("save_as_over");
18805        std::fs::write(&new, "theirs\n").unwrap();
18806        let mut d = doc_with("save_as_over", "ours\n");
18807        d.save_as(new.clone());
18808        assert_eq!(std::fs::read_to_string(&new).unwrap(), "ours\n");
18809        let _ = std::fs::remove_file(&new);
18810    }
18811
18812    #[test]
18813    fn a_save_as_that_fails_leaves_the_document_where_it_was() {
18814        let mut d = doc_with("save_as_fail", "body\n");
18815        let old = d.path.clone();
18816        d.insert("x");
18817        // A directory that doesn't exist: the write can't land.
18818        let bad = std::env::temp_dir().join("leaf_test_no_such_dir_9f2/doc.md");
18819        d.save_as(bad);
18820
18821        assert_eq!(
18822            d.path, old,
18823            "the document must not move to a file that isn't there"
18824        );
18825        assert!(d.dirty, "and must not believe it saved");
18826        assert!(
18827            d.status.as_deref().unwrap().starts_with("save failed:"),
18828            "the same failure a plain save reports, got {:?}",
18829            d.status
18830        );
18831        // The original is still the document's file, and still saveable.
18832        d.save();
18833        assert_eq!(std::fs::read_to_string(&old).unwrap(), "xbody\n");
18834        assert!(!d.dirty);
18835    }
18836
18837    #[test]
18838    fn save_as_renames_without_reparsing_the_format() {
18839        // `.dj` on the name doesn't make the buffer djot: it was parsed as
18840        // Markdown and still is, and saying otherwise would be a conversion the
18841        // user never asked for (and an undo history thrown away to do it).
18842        let mut d = doc_with("save_as_format", "**b**\n");
18843        let mut new = temp_path("save_as_format");
18844        new.set_extension("dj");
18845        d.save_as(new.clone());
18846        assert_eq!(d.format_name(), "markdown");
18847        let _ = std::fs::remove_file(&new);
18848    }
18849
18850    // ── external change / reload ──────────────────────────────────────────────
18851
18852    #[test]
18853    fn an_untouched_file_reports_unchanged() {
18854        let mut d = doc_with("disk_clean", "body\n");
18855        assert_eq!(d.disk_state(), DiskState::Unchanged);
18856        // Editing the buffer is not editing the file.
18857        d.insert("x");
18858        assert_eq!(d.disk_state(), DiskState::Unchanged);
18859        assert!(d.dirty);
18860        // Saving re-stamps the watermark rather than reporting our own bytes back.
18861        d.save();
18862        assert_eq!(d.disk_state(), DiskState::Unchanged);
18863    }
18864
18865    #[test]
18866    fn a_file_written_underneath_reports_changed() {
18867        let mut d = doc_with("disk_changed", "body\n");
18868        std::fs::write(&d.path, "someone else\n").unwrap();
18869        assert_eq!(d.disk_state(), DiskState::Changed);
18870        // Dirty *and* changed is the clobber: both halves are readable, and
18871        // leaf-core takes neither side.
18872        d.insert("x");
18873        assert!(d.dirty && d.disk_state() == DiskState::Changed);
18874        // Saving anyway is allowed — the frontend asked, or chose not to.
18875        d.save();
18876        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "xbody\n");
18877        assert_eq!(d.disk_state(), DiskState::Unchanged);
18878    }
18879
18880    #[test]
18881    fn a_file_rewritten_with_the_same_bytes_is_unchanged() {
18882        // The hash is what makes this honest: the file was written (a fresh
18883        // mtime), and nothing about the document is stale.
18884        let d = doc_with("disk_same_bytes", "body\n");
18885        std::fs::write(&d.path, "body\n").unwrap();
18886        assert_eq!(d.disk_state(), DiskState::Unchanged);
18887    }
18888
18889    #[test]
18890    fn a_deleted_file_reports_missing() {
18891        let mut d = doc_with("disk_missing", "body\n");
18892        std::fs::remove_file(&d.path).unwrap();
18893        assert_eq!(d.disk_state(), DiskState::Missing);
18894        // A save recreates it, and the document is whole again.
18895        d.save();
18896        assert_eq!(d.disk_state(), DiskState::Unchanged);
18897        assert_eq!(std::fs::read_to_string(&d.path).unwrap(), "body\n");
18898    }
18899
18900    #[test]
18901    fn reload_replaces_the_document_with_the_file() {
18902        for (view, tag) in VIEWS {
18903            let mut d = doc_in(view, &format!("reload_{tag}"), "one\n\ntwo\n");
18904            d.insert("edited ");
18905            assert!(d.dirty);
18906            std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
18907            d.reload();
18908
18909            assert_eq!(d.source, "one\n\ntwo\n\nthree\n", "{tag}");
18910            assert!(!d.dirty, "{tag}: the file is what we have");
18911            assert_eq!(d.disk_state(), DiskState::Unchanged, "{tag}");
18912            assert_eq!(
18913                d.status.as_deref(),
18914                Some(&*format!("reloaded {}", d.file_name()))
18915            );
18916            // The reloaded tree is live, not the old parse.
18917            d.caret = d.source.find("three").unwrap();
18918            assert_eq!(d.breadcrumb(), "doc › para › str", "{tag}");
18919        }
18920    }
18921
18922    #[test]
18923    fn reload_clamps_the_caret_and_drops_the_selection() {
18924        let mut d = doc_with("reload_caret", "a long first line\n");
18925        d.caret = 12;
18926        d.anchor = Some(4);
18927        std::fs::write(&d.path, "short\n").unwrap();
18928        d.reload();
18929        assert_eq!(d.caret, d.source.len(), "clamped into the shorter file");
18930        assert_eq!(
18931            d.anchor, None,
18932            "a selection over bytes that changed is a lie"
18933        );
18934        assert!(d.selection().is_none());
18935
18936        // A caret the file still has room for stays put.
18937        let mut d = doc_with("reload_caret_keep", "one\n\ntwo\n");
18938        d.caret = 2;
18939        std::fs::write(&d.path, "one\n\ntwo\n\nthree\n").unwrap();
18940        d.reload();
18941        assert_eq!(d.caret, 2);
18942    }
18943
18944    /// A silent reload is something that happened *to* a reader — a formatter,
18945    /// a `git checkout` — so it has to be undoable like anything else that
18946    /// changes the document, and undoable as one step rather than as however
18947    /// many the file happens to differ by.
18948    #[test]
18949    fn reload_is_one_undo_step_and_keeps_the_history_under_it() {
18950        let mut d = doc_with("reload_undo", "body\n");
18951        d.insert("x");
18952        assert_eq!(d.source, "xbody\n");
18953        std::fs::write(&d.path, "replaced\n").unwrap();
18954        d.reload();
18955        assert_eq!(d.source, "replaced\n");
18956        assert!(!d.dirty, "a reload lands clean");
18957
18958        // One ^Z takes the whole swap off, and hands back the unsaved work it
18959        // replaced — which is unsaved again, because the file no longer says it.
18960        d.undo();
18961        assert_eq!(d.source, "xbody\n", "the reload comes off in one step");
18962        assert!(d.dirty, "and what it comes back to is unsaved");
18963        // …and the history under it is still there.
18964        d.undo();
18965        assert_eq!(
18966            d.source, "body\n",
18967            "the typing before the reload undoes too"
18968        );
18969        // Redo walks back up through the reload.
18970        d.redo();
18971        d.redo();
18972        assert_eq!(d.source, "replaced\n");
18973    }
18974
18975    /// A file rewritten with the bytes it already had is not an edit, so it
18976    /// must not leave an undo step behind for something nobody did.
18977    #[test]
18978    fn reloading_identical_bytes_pushes_no_undo_step() {
18979        let mut d = doc_with("reload_same", "body\n");
18980        d.insert("x");
18981        std::fs::write(&d.path, "xbody\n").unwrap();
18982        d.reload();
18983        assert_eq!(d.source, "xbody\n");
18984        assert!(!d.dirty, "the file now says what the buffer does");
18985        d.undo();
18986        assert_eq!(
18987            d.source, "body\n",
18988            "one step back is the typing, not a no-op"
18989        );
18990    }
18991
18992    #[test]
18993    fn a_reload_that_cant_read_leaves_the_document_alone() {
18994        let mut d = doc_with("reload_gone", "body\n");
18995        d.insert("x");
18996        std::fs::remove_file(&d.path).unwrap();
18997        d.reload();
18998        assert_eq!(d.source, "xbody\n", "the unsaved work is still here");
18999        assert!(d.dirty);
19000        assert!(
19001            d.status.as_deref().unwrap().starts_with("reload failed:"),
19002            "{:?}",
19003            d.status
19004        );
19005
19006        // And an untitled document has nothing to reload from.
19007        let mut d = Doc::blank().unwrap();
19008        d.insert("typed");
19009        d.reload();
19010        assert_eq!(d.source, "typed");
19011        assert_eq!(d.status.as_deref(), Some("no file to reload"));
19012    }
19013
19014    #[test]
19015    fn a_read_only_document_refuses_every_door() {
19016        let mut d = doc_with("readonly", "one two three\n");
19017        d.insert("x");
19018        assert!(d.dirty, "writable first, so the undo step exists");
19019        d.set_read_only(true);
19020        let before = d.source.clone();
19021        d.insert("y");
19022        d.backspace();
19023        d.undo();
19024        d.redo();
19025        assert_eq!(d.source, before, "no door moved a byte");
19026        d.set_read_only(false);
19027        d.undo();
19028        assert_ne!(d.source, before, "off again, the same doors work");
19029    }
19030
19031    /// The doors that go to twig's own verbs rather than through the splice.
19032    /// Typed text in the rendered view under the default markup mode is the
19033    /// everyday one — it is what a keystroke in leaf-web or the Apple views
19034    /// becomes — and it walked straight past the gate.
19035    #[test]
19036    fn a_read_only_document_refuses_the_doors_around_the_splice() {
19037        let mut d = wysiwyg_doc(
19038            "readonly-doors",
19039            "one two three\n\n| a | b |\n|---|---|\n| c | d |\n",
19040        );
19041        d.set_markup_mode(MarkupMode::None);
19042        d.set_read_only(true);
19043        let before = d.source.clone();
19044        d.place_caret(3, false);
19045        d.insert("y");
19046        d.insert_link("https://example.com");
19047        d.insert_image("a.png", "alt");
19048        d.insert_thematic_break();
19049        d.insert_footnote();
19050        d.place_caret(0, false);
19051        d.place_caret(3, true);
19052        d.toggle(InlineKind::Strong);
19053        d.toggle_heading(2);
19054        d.set_block(BlockKind::Paragraph);
19055        d.toggle_list(false);
19056        d.toggle_blockquote();
19057        d.toggle_task_item();
19058        d.newline();
19059        d.indent();
19060        d.set_code_language("rust");
19061        let in_cell = d.source.find("| c").unwrap() + 2;
19062        d.place_caret(in_cell, false);
19063        assert!(d.caret_in_table(), "the caret is in the grid");
19064        assert!(!d.cell_line_break(), "the cell break reports the refusal");
19065        assert_eq!(d.source, before, "no door moved a byte");
19066        assert!(!d.dirty, "nothing to save");
19067        d.set_read_only(false);
19068        d.place_caret(3, false);
19069        d.insert("y");
19070        assert_ne!(d.source, before, "off again, the same doors work");
19071    }
19072
19073    #[test]
19074    fn a_selection_quote_carries_its_context_on_char_boundaries() {
19075        let mut d = doc_with("quote", "before 你好 exact 世界 after\n");
19076        let start = d.source.find("exact").unwrap();
19077        d.place_caret(start, false);
19078        d.place_caret(start + "exact".len(), true);
19079        let q = d.selection_quote(3).unwrap();
19080        assert_eq!(q.exact, "exact");
19081        assert_eq!(
19082            q.prefix, "你好 ",
19083            "chars, not bytes — the multibyte pair counts as two"
19084        );
19085        assert_eq!(q.suffix, " 世界");
19086        assert_eq!(&d.source[q.start..q.end], "exact");
19087        // At the edges the context clips rather than erring.
19088        d.place_caret(0, false);
19089        d.place_caret(6, true);
19090        let q = d.selection_quote(40).unwrap();
19091        assert_eq!(q.prefix, "");
19092        assert_eq!(q.exact, "before");
19093        // No selection is no quote.
19094        d.place_caret(0, false);
19095        assert!(d.selection_quote(3).is_none());
19096    }
19097
19098    #[test]
19099    fn highlights_are_kept_sorted_and_answer_point_queries() {
19100        let mut d = doc_with("hl", "one two three\n");
19101        d.set_highlights(vec![
19102            Highlight {
19103                start: 8,
19104                end: 13,
19105                id: "b".into(),
19106                color: None,
19107                marker: None,
19108            },
19109            Highlight {
19110                start: 0,
19111                end: 3,
19112                id: "a".into(),
19113                color: Some("#ffe066".into()),
19114                marker: None,
19115            },
19116            Highlight {
19117                start: 5,
19118                end: 5,
19119                id: "empty".into(),
19120                color: None,
19121                marker: None,
19122            },
19123        ]);
19124        assert_eq!(
19125            d.highlights()
19126                .iter()
19127                .map(|h| h.id.as_str())
19128                .collect::<Vec<_>>(),
19129            ["a", "b"],
19130            "sorted by start, the empty range dropped"
19131        );
19132        assert_eq!(d.highlight_at(1).map(|h| h.id.as_str()), Some("a"));
19133        assert_eq!(d.highlight_at(3), None, "end is exclusive");
19134        assert_eq!(d.highlight_at(8).map(|h| h.id.as_str()), Some("b"));
19135        d.set_highlights(Vec::new());
19136        assert!(d.highlights().is_empty(), "a replace is a replace");
19137    }
19138
19139    /// `Highlight::covering` and the cursor over it are what both painters ask
19140    /// per glyph, so they have to answer the same as the scan they replaced —
19141    /// including in the gaps, which is where most glyphs are.
19142    #[test]
19143    fn covering_answers_from_a_sorted_list_without_scanning_all_of_it() {
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        // Disjoint, as search hits are: in a range, in a gap, and past the end.
19152        let hits: Vec<Highlight> = (0..20).map(|i| hl(i * 10, i * 10 + 3, "hit")).collect();
19153        assert_eq!(Highlight::covering(&hits, 0).map(|h| h.start), Some(0));
19154        assert_eq!(Highlight::covering(&hits, 102).map(|h| h.start), Some(100));
19155        assert_eq!(
19156            Highlight::covering(&hits, 105),
19157            None,
19158            "a gap covers nothing"
19159        );
19160        assert_eq!(Highlight::covering(&hits, 103), None, "end is exclusive");
19161        assert_eq!(Highlight::covering(&hits, 9_999), None);
19162        assert_eq!(Highlight::covering(&[], 0), None);
19163
19164        // Nested: first by start, so a hit inside an annotation still resolves
19165        // to the annotation — and the range that stops short doesn't mask it.
19166        let nested = vec![hl(0, 20, "outer"), hl(5, 10, "inner")];
19167        assert_eq!(
19168            Highlight::covering(&nested, 7).map(|h| h.id.as_str()),
19169            Some("outer")
19170        );
19171        assert_eq!(
19172            Highlight::covering(&nested, 15).map(|h| h.id.as_str()),
19173            Some("outer")
19174        );
19175    }
19176
19177    /// The cursor is an optimisation, so the only thing worth asserting is that
19178    /// it is not also a change of answer — at every offset, over a list with a
19179    /// nest in it, walked forwards and then backwards.
19180    #[test]
19181    fn the_highlight_cursor_answers_exactly_what_a_fresh_scan_would() {
19182        let hl = |start: usize, end: usize, id: &str| Highlight {
19183            start,
19184            end,
19185            id: id.into(),
19186            color: None,
19187            marker: None,
19188        };
19189        let mut list = vec![
19190            hl(0, 20, "outer"),
19191            hl(5, 10, "inner"),
19192            hl(30, 33, "hit"),
19193            hl(40, 43, "hit"),
19194        ];
19195        list.sort_by_key(|h| (h.start, h.end));
19196
19197        let mut cursor = HighlightCursor::new(&list);
19198        for offset in 0..50 {
19199            assert_eq!(
19200                cursor.at(offset).map(|h| h.id.as_str()),
19201                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19202                "cursor disagrees at {offset}"
19203            );
19204        }
19205        // Backwards: the cursor re-seats rather than answering from where it
19206        // had got to, so a painter that revisits a row is still told the truth.
19207        for offset in (0..50).rev() {
19208            assert_eq!(
19209                cursor.at(offset).map(|h| h.id.as_str()),
19210                Highlight::covering(&list, offset).map(|h| h.id.as_str()),
19211                "cursor disagrees walking back at {offset}"
19212            );
19213        }
19214    }
19215
19216    // ── the presentation vocabulary ─────────────────────────────────────────
19217
19218    /// A document in `format`, for the gesture tests that want more than the
19219    /// Markdown `doc_with` writes.
19220    fn fmt_doc(body: &str, format: Format) -> Doc {
19221        Doc::from_source(body.to_string(), format).unwrap()
19222    }
19223
19224    /// Alignment is a block property, so the gesture is `set_block_attrs` on
19225    /// the caret's block whatever is selected — and each format spells it its
19226    /// own way: djot's `{…}` line above the block, a `<div>` around it in
19227    /// Markdown (the format has nowhere else to put it), the tag in HTML.
19228    #[test]
19229    fn set_alignment_spells_the_class_the_format_s_own_way() {
19230        let mut dj = fmt_doc("hello\n", Format::Djot);
19231        dj.caret = 1;
19232        dj.set_alignment(Some(Align::Center));
19233        assert_eq!(dj.source, "{.center}\nhello\n");
19234        assert!(dj.dirty);
19235        assert_eq!(dj.status, None);
19236
19237        let mut md = fmt_doc("hello\n", Format::Markdown);
19238        md.caret = 1;
19239        md.set_alignment(Some(Align::Right));
19240        assert_eq!(md.source, "<div class=\"right\">\n\nhello\n\n</div>\n");
19241
19242        let mut html = fmt_doc("<p>hello</p>\n", Format::Html);
19243        html.caret = html.source.find("hello").unwrap();
19244        html.set_alignment(Some(Align::Justify));
19245        assert_eq!(html.source, "<p class=\"justify\">hello</p>\n");
19246    }
19247
19248    /// Each gesture edits **one key and keeps the rest** — twig's contract is
19249    /// replace-not-merge, so leaf reads the node's attributes, edits its own
19250    /// key out of them, and passes the list back whole. A document from
19251    /// elsewhere passes through the editor unharmed.
19252    #[test]
19253    fn a_presentation_gesture_keeps_every_attribute_it_did_not_write() {
19254        let mut d = fmt_doc(
19255            "{.lead .center #intro data-line-height=\"1.5\"}\nhello\n",
19256            Format::Djot,
19257        );
19258        d.caret = d.source.find("hello").unwrap();
19259        d.set_alignment(Some(Align::Right));
19260        // `center` goes, `lead` stays, and neither the id nor the spacing is
19261        // touched.
19262        // The serializer picks the order; what matters is which keys survive.
19263        assert!(d.source.contains(".lead"), "{:?}", d.source);
19264        assert!(d.source.contains(".right"), "{:?}", d.source);
19265        assert!(!d.source.contains(".center"), "{:?}", d.source);
19266        assert!(d.source.contains("#intro"), "{:?}", d.source);
19267        assert!(
19268            d.source.contains("data-line-height=\"1.5\""),
19269            "{:?}",
19270            d.source
19271        );
19272        assert_eq!(d.alignment_at_caret(), Some(Align::Right));
19273        assert_eq!(
19274            d.line_spacing_at_caret(),
19275            Some(LineHeight::Step(LineSpacing::OneHalf))
19276        );
19277
19278        // And the other way round: the spacing gesture leaves the classes be.
19279        d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19280        assert!(d.source.contains(".lead"), "{:?}", d.source);
19281        assert!(d.source.contains(".right"), "{:?}", d.source);
19282        assert_eq!(
19283            d.line_spacing_at_caret(),
19284            Some(LineHeight::Step(LineSpacing::Double))
19285        );
19286    }
19287
19288    /// Clearing is the same gesture with `None`: the key goes, the tokens leaf
19289    /// owns go out of `class`, and a block left with nothing at all is spelled
19290    /// bare again — in Markdown by unwrapping the div twig wrapped it in.
19291    #[test]
19292    fn none_clears_a_key_and_an_empty_set_unwraps_the_block() {
19293        let mut dj = fmt_doc("{.lead .center}\nhello\n", Format::Djot);
19294        dj.caret = dj.source.find("hello").unwrap();
19295        dj.set_alignment(None);
19296        assert_eq!(dj.source, "{.lead}\nhello\n", "the foreign class stays");
19297        assert_eq!(dj.alignment_at_caret(), None);
19298
19299        let mut bare = fmt_doc("{.center}\nhello\n", Format::Djot);
19300        bare.caret = bare.source.find("hello").unwrap();
19301        bare.set_alignment(None);
19302        assert_eq!(
19303            bare.source, "hello\n",
19304            "the last key takes the line with it"
19305        );
19306
19307        let mut md = fmt_doc("hello\n", Format::Markdown);
19308        md.caret = 1;
19309        md.set_alignment(Some(Align::Center));
19310        assert_eq!(md.source, "<div class=\"center\">\n\nhello\n\n</div>\n");
19311        md.caret = md.source.find("hello").unwrap();
19312        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::OneFifteen)));
19313        assert_eq!(
19314            md.source, "<div class=\"center\" data-line-height=\"1.15\">\n\nhello\n\n</div>\n",
19315            "the second key rewrites the div rather than nesting a second"
19316        );
19317        md.caret = md.source.find("hello").unwrap();
19318        md.set_alignment(None);
19319        md.caret = md.source.find("hello").unwrap();
19320        md.set_line_spacing(None);
19321        assert_eq!(md.source, "hello\n", "an empty set unwraps the div");
19322    }
19323
19324    /// Size, face and colour are the run's over a selection and the block's
19325    /// with none — so "make this paragraph larger" is a click with the caret in
19326    /// it rather than a select-all first.
19327    #[test]
19328    fn a_run_gesture_wraps_a_selection_and_sets_the_block_without_one() {
19329        // With a selection: a span, in each format's own spelling.
19330        let mut dj = fmt_doc("a big b\n", Format::Djot);
19331        dj.anchor = Some(2);
19332        dj.caret = 5;
19333        dj.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19334        assert_eq!(dj.source, "a [big]{data-size=\"large\"} b\n");
19335        assert_eq!(
19336            dj.font_size_at_caret(),
19337            Some(FontSize::Step(SizeStep::Large))
19338        );
19339
19340        let mut md = fmt_doc("a big b\n", Format::Markdown);
19341        md.anchor = Some(2);
19342        md.caret = 5;
19343        md.set_text_color(Some(TextColor::Named(MarkColor::Blue)));
19344        assert_eq!(md.source, "a <span data-color=\"blue\">big</span> b\n");
19345        assert_eq!(
19346            md.text_color_at_caret(),
19347            Some(TextColor::Named(MarkColor::Blue))
19348        );
19349
19350        // Without one: the caret's block, through the block gesture.
19351        let mut block = fmt_doc("a big b\n", Format::Djot);
19352        block.caret = 3;
19353        block.set_font_family(Some(FontFace::Generic(FontFamily::Monospace)));
19354        assert_eq!(block.source, "{data-font=\"monospace\"}\na big b\n");
19355        assert_eq!(
19356            block.font_family_at_caret(),
19357            Some(FontFace::Generic(FontFamily::Monospace))
19358        );
19359    }
19360
19361    /// The *Other…* row of each of the four menus: a value goes into the
19362    /// document in its canonical spelling and comes back out of the query as
19363    /// the same value. One round trip per property, because the four go out
19364    /// through different doors — two block gestures, and the run three through
19365    /// the span that `wrap_range_attrs` mints.
19366    #[test]
19367    fn an_exact_value_round_trips_through_the_gesture_and_the_query() {
19368        // Size: the run three, over a selection.
19369        let mut d = fmt_doc("a big b\n", Format::Djot);
19370        d.anchor = Some(2);
19371        d.caret = 5;
19372        d.set_font_size(FontSize::points(14.0));
19373        assert_eq!(d.source, "a [big]{data-size=\"14pt\"} b\n");
19374        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19375
19376        // Colour, onto the same span — the gesture keeps the size it finds.
19377        d.set_text_color(Some(TextColor::Rgb {
19378            r: 0xc0,
19379            g: 0x30,
19380            b: 0x30,
19381        }));
19382        assert_eq!(
19383            d.source,
19384            "a [big]{data-size=\"14pt\" data-color=\"#c03030\"} b\n"
19385        );
19386        assert_eq!(
19387            d.text_color_at_caret(),
19388            Some(TextColor::Rgb {
19389                r: 0xc0,
19390                g: 0x30,
19391                b: 0x30
19392            })
19393        );
19394
19395        // Face: a family name, as given.
19396        d.set_font_family(Some(FontFace::Named("Garamond".into())));
19397        assert!(
19398            d.source.contains("data-font=\"Garamond\""),
19399            "{:?}",
19400            d.source
19401        );
19402        assert_eq!(
19403            d.font_family_at_caret(),
19404            Some(FontFace::Named("Garamond".into()))
19405        );
19406
19407        // Line spacing: a block gesture, and an exact ratio.
19408        let mut block = fmt_doc("hello\n", Format::Djot);
19409        block.caret = 1;
19410        block.set_line_spacing(LineHeight::ratio(1.3));
19411        assert_eq!(block.source, "{data-line-height=\"1.3\"}\nhello\n");
19412        assert_eq!(block.line_spacing_at_caret(), LineHeight::ratio(1.3));
19413
19414        // And a value spelled long is written back short, so the same press
19415        // twice writes the same bytes: `14.0pt` in, `14pt` out.
19416        let mut long = fmt_doc("{data-size=\"14.0pt\"}\nhello\n", Format::Djot);
19417        long.caret = long.source.find("hello").unwrap();
19418        assert_eq!(long.font_size_at_caret(), FontSize::points(14.0));
19419        let in_force = long.font_size_at_caret();
19420        long.set_font_size(in_force);
19421        assert_eq!(long.source, "{data-size=\"14pt\"}\nhello\n");
19422    }
19423
19424    /// A value the grammar does not cover is what it was before the vocabulary
19425    /// opened: carried untouched by the document, answered `None` by the query
19426    /// so the menu ticks *Default*, and rewritten only by a gesture on its own
19427    /// key. leaf is not going to grow a CSS parser to guess at `1.3em`.
19428    #[test]
19429    fn a_value_outside_the_grammar_is_carried_and_the_menu_ticks_the_default() {
19430        let src =
19431            "{data-size=\"huge\" data-color=\"rgb(1,2,3)\" data-line-height=\"1.3em\"}\nhello\n";
19432        let mut d = fmt_doc(src, Format::Djot);
19433        d.caret = d.source.find("hello").unwrap();
19434        assert_eq!(d.font_size_at_caret(), None);
19435        assert_eq!(d.text_color_at_caret(), None);
19436        assert_eq!(d.line_spacing_at_caret(), None);
19437
19438        // The keys are still there, untouched, after a gesture on a *different*
19439        // key — "edit one key and keep the rest" holds for a value it cannot
19440        // read as readily as for one it can.
19441        d.set_alignment(Some(Align::Center));
19442        assert!(d.source.contains("data-size=\"huge\""), "{:?}", d.source);
19443        assert!(
19444            d.source.contains("data-color=\"rgb(1,2,3)\""),
19445            "{:?}",
19446            d.source
19447        );
19448        assert!(
19449            d.source.contains("data-line-height=\"1.3em\""),
19450            "{:?}",
19451            d.source
19452        );
19453        // And the gesture on its *own* key replaces it, which is the one way a
19454        // carried value ever changes.
19455        d.caret = d.source.find("hello").unwrap();
19456        d.set_font_size(FontSize::points(12.0));
19457        assert!(d.source.contains("data-size=\"12pt\""), "{:?}", d.source);
19458        assert!(!d.source.contains("huge"), "{:?}", d.source);
19459    }
19460
19461    /// The nearest node wins whichever *form* either node wrote: a value inside
19462    /// a name, a name inside a value. The fold has one rule and does not learn
19463    /// a second one for exact values.
19464    #[test]
19465    fn the_nearest_node_wins_whether_it_named_a_size_or_measured_one() {
19466        // A value inside a name: the block says `small`, the span says `14pt`.
19467        let mut d = fmt_doc(
19468            "{data-size=\"small\"}\nx [y]{data-size=\"14pt\"} z\n",
19469            Format::Djot,
19470        );
19471        d.caret = d.source.find('y').unwrap();
19472        assert_eq!(d.font_size_at_caret(), FontSize::points(14.0));
19473        d.caret = d.source.find('x').unwrap();
19474        assert_eq!(
19475            d.font_size_at_caret(),
19476            Some(FontSize::Step(SizeStep::Small))
19477        );
19478
19479        // And a name inside a value, which is the same rule read the other way.
19480        let mut e = fmt_doc(
19481            "{data-size=\"14pt\" data-color=\"#c03030\"}\nx [y]{data-size=\"small\"} z\n",
19482            Format::Djot,
19483        );
19484        e.caret = e.source.find('y').unwrap();
19485        assert_eq!(
19486            e.font_size_at_caret(),
19487            Some(FontSize::Step(SizeStep::Small))
19488        );
19489        assert_eq!(
19490            e.text_color_at_caret(),
19491            Some(TextColor::Rgb {
19492                r: 0xc0,
19493                g: 0x30,
19494                b: 0x30
19495            }),
19496            "the block's colour still reaches the span"
19497        );
19498        e.caret = e.source.find('x').unwrap();
19499        assert_eq!(e.font_size_at_caret(), FontSize::points(14.0));
19500    }
19501
19502    /// twig re-styles the span a range already lies in rather than nesting a
19503    /// second, and an empty set unwraps it — so a second press of the menu
19504    /// fixes the size instead of building `[[big]{.a}]{.b}`, and the entry that
19505    /// means "the theme's own" takes the span away.
19506    #[test]
19507    fn a_second_run_gesture_re_styles_the_span_and_none_unwraps_it() {
19508        let mut d = fmt_doc("a big b\n", Format::Djot);
19509        d.anchor = Some(2);
19510        d.caret = 5;
19511        d.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19512        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19513
19514        // The selection `wrap_range_attrs` left behind covers the whole span;
19515        // colouring it now keeps the size, because the gesture reads the span's
19516        // attributes before it edits its own key.
19517        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19518        assert_eq!(
19519            d.source, "a [big]{data-size=\"large\" data-color=\"red\"} b\n",
19520            "one span, both keys"
19521        );
19522        assert_eq!(
19523            d.font_size_at_caret(),
19524            Some(FontSize::Step(SizeStep::Large))
19525        );
19526        assert_eq!(
19527            d.text_color_at_caret(),
19528            Some(TextColor::Named(MarkColor::Red))
19529        );
19530
19531        d.set_text_color(None);
19532        assert_eq!(d.source, "a [big]{data-size=\"large\"} b\n");
19533        d.set_font_size(None);
19534        assert_eq!(d.source, "a big b\n", "the last key unwraps the span");
19535        assert_eq!(d.font_size_at_caret(), None);
19536    }
19537
19538    /// The queries read the nearest node that names the property: the span the
19539    /// caret is in, then its block, then the `div`s around it.
19540    #[test]
19541    fn a_presentation_query_reads_the_nearest_node_that_names_it() {
19542        let mut d = fmt_doc(
19543            "{.center data-size=\"small\" data-font=\"serif\"}\nx [y]{data-size=\"xx-large\"} z\n",
19544            Format::Djot,
19545        );
19546        // In the span: its own size, the block's face and alignment.
19547        d.caret = d.source.find('y').unwrap();
19548        assert_eq!(
19549            d.font_size_at_caret(),
19550            Some(FontSize::Step(SizeStep::XxLarge))
19551        );
19552        assert_eq!(
19553            d.font_family_at_caret(),
19554            Some(FontFace::Generic(FontFamily::Serif))
19555        );
19556        assert_eq!(d.alignment_at_caret(), Some(Align::Center));
19557        assert_eq!(d.line_spacing_at_caret(), None);
19558        assert_eq!(d.text_color_at_caret(), None);
19559
19560        // Outside it: the block's size.
19561        d.caret = d.source.find('x').unwrap();
19562        assert_eq!(
19563            d.font_size_at_caret(),
19564            Some(FontSize::Step(SizeStep::Small))
19565        );
19566
19567        // And through a Markdown div, which is where a Markdown block's
19568        // attributes live.
19569        let mut md = fmt_doc(
19570            "<div class=\"center\" data-size=\"large\">\n\nhello\n\n</div>\n",
19571            Format::Markdown,
19572        );
19573        md.caret = md.source.find("hello").unwrap();
19574        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19575        assert_eq!(
19576            md.font_size_at_caret(),
19577            Some(FontSize::Step(SizeStep::Large))
19578        );
19579
19580        // A document that names none of it answers `None` everywhere, which is
19581        // "the theme's own" and what every toolbar draws unlit.
19582        let mut plain = doc_with("plain_presentation", "hello\n");
19583        plain.caret = 1;
19584        assert_eq!(plain.alignment_at_caret(), None);
19585        assert_eq!(plain.line_spacing_at_caret(), None);
19586        assert_eq!(plain.font_size_at_caret(), None);
19587        assert_eq!(plain.font_family_at_caret(), None);
19588        assert_eq!(plain.text_color_at_caret(), None);
19589    }
19590
19591    /// A djot fenced div is anonymous the way an attributed span is, and is a
19592    /// block all the same — the *form* is the whole of what tells them apart.
19593    /// Read as a span it poisoned both halves: the run gesture copied the div's
19594    /// entire attribute set onto the span it minted, duplicating the `id`, and
19595    /// the run and block queries answered off a node the walker draws nothing
19596    /// for.
19597    #[test]
19598    fn a_djot_fenced_div_is_not_an_attributed_span() {
19599        let src = "{.center data-size=\"small\" #box}\n:::\nhello world\n:::\n";
19600        let mut d = fmt_doc(src, Format::Djot);
19601        let at = d.source.find("world").unwrap();
19602        d.anchor = Some(at);
19603        d.caret = at + "world".len();
19604        d.set_text_color(Some(TextColor::Named(MarkColor::Red)));
19605        assert_eq!(
19606            d.source,
19607            "{.center data-size=\"small\" #box}\n:::\nhello [world]{data-color=\"red\"}\n:::\n",
19608            "the span carries its own key and nothing of the div's"
19609        );
19610
19611        // And the queries stop at the block: a djot div is not a `<div>`, the
19612        // walker lends its keys to nothing inside it, and a query that said
19613        // otherwise would tick a menu entry no glyph on screen obeys.
19614        assert_eq!(
19615            d.text_color_at_caret(),
19616            Some(TextColor::Named(MarkColor::Red))
19617        );
19618        assert_eq!(d.font_size_at_caret(), None);
19619        assert_eq!(d.alignment_at_caret(), None);
19620    }
19621
19622    /// Clearing a property the block does not name and a `div` around it does
19623    /// would write nothing and change nothing — twig's `set_block_attrs`
19624    /// reaches one node, and the div is not it. The gesture says so instead of
19625    /// leaving the author pressing an entry that never ticks.
19626    #[test]
19627    fn clearing_a_property_an_enclosing_div_names_says_so_and_writes_nothing() {
19628        // Markdown, two paragraphs in one div: not the sole-child shape twig
19629        // writes, so `block_attrs_at_caret` reads the paragraph and the
19630        // paragraph names none of it.
19631        let src = "<div class=\"center\" data-line-height=\"1.5\" data-size=\"large\">\n\nhello\n\nworld\n\n</div>\n";
19632        let mut md = fmt_doc(src, Format::Markdown);
19633        md.caret = md.source.find("hello").unwrap();
19634        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19635
19636        md.set_alignment(None);
19637        assert_eq!(md.source, src, "nothing written");
19638        assert!(!md.dirty);
19639        assert_eq!(
19640            md.status.as_deref(),
19641            Some("alignment: set on the div around the block")
19642        );
19643        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19644
19645        // The same for a `data-` key, at both levels — the block pair and the
19646        // run three, the run three at a bare caret being the block gesture.
19647        md.set_line_spacing(None);
19648        assert_eq!(md.source, src);
19649        assert_eq!(
19650            md.status.as_deref(),
19651            Some("line spacing: set on the div around the block")
19652        );
19653        md.set_font_size(None);
19654        assert_eq!(md.source, src);
19655        assert_eq!(
19656            md.status.as_deref(),
19657            Some("size: set on the div around the block")
19658        );
19659
19660        // HTML has no sole-child fold at all: a block's attributes go on the
19661        // block, so the div around one is always out of reach.
19662        let html_src = "<div class=\"center\"><p>hi</p></div>\n";
19663        let mut html = fmt_doc(html_src, Format::Html);
19664        html.caret = html.source.find("hi").unwrap();
19665        assert_eq!(html.alignment_at_caret(), Some(Align::Center));
19666        html.set_alignment(None);
19667        assert_eq!(html.source, html_src);
19668        assert!(!html.dirty);
19669        assert_eq!(
19670            html.status.as_deref(),
19671            Some("alignment: set on the div around the block")
19672        );
19673
19674        // And it is a refusal, not a rule against clearing: a block that names
19675        // the property itself still loses it, div or no div.
19676        let mut own = fmt_doc(
19677            "<div class=\"center\"><p class=\"right\">hi</p></div>\n",
19678            Format::Html,
19679        );
19680        own.caret = own.source.find("hi").unwrap();
19681        own.set_alignment(None);
19682        assert_eq!(own.source, "<div class=\"center\"><p>hi</p></div>\n");
19683        assert_eq!(own.status, None);
19684    }
19685
19686    /// An edited key is rewritten **where it stands**. The proposal's worked
19687    /// example is the test: a paragraph that came in as `id="intro"
19688    /// class="lead center" data-line-height="1.5"` and is right-aligned goes
19689    /// out as the same list with one token changed. Removing the key and
19690    /// pushing it back shuffled a document's attributes on every press.
19691    #[test]
19692    fn an_edited_key_keeps_its_place_among_the_attributes() {
19693        let mut html = fmt_doc(
19694            "<p id=\"intro\" class=\"lead center\" data-line-height=\"1.5\">hello</p>\n",
19695            Format::Html,
19696        );
19697        html.caret = html.source.find("hello").unwrap();
19698        html.set_alignment(Some(Align::Right));
19699        assert_eq!(
19700            html.source,
19701            "<p id=\"intro\" class=\"lead right\" data-line-height=\"1.5\">hello</p>\n"
19702        );
19703
19704        // A `data-` key the same way, and a key the block did not have still
19705        // goes on the end.
19706        html.caret = html.source.find("hello").unwrap();
19707        html.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19708        assert_eq!(
19709            html.source,
19710            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\">hello</p>\n"
19711        );
19712        html.caret = html.source.find("hello").unwrap();
19713        html.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19714        assert_eq!(
19715            html.source,
19716            "<p id=\"intro\" class=\"lead right\" data-line-height=\"2\" data-size=\"large\">hello</p>\n"
19717        );
19718
19719        // Djot writes the same list in its own spelling, and the order is the
19720        // author's there too.
19721        let mut dj = fmt_doc(
19722            "{#intro .lead .center data-line-height=\"1.5\"}\nhello\n",
19723            Format::Djot,
19724        );
19725        dj.caret = dj.source.find("hello").unwrap();
19726        dj.set_alignment(Some(Align::Right));
19727        assert_eq!(
19728            dj.source,
19729            "{#intro .lead .right data-line-height=\"1.5\"}\nhello\n"
19730        );
19731    }
19732
19733    /// A page break is a block, so twig alone lands one after the caret's whole
19734    /// block; the paragraph is parted at the caret first, exactly as
19735    /// `insert_thematic_break` parts it, and each format spells the directive
19736    /// its own way.
19737    #[test]
19738    fn insert_page_break_parts_the_paragraph_and_spells_the_directive() {
19739        let mut md = doc_with("page_break_md", "hello world\n");
19740        md.caret = 5;
19741        md.insert_page_break();
19742        assert_eq!(md.source, "hello\n\n::page-break\n\nworld\n");
19743        assert!(md.dirty);
19744        assert_eq!(md.status, None);
19745
19746        let mut dj = fmt_doc("hello world\n", Format::Djot);
19747        dj.caret = 5;
19748        dj.insert_page_break();
19749        assert_eq!(dj.source, "hello\n\n::: page-break\n:::\n\nworld\n");
19750
19751        // At a block's end there is no second half to mint, so the break simply
19752        // follows the block — the rule the rule button already has.
19753        let mut end = doc_with("page_break_end", "hello\n");
19754        end.caret = 5;
19755        end.insert_page_break();
19756        assert_eq!(end.source, "hello\n\n::page-break\n\n");
19757        assert_eq!(end.caret, end.source.len(), "on the line under the break");
19758
19759        // And it reaches the map as the placeholder row a frontend paginates on.
19760        end.view = View::Wysiwyg;
19761        end.build_visual(80);
19762        assert_eq!(
19763            end.vmap
19764                .rows
19765                .iter()
19766                .find_map(|r| r.leaf_directive.as_ref())
19767                .map(|m| m.name.as_str()),
19768            Some(PAGE_BREAK)
19769        );
19770
19771        // HTML and AsciiDoc spell it their own way, and draw it the same.
19772        for (fmt, src, spelled) in [
19773            (Format::Html, "<p>hello</p>\n", "<page-break></page-break>"),
19774            (Format::Asciidoc, "hello\n", "<<<"),
19775        ] {
19776            let mut d = fmt_doc(src, fmt);
19777            d.caret = d.source.find("hello").unwrap() + 5;
19778            d.insert_page_break();
19779            assert!(d.source.contains(spelled), "{fmt:?}: {:?}", d.source);
19780            d.view = View::Wysiwyg;
19781            d.build_visual(80);
19782            let marks = d
19783                .vmap
19784                .rows
19785                .iter()
19786                .filter_map(|r| r.leaf_directive.as_ref())
19787                .map(|m| m.name.as_str())
19788                .collect::<Vec<_>>();
19789            assert_eq!(marks, [PAGE_BREAK], "{fmt:?}");
19790        }
19791    }
19792
19793    /// The vocabulary's capabilities, per format. The two block properties are
19794    /// `SetBlockAttrs` and the three run ones `WrapRangeAttrs`, which is why
19795    /// AsciiDoc can align a paragraph and not size a run: its `[#id.role]#text#`
19796    /// keeps an id and a role and has no slot for a `data-` key.
19797    #[test]
19798    fn the_presentation_capabilities_are_ragged_per_format() {
19799        for fmt in [Format::Markdown, Format::Djot, Format::Html] {
19800            let c = Capabilities::of(fmt);
19801            assert!(c.alignment, "{fmt:?} alignment");
19802            assert!(c.line_spacing, "{fmt:?} line spacing");
19803            assert!(c.font_size, "{fmt:?} size");
19804            assert!(c.font_family, "{fmt:?} face");
19805            assert!(c.text_color, "{fmt:?} colour");
19806        }
19807        // Markdown spells both only under the extensions leaf parses with — a
19808        // `<div>` and a `<span>` read back as containers under `html_elements`,
19809        // and `::page-break` as a directive under `directives`. Ask twig's own
19810        // defaults and the answer is no, which is why `Capabilities` is built
19811        // with `supports_with`.
19812        assert!(!Format::Markdown.supports(Gesture::SetBlockAttrs));
19813        assert!(!Format::Markdown.supports(Gesture::WrapRangeAttrs));
19814        assert!(!Format::Markdown.supports(Gesture::InsertDirective));
19815
19816        let adoc = Capabilities::of(Format::Asciidoc);
19817        assert!(adoc.alignment && adoc.line_spacing, "AsciiDoc's `[…]` line");
19818        assert!(
19819            !adoc.font_size && !adoc.font_family && !adoc.text_color,
19820            "AsciiDoc has no inline spelling that keeps a data- key"
19821        );
19822
19823        // XML spells none of it, and neither page break — nor has it blocks a
19824        // caret could name for a move.
19825        let xml = Capabilities::of(Format::Xml);
19826        assert!(!xml.alignment && !xml.font_size && !xml.page_break && !xml.move_block);
19827        for f in [Format::Markdown, Format::Djot, Format::Html] {
19828            assert!(Capabilities::of(f).move_block, "{f:?} moves blocks");
19829        }
19830        for f in [
19831            Format::Markdown,
19832            Format::Djot,
19833            Format::Html,
19834            Format::Asciidoc,
19835        ] {
19836            assert!(Capabilities::of(f).page_break, "{f:?} breaks pages");
19837        }
19838    }
19839
19840    /// A format that cannot spell a property refuses in its own words and
19841    /// writes nothing — the guard every other gesture has.
19842    #[test]
19843    fn a_presentation_gesture_a_format_cannot_spell_is_refused_with_a_reason() {
19844        let src = "<doc><p>hello</p></doc>\n";
19845        #[allow(clippy::type_complexity)]
19846        let ops: [(&str, &dyn Fn(&mut Doc)); 6] = [
19847            ("alignment", &|d: &mut Doc| {
19848                d.set_alignment(Some(Align::Center))
19849            }),
19850            ("line spacing", &|d: &mut Doc| {
19851                d.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)))
19852            }),
19853            ("size", &|d: &mut Doc| {
19854                d.set_font_size(Some(FontSize::Step(SizeStep::Large)))
19855            }),
19856            ("face", &|d: &mut Doc| {
19857                d.set_font_family(Some(FontFace::Generic(FontFamily::Serif)))
19858            }),
19859            ("colour", &|d: &mut Doc| {
19860                d.set_text_color(Some(TextColor::Named(MarkColor::Red)))
19861            }),
19862            ("page break", &|d: &mut Doc| d.insert_page_break()),
19863        ];
19864        for (name, op) in ops {
19865            let mut d = fmt_doc(src, Format::Xml);
19866            let at = d.source.find("hello").unwrap();
19867            d.caret = at;
19868            d.anchor = Some(at + 5);
19869            op(&mut d);
19870            assert_eq!(d.source, src, "{name} edited an XML document");
19871            assert!(!d.dirty, "{name} marked the document dirty");
19872            let status = d.status.as_deref().unwrap_or("");
19873            assert!(
19874                status.contains("xml"),
19875                "{name}: the refusal should name the format, got {status:?}"
19876            );
19877        }
19878
19879        // AsciiDoc is the ragged one: the block gesture works where the run
19880        // gesture does not, and a *selection* is what tells the two apart.
19881        let mut adoc = fmt_doc("hello world\n", Format::Asciidoc);
19882        adoc.anchor = Some(0);
19883        adoc.caret = 5;
19884        adoc.set_font_size(Some(FontSize::Step(SizeStep::Large)));
19885        assert_eq!(adoc.source, "hello world\n", "no inline spelling");
19886        assert!(adoc.status.is_some());
19887    }
19888
19889    /// A read-only document takes none of it, and a caret on a blank line has
19890    /// no block to carry an attribute — both say so rather than writing.
19891    #[test]
19892    fn a_presentation_gesture_respects_read_only_and_a_blank_line() {
19893        let mut ro = fmt_doc("hello\n", Format::Djot);
19894        ro.read_only = true;
19895        ro.caret = 1;
19896        ro.set_alignment(Some(Align::Center));
19897        assert_eq!(ro.source, "hello\n");
19898
19899        let mut blank = fmt_doc("a\n\n\nb\n", Format::Djot);
19900        blank.caret = 2; // the empty line between the two paragraphs
19901        blank.set_alignment(Some(Align::Center));
19902        assert_eq!(blank.source, "a\n\n\nb\n");
19903        assert!(
19904            blank.status.as_deref().unwrap_or("").contains("no block"),
19905            "got {:?}",
19906            blank.status
19907        );
19908    }
19909
19910    /// A block attribute gesture keeps the caret on the **text** it was on, not
19911    /// on the byte offset it had. Markdown has nowhere to put a paragraph's
19912    /// attributes but a `<div>` around it, and twig splices the div and the
19913    /// block it wraps as one region — so a caret that kept its offset landed in
19914    /// the markup, and every press after the first answered "no block at the
19915    /// caret" with the toolbar's queries reading nothing.
19916    #[test]
19917    fn a_markdown_block_gesture_keeps_the_caret_on_its_text() {
19918        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
19919        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
19920        md.caret = md.source.find("brown").unwrap() + 2; // "br|own"
19921
19922        // Wrapping: the div and two blank lines open above the block.
19923        md.set_alignment(Some(Align::Center));
19924        assert_eq!(
19925            md.source,
19926            "<div class=\"center\">\n\nthe quick brown fox\n\n</div>\n"
19927        );
19928        assert_eq!(word(&md), 2, "the caret left its word: {}", md.caret);
19929        assert_eq!(md.alignment_at_caret(), Some(Align::Center));
19930
19931        // Re-styling: the attribute line changes length under the same caret,
19932        // and the second press reaches the same block rather than nothing.
19933        md.set_alignment(Some(Align::Right));
19934        assert_eq!(
19935            md.source, "<div class=\"right\">\n\nthe quick brown fox\n\n</div>\n",
19936            "a second press re-styles the div"
19937        );
19938        assert_eq!(md.status, None);
19939        assert_eq!(word(&md), 2);
19940
19941        // A second key on the same div — the line grows, the caret rides it.
19942        md.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19943        assert_eq!(
19944            md.source,
19945            "<div class=\"right\" data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
19946        );
19947        assert_eq!(word(&md), 2);
19948        assert_eq!(
19949            md.line_spacing_at_caret(),
19950            Some(LineHeight::Step(LineSpacing::Double))
19951        );
19952
19953        // Unwrapping: the line shrinks, and then the div goes altogether.
19954        md.set_alignment(None);
19955        assert_eq!(
19956            md.source,
19957            "<div data-line-height=\"2\">\n\nthe quick brown fox\n\n</div>\n"
19958        );
19959        assert_eq!(word(&md), 2);
19960        md.set_line_spacing(None);
19961        assert_eq!(md.source, "the quick brown fox\n", "the last key unwraps");
19962        assert_eq!(word(&md), 2, "the caret came back down with the block");
19963        assert_eq!(md.alignment_at_caret(), None);
19964        assert_eq!(md.status, None);
19965    }
19966
19967    /// The same rule in djot, where the spelling is a `{…}` line *above* the
19968    /// block rather than a wrapper around it: inserting it pushes the block
19969    /// down, re-styling it changes the line's length, and clearing the last key
19970    /// takes the line away again. The caret rides all three.
19971    #[test]
19972    fn a_djot_attribute_line_keeps_the_caret_on_its_text() {
19973        let word = |d: &Doc| d.caret - d.source.find("brown").unwrap();
19974        let mut dj = fmt_doc("the quick brown fox\n", Format::Djot);
19975        dj.caret = dj.source.find("brown").unwrap() + 2;
19976
19977        dj.set_alignment(Some(Align::Center));
19978        assert_eq!(dj.source, "{.center}\nthe quick brown fox\n");
19979        assert_eq!(word(&dj), 2);
19980        assert_eq!(dj.alignment_at_caret(), Some(Align::Center));
19981
19982        dj.set_line_spacing(Some(LineHeight::Step(LineSpacing::Double)));
19983        assert_eq!(
19984            dj.source, "{.center data-line-height=\"2\"}\nthe quick brown fox\n",
19985            "a second press edits the line the first wrote"
19986        );
19987        assert_eq!(word(&dj), 2);
19988
19989        dj.set_alignment(None);
19990        assert_eq!(dj.source, "{data-line-height=\"2\"}\nthe quick brown fox\n");
19991        assert_eq!(word(&dj), 2);
19992
19993        dj.set_line_spacing(None);
19994        assert_eq!(dj.source, "the quick brown fox\n");
19995        assert_eq!(word(&dj), 2);
19996        assert_eq!(dj.status, None);
19997    }
19998
19999    /// The run gestures with no selection are the block gesture, so they keep
20000    /// the caret the same way — and a heading keeps it inside the heading's own
20001    /// text, past the `# ` its content span starts after. A selection rides
20002    /// along whole: a block gesture is not a run gesture, and what was selected
20003    /// before the press is still selected after it.
20004    #[test]
20005    fn a_block_gesture_carries_a_selection_and_a_heading_caret_too() {
20006        // No selection: the run gesture goes through the block door.
20007        let mut md = fmt_doc("the quick brown fox\n", Format::Markdown);
20008        md.caret = md.source.find("brown").unwrap() + 2;
20009        md.set_font_size(Some(FontSize::Step(SizeStep::Large)));
20010        assert_eq!(
20011            md.source,
20012            "<div data-size=\"large\">\n\nthe quick brown fox\n\n</div>\n"
20013        );
20014        assert_eq!(md.caret - md.source.find("brown").unwrap(), 2);
20015        assert_eq!(
20016            md.font_size_at_caret(),
20017            Some(FontSize::Step(SizeStep::Large))
20018        );
20019        md.set_font_size(Some(FontSize::Step(SizeStep::Small)));
20020        assert_eq!(
20021            md.font_size_at_caret(),
20022            Some(FontSize::Step(SizeStep::Small)),
20023            "the second press reached the same block"
20024        );
20025
20026        // A selection: alignment is the block's whatever is selected, and the
20027        // words stay selected.
20028        let mut sel = fmt_doc("the quick brown fox\n", Format::Markdown);
20029        let at = sel.source.find("brown").unwrap();
20030        sel.anchor = Some(at);
20031        sel.caret = at + 5;
20032        sel.set_alignment(Some(Align::Center));
20033        let now = sel.source.find("brown").unwrap();
20034        assert_eq!(sel.selection(), Some((now, now + 5)), "the words moved out");
20035
20036        // A heading: the content span starts past the `# `.
20037        let mut h = fmt_doc("# hi there\n\nbody\n", Format::Markdown);
20038        h.caret = h.source.find("there").unwrap() + 1;
20039        h.set_alignment(Some(Align::Right));
20040        assert_eq!(
20041            h.source,
20042            "<div class=\"right\">\n\n# hi there\n\n</div>\n\nbody\n"
20043        );
20044        assert_eq!(h.caret, h.source.find("there").unwrap() + 1);
20045        assert_eq!(h.alignment_at_caret(), Some(Align::Right));
20046    }
20047
20048    /// A djot document open in the rich view, with its map built as
20049    /// [`wysiwyg_doc`] builds a Markdown one's.
20050    fn wysiwyg_djot(body: &str) -> Doc {
20051        let mut d = fmt_doc(body, Format::Djot);
20052        d.view = View::Wysiwyg;
20053        d.build_visual(80);
20054        d
20055    }
20056
20057    /// Backspace at the start of a block whose presentation is spelled as
20058    /// hidden markup before it strips that presentation, the way Backspace at
20059    /// a heading's start strips its `#`. The ordinary delete fused djot's
20060    /// `{.center}` line onto the text and took the blank line a Markdown div
20061    /// needs between its tag and its paragraph.
20062    #[test]
20063    fn backspace_at_the_start_of_a_centred_paragraph_strips_its_attributes() {
20064        let mut md = wysiwyg_doc(
20065            "wys_attr_bksp",
20066            "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
20067        );
20068        md.caret = md.source.find("hello").unwrap();
20069        md.backspace();
20070        assert_eq!(
20071            md.source, "above\n\nhello\n\nbelow\n",
20072            "the div is unwrapped"
20073        );
20074        assert_eq!(md.caret, 7, "the caret stays at the start of its text");
20075        md.backspace();
20076        assert_eq!(
20077            md.source, "above\nhello\n\nbelow\n",
20078            "the next press joins the paragraphs, as it always did"
20079        );
20080
20081        let mut dj = wysiwyg_djot("above\n\n{.center}\nhello\n\nbelow\n");
20082        dj.caret = dj.source.find("hello").unwrap();
20083        dj.backspace();
20084        assert_eq!(
20085            dj.source, "above\n\nhello\n\nbelow\n",
20086            "the attribute line goes"
20087        );
20088        assert_eq!(dj.caret, 7);
20089
20090        // A heading's own marker is the nearer hidden markup, and goes first;
20091        // the attributes are the next press's.
20092        let mut dj = wysiwyg_djot("{.center}\n# Title\n");
20093        dj.caret = dj.source.find("Title").unwrap();
20094        dj.backspace();
20095        assert_eq!(dj.source, "{.center}\nTitle\n", "the `#` first");
20096        dj.build_visual(80);
20097        dj.backspace();
20098        assert_eq!(dj.source, "Title\n", "then the attributes");
20099        assert_eq!(dj.caret, 0);
20100    }
20101
20102    /// A div around several blocks has no sole child for twig to unwrap, so
20103    /// at its first block the caret steps back to the stop before rather than
20104    /// taking the div apart; a later block has an ordinary paragraph above it
20105    /// and joins as any paragraph does.
20106    #[test]
20107    fn backspace_at_the_first_of_a_div_s_blocks_steps_back_and_a_later_one_joins() {
20108        let src = "above\n\n<div class=\"center\">\n\nhello\n\nworld\n\n</div>\n";
20109        let mut d = wysiwyg_doc("wys_div_first", src);
20110        d.caret = d.source.find("hello").unwrap();
20111        d.backspace();
20112        assert_eq!(d.source, src, "nothing is deleted");
20113        assert_eq!(d.caret, 5, "the caret steps back to the end of `above`");
20114
20115        let mut d = wysiwyg_doc("wys_div_later", src);
20116        d.caret = d.source.find("world").unwrap();
20117        d.backspace();
20118        assert_eq!(
20119            d.source, "above\n\n<div class=\"center\">\n\nhello\nworld\n\n</div>\n",
20120            "a later block joins the one above it"
20121        );
20122    }
20123
20124    /// Backspace at the start of the paragraph after a Markdown div joins it
20125    /// into the div's last paragraph — the join any two paragraphs make, with
20126    /// the hidden `</div>` carried past the joined text. The ordinary delete
20127    /// took the newline under the tag, which drew nothing different, and the
20128    /// next press took the `>` and left the div unclosed.
20129    #[test]
20130    fn backspace_after_a_div_joins_the_paragraph_into_it() {
20131        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20132        let mut d = wysiwyg_doc("wys_div_join", src);
20133        d.caret = d.source.find("below").unwrap();
20134        d.backspace();
20135        assert_eq!(
20136            d.source,
20137            "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n"
20138        );
20139        assert_eq!(
20140            d.caret,
20141            d.source.find("below").unwrap(),
20142            "the caret stays at the start of the joined text"
20143        );
20144        d.build_visual(80);
20145        assert_eq!(
20146            d.alignment_at_caret(),
20147            Some(Align::Center),
20148            "and is centred now"
20149        );
20150        d.undo();
20151        assert_eq!(d.source, src, "one undo step");
20152
20153        // A list closes the div: the paragraph joins the last item's text,
20154        // under the item's continuation indent, inside the div.
20155        let src = "<div class=\"center\">\n\n- item\n\n</div>\n\nbelow\n";
20156        let mut d = wysiwyg_doc("wys_div_list", src);
20157        d.caret = d.source.find("below").unwrap();
20158        d.backspace();
20159        assert_eq!(
20160            d.source, "<div class=\"center\">\n\n- item\n  below\n\n</div>\n",
20161            "the paragraph joins the item"
20162        );
20163        assert_eq!(d.caret, d.source.find("below").unwrap());
20164
20165        // And where twig has nothing to join into — a code block above — the
20166        // caret steps back to the stop before, and nothing is deleted.
20167        let src = "```\ncode\n```\n\nbelow\n";
20168        let mut d = wysiwyg_doc("wys_code_then_para", src);
20169        d.caret = d.source.find("below").unwrap();
20170        d.backspace();
20171        assert_eq!(d.source, src, "nothing is deleted");
20172        assert!(
20173            d.caret < d.source.find("below").unwrap(),
20174            "the caret stepped back"
20175        );
20176    }
20177
20178    /// Backspace on a blank line collapses to the stop before it — but not
20179    /// across hidden markup, which that collapse deleted whole: a `</div>`,
20180    /// or a comment between two blocks. There the blank line goes alone, and
20181    /// the caret lands where the collapse would have put it.
20182    #[test]
20183    fn backspace_on_a_blank_line_after_hidden_markup_keeps_the_markup() {
20184        let mut d = wysiwyg_doc(
20185            "wys_div_blank",
20186            "<div class=\"center\">\n\nhello\n\n</div>\n\n\n\nbelow\n",
20187        );
20188        d.caret = d.source.find("below").unwrap() - 2; // the empty paragraph
20189        assert!(
20190            d.vmap.is_stop(d.caret),
20191            "the empty paragraph is a caret home"
20192        );
20193        d.backspace();
20194        assert_eq!(
20195            d.source, "<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n",
20196            "the blank line goes and the div stays closed"
20197        );
20198        assert_eq!(
20199            d.caret,
20200            d.source.find("hello").unwrap() + 5,
20201            "onto the end of `hello`"
20202        );
20203
20204        let mut d = wysiwyg_doc("wys_comment_blank", "above\n\n<!-- note -->\n\n\n\nbelow\n");
20205        d.caret = d.source.find("below").unwrap() - 2;
20206        assert!(d.vmap.is_stop(d.caret));
20207        d.backspace();
20208        assert_eq!(
20209            d.source, "above\n\n<!-- note -->\n\nbelow\n",
20210            "the comment stays"
20211        );
20212        assert_eq!(d.caret, 5);
20213    }
20214
20215    /// Backspace at the end of an attributed span steps inside its hidden
20216    /// closing tag the way it steps inside a `**`, and takes the span with
20217    /// its last letter. Before, the byte-step took the `>` of `</span>`,
20218    /// which left the paragraph unparseable: it vanished from the rich view,
20219    /// and the Backspace after that joined the next block into the wreck.
20220    #[test]
20221    fn backspace_walks_into_a_sized_span_and_takes_the_emptied_span_with_its_space() {
20222        let src = "above\n\nThis <span data-size=\"x-large\">is</span> a test\n\nTest 2\n";
20223        let mut d = wysiwyg_doc("wys_span_bs", src);
20224        d.caret = d.source.find("a test").unwrap() + 6;
20225        for _ in 0..7 {
20226            d.backspace();
20227        }
20228        assert_eq!(
20229            d.source,
20230            "above\n\nThis <span data-size=\"x-large\">is</span>\n\nTest 2\n"
20231        );
20232        d.backspace();
20233        assert_eq!(
20234            d.source, "above\n\nThis <span data-size=\"x-large\">i</span>\n\nTest 2\n",
20235            "the first Backspace after the tag takes the letter, not the `>`"
20236        );
20237        d.backspace();
20238        assert_eq!(
20239            d.source, "above\n\nThis \n\nTest 2\n",
20240            "the last letter takes the span with it"
20241        );
20242        assert_eq!(d.caret, 12, "the caret is where the letter was");
20243        d.backspace();
20244        assert_eq!(d.source, "above\n\nThis\n\nTest 2\n");
20245        assert_eq!(d.caret, 11);
20246        d.build_visual(80);
20247        assert!(
20248            d.vmap
20249                .rows
20250                .iter()
20251                .any(|r| r.glyphs.iter().map(|g| g.ch).collect::<String>() == "This"),
20252            "the paragraph is still drawn"
20253        );
20254    }
20255
20256    #[test]
20257    fn backspace_walks_into_a_djot_sized_span_too() {
20258        let mut d = wysiwyg_djot("This [is]{data-size=\"x-large\"}\n\nTest 2\n");
20259        d.caret = d.source.find("\n\nTest 2").unwrap();
20260        // The caret home at the paragraph's end is inside the span, before
20261        // its `]`: the map offers no stop after `]{…}`.
20262        d.build_visual(80);
20263        assert_eq!(d.vmap.stop_before(31), Some(8));
20264        d.caret = 8;
20265        d.backspace();
20266        assert_eq!(d.source, "This [i]{data-size=\"x-large\"}\n\nTest 2\n");
20267        d.backspace();
20268        assert_eq!(
20269            d.source, "This \n\nTest 2\n",
20270            "the attribute block outside the span goes with it"
20271        );
20272        d.backspace();
20273        assert_eq!(d.source, "This\n\nTest 2\n");
20274        assert_eq!(d.caret, 4);
20275    }
20276
20277    /// A span that is empty as the file was written has no stop of its own;
20278    /// Backspace reaching it from behind takes it with the character before
20279    /// it, the character the key looked aimed at.
20280    #[test]
20281    fn backspace_over_an_already_empty_span_takes_it_with_the_character_before() {
20282        let src = "This <span data-size=\"x-large\"></span> a test\n";
20283        let mut d = wysiwyg_doc("wys_span_empty", src);
20284        d.caret = d.source.find(" a test").unwrap();
20285        d.backspace();
20286        assert_eq!(d.source, "This a test\n");
20287        assert_eq!(d.caret, 4);
20288    }
20289
20290    /// The mirror: Delete in front of a span's opening tag takes its first
20291    /// letter, and the span with its last.
20292    #[test]
20293    fn delete_walks_into_a_sized_span_and_takes_the_span_with_its_last_letter() {
20294        let src = "This <span data-size=\"x-large\">is</span> a test\n";
20295        let mut d = wysiwyg_doc("wys_span_del", src);
20296        d.caret = 5;
20297        d.delete_forward();
20298        assert_eq!(
20299            d.source,
20300            "This <span data-size=\"x-large\">s</span> a test\n"
20301        );
20302        d.delete_forward();
20303        assert_eq!(d.source, "This  a test\n");
20304        assert_eq!(d.caret, 5);
20305        d.delete_forward();
20306        assert_eq!(d.source, "This a test\n");
20307        assert_eq!(d.caret, 5);
20308    }
20309
20310    /// The block version of the span's emptying rule. Centre a one-letter
20311    /// paragraph — Markdown spells that as a `<div>` around it — and
20312    /// Backspace the letter: the div goes with it, leaving a plain blank line
20313    /// the caret is at home on, in the incremental map and the from-scratch
20314    /// one alike. Before, the letter went alone; the emptied div drew a
20315    /// caret home only the stale map had, and the next Backspace collapsed
20316    /// the line and left `<div class="center">\n\n</div>` standing invisibly
20317    /// in the file.
20318    #[test]
20319    fn backspace_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20320        let mut d = wysiwyg_doc("wys_div_empty", "Try the toolbar.\n\nT\n");
20321        d.caret = d.source.len() - 1;
20322        d.set_alignment(Some(Align::Center));
20323        assert_eq!(
20324            d.source,
20325            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n"
20326        );
20327        d.backspace();
20328        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20329        assert_eq!(d.caret, 18, "on the blank line where the letter was");
20330        // The host rebuilds the map after every key; the spliced map and a
20331        // fresh one both give the line a caret home.
20332        d.build_visual_unwrapped();
20333        assert!(d.vmap.is_stop(18));
20334        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20335        d.backspace();
20336        assert_eq!(
20337            d.source, "Try the toolbar.\n",
20338            "then the blank line collapses"
20339        );
20340        assert_eq!(d.caret, 16);
20341
20342        // With a block after the div the blank line keeps a gap each side.
20343        let mut d = wysiwyg_doc(
20344            "wys_div_empty_mid",
20345            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n\nbelow\n",
20346        );
20347        d.caret = d.source.find("T\n").unwrap() + 1;
20348        d.backspace();
20349        assert_eq!(d.source, "Try the toolbar.\n\n\n\nbelow\n");
20350        assert_eq!(d.caret, 18);
20351        d.build_visual_unwrapped();
20352        assert!(d.vmap.is_stop(18));
20353        wysiwyg::assert_maps_eq(&d.vmap, &reference_map(&d.source), "after the div goes");
20354    }
20355
20356    /// djot spells the same paragraph as a `{.center}` line above it, and
20357    /// twig has no node at all for that line once the paragraph is gone —
20358    /// so the line goes with the letter too.
20359    #[test]
20360    fn backspace_that_empties_a_centred_paragraph_takes_its_djot_attrs_line_too() {
20361        let mut d = fmt_doc("Try the toolbar.\n\nT\n", Format::Djot);
20362        d.build_visual(80);
20363        d.caret = d.source.len() - 1;
20364        d.set_alignment(Some(Align::Center));
20365        assert_eq!(d.source, "Try the toolbar.\n\n{.center}\nT\n");
20366        d.backspace();
20367        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20368        assert_eq!(d.caret, 18);
20369        d.build_visual(80);
20370        assert!(d.vmap.is_stop(18));
20371    }
20372
20373    /// The rule is for a block that would be no block: a div holding more
20374    /// keeps its tags, and an emptied heading is still a heading.
20375    #[test]
20376    fn emptying_a_paragraph_keeps_a_div_that_holds_more_and_a_heading_its_marker() {
20377        let mut d = wysiwyg_doc(
20378            "wys_div_more",
20379            "<div class=\"center\">\n\nText\n\nT\n\n</div>\n",
20380        );
20381        d.caret = d.source.find("T\n").unwrap() + 1;
20382        d.backspace();
20383        assert_eq!(d.source, "<div class=\"center\">\n\nText\n\n\n\n</div>\n");
20384        assert_eq!(d.caret, 28, "the blank line inside the div, as after Enter");
20385
20386        let mut d = wysiwyg_doc(
20387            "wys_div_heading",
20388            "<div class=\"center\">\n\n# T\n\n</div>\n",
20389        );
20390        d.caret = d.source.find("T\n").unwrap() + 1;
20391        d.backspace();
20392        assert_eq!(d.source, "<div class=\"center\">\n\n# \n\n</div>\n");
20393        assert_eq!(d.caret, 24);
20394        d.build_visual(80);
20395        assert!(
20396            d.vmap.is_stop(24),
20397            "the empty heading is still a caret home"
20398        );
20399    }
20400
20401    /// The mirror: Delete in front of the letter takes the div with it.
20402    #[test]
20403    fn delete_that_empties_a_centred_paragraph_takes_its_div_with_the_letter() {
20404        let mut d = wysiwyg_doc(
20405            "wys_div_empty_del",
20406            "Try the toolbar.\n\n<div class=\"center\">\n\nT\n\n</div>\n",
20407        );
20408        d.caret = d.source.find("T\n").unwrap();
20409        d.delete_forward();
20410        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20411        assert_eq!(d.caret, 18);
20412        d.build_visual(80);
20413        assert!(d.vmap.is_stop(18));
20414
20415        let mut d = fmt_doc("Try the toolbar.\n\n{.center}\nT\n", Format::Djot);
20416        d.build_visual(80);
20417        d.caret = d.source.find("T\n").unwrap();
20418        d.delete_forward();
20419        assert_eq!(d.source, "Try the toolbar.\n\n\n");
20420        assert_eq!(d.caret, 18);
20421    }
20422
20423    /// Backspace at a block's start is twig's join, spelled per format — so
20424    /// the cases the one-newline delete got wrong come out right: a
20425    /// paragraph joins onto a heading's line, HTML's `</p><p>` goes as one,
20426    /// and a quote's prefix is written on the joined line.
20427    #[test]
20428    fn backspace_at_a_block_start_joins_it_the_format_s_way() {
20429        let mut d = wysiwyg_doc("wys_join_heading", "# Title\n\nbelow\n");
20430        d.caret = d.source.find("below").unwrap();
20431        d.backspace();
20432        assert_eq!(d.source, "# Title below\n", "onto the heading's line");
20433        assert_eq!(d.caret, d.source.find("below").unwrap());
20434        d.undo();
20435        assert_eq!(d.source, "# Title\n\nbelow\n", "one undo step");
20436
20437        let mut d = wysiwyg_doc("wys_join_quote", "> a\n\nb\n");
20438        d.caret = d.source.find('b').unwrap();
20439        d.backspace();
20440        assert_eq!(d.source, "> a\n> b\n", "into the quote, with its prefix");
20441        assert_eq!(d.caret, d.source.find('b').unwrap());
20442
20443        let mut h = fmt_doc("<p>above</p>\n<p class=\"x\">below</p>\n", Format::Html);
20444        h.view = View::Wysiwyg;
20445        h.build_visual(80);
20446        h.caret = h.source.find("below").unwrap();
20447        h.backspace();
20448        assert_eq!(
20449            h.source, "<p>above\nbelow</p>\n",
20450            "one paragraph, the tag gone whole"
20451        );
20452        assert_eq!(h.caret, h.source.find("below").unwrap());
20453    }
20454
20455    /// Delete at the end of a block's content is the same join aimed at the
20456    /// block after it, and the caret stays where the joined text now begins.
20457    #[test]
20458    fn delete_at_a_block_end_joins_the_next_block_into_it() {
20459        let src = "above\n\n<div class=\"center\">\n\nhello\n\n</div>\n\nbelow\n";
20460        let mut d = wysiwyg_doc("wys_del_join", src);
20461        d.caret = d.source.find("hello").unwrap() + 5;
20462        d.delete_forward();
20463        assert_eq!(
20464            d.source, "above\n\n<div class=\"center\">\n\nhello\nbelow\n\n</div>\n",
20465            "below joins hello inside the div"
20466        );
20467        assert_eq!(
20468            d.caret,
20469            d.source.find("hello").unwrap() + 5,
20470            "the caret stays"
20471        );
20472
20473        let mut d = wysiwyg_doc("wys_del_join_head", "above\n\n# Title\n");
20474        d.caret = 5;
20475        d.delete_forward();
20476        assert_eq!(
20477            d.source, "above\nTitle\n",
20478            "the heading's marker goes with the join"
20479        );
20480        assert_eq!(d.caret, 5);
20481
20482        // A code block after the paragraph: nothing to join, the caret steps
20483        // forward onto the next stop and nothing is deleted.
20484        let src = "above\n\n```\ncode\n```\n";
20485        let mut d = wysiwyg_doc("wys_del_code", src);
20486        d.caret = 5;
20487        d.delete_forward();
20488        assert_eq!(d.source, src);
20489        assert!(d.caret > 5, "the caret stepped forward");
20490    }
20491
20492    // ── Text statistics ──────────────────────────────────────────────────────
20493
20494    /// The counts of `body`, from a document open in the WYSIWYG view — the
20495    /// shape every case below starts from.
20496    fn counts_of(name: &str, body: &str) -> TextCounts {
20497        doc_in(View::Wysiwyg, name, body).counts()
20498    }
20499
20500    #[test]
20501    fn counts_tally_plain_prose() {
20502        let c = counts_of(
20503            "counts_prose",
20504            "The quick brown fox jumps over the lazy dog.\n",
20505        );
20506        assert_eq!(
20507            c,
20508            TextCounts {
20509                words: 9,
20510                characters: 44,
20511                characters_without_spaces: 36,
20512                paragraphs: 1,
20513            }
20514        );
20515    }
20516
20517    #[test]
20518    fn counts_read_the_text_and_not_the_markup() {
20519        // The `**` are four bytes of source and no part of the word.
20520        assert_eq!(
20521            counts_of("counts_marks", "a **bold** word\n"),
20522            TextCounts {
20523                words: 3,
20524                characters: 11,
20525                characters_without_spaces: 9,
20526                paragraphs: 1,
20527            }
20528        );
20529        // A link is its label; the destination is plumbing, however long.
20530        assert_eq!(
20531            counts_of(
20532                "counts_link",
20533                "see [the label](https://example.com/a/b/c) here\n"
20534            ),
20535            TextCounts {
20536                words: 4,
20537                characters: 18,
20538                characters_without_spaces: 15,
20539                paragraphs: 1,
20540            }
20541        );
20542    }
20543
20544    #[test]
20545    fn counts_spend_nothing_on_a_picture() {
20546        // A block image renders as a `🖼 alt` placeholder — a picture, not a
20547        // sentence, and not a paragraph either.
20548        assert_eq!(
20549            counts_of("counts_image", "![a long caption](pic.png)\n"),
20550            TextCounts::default()
20551        );
20552        // And it adds nothing to the prose around it.
20553        assert_eq!(
20554            counts_of("counts_image_prose", "text\n\n![a long caption](pic.png)\n"),
20555            TextCounts {
20556                words: 1,
20557                characters: 4,
20558                characters_without_spaces: 4,
20559                paragraphs: 1,
20560            }
20561        );
20562    }
20563
20564    #[test]
20565    fn counts_spend_nothing_on_drawn_furniture() {
20566        // A thematic break is drawn, not written, and an empty paragraph has
20567        // nothing in it — neither is a paragraph of the document.
20568        assert_eq!(
20569            counts_of("counts_rule", "one\n\n---\n\ntwo\n"),
20570            TextCounts {
20571                words: 2,
20572                characters: 6,
20573                characters_without_spaces: 6,
20574                paragraphs: 2,
20575            }
20576        );
20577    }
20578
20579    #[test]
20580    fn counts_measure_characters_as_a_reader_does() {
20581        // Four Han characters (each its own word under UAX#29), one ZWJ emoji
20582        // family that is a single grapheme cluster, and two letters.
20583        let c = counts_of(
20584            "counts_graphemes",
20585            "你好世界 👩\u{200d}👩\u{200d}👧\u{200d}👦 ok\n",
20586        );
20587        assert_eq!(
20588            c,
20589            TextCounts {
20590                words: 5,
20591                characters: 9,
20592                characters_without_spaces: 7,
20593                paragraphs: 1,
20594            }
20595        );
20596    }
20597
20598    #[test]
20599    fn counts_take_a_code_block_as_one_paragraph() {
20600        let c = counts_of("counts_code", "```rust\nlet x = 1;\n\nlet y = 2;\n```\n");
20601        assert_eq!(
20602            c,
20603            TextCounts {
20604                words: 6,
20605                characters: 20,
20606                characters_without_spaces: 14,
20607                paragraphs: 1,
20608            }
20609        );
20610    }
20611
20612    #[test]
20613    fn counts_take_a_table_as_one_paragraph() {
20614        // The box-drawn borders and the column padding are the renderer's, not
20615        // the author's; the cells are what was written.
20616        let c = counts_of("counts_table", "| a b | c |\n| - | - |\n| d | e |\n");
20617        assert_eq!(
20618            c,
20619            TextCounts {
20620                words: 5,
20621                characters: 6,
20622                characters_without_spaces: 5,
20623                paragraphs: 1,
20624            }
20625        );
20626    }
20627
20628    #[test]
20629    fn counts_give_every_item_and_every_quoted_paragraph_its_own_paragraph() {
20630        let c = counts_of(
20631            "counts_blocks",
20632            "- one\n- two\n- three\n\n> first quoted\n>\n> second quoted\n",
20633        );
20634        assert_eq!(
20635            c,
20636            TextCounts {
20637                words: 7,
20638                characters: 36,
20639                characters_without_spaces: 34,
20640                paragraphs: 5,
20641            }
20642        );
20643    }
20644
20645    #[test]
20646    fn counts_leave_the_frontmatter_out() {
20647        // The WYSIWYG view doesn't render it and a writer didn't write it.
20648        let c = counts_of(
20649            "counts_frontmatter",
20650            "---\ntitle: Hidden\n---\n\nvisible words here\n",
20651        );
20652        assert_eq!(
20653            c,
20654            TextCounts {
20655                words: 3,
20656                characters: 18,
20657                characters_without_spaces: 16,
20658                paragraphs: 1,
20659            }
20660        );
20661    }
20662
20663    #[test]
20664    fn counts_of_an_empty_document_are_all_zero() {
20665        assert_eq!(counts_of("counts_empty", ""), TextCounts::default());
20666    }
20667
20668    /// UAX#29 puts a boundary at the hyphen, so a hyphenated compound is two
20669    /// words. Recorded rather than corrected: it is what the algorithm says,
20670    /// and what every other UAX#29 counter reports.
20671    #[test]
20672    fn counts_split_a_hyphenated_compound_in_two() {
20673        let c = counts_of("counts_hyphen", "well-known example\n");
20674        assert_eq!(c.words, 3);
20675        assert_eq!(c.characters, 18);
20676        // Punctuation on its own is no word, and an apostrophe doesn't split one.
20677        assert_eq!(counts_of("counts_punct", "don't ... stop\n").words, 2);
20678    }
20679
20680    #[test]
20681    fn selection_counts_measure_the_selection_and_nothing_without_one() {
20682        let src = "alpha beta\n\ngamma delta\n";
20683        let mut d = doc_in(View::Wysiwyg, "counts_sel", src);
20684        assert_eq!(d.selection_counts(), None, "no selection, no counts");
20685
20686        // From the `b` of `beta` to the end of `gamma`: two blocks clipped.
20687        d.select_range(6, 17);
20688        assert_eq!(
20689            d.selection_counts(),
20690            Some(TextCounts {
20691                words: 2,
20692                characters: 9,
20693                characters_without_spaces: 9,
20694                paragraphs: 2,
20695            })
20696        );
20697    }
20698
20699    /// The count is of the document, not of the window it is shown in — so
20700    /// ⌘E must not move it, and neither must a resize or an edit made with no
20701    /// map built at all.
20702    #[test]
20703    fn counts_agree_across_the_views() {
20704        let src =
20705            "# Head\n\nA **bold** word, a [label](http://x), and more.\n\n- item one\n- item two\n";
20706        let mut d = doc_in(View::Wysiwyg, "counts_views", src);
20707        let wysiwyg = d.counts();
20708        assert!(wysiwyg.words > 0 && wysiwyg.paragraphs == 4);
20709
20710        d.toggle_view();
20711        assert_eq!(d.view, View::Source);
20712        d.build_source();
20713        assert_eq!(d.counts(), wysiwyg, "the source view counts the same text");
20714
20715        // A narrower measure is a narrower window, not a shorter document.
20716        d.toggle_view();
20717        d.build_visual(24);
20718        assert_eq!(d.counts(), wysiwyg, "wrapping is not an input");
20719
20720        // And an edit made in the source view, with the visual map left stale,
20721        // still counts the document as it now stands.
20722        d.toggle_view();
20723        d.caret = d.source.len();
20724        d.insert("\n\ntail words\n");
20725        let after = d.counts();
20726        assert_eq!(after.paragraphs, wysiwyg.paragraphs + 1);
20727        assert_eq!(after.words, wysiwyg.words + 2);
20728    }
20729
20730    // ── math ─────────────────────────────────────────────────────────────────
20731
20732    #[test]
20733    fn a_formula_reveals_on_the_caret_line_in_the_hidden_modes() {
20734        // The rule the proposal states: a formula's content is its TeX, not
20735        // its picture, so it reveals on the caret's line in *every* mode —
20736        // and nothing else on that line does outside `Full`.
20737        let mut d = doc_in(
20738            View::Wysiwyg,
20739            "math_reveal",
20740            "*one* $x+y$ here\n\ntwo there\n",
20741        );
20742        d.set_inline_pictures(true);
20743        assert_eq!(d.markup_mode(), MarkupMode::None);
20744
20745        // Away from the formula's line: the atom, and no reveal at all.
20746        caret_at(&mut d, "two");
20747        assert!(
20748            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20749            "{:?}",
20750            drawn_rows(&d)
20751        );
20752        assert_eq!(d.vmap.math.len(), 1);
20753        assert_eq!(d.reveal_line(), None, "a line with no math keys nothing");
20754
20755        // On it: the formula is its source, the emphasis is still resolved.
20756        caret_at(&mut d, "here");
20757        assert!(
20758            drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"),
20759            "{:?}",
20760            drawn_rows(&d)
20761        );
20762        assert!(d.vmap.math.is_empty());
20763        assert_eq!(d.reveal_line(), Some(Reveal::math(0..16)));
20764
20765        // Off again, and the picture is back.
20766        caret_at(&mut d, "two");
20767        assert!(drawn_rows(&d).iter().any(|r| r == "one ∑ here"));
20768
20769        // The same in Shortcuts; and Full reveals the emphasis too.
20770        d.set_markup_mode(MarkupMode::Shortcuts);
20771        caret_at(&mut d, "here");
20772        assert!(drawn_rows(&d).iter().any(|r| r == "one $x+y$ here"));
20773        d.set_markup_mode(MarkupMode::Full);
20774        caret_at(&mut d, "here");
20775        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20776    }
20777
20778    #[test]
20779    fn an_unrevealed_map_shows_the_carets_line_as_a_page_does() {
20780        let mut d = doc_in(
20781            View::Wysiwyg,
20782            "math_unrevealed",
20783            "*one* $x+y$ here\n\ntwo there\n",
20784        );
20785        d.set_inline_pictures(true);
20786        d.set_markup_mode(MarkupMode::Full);
20787        caret_at(&mut d, "here");
20788        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20789        let (screen, caret) = (d.visual_key(), d.caret);
20790
20791        // On paper: the delimiters hidden and the formula a picture, though
20792        // the caret has not moved off the line.
20793        d.set_unrevealed(true);
20794        d.build_visual(80);
20795        assert!(
20796            drawn_rows(&d).iter().any(|r| r == "one ∑ here"),
20797            "{:?}",
20798            drawn_rows(&d)
20799        );
20800        assert_eq!(d.vmap.math.len(), 1);
20801        assert_eq!(d.caret, caret);
20802
20803        // Off again: the screen's map is back as it was, and the next build
20804        // reuses it rather than building it over.
20805        d.set_unrevealed(false);
20806        assert_eq!(d.visual_key(), screen);
20807        d.build_visual(80);
20808        assert_eq!(d.visual_key(), screen);
20809        assert!(drawn_rows(&d).iter().any(|r| r == "*one* $x+y$ here"));
20810        assert_eq!(d.caret, caret);
20811    }
20812
20813    #[test]
20814    fn a_formula_closed_by_typing_reveals_at_once() {
20815        // The reveal line is decided from the last build's layout, which
20816        // across an edit is stale: the keystroke that closes a `$…$` asks a
20817        // layout that knew no math. `build_map` asks again once the new
20818        // layout is in, so the formula does not snap to its picture under
20819        // the caret.
20820        let mut d = doc_in(View::Wysiwyg, "math_typed", "say \n");
20821        d.set_inline_pictures(true);
20822        d.set_markup_mode(MarkupMode::Shortcuts);
20823        d.caret = 4;
20824        for ch in ["$", "x", "$"] {
20825            d.insert(ch);
20826            d.build_visual(80);
20827        }
20828        assert_eq!(d.source, "say $x$\n");
20829        assert_eq!(
20830            drawn_rows(&d)[0],
20831            "say $x$",
20832            "source, not a picture, under the caret"
20833        );
20834        assert!(d.vmap.math.is_empty());
20835        // Leaving the line folds it — there is only one line, so add one.
20836        d.newline();
20837        d.insert("more");
20838        d.build_visual(80);
20839        assert_eq!(drawn_rows(&d)[0], "say ∑");
20840        assert_eq!(d.vmap.math.len(), 1);
20841        // And deleting the formula while revealed drops the reveal with it.
20842        d.caret = 7;
20843        d.build_visual(80);
20844        assert_eq!(drawn_rows(&d)[0], "say $x$");
20845        for _ in 0..3 {
20846            d.backspace();
20847        }
20848        d.build_visual(80);
20849        assert_eq!(d.source, "say \n\nmore\n");
20850        assert_eq!(d.reveal_line(), None);
20851    }
20852
20853    #[test]
20854    fn a_display_block_is_edited_where_it_stands() {
20855        let mut d = doc_in(
20856            View::Wysiwyg,
20857            "math_block",
20858            "intro\n\n$$\n\\int_0^1 x\n$$\n\nend\n",
20859        );
20860        caret_at(&mut d, "end");
20861        assert_eq!(
20862            drawn_rows(&d),
20863            vec!["intro", "", "∑ \\int_0^1 x", "", "end"]
20864        );
20865        // Up from `end` lands on the placeholder, whose glyphs all carry the
20866        // block's start — which is on its `$$` line, so the block reveals.
20867        d.move_up(false);
20868        d.build_visual(80);
20869        assert_eq!(d.caret, 7);
20870        assert_eq!(
20871            drawn_rows(&d),
20872            vec!["intro", "", "$$", "\\int_0^1 x", "$$", "", "end"]
20873        );
20874        // Down walks the source lines, still revealed; typing edits the TeX.
20875        d.move_down(false);
20876        d.build_visual(80);
20877        assert_eq!(d.caret, 10);
20878        d.move_end(false);
20879        d.insert("^2");
20880        d.build_visual(80);
20881        assert_eq!(d.source, "intro\n\n$$\n\\int_0^1 x^2\n$$\n\nend\n");
20882        assert_eq!(drawn_rows(&d)[3], "\\int_0^1 x^2");
20883        // Out below, and it folds to the placeholder with the new TeX.
20884        d.move_down(false);
20885        d.move_down(false);
20886        d.move_down(false);
20887        d.build_visual(80);
20888        assert_eq!(drawn_rows(&d)[2], "∑ \\int_0^1 x^2");
20889        assert_eq!(d.vmap.math[0].tex, "\n\\int_0^1 x^2\n");
20890    }
20891
20892    #[test]
20893    fn set_math_rows_reserves_filler_rows_by_tex() {
20894        let mut d = doc_in(View::Wysiwyg, "math_rows", "$$\nx\n$$\n\nend\n");
20895        caret_at(&mut d, "end");
20896        assert_eq!(d.vmap.math[0].rows_span, 0..1);
20897        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
20898        d.build_visual(80);
20899        assert_eq!(d.vmap.math[0].rows_span, 0..3);
20900        assert_eq!(drawn_rows(&d)[..3], ["∑ x", "", ""]);
20901        // Cheap when nothing changed.
20902        let key = d.visual_key();
20903        d.set_math_rows(HashMap::from([(d.vmap.math[0].tex.clone(), 3)]));
20904        d.build_visual(80);
20905        assert_eq!(d.visual_key(), key);
20906    }
20907
20908    #[test]
20909    fn a_dollar_typed_in_shortcuts_authors_math() {
20910        let mut d = doc_in(View::Wysiwyg, "math_dollar_sc", "\n");
20911        d.set_markup_mode(MarkupMode::Shortcuts);
20912        d.caret = 0;
20913        d.insert("$x$");
20914        assert_eq!(d.source, "$x$\n");
20915        d.caret = 1;
20916        assert_eq!(d.breadcrumb(), "doc › para › inline_math");
20917
20918        // `None` keeps typed syntax literal, and under the math extension a
20919        // `$` is syntax: twig escapes it, and the paragraph stays text.
20920        let mut d = doc_in(View::Wysiwyg, "math_dollar_none", "\n");
20921        assert_eq!(d.markup_mode(), MarkupMode::None);
20922        d.caret = 0;
20923        d.insert("$x$");
20924        assert_eq!(d.source, "\\$x\\$\n");
20925        d.caret = 2;
20926        assert_eq!(d.breadcrumb(), "doc › para › str");
20927    }
20928
20929    #[test]
20930    fn counts_see_a_formula_as_a_picture_however_it_is_written() {
20931        let c = counts_of(
20932            "counts_math",
20933            "the sum $\\sum_i x_i$ and\n\n$$\ny = mx + c\n$$\n",
20934        );
20935        // `the sum … and` is three words; neither formula counts, and the
20936        // display block is not a paragraph of text.
20937        assert_eq!(c.words, 3);
20938        assert_eq!(c.paragraphs, 1);
20939    }
20940}