Skip to main content

escriba_runtime/
lib.rs

1//! `escriba-runtime` — editor state machine.
2//!
3//! Wraps everything: `BufferSet`, `ModalState`, `Keymap`, `CommandRegistry`,
4//! `Layout`. Exposes `tick(input)` which advances one frame's worth of
5//! state given one input event. Pure — no rendering, no I/O beyond file
6//! save/load through `BufferSet`.
7
8extern crate self as escriba_runtime;
9
10pub mod breakpoint;
11mod courier;
12mod plugin_host;
13pub mod scan;
14pub use breakpoint::Breakpoints;
15pub use plugin_host::{LazyTrigger, PluginHost};
16
17pub mod status;
18
19/// Re-exported from [`escriba_mode`], which now OWNS the operator-pending FSM.
20///
21/// It moved down in 0.1.68 because it only ever needed `escriba-core` +
22/// `zenmai`; keeping it here meant a consumer had to depend on the entire
23/// editor to compose `d` with `w`. This re-export is deliberate rather than a
24/// deprecation shim: `escriba_runtime::OpState` is the spelling every existing
25/// consumer and test uses, and a path change would be a breaking one for no
26/// gain.
27pub use escriba_mode::{OpState, OperatorPending};
28
29/// What one key meant to the operator-pending object layer.
30enum ObjectKey {
31    /// Swallowed — the key began an object and nothing runs yet.
32    Consumed,
33    /// The object is complete; run this.
34    Compose(Action),
35}
36pub use status::{PromptKind, StatusModel};
37
38use std::collections::HashMap;
39
40use awase::KeyRepeatGate;
41use escriba_buffer::BufferSet;
42use escriba_buffer::TextRev;
43use escriba_command::CommandRegistry;
44use escriba_core::{
45    Action, Anchored, Bound, BufferId, Cursors, Damage, Edit, EditGen, HighlightEffect, InsertAt,
46    JumpList, Mode, Motion, Operator, Position, Range, Register, RegisterKind, TextEffect,
47    WindowId,
48};
49use escriba_input::{InputOutcome, translate_app_event};
50use escriba_keymap::{Key, Keymap};
51use escriba_madoguchi::{Negai, Outcome};
52use escriba_mode::ModalState;
53use escriba_search::{Direction as SearchDirection, MatchCount, SearchState};
54use escriba_ui::chrome::{ChromePalette, FleetTheme};
55use escriba_ui::splash::Splash;
56use escriba_ui::{Layout, Viewport, Window};
57use escriba_vm::{EditorSnapshot, EscribaHost, EscribaVm, VmError};
58use madori::AppEvent;
59use std::time::Instant;
60
61/// Full editor state — the single Rust value the binary hands to the
62/// renderer each frame.
63pub struct EditorState {
64    pub buffers: BufferSet,
65    pub modal: ModalState,
66    /// Search session — the committed pattern, its matches, the live `/`
67    /// prompt and history. Owns no buffer or cursor; it answers questions
68    /// about text and this runtime applies the answers.
69    pub search: SearchState,
70    pub keymap: Keymap,
71    pub commands: CommandRegistry,
72    pub layout: Layout,
73    pub active: BufferId,
74    /// The single typed home for cursor state. Phase-1 holds one primary
75    /// [`Position`]; reads go through [`Self::cursor`], writes through
76    /// [`Self::set_cursor`] → [`Cursors::set_primary`]. There is no loose
77    /// `Position` field beside an unused multi-caret type to desync.
78    cursors: Cursors,
79    pub quit_requested: bool,
80    /// Messages surfaced to the user (status line / `:messages`) — the
81    /// sink for the tatara-lisp `(message …)` effect and other feedback.
82    pub messages: Vec<String>,
83    /// Which match the cursor last landed on (0-based) — the `[3/17]`
84    /// numerator, ANCHORED to the text revision it was computed against.
85    ///
86    /// The anchor is what removes the manual invalidation this field used to
87    /// need. An ordinal indexes a match set; when the text changes the set
88    /// changes underneath it and the number silently means something else.
89    /// Reading through `Anchored::get(current_rev)` makes that a `None`, so
90    /// forgetting to clear is no longer a thing that can be forgotten.
91    search_at: Option<Anchored<usize, TextRev>>,
92    /// The last text change, for `.`.
93    ///
94    /// An action plus whatever was typed while it held Insert open. Both
95    /// halves are needed: `cw` alone is not a change, it is the FIRST HALF of
96    /// one — the text that followed is the rest, and replaying without it
97    /// would delete a word and leave the buffer in Insert.
98    last_change: Option<LastChange>,
99    /// True while an insert session belonging to `last_change` is open, so
100    /// typed characters are appended to it. Cleared on leaving Insert.
101    recording_insert: bool,
102
103    /// Where the cursor was before each far jump — `<C-o>` / `<C-i>`.
104    /// Search commits, `n`/`N` and `*`/`#` all record into it, which is what
105    /// makes a search a place you can come back from.
106    pub jumps: JumpList,
107    /// Generic editor option store (name → value). Written by the
108    /// tatara-lisp `(set-option …)` effect and the declarative
109    /// `defoption` apply path; typed accessors layer on top later.
110    pub options: HashMap<String, String>,
111    /// Cached embedded tatara-lisp runtime, built lazily on first
112    /// `run_lisp`. Caching avoids re-installing the ~175-definition full
113    /// stdlib on every call; the interpreter's top-level env also
114    /// persists across calls, giving REPL-like session semantics (an
115    /// earlier `(define …)` is visible to a later `run_lisp`).
116    lisp_vm: Option<EscribaVm>,
117    /// Keys accumulated for an in-progress multi-key sequence — e.g.
118    /// holding `[,, f]` while waiting for the final key of
119    /// `<leader>ff`. Empty when not mid-sequence. Lives on
120    /// `EditorState` (not `ModalState`) so `escriba-mode` needn't
121    /// depend on `escriba-keymap`'s `Key`.
122    pub pending_keys: Vec<Key>,
123    /// Per-key debouncer for OS key-repeat storms. Holding `j`/`l` makes
124    /// the windowing system deliver one `KeyDown` per repeat tick
125    /// (~30-50ms); without a gate those flood the motion path and thrash
126    /// the viewport. The gate lets ONE event per `min_interval` (80ms
127    /// default — ~12 intentional taps/sec still pass) reach the editor in
128    /// the navigation modes. The fleet primitive (`awase::KeyRepeatGate`,
129    /// the same one mado uses) is reused — not reinvented.
130    repeat_gate: KeyRepeatGate<Key>,
131    /// Runtime lazy-activation host for USER plugin caixas (the bundled
132    /// default catalog is applied eagerly at boot, not through here).
133    /// A command / filetype-open / event fires the matching plugins'
134    /// entries through the escriba-lisp apply paths. See [`PluginHost`].
135    pub plugin_host: PluginHost,
136    /// The unnamed register — the home for text an operator yanks or
137    /// deletes (`Operator::leaves_register`). `None` until the first
138    /// register-leaving operator runs. Phase-1 holds the single unnamed
139    /// register; named registers (`"ay`) layer on later.
140    ///
141    /// Typed as a [`Register`], not a `String`: the put has to know whether
142    /// the text was captured CHARWISE (`dw`) or LINEWISE (`dd`), and the
143    /// capture is the only place that knows. A `String` register makes `p`
144    /// after `dd` guess, and the only guess available is the wrong one —
145    /// splicing a whole line into the middle of another.
146    register: Option<Register>,
147    /// The operator-pending FSM (`d`/`c`/`y` then a motion → `dw`/`c$`/`y0`),
148    /// standing on the fleet `zenmai` Mealy-machine primitive. Every dispatched
149    /// action passes through it; only an operator-then-motion pair is rewritten
150    /// into an [`Action::ApplyOperator`].
151    op_pending: zenmai::Stateful<OperatorPending>,
152    /// Operator-pending OBJECT selection, held at the KEY layer.
153    ///
154    /// `Some(around)` means `d` + `i`/`a` have been pressed and the NEXT key
155    /// names the object. It lives here rather than in the operator FSM
156    /// because the FSM sees `Action`s and this decision needs the KEY: `a`
157    /// and every bracket are unbound in Normal, so they all arrive as
158    /// `Action::Pending` with the character already discarded. vim has a
159    /// whole operator-pending keymap for the same reason.
160    pending_object: Option<bool>,
161    /// `f`/`F`/`t`/`T` was pressed and the editor is waiting for the character
162    /// to search for. Like [`Self::pending_object`] this is a KEY-layer
163    /// concern: the character never reaches the keymap, so it cannot be a
164    /// binding, and it must be claimed before the sequence stepper or `f` then
165    /// `f` would resolve as the bound `ff` sequence.
166    pending_find: Option<FindSpec>,
167    /// `r` was pressed and the editor is waiting for the replacement
168    /// character. Same key-layer shape as [`Self::pending_find`], and needed
169    /// for the same reason: `rw` must not read as `r` then *move a word*, and
170    /// `rr` must reach the operand branch rather than resolve as a sequence.
171    pending_replace: bool,
172    /// The last resolved character search — what `;` and `,` repeat.
173    last_find: Option<FindSpec>,
174    /// `m`, `` ` `` or `'` was pressed and the editor is waiting for the mark
175    /// letter. Same key-layer shape as [`Self::pending_find`].
176    pending_mark: Option<MarkKey>,
177    /// `m{a-z}` → position. Buffer-agnostic today, which is honest and
178    /// limited: vim's `a-z` marks are per-buffer and `A-Z` are global, and a
179    /// single map is `a-z`-shaped. Jumping to a mark set in another buffer
180    /// would land at that position in THIS one, so only `a-z` are accepted.
181    marks: HashMap<char, Position>,
182    /// Monotonic refresh-generation stamp — the root of the sealed refresh
183    /// tree (`theory/ESCRIBA.md` §Refresh-Seal). Bumped on every applied
184    /// action + resize; the renderer gates on it so an idle frame does zero
185    /// re-highlight / re-shape, and a stale frame is unreachable.
186    edit_gen: EditGen,
187    /// The accumulated dirty region since the renderer last drained it (M1).
188    /// Only ever widened via [`Damage::join`] at the mutation funnel, so it
189    /// always covers the changed region (`Damage ⊇ changed`); the renderer
190    /// drains it with [`take_damage`](Self::take_damage) to scope its work.
191    damage: Damage,
192    /// The theme every face paints with.
193    ///
194    /// ONE owner. Before this, `(deftheme :preset …)` parsed, validated,
195    /// resolved to a real `FleetTheme` — and then nothing consumed it,
196    /// because each renderer called `ChromePalette::prescribed()` at every
197    /// paint site. The declaration was honoured on paper only. Holding it
198    /// here means a face reads the operator's theme the same way it reads
199    /// the cursor: from the state, per frame.
200    theme: FleetTheme,
201    /// `theme` resolved to concrete colours — cached because it is a plain
202    /// `Copy` struct read many times per frame, and re-derived only in
203    /// [`set_theme`](Self::set_theme), so the two cannot disagree.
204    chrome: ChromePalette,
205    /// How deep the current command dispatch is nested.
206    ///
207    /// `Negai::RunCommand` lets a command invoke a command, which is useful
208    /// and which can also recurse forever. The budget makes the runaway
209    /// bounded and REPORTED rather than a stack overflow — the difference
210    /// between a typed refusal and the editor dying under the operator.
211    dispatch_depth: u8,
212    /// Every live result list — diagnostics, hunks, grep hits, TODOs.
213    ///
214    /// Public so a producer outside the runtime can publish into it once the
215    /// courier lands; today the only producer is the marker scan.
216    pub results: escriba_shirube::ListRegistry,
217    /// The open picker, if any.
218    ///
219    /// `Option<Picker>` on the state, exactly like `splash` — deliberately
220    /// NOT a `Mode` variant. A mode is a state keys are interpreted IN; this
221    /// is a surface that OWNS keys while it is up, which is a different
222    /// thing and composes differently with the keymap.
223    picker: Option<escriba_ui::picker::Picker>,
224    /// The git-index generation. See [`world`](Self::world) — every axis the
225    /// world can move is emitted unconditionally, so a producer anchoring on
226    /// one is not born permanently stale.
227    index_rev: escriba_shirube::IndexRev,
228    /// The language-server generation — bumped when a server restarts.
229    lsp_gen: escriba_shirube::SessionGen,
230    /// The filesystem-scan generation — bumped when a surface a scan feeds
231    /// opens or closes, which is what supersedes an in-flight scan.
232    scan_gen: escriba_shirube::SessionGen,
233    /// Work handed off the editor thread. Inert until the composition root
234    /// hires a crew, so every existing `EditorState::new*` call site is
235    /// unchanged and the editor is fully usable with no runners at all.
236    courier: courier::Courier,
237    /// Which findings list the open picker is a VIEW of, if any —
238    /// `(workspace, list)`. Set when a picker opens over a live producer,
239    /// cleared whenever the picker closes.
240    picker_projects: Option<(bool, Option<String>)>,
241    /// Extension → language facts, populated from `(defmode …)`.
242    ///
243    /// The consumer `:commentstring` never had. Public so the binary's apply
244    /// pass can fill it the way it fills the keymap and the option store.
245    pub filetypes: escriba_core::FiletypeTable,
246    /// The start screen, while it is up.
247    ///
248    /// `Some` only between boot and the first keypress, and only when the
249    /// editor opened with no file. It is deliberately NOT a `Mode`: a mode
250    /// is a state keys are interpreted *in*, and the splash interprets
251    /// exactly one key before it is gone. Modelling it as `Option<Splash>`
252    /// keeps the modal state machine's variant set — and every exhaustive
253    /// match over it — untouched.
254    splash: Option<Splash>,
255    /// What a language server last said one buffer's tokens MEAN.
256    ///
257    /// One slot, not a per-buffer map, and that is the honest shape of what
258    /// produces it: the diagnostics errand runs per OPEN, so at any moment
259    /// there is one buffer whose tokens are both present and fresh. A map
260    /// would model a fan-out that has no producer.
261    ///
262    /// Sealed, and read through [`semantic_spans`](Self::semantic_spans) —
263    /// never directly — for the same reason a `ResultList` is: a colour
264    /// derived from text the operator has since edited is *confidently wrong*,
265    /// which is worse than absent. A stale read is an empty read and the face
266    /// falls back to its own lexer.
267    semantic: Option<SemanticPaint>,
268    /// Where the operator asked the debugger to stop.
269    ///
270    /// Its own field rather than a [`escriba_shirube::ResultList`], and the
271    /// difference is the whole reason [`Breakpoints`] exists as a type: every
272    /// result list is ANCHORED and a stale read is an empty read, so a
273    /// breakpoint published as a finding would vanish on the next keystroke —
274    /// and `publish` also FOCUSES the list it replaces, so `]d` would start
275    /// walking breakpoints. See [`crate::breakpoint`] for the full argument
276    /// and for what the line-number key does not yet survive.
277    breakpoints: Breakpoints,
278}
279
280/// Semantic tokens for one buffer, sealed with the world they describe.
281///
282/// A twin of [`escriba_shirube::ResultList`] rather than a use of it: that
283/// type's payload is `Vec<Finding>`, and a token is deliberately not a finding
284/// (see [`escriba_madoguchi::SemanticSpan`]). What IS shared is the part that
285/// matters — the [`Anchor`](escriba_shirube::Anchor) and the rule that a stale
286/// read yields nothing.
287#[derive(Debug, Clone, PartialEq, Eq)]
288pub struct SemanticPaint {
289    buffer: BufferId,
290    spans: Vec<escriba_madoguchi::SemanticSpan>,
291    anchor: escriba_shirube::Anchor,
292}
293
294impl SemanticPaint {
295    #[must_use]
296    pub const fn new(
297        buffer: BufferId,
298        spans: Vec<escriba_madoguchi::SemanticSpan>,
299        anchor: escriba_shirube::Anchor,
300    ) -> Self {
301        Self {
302            buffer,
303            spans,
304            anchor,
305        }
306    }
307
308    /// The spans, IF they describe `buffer` AND are still fresh against
309    /// `world`. Anything else is empty.
310    #[must_use]
311    pub fn fresh(
312        &self,
313        world: &escriba_shirube::Anchor,
314        buffer: BufferId,
315    ) -> &[escriba_madoguchi::SemanticSpan] {
316        if self.buffer == buffer && self.anchor.is_fresh(world) {
317            &self.spans
318        } else {
319            &[]
320        }
321    }
322}
323
324/// What the start screen did with a keypress.
325///
326/// Total, and matched exhaustively at its one call site, so a future
327/// outcome (a menu that opens a submenu, say) is a compile error rather
328/// than a key that silently falls through to the buffer.
329enum SplashKey {
330    /// No start screen is up — the key is the buffer's.
331    NotShowing,
332    /// The key selected a menu entry; run this.
333    Ran(Action),
334    /// The screen is gone and the key was not a menu key, so it still
335    /// means whatever it normally means. Anything else would make the
336    /// first keystroke after boot vanish.
337    Dismissed,
338}
339
340// ─── The counter, and the one place slips become mutations ───────────────
341
342/// `EditorState` read through the counter.
343///
344/// Borrowed, never copied: building it is free, so a command dispatch does
345/// not pay for a snapshot of the buffers.
346pub struct EditorWindow<'a> {
347    state: &'a EditorState,
348}
349
350impl escriba_madoguchi::CursorView for EditorWindow<'_> {
351    fn position(&self) -> Position {
352        self.state.cursor()
353    }
354    fn mode(&self) -> Mode {
355        self.state.modal.mode()
356    }
357}
358
359impl escriba_madoguchi::SyntaxView for EditorWindow<'_> {
360    fn filetype(&self) -> Option<&escriba_core::Filetype> {
361        let path = self.state.buffers.get(self.state.active)?.path.as_deref()?;
362        self.state.filetypes.resolve(path)
363    }
364}
365
366impl escriba_madoguchi::SearchView for EditorWindow<'_> {
367    fn pattern(&self) -> Option<&str> {
368        self.state.search.committed_pattern()
369    }
370    fn match_count(&self) -> Option<usize> {
371        // `None` means "nothing committed", which is not the same as zero
372        // matches — a distinction the status line already makes and that a
373        // handler must not have to re-derive.
374        self.state
375            .search
376            .committed_pattern()
377            .map(|_| self.state.search.match_count())
378    }
379    fn is_prompting(&self) -> bool {
380        self.state.search.is_prompting()
381    }
382}
383
384impl escriba_madoguchi::Snapshot for EditorWindow<'_> {
385    fn active(&self) -> Option<&dyn escriba_madoguchi::BufferView> {
386        self.buffer(self.state.active)
387    }
388    fn buffer(&self, id: BufferId) -> Option<&dyn escriba_madoguchi::BufferView> {
389        self.state
390            .buffers
391            .get(id)
392            .map(|b| b as &dyn escriba_madoguchi::BufferView)
393    }
394    fn buffer_ids(&self) -> Vec<BufferId> {
395        self.state.buffers.ids()
396    }
397    fn cursor(&self) -> &dyn escriba_madoguchi::CursorView {
398        self
399    }
400    fn option(&self, name: &str) -> Option<&str> {
401        self.state.options.get(name).map(String::as_str)
402    }
403    fn search(&self) -> &dyn escriba_madoguchi::SearchView {
404        self
405    }
406    fn syntax(&self) -> &dyn escriba_madoguchi::SyntaxView {
407        self
408    }
409}
410
411impl EditorState {
412    /// A read-only window onto this editor.
413    #[must_use]
414    pub fn window(&self) -> EditorWindow<'_> {
415        EditorWindow { state: self }
416    }
417
418    /// Honour an [`Outcome`] — the ONLY place slips become mutations.
419    ///
420    /// Every `&mut self` in the dispatch path lives here. A command cannot
421    /// reach editor state, so if the editor ends up in a state nobody
422    /// designed, this function is where it happened; that narrowing is the
423    /// whole return on the seam.
424    ///
425    /// A failed outcome's slips are DROPPED rather than half-applied: a
426    /// handler that reported failure has no business also mutating, and
427    /// applying part of what it asked for is how an editor reaches a state
428    /// nobody designed.
429    pub fn interpret(&mut self, outcome: Outcome) {
430        if let Some(m) = outcome.verdict.message() {
431            self.messages.push(m.to_string());
432            self.damage = self.damage.join(Damage::Viewport);
433            self.bump_gen();
434        }
435        if outcome.verdict.is_failure() {
436            return;
437        }
438        for slip in outcome.slips {
439            self.honour(slip);
440        }
441    }
442
443    /// Lower an [`Action`] to slips, when it has an exact slip equivalent.
444    ///
445    /// `None` means "editor mechanics" — 23 of the 30 variants are prompt
446    /// editing, the operator-pending FSM, motion resolution, the jumplist,
447    /// the dot register. Those are the KEYMAP's vocabulary, not the AUTHORED
448    /// one, and forcing them into `Negai` would put `DeleteToLineStart` and
449    /// `SearchPreviewStep` in front of every plugin author and make the
450    /// capability question meaningless (what capability does a caret move
451    /// read?). One type serving two vocabularies is the mistake this avoids.
452    ///
453    /// The plan's M3 predicate was "apply_resolved contains zero `self.`
454    /// mutations", which would have forced exactly that. Amended: the
455    /// invariant worth having is ONE IMPLEMENTATION PER MUTATION, not one
456    /// vocabulary. See docs/backlog-plan.md §V Phase 1.
457    fn lower(action: &Action, active: BufferId) -> Option<Vec<Negai>> {
458        Some(match action {
459            Action::Quit => vec![Negai::Quit],
460            Action::ClearSearchHighlight => vec![Negai::ClearSearchHighlight],
461            Action::Save => vec![Negai::Save { buffer: active }],
462            Action::Undo => vec![Negai::Undo { buffer: active }],
463            Action::Redo => vec![Negai::Redo { buffer: active }],
464            // `apply_edit` was a STUB that did nothing, so this action was a
465            // silent no-op while `Negai::Edit` applied for real. Lowering it
466            // makes keymap-originated edits work for the first time — and
467            // nothing binds it today, so the duplication goes away at zero
468            // risk.
469            Action::Edit(edit) => vec![Negai::Edit {
470                buffer: active,
471                edit: edit.clone(),
472            }],
473            _ => return None,
474        })
475    }
476
477    /// What the world currently is, for freshness.
478    ///
479    /// One text axis per open buffer. A list sealed against this is fresh
480    /// exactly while the buffers it depends on are unchanged — and a buffer
481    /// that has since CLOSED drops out, which makes lists about it stale
482    /// rather than silently kept.
483    #[must_use]
484    pub fn world(&self) -> escriba_shirube::Anchor {
485        let mut a = escriba_shirube::Anchor::new();
486        for id in self.buffers.ids() {
487            if let Some(b) = self.buffers.get(id) {
488                a = a.on(escriba_shirube::Axis::Text(id, b.text_rev()));
489            }
490        }
491        // Every axis the world can move, ALWAYS present — not only the ones
492        // some producer happens to use today.
493        //
494        // `Anchor::is_fresh` treats an ABSENT axis as stale, deliberately:
495        // unknowable is not unchanged. The consequence, unnoticed until a
496        // recon pass went looking, is that a list anchored on an axis this
497        // function never emits is born PERMANENTLY stale — `]c` would answer
498        // "that list is out of date" forever, and nothing would say why. The
499        // two-axis model was built for git hunks and then only ever fed one
500        // axis.
501        //
502        // Emitting them unconditionally means a producer can anchor on any
503        // axis and get an honest answer. A counter that never moves reads as
504        // "unchanged", which is exactly right for a plane escriba does not
505        // track yet.
506        a = a.on(escriba_shirube::Axis::Index(self.index_rev));
507        // Both session kinds, unconditionally, for the reason above: a
508        // producer anchoring on either must get an honest answer rather than
509        // permanent staleness. They are separate axes because they move
510        // independently — a picker closing must not invalidate diagnostics.
511        a = a.on(escriba_shirube::Axis::Session(
512            escriba_shirube::SessionKind::Lsp,
513            self.lsp_gen,
514        ));
515        a.on(escriba_shirube::Axis::Session(
516            escriba_shirube::SessionKind::Scan,
517            self.scan_gen,
518        ))
519    }
520
521    /// Where the cursor is, WITH the buffer it is in.
522    ///
523    /// Every jumplist push goes through this. A bare `Position` is what let
524    /// `<C-o>` return to the right line in the wrong file.
525    #[must_use]
526    pub fn spot(&self) -> escriba_core::Spot {
527        escriba_core::Spot::new(self.active, self.cursor())
528    }
529
530    /// Move to a `Spot`, switching buffer if it names another one.
531    ///
532    /// The read half of [`spot`](Self::spot). `<C-o>` and `<C-i>` both land
533    /// here so neither can forget the buffer.
534    fn goto_spot(&mut self, s: escriba_core::Spot) {
535        if s.buffer != self.active && self.buffers.get(s.buffer).is_some() {
536            self.active = s.buffer;
537        }
538        let clamped = self
539            .buffers
540            .get(self.active)
541            .map_or(s.pos, |b| b.clamp(s.pos));
542        self.set_cursor(clamped);
543    }
544
545    /// Advance the git-index generation — every list anchored on
546    /// `Axis::Index` goes stale.
547    ///
548    /// Not called yet; a git layer calls it after a stage/reset. Present so
549    /// the axis is WIRED rather than declared, because an axis nothing can
550    /// move is indistinguishable from an axis that does not exist.
551    pub fn bump_index_rev(&mut self) {
552        self.index_rev = escriba_shirube::IndexRev(self.index_rev.0.wrapping_add(1));
553    }
554
555    /// Advance the language-server generation — a server restarted, so every
556    /// diagnostic it produced describes a conversation that no longer exists.
557    /// See [`bump_index_rev`](Self::bump_index_rev).
558    pub fn bump_lsp_gen(&mut self) {
559        self.lsp_gen = escriba_shirube::SessionGen(self.lsp_gen.0.wrapping_add(1));
560    }
561
562    /// Advance the filesystem-scan generation.
563    ///
564    /// This is what makes a superseded scan's rows stale. A scan runs on its
565    /// own thread and cannot be stopped mid-walk; bumping this means its
566    /// remaining batches are *ignored on arrival*, which is a reply filter, not
567    /// cancellation — the thread keeps going until it notices. Say the weaker
568    /// thing, because the stronger one is not true.
569    ///
570    /// Deliberately separate from [`bump_lsp_gen`](Self::bump_lsp_gen): they
571    /// move for unrelated reasons, and when they shared one axis, closing a
572    /// picker staled every diagnostic in the gutter.
573    pub fn bump_scan_gen(&mut self) {
574        self.scan_gen = escriba_shirube::SessionGen(self.scan_gen.0.wrapping_add(1));
575    }
576
577    /// Install the courier's runners. Called once, by the composition root.
578    pub fn hire(&mut self, crew: escriba_madoguchi::errand::Crew) {
579        self.courier.hire(crew);
580    }
581
582    /// Diagnose every buffer that is already open.
583    ///
584    /// **Call this LAST, after the plan has been applied.** It has two
585    /// prerequisites and they are in different places: the courier needs its
586    /// crew ([`hire`](Self::hire)), and `language_of` needs the filetype table,
587    /// which `apply_plan_to_filetypes` fills from the catalog's `defmode`
588    /// forms. Both are set up by the composition root, in that order, and this
589    /// belongs after both.
590    ///
591    /// # Why this exists at all
592    ///
593    /// `ask_for_diagnostics` had exactly one caller — `Negai::OpenPath`, the
594    /// path a file takes when opened from INSIDE the editor. A file named on
595    /// the command line never travels it: the composition root reads the file
596    /// and hands the buffer to `new_with_buffer`. So `escriba main.rs` opened a
597    /// buffer that was never diagnosed while `:e main.rs` on the same file was,
598    /// and nothing on screen distinguished them — a file with errors simply
599    /// looked clean.
600    ///
601    /// # The ordering trap, which cost an hour
602    ///
603    /// The first fix hung this off `hire`, reasoning that hiring is the moment
604    /// diagnosis becomes possible. It is not: hiring makes the courier able to
605    /// RUN, but the filetype table is still empty there, so every errand went
606    /// out carrying `language: None`. The runner then fell back to its own
607    /// two-extension `language_of`, which does not know `.b`, and declined —
608    /// **silently, and correctly**, because "most files have no server" is the
609    /// common case and saying so on every open would be noise.
610    ///
611    /// Nothing was broken enough to report. `blue check` said `diag.b:8:3`
612    /// while the gutter stayed empty, and the only visible difference between
613    /// "no server for this language" and "the language was not resolved yet"
614    /// was a `None` in a struct field. **A prerequisite that is satisfied
615    /// somewhere else, later, is not a prerequisite the caller can see.**
616    pub fn diagnose_open_buffers(&mut self) {
617        // Every buffer, not just the active one: a session restored with a
618        // split, or a future `escriba a.rs b.rs`, opens more than one.
619        for id in self.buffers.ids() {
620            self.ask_for_diagnostics(id);
621        }
622    }
623
624    /// What an errand of this class depends on — the ONE place a courier
625    /// anchor is minted.
626    ///
627    /// A total match, so a new [`Freight`](escriba_madoguchi::errand::Freight)
628    /// variant does not compile until somebody decides what makes its results
629    /// stale. That is the point: the failure this prevents is not a wrong
630    /// answer, it is an errand class shipping with no freshness rule at all and
631    /// nobody noticing, because "no rule" reads at runtime as "always fresh".
632    ///
633    /// The return type forbids the empty anchor by construction — see
634    /// [`NonEmptyAnchor`](escriba_shirube::NonEmptyAnchor).
635    fn seal(
636        &self,
637        freight: &escriba_madoguchi::errand::Freight,
638    ) -> escriba_shirube::NonEmptyAnchor {
639        use escriba_madoguchi::errand::Freight;
640        use escriba_shirube::{Axis, NonEmptyAnchor, SessionKind};
641        match freight {
642            // A scan reads the filesystem, which no axis tracks, so text
643            // revisions are irrelevant to it — anchoring one on the buffers
644            // would make it die on the next keystroke for no reason. What DOES
645            // supersede it is the surface it feeds opening or closing, which is
646            // exactly what `scan_gen` counts.
647            Freight::Scan { .. } => {
648                NonEmptyAnchor::on(Axis::Session(SessionKind::Scan, self.scan_gen))
649            }
650            // Diagnostics describe ONE buffer at one revision, from one server
651            // session. Narrow on purpose: anchoring on the whole world would
652            // mean an edit in an unrelated buffer discards them.
653            Freight::Diagnostics { buffer, .. } => {
654                let rev = self.buffers.get(*buffer).map_or_else(
655                    escriba_buffer::TextRev::default,
656                    escriba_buffer::Buffer::text_rev,
657                );
658                NonEmptyAnchor::on(Axis::Text(*buffer, rev))
659                    .and(Axis::Session(SessionKind::Lsp, self.lsp_gen))
660            }
661            // A formatter reply REWRITES text. It must be judged against the
662            // revision it read and nothing else — the whole hazard is applying
663            // one to a buffer the operator kept typing into.
664            Freight::Format { path, .. } => match self.buffers.find_by_path(path) {
665                Some(id) => {
666                    let rev = self.buffers.get(id).map_or_else(
667                        escriba_buffer::TextRev::default,
668                        escriba_buffer::Buffer::text_rev,
669                    );
670                    NonEmptyAnchor::on(Axis::Text(id, rev))
671                }
672                // No open buffer for that path: seal on the LSP session so the
673                // reply is judged against SOMETHING. Never an empty anchor —
674                // that would be fresh forever, which is the whole hazard.
675                None => NonEmptyAnchor::on(Axis::Session(SessionKind::Lsp, self.lsp_gen)),
676            },
677        }
678    }
679
680    /// How many courier replies one tick may apply.
681    ///
682    /// Bounded so a chatty runner cannot hold a frame open. The remainder is
683    /// not dropped — it lands on the next tick.
684    const DELIVER_BUDGET: usize = 64;
685
686    /// Apply whatever the courier has delivered since the last tick.
687    ///
688    /// Must run BEFORE input translation: a redraw event maps to
689    /// `InputOutcome::None`, so a drain hung off the input path would never see
690    /// a tick that carried no keystroke — which is every tick during a scan.
691    pub fn deliver(&mut self) {
692        let slips = self.courier.drain(Self::DELIVER_BUDGET);
693        if slips.is_empty() {
694            return;
695        }
696        for slip in slips {
697            self.honour_one(slip);
698        }
699        // Something landed, so the screen is out of date.
700        self.bump_gen();
701    }
702
703    /// Move the cursor to the next/previous finding in `list`.
704    ///
705    /// Reports the wrap, because `n`/`N` do and a reader losing their place
706    /// in a long file is the same problem either way.
707    fn walk_list(&mut self, list: &str, forward: bool) {
708        let world = self.world();
709        let Some(result) = self.results.get(list) else {
710            let mut m = String::from("no list named ");
711            m.push_str(list);
712            self.messages.push(m);
713            return;
714        };
715        if result.is_stale(&world) {
716            self.messages
717                .push("that list is out of date — run it again".to_string());
718            return;
719        }
720        let here = (Some(self.active), self.cursor().line);
721        let Some(found) = result.step(&world, here, forward, escriba_shirube::Bound::Exclusive)
722        else {
723            let mut m = String::from("no entries in ");
724            m.push_str(list);
725            self.messages.push(m);
726            return;
727        };
728        let site = found.site.clone();
729        let msg = found.message.clone();
730        self.jump_to_site(&site);
731        self.messages.push(msg);
732    }
733
734    /// Move the cursor to a located finding's SITE — the one operation that
735    /// cannot drop the buffer half of a location.
736    ///
737    /// A `Site` is `(buffer, range)`. Every jumper before this re-derived the
738    /// move itself and clamped against `self.active`, so a finding in another
739    /// file landed on the right LINE in the WRONG file. `on_line` and
740    /// `worst_on_line` already filter by buffer, so the gutter and the walker
741    /// disagreed — latent only because the first producer scanned one buffer.
742    ///
743    /// Every future producer (diagnostics, hunks, grep hits, test failures)
744    /// is cross-file by nature, which is why this is a shared operation
745    /// rather than a fix at the one call site that has it wrong today.
746    ///
747    /// Always a FAR jump: it pushes the jumplist, so `<C-o>` returns from a
748    /// `]t` exactly as it returns from an `n`.
749    pub fn jump_to_site(&mut self, site: &escriba_shirube::Site) {
750        self.jumps.push(self.spot());
751        // Switch buffers FIRST — clamping against the wrong buffer is how the
752        // position gets silently mangled before anyone can notice.
753        if let Some(target) = site.buffer {
754            if target != self.active && self.buffers.get(target).is_some() {
755                self.active = target;
756                self.refollow_cursor();
757            }
758        }
759        let to = site.range.start;
760        let clamped = self.buffers.get(self.active).map_or(to, |b| b.clamp(to));
761        self.set_cursor(clamped);
762    }
763
764    /// Close a buffer, keeping "there is always an active buffer" true.
765    ///
766    /// The invariant is the whole reason this is not just
767    /// `self.buffers.close(id)`. `EditorState::active` is a `BufferId`, not
768    /// an `Option`, so a dangling active is not a degraded state — it is a
769    /// state where every read of the active buffer returns `None` and the
770    /// editor renders `<no buffer>` forever. Closing the last buffer opens a
771    /// scratch rather than emptying the set, which is what vim's `:bd` does
772    /// and what the type demands.
773    fn close_buffer(&mut self, id: BufferId) {
774        if self.buffers.close(id).is_none() {
775            self.messages.push("no such buffer".to_string());
776            return;
777        }
778        if self.active != id {
779            return;
780        }
781        // The active buffer went. Prefer the next one by id so repeated
782        // closes walk forward predictably rather than jumping around.
783        let next = self.buffers.ids().into_iter().find(|b| *b > id);
784        self.active = match next.or_else(|| self.buffers.ids().into_iter().next_back()) {
785            Some(b) => b,
786            None => self.buffers.scratch(""),
787        };
788        self.set_cursor(Position::ZERO);
789        if let Some(w) = self.layout.active_window_mut() {
790            w.buffer_id = self.active;
791        }
792    }
793
794    /// Move to the next or previous buffer, wrapping.
795    fn cycle_buffer(&mut self, forward: bool) {
796        let ids = self.buffers.ids();
797        if ids.len() < 2 {
798            self.messages.push("only one buffer".to_string());
799            return;
800        }
801        let at = ids.iter().position(|b| *b == self.active).unwrap_or(0);
802        let next = if forward {
803            (at + 1) % ids.len()
804        } else {
805            (at + ids.len() - 1) % ids.len()
806        };
807        self.active = ids[next];
808        self.set_cursor(Position::ZERO);
809        if let Some(w) = self.layout.active_window_mut() {
810            w.buffer_id = self.active;
811        }
812    }
813
814    /// Re-clamp the cursor and re-contain the viewport after a buffer
815    /// mutation.
816    ///
817    /// An undo can SHRINK the buffer under a cursor that was legal a moment
818    /// ago, leaving it out of bounds and its viewport scrolled past the end.
819    /// The Action executor has always done this (`self.set_cursor(self.cursor())`
820    /// after undo/redo/save); the M1 interpreter did NOT, so `u` re-followed
821    /// and `:undo` did not — two implementations of one operation, already
822    /// drifted within one milestone of being written. Naming it once is the
823    /// fix; lowering the Action arms onto the same slips is what keeps it
824    /// fixed.
825    fn refollow(&mut self) {
826        self.set_cursor(self.cursor());
827    }
828
829    /// Apply one slip and record what it damaged.
830    ///
831    /// The bookkeeping wrapper. The Action executor calls
832    /// [`honour_one`](Self::honour_one) directly because it does its own,
833    /// wider bookkeeping (the dot register, the S3 damage seal) around a
834    /// whole action.
835    fn honour(&mut self, slip: Negai) {
836        let touches_text = slip.touches_text();
837        self.honour_one(slip);
838        self.damage = self.damage.join(if touches_text {
839            Damage::Full
840        } else {
841            Damage::Viewport
842        });
843        self.bump_gen();
844    }
845
846    /// Apply one slip. THE single implementation of every mutation a slip
847    /// can ask for.
848    ///
849    /// Total over `Negai`: a new request variant is a compile error here
850    /// rather than a request silently ignored — the same failure Phase 0
851    /// removed one layer up.
852    fn honour_one(&mut self, slip: Negai) {
853        match slip {
854            Negai::Edit { buffer, edit } => {
855                if let Some(b) = self.buffers.get_mut(buffer) {
856                    let _ = b.apply(&edit);
857                }
858                self.refollow();
859            }
860            Negai::SetCursor { buffer, to } => {
861                // Clamping is the interpreter's job, exactly so that no
862                // handler has to re-implement it and get it wrong.
863                let clamped = self.buffers.get(buffer).map_or(to, |b| b.clamp(to));
864                self.set_cursor(clamped);
865            }
866            Negai::EnterMode(m) => self.modal.enter(m),
867            Negai::OpenPicker(source) => self.open_picker(source),
868            Negai::SplitWindow { stacked } => {
869                let axis = if stacked {
870                    escriba_ui::shikiri::Axis::Stacked
871                } else {
872                    escriba_ui::shikiri::Axis::SideBySide
873                };
874                self.layout.split_active(axis);
875                // The new pane is narrower/shorter than the old one, so the
876                // cursor can now be outside it. Every face re-reports its
877                // frame on the next draw, but the invariant must hold NOW —
878                // an operator who splits and immediately types should not be
879                // editing off-screen.
880                self.refollow_cursor();
881                self.damage = self.damage.join(Damage::Viewport);
882            }
883            Negai::CloseWindow => {
884                let id = self.layout.active();
885                if self.layout.close(id) {
886                    self.refollow_cursor();
887                    self.damage = self.damage.join(Damage::Viewport);
888                } else {
889                    // vim's E444, and the same refusal: the last window is
890                    // the editor. Closing it would mean "quit", which is a
891                    // different verb the operator did not type.
892                    self.messages
893                        .push("E444: Cannot close last window".to_string());
894                }
895            }
896            Negai::FocusDir { dx, dy } => {
897                use escriba_ui::Dir;
898                let dir = match (dx, dy) {
899                    (d, _) if d < 0 => Dir::Left,
900                    (d, _) if d > 0 => Dir::Right,
901                    (_, d) if d < 0 => Dir::Up,
902                    _ => Dir::Down,
903                };
904                if let Some(id) = self.layout.neighbour(dir) {
905                    self.layout.focus(id);
906                    // The window we moved to has its OWN buffer; the editor's
907                    // active buffer follows focus, or the next keystroke
908                    // would edit the file we just navigated away from.
909                    if let Some(w) = self.layout.active_window() {
910                        self.active = w.buffer_id;
911                    }
912                    self.refollow_cursor();
913                    self.damage = self.damage.join(Damage::Viewport);
914                }
915                // No neighbour is not an error — it is the edge of the
916                // layout, and vim says nothing there either.
917            }
918            Negai::GrepProject { pattern } => self.grep_project(&pattern),
919            Negai::FormatBuffer => self.ask_for_format(self.active),
920            Negai::ToggleBreakpoint => self.toggle_breakpoint(),
921            Negai::CycleBuffer { forward } => self.cycle_buffer(forward),
922            Negai::FocusBuffer(id) => {
923                if self.buffers.get(id).is_some() {
924                    self.active = id;
925                }
926            }
927            Negai::OpenPath(path) => match self.buffers.open(&path) {
928                Ok(id) => {
929                    self.active = id;
930                    self.ask_for_diagnostics(id);
931                }
932                Err(e) => self.messages.push(e.to_string()),
933            },
934            Negai::CloseBuffer(id) => self.close_buffer(id),
935            Negai::Save { buffer } => {
936                if let Some(b) = self.buffers.get_mut(buffer) {
937                    if let Err(e) = b.save() {
938                        self.messages.push(e.to_string());
939                    }
940                }
941                self.refollow();
942            }
943            Negai::Undo { buffer } => {
944                if let Some(b) = self.buffers.get_mut(buffer) {
945                    let _ = b.undo();
946                }
947                self.refollow();
948            }
949            Negai::Redo { buffer } => {
950                if let Some(b) = self.buffers.get_mut(buffer) {
951                    let _ = b.redo();
952                }
953                self.refollow();
954            }
955            Negai::Yank { text, kind, .. } => self.register = Some(Register::new(text, kind)),
956            Negai::ClearSearchHighlight => self.search.clear_highlight(),
957            Negai::SetOption { name, value } => {
958                self.options.insert(name, value);
959            }
960            Negai::InsertText(text) => self.insert_text(&text),
961            Negai::RunCommand { name, args } => self.run_command(&name, &args),
962            Negai::PublishFindings { list, findings } => {
963                let world = self.world();
964                self.results
965                    .publish(list, escriba_shirube::ResultList::new(findings, world));
966            }
967            // Sealed at `world()`, exactly like the `PublishFindings` above and
968            // for the same reason: an ON-TICK producer computed this against
969            // the world as it is right now. The off-tick path is the
970            // `ErrandReply` arm below, which must NOT reseal — see the note
971            // there.
972            Negai::PublishSemanticTokens { buffer, tokens } => {
973                let world = self.world();
974                self.semantic = Some(SemanticPaint::new(buffer, tokens, world));
975            }
976            // A reply from off the tick. Honour it only if the world it was
977            // computed against still holds.
978            //
979            // The drop is silent BY DESIGN, and this is the one place in the
980            // slip vocabulary where silence is right: a stale reply is not a
981            // failure anyone can act on. The operator kept typing, which is
982            // the correct thing to have done, and telling them "a diagnostic
983            // you never asked for was discarded" is noise. The producer
984            // re-runs against the new world; that is the whole contract.
985            Negai::ErrandReply { anchor, then } => {
986                if anchor.is_fresh(&self.world()) {
987                    match *then {
988                        // The reply's OWN anchor becomes the list's seal.
989                        //
990                        // Passing the gate and then re-sealing at `world()` —
991                        // which is what the direct `PublishFindings` arm does,
992                        // correctly, for an on-tick producer — is wrong for a
993                        // reply that crossed a thread. It widens a narrow claim
994                        // into a broad one: findings that depended on one
995                        // buffer would be stored as depending on every open
996                        // buffer, so an edit anywhere kills them. And it
997                        // upgrades an unearned claim into a durable one.
998                        //
999                        // Special-cased on this one payload because
1000                        // `ErrandReply` WRAPS a slip rather than putting an
1001                        // anchor field on `PublishFindings`; adding one there
1002                        // now would reopen exactly the hole the wrapper closed.
1003                        Negai::PublishFindings { list, findings } => {
1004                            self.results.publish(
1005                                list.clone(),
1006                                escriba_shirube::ResultList::new(findings, anchor),
1007                            );
1008                            self.refresh_projected_picker(&list);
1009                        }
1010                        // The second payload of one language-server
1011                        // conversation, and special-cased here for exactly the
1012                        // reason `PublishFindings` is: it must keep the
1013                        // reply's OWN anchor. Falling through to
1014                        // `honour_one` would reseal it at `world()` — passing
1015                        // the gate and then widening the claim, which turns
1016                        // "these colours describe buffer 3 at revision 7" into
1017                        // "these colours describe the world", so the next
1018                        // keystroke in ANY buffer would blank them and an
1019                        // unearned claim would have been made durable.
1020                        Negai::PublishSemanticTokens { buffer, tokens } => {
1021                            self.semantic = Some(SemanticPaint::new(buffer, tokens, anchor));
1022                        }
1023                        other => self.honour_one(other),
1024                    }
1025                }
1026            }
1027            Negai::WalkList { list, forward } => self.walk_list(&list, forward),
1028            Negai::Message(m) => self.messages.push(m),
1029            Negai::Quit => self.quit_requested = true,
1030            // Hand the freight to the courier, sealed against the world it
1031            // was dispatched in.
1032            //
1033            // The seal happens HERE and nowhere else. A handler named a class
1034            // of work; it did not — and could not — say what world that work
1035            // depends on, because a handler holds a read-only snapshot. If the
1036            // slip carried an anchor, any handler could mint one depending on
1037            // nothing, which is fresh forever, and the freshness gate would
1038            // stop meaning anything.
1039            Negai::Errand(freight) => {
1040                let anchor = self.seal(&freight);
1041                self.courier.send(*freight, anchor);
1042            }
1043            // Still unwired: the AwaitKey resume (M3). Announced, never
1044            // silently dropped — a slip that vanishes is the class Phase 0
1045            // sealed.
1046            Negai::AwaitKey { .. } => {
1047                self.messages
1048                    .push("deferred work is not wired yet".to_string());
1049            }
1050        }
1051    }
1052}
1053
1054/// Outcome of feeding one key to the multi-key pending-stroke loop.
1055enum SeqStep {
1056    /// Key consumed into an in-progress sequence; wait for the next.
1057    Pending,
1058    /// A full bound sequence resolved — run this action.
1059    Resolved(Action),
1060    /// Key is not part of any sequence; hand it to single-key dispatch.
1061    Passthrough,
1062}
1063
1064/// Keys whose HELD repeat is a viewport storm, and which the repeat gate
1065/// therefore exists to debounce.
1066///
1067/// This is an ALLOW-LIST, and it used to be the complement — an exception list
1068/// of "discrete" keys that grew three times (`n`/`N`/`*`/`#`, then `.`/`u`/
1069/// `<C-r>`, then `/`/`?`/`:`), each time because a key had been silently
1070/// swallowed and someone noticed. The third growth is the signal that the
1071/// default was backwards: almost every key in a modal editor is a discrete,
1072/// deliberate press, and only a handful are ones you HOLD.
1073///
1074/// Inverting it makes the failure mode safe. Forgetting to list a key here now
1075/// means it is ungated — one extra keypress honoured — instead of silently
1076/// dropped, and a dropped key is indistinguishable from a dead one.
1077///
1078/// Measured cost of the old direction: `/foo<CR>` then `/<CR>` (vim's
1079/// reuse-the-previous-pattern) lost the second `/` outright, because the gate
1080/// is keyed by KEY and the two presses fell inside one debounce window.
1081const fn is_repeat_storm_candidate(key: &Key) -> bool {
1082    matches!(
1083        key,
1084        // The four navigation keys a user actually holds down. `h`/`l` and
1085        // `j`/`k` flood the motion path and thrash the viewport; everything
1086        // else is pressed once and meant once.
1087        Key::Char('h')
1088            | Key::Char('j')
1089            | Key::Char('k')
1090            | Key::Char('l')
1091            | Key::Left
1092            | Key::Right
1093            | Key::Up
1094            | Key::Down
1095    )
1096}
1097
1098/// Turn a command failure into the sentence an operator should read.
1099///
1100/// The two failures mean genuinely different things and must not be reported
1101/// the same way:
1102///
1103/// - `:flurb` — the operator typed a name that does not exist. "command not
1104///   found" is exactly right; it says *you* made a typo.
1105/// - `<leader>ff` bound to `picker.files` — escriba's OWN shipped config
1106///   declares this, `--list-rc` counts it, and it is not built yet. Telling
1107///   the operator "command not found" blames them for a gap we shipped.
1108///
1109/// The discriminator is the dotted form. `:action` takes action SYMBOLS
1110/// (`picker.files`), never command names — that boundary is already pinned by
1111/// `action_naming_a_command_is_inert_not_recursive` in escriba-command. So a
1112/// dotted name that reached dispatch and resolved to nothing is a declared
1113/// capability with no implementation, which is precisely what the 85 entries
1114/// in `escriba/tests/action_resolution.rs` are.
1115fn describe_command_failure(name: &str, e: &escriba_command::CommandError) -> String {
1116    use escriba_command::CommandError as E;
1117    match e {
1118        // Already the right words — the registry knew it was declared.
1119        E::Unhandled(_) => e.to_string(),
1120        E::NotFound(n) if n.contains('.') => {
1121            let mut m = String::with_capacity(n.len() + 48);
1122            m.push('`');
1123            m.push_str(n);
1124            m.push_str("` is declared but not implemented yet");
1125            m
1126        }
1127        _ => {
1128            let _ = name;
1129            e.to_string()
1130        }
1131    }
1132}
1133
1134/// What committing the open search prompt did.
1135///
1136/// The two commit paths — bare `/` and operated `d/` — used to own private
1137/// copies of the whole sequence (read origin+skip, `accept`, three-arm
1138/// match, `commit_step_skipping`), and they drifted: the operated one
1139/// never reported the wrap, so `d/foo<CR>` that wrapped the file was
1140/// silent where `/foo<CR>` printed "search hit BOTTOM, continuing at TOP".
1141///
1142/// Total, and matched exhaustively at BOTH call sites, so a new outcome is
1143/// a compile error in two places rather than a case one path quietly
1144/// forgets. It does not make divergence impossible — the two paths
1145/// genuinely differ at the landing step — it makes FORGETTING A CASE
1146/// impossible, which is the failure that actually happened.
1147enum CommitOutcome {
1148    /// The prompt committed and a match was found.
1149    Landed {
1150        origin: usize,
1151        step: escriba_search::Step,
1152    },
1153    /// Committed, but nothing matched. E486 already reported.
1154    NotFound,
1155    /// Nothing typed and no previous pattern. E35 already reported.
1156    NoPrevious,
1157    /// No prompt was open.
1158    NoPrompt,
1159}
1160
1161/// A replayable text change.
1162#[derive(Debug, Clone)]
1163struct LastChange {
1164    /// The action that began the change.
1165    action: Action,
1166    /// How many times it ran.
1167    count: u32,
1168    /// Characters typed while the change held Insert mode open.
1169    inserted: String,
1170}
1171
1172impl EditorState {
1173    /// Build a fresh editor with one buffer (scratch or file-backed).
1174    pub fn new_with_buffer(initial: BufferSet, active: BufferId) -> Self {
1175        let window = Window {
1176            id: WindowId(1),
1177            buffer_id: active,
1178            viewport: Viewport {
1179                top_line: 0,
1180                left_column: 0,
1181                visible_lines: 40,
1182                visible_columns: 160,
1183            },
1184        };
1185        Self {
1186            buffers: initial,
1187            modal: ModalState::new(),
1188            search: SearchState::new(escriba_search::CaseMode::Smart),
1189            search_at: None,
1190            last_change: None,
1191            recording_insert: false,
1192            jumps: JumpList::new(),
1193            keymap: Keymap::default_vim(),
1194            commands: CommandRegistry::default_set(),
1195            layout: Layout::single(window),
1196            active,
1197            cursors: Cursors::single(Position::ZERO),
1198            quit_requested: false,
1199            register: None,
1200            op_pending: zenmai::Stateful::new(OpState::Resting),
1201            pending_object: None,
1202            pending_find: None,
1203            pending_replace: false,
1204            last_find: None,
1205            pending_mark: None,
1206            marks: HashMap::new(),
1207            messages: Vec::new(),
1208            options: HashMap::new(),
1209            lisp_vm: None,
1210            pending_keys: Vec::new(),
1211            repeat_gate: KeyRepeatGate::new(),
1212            plugin_host: PluginHost::default(),
1213            edit_gen: EditGen::default(),
1214            damage: Damage::None,
1215            // The FLEET default until an rc says otherwise — never a
1216            // hand-written theme name, so a fleet re-point lands for free.
1217            dispatch_depth: 0,
1218            filetypes: escriba_core::FiletypeTable::new(),
1219            results: escriba_shirube::ListRegistry::new(),
1220            picker: None,
1221            index_rev: escriba_shirube::IndexRev::default(),
1222            lsp_gen: escriba_shirube::SessionGen::default(),
1223            scan_gen: escriba_shirube::SessionGen::default(),
1224            courier: courier::Courier::inert(),
1225            picker_projects: None,
1226            theme: FleetTheme::prescribed_default(),
1227            chrome: ChromePalette::prescribed(),
1228            splash: None,
1229            semantic: None,
1230            breakpoints: Breakpoints::default(),
1231        }
1232    }
1233
1234    /// What a language server says `buffer`'s tokens mean, if that answer is
1235    /// still about this buffer at this revision.
1236    ///
1237    /// The ONLY reader — the field is private so a face cannot reach past the
1238    /// freshness check the way an earlier `results` reader could have. Empty is
1239    /// the honest answer for "no server", "not this buffer" and "you have typed
1240    /// since", and every one of them means the same thing to a renderer: paint
1241    /// with your own lexer.
1242    #[must_use]
1243    pub fn semantic_spans(&self, buffer: BufferId) -> &[escriba_madoguchi::SemanticSpan] {
1244        self.semantic
1245            .as_ref()
1246            .map_or(&[][..], |p| p.fresh(&self.world(), buffer))
1247    }
1248
1249    /// Everything the gutter has to say about one line of one buffer.
1250    ///
1251    /// ONE function, so the three faces cannot disagree about which planes
1252    /// the gutter reads. Before this each face called `worst_on_line` for
1253    /// itself, which was fine while there was one plane and is exactly how a
1254    /// second plane lands on two faces out of three — the divergence
1255    /// `escriba_ui::gutter` was extracted to stop, reappearing one layer up
1256    /// in the ARGUMENTS rather than in the composition.
1257    ///
1258    /// Takes `world` rather than computing it so a face that already holds
1259    /// one for the frame does not rebuild it per line.
1260    #[must_use]
1261    pub fn gutter_marks(
1262        &self,
1263        world: &escriba_shirube::Anchor,
1264        buffer: BufferId,
1265        line: u32,
1266    ) -> escriba_ui::gutter::GutterMarks {
1267        escriba_ui::gutter::GutterMarks::new(
1268            self.results.worst_on_line(world, buffer, line),
1269            self.breakpoints.is_set(buffer, line),
1270        )
1271    }
1272
1273    /// Where the operator asked the debugger to stop.
1274    ///
1275    /// Read-only: the only way to change it is [`Negai::ToggleBreakpoint`],
1276    /// so the refresh-generation bump that makes a face repaint cannot be
1277    /// forgotten by a caller that reached in and mutated the set.
1278    #[must_use]
1279    pub const fn breakpoints(&self) -> &Breakpoints {
1280        &self.breakpoints
1281    }
1282
1283    /// The theme this editor is set to.
1284    #[must_use]
1285    pub const fn theme(&self) -> FleetTheme {
1286        self.theme
1287    }
1288
1289    /// The colours every face paints with — read once per frame.
1290    #[must_use]
1291    pub const fn chrome(&self) -> ChromePalette {
1292        self.chrome
1293    }
1294
1295    /// Point the editor at a theme. The wiring that makes
1296    /// `(deftheme :preset …)` real.
1297    ///
1298    /// Bumps the refresh generation, because a theme change repaints
1299    /// everything: the GPU face caches its shaped buffer against that
1300    /// generation and would otherwise keep the old colours until an
1301    /// unrelated edit happened to invalidate it.
1302    pub fn set_theme(&mut self, theme: FleetTheme) {
1303        if self.theme == theme {
1304            return;
1305        }
1306        self.theme = theme;
1307        self.chrome = ChromePalette::for_theme(theme);
1308        self.damage = self.damage.join(Damage::Viewport);
1309        self.bump_gen();
1310    }
1311
1312    /// The start screen, if one is up. Renderers paint this INSTEAD of the
1313    /// buffer pane; `None` is the ordinary editor.
1314    #[must_use]
1315    pub fn splash(&self) -> Option<&Splash> {
1316        self.splash.as_ref()
1317    }
1318
1319    /// Raise the start screen. The binary calls this at boot when no file
1320    /// was named; an empty splash is refused so a face never has to render
1321    /// a blank screen over a perfectly good buffer.
1322    pub fn set_splash(&mut self, splash: Splash) {
1323        if splash.is_empty() {
1324            return;
1325        }
1326        self.splash = Some(splash);
1327        self.damage = self.damage.join(Damage::Viewport);
1328        self.bump_gen();
1329    }
1330
1331    /// Take the start screen down. Idempotent; bumps the refresh generation
1332    /// only when something actually changed, so dismissing twice does not
1333    /// cost a repaint.
1334    pub fn dismiss_splash(&mut self) {
1335        if self.splash.take().is_some() {
1336            self.damage = self.damage.join(Damage::Viewport);
1337            self.bump_gen();
1338        }
1339    }
1340
1341    /// Offer `key` to the start screen.
1342    ///
1343    /// A menu key runs its entry; ANY other key simply takes the screen
1344    /// down and is then handled normally — so the first thing an operator
1345    /// types is never swallowed.
1346    /// The open picker, for a face to paint.
1347    #[must_use]
1348    pub fn picker(&self) -> Option<&escriba_ui::picker::Picker> {
1349        self.picker.as_ref()
1350    }
1351
1352    /// Give an open picker the key.
1353    ///
1354    /// Runs BEFORE the keymap, and before the sequence stepper: while a
1355    /// picker is up it owns every key, including ones it has no meaning for.
1356    /// An overlay that let unknown keys fall through would edit the file
1357    /// behind itself.
1358    /// Ask the courier what a language server thinks of this buffer.
1359    ///
1360    /// Fires on open, and only on open. Re-asking on every keystroke is what a
1361    /// real diagnostics pump does, and it needs a session that outlives one
1362    /// errand plus `didChange` to keep the server's copy current — neither
1363    /// exists yet, and dispatching per keystroke against a one-shot runner
1364    /// would spawn a language server per character typed.
1365    ///
1366    /// A buffer with no path is skipped: a scratch buffer has no document for
1367    /// a server to have an opinion about.
1368    fn ask_for_diagnostics(&mut self, buffer: escriba_core::BufferId) {
1369        let Some(b) = self.buffers.get(buffer) else {
1370            return;
1371        };
1372        let Some(path) = b.path.clone() else {
1373            return;
1374        };
1375        let text = b.to_string();
1376        let language = self.language_of(&path);
1377        let freight = escriba_madoguchi::errand::Freight::Diagnostics {
1378            buffer,
1379            path,
1380            language,
1381            text,
1382        };
1383        let anchor = self.seal(&freight);
1384        self.courier.send(freight, anchor);
1385    }
1386
1387    /// The language of `path`, as the CATALOG declared it.
1388    ///
1389    /// `FiletypeTable` is populated from every `(defmode … :extensions …)` the
1390    /// catalog carries, so this answer covers every language escriba has been
1391    /// told about — 11 of them today — rather than the two extensions
1392    /// `escriba_lsp_client::runner::language_of` hardcodes. That is why blue
1393    /// resolves here without anything in this crate naming blue: the
1394    /// declaration already existed, and nothing was reading it.
1395    ///
1396    /// `None` when the table has no entry, which is not an error — it is the
1397    /// answer for a plain `.txt`, and it is also what a `--no-defaults` boot
1398    /// gives for everything, so the runner keeps its own fallback.
1399    fn language_of(&self, path: &std::path::Path) -> Option<String> {
1400        self.filetypes.resolve(path).map(|f| f.name.clone())
1401    }
1402
1403    /// Ask the formatter runner to format `buffer`.
1404    ///
1405    /// The buffer's CURRENT text goes with the errand and the anchor seals on
1406    /// its revision, so a reply computed against text the operator has since
1407    /// changed is refused rather than applied — see `seal`'s `Format` arm,
1408    /// which was written before anything could construct this errand.
1409    fn ask_for_format(&mut self, buffer: escriba_core::BufferId) {
1410        let Some(b) = self.buffers.get(buffer) else {
1411            return;
1412        };
1413        // A formatter needs a path: it is how the server is chosen and how the
1414        // project root is found. A scratch buffer has none, and saying so beats
1415        // silently doing nothing to a keystroke the operator pressed.
1416        let Some(path) = b.path.clone() else {
1417            self.messages
1418                .push("format: this buffer has no path".to_string());
1419            self.damage = self.damage.join(Damage::Viewport);
1420            self.bump_gen();
1421            return;
1422        };
1423        let text = b.to_string();
1424        let language = self.language_of(&path);
1425        let freight = escriba_madoguchi::errand::Freight::Format {
1426            buffer,
1427            path,
1428            language,
1429            text,
1430        };
1431        let anchor = self.seal(&freight);
1432        self.courier.send(freight, anchor);
1433    }
1434
1435    /// Set or clear a breakpoint on the cursor's line of the active buffer.
1436    ///
1437    /// The SOLE writer of `self.breakpoints`, which is why the field is
1438    /// private and [`breakpoints`](Self::breakpoints) hands out a `&`: the
1439    /// mark has to reach the screen, and the GPU face rebuilds its cached
1440    /// shaped gutter buffer ONLY on a refresh-generation change
1441    /// (`escriba-render/src/gpu.rs:260`). A caller that reached in and
1442    /// mutated the set would change the state and not the picture until some
1443    /// unrelated edit invalidated the cache — the defect `set_theme` had.
1444    ///
1445    /// It does NOT bump the generation itself, and that is deliberate rather
1446    /// than an omission: [`honour`](Self::honour) widens the damage and bumps
1447    /// for EVERY slip, so doing it here as well would be a second
1448    /// implementation of one guarantee — measured 2026-08-12, the first cut
1449    /// of this method did exactly that and the redundancy was invisible
1450    /// because both spellings produce the same answer.
1451    fn toggle_breakpoint(&mut self) {
1452        let buffer = self.active;
1453        let line = self.cursor().line;
1454        // No buffer means no line to mark, and marking a row of nothing would
1455        // put a breakpoint somewhere a future DAP client cannot name.
1456        if self.buffers.get(buffer).is_none() {
1457            return;
1458        }
1459        let set = self.breakpoints.toggle(buffer, line);
1460        // Built by `push_str` + `Display`, not `format!` — ★★ TYPED EMISSION.
1461        // The number is 1-based, like the gutter it appears beside and like
1462        // every message vim prints; reporting the internal 0-based row would
1463        // disagree with the label painted next to the mark.
1464        let mut msg = String::from(if set {
1465            "breakpoint set at line "
1466        } else {
1467            "breakpoint cleared at line "
1468        });
1469        msg.push_str(&(line + 1).to_string());
1470        self.messages.push(msg);
1471    }
1472
1473    /// Close the picker — the SOLE writer of `self.picker = None`.
1474    ///
1475    /// Sole on purpose. Closing has three consequences that must not come
1476    /// apart: the overlay goes, the screen repaints, and any scan feeding that
1477    /// overlay is superseded. Spread across call sites, one of them eventually
1478    /// forgets the third and a dismissed picker springs back open when a late
1479    /// batch arrives.
1480    ///
1481    /// `cancel_all` is asked as well as the generation bumped, but note which
1482    /// one is load-bearing: the bump is what makes late rows *ignored*, and it
1483    /// works whether or not any runner reads its flag. The cancel is a courtesy
1484    /// to a runner that checks.
1485    fn close_picker(&mut self) {
1486        self.picker = None;
1487        self.picker_projects = None;
1488        self.bump_scan_gen();
1489        self.courier.cancel_all();
1490        self.bump_gen();
1491    }
1492
1493    fn consume_picker_key(&mut self, key: &Key) -> escriba_ui::picker::Consumed {
1494        use escriba_ui::picker::Consumed;
1495        let Some(p) = self.picker.as_mut() else {
1496            return Consumed::NotShowing;
1497        };
1498        let outcome = p.on_key(key);
1499        match &outcome {
1500            // BOTH arms close the picker — choosing a row dismisses it just as
1501            // surely as pressing Esc, and an earlier reading of this that only
1502            // considered Esc would have left a scan running after every pick.
1503            Consumed::Dismissed | Consumed::Chose(_) => self.close_picker(),
1504            Consumed::Held => self.bump_gen(),
1505            Consumed::NotShowing => {}
1506        }
1507        outcome
1508    }
1509
1510    /// Lower an accepted pick into the ONE interpreter.
1511    ///
1512    /// The whole reason `Choice` is a closed enum: a new source must decide
1513    /// here, and the compiler says so.
1514    fn honour_choice(&mut self, choice: escriba_ui::picker::Choice) {
1515        use escriba_ui::picker::Choice;
1516        let slip = match choice {
1517            Choice::Buffer(id) => Negai::FocusBuffer(id),
1518            Choice::Command(name) => Negai::RunCommand {
1519                name,
1520                args: Vec::new(),
1521            },
1522            Choice::OpenFile(path) => Negai::OpenPath(path),
1523            Choice::Location { path, line } => {
1524                // Open FIRST, then jump: the buffer may not exist yet, and
1525                // `jump_to_site` needs a BufferId. Two slips, one interpret.
1526                self.interpret(Outcome::did(vec![Negai::OpenPath(path)]));
1527                let site = escriba_shirube::Site::in_buffer(
1528                    self.active,
1529                    escriba_core::Range::new(
1530                        escriba_core::Position::new(line, 0),
1531                        escriba_core::Position::new(line, 1),
1532                    ),
1533                );
1534                self.jump_to_site(&site);
1535                return;
1536            }
1537        };
1538        self.interpret(Outcome::did(vec![slip]));
1539    }
1540
1541    /// How many files a project grep will read, and how many hits it keeps.
1542    ///
1543    /// BOUNDED, and the bound is here rather than hidden, because this is a
1544    /// SYNCHRONOUS scan on the editor's own thread. The interpreter already
1545    /// does synchronous filesystem I/O (`OpenPath`, `Save`), so the posture
1546    /// is not new — but those touch one file and this walks a tree, which is
1547    /// the first one big enough to freeze the editor.
1548    ///
1549    /// GREP NO LONGER USES THIS. The courier carries the scan now, with no
1550    /// ceiling at all, and `GREP_HIT_LIMIT` is gone with it — the bound was
1551    /// a symptom of walking the tree on the thread that draws the screen.
1552    ///
1553    /// It survives for the files and project pickers, which still build
1554    /// their row set synchronously at open. Moving those onto the courier
1555    /// is the same change again and has not been made.
1556    const GREP_FILE_LIMIT: usize = 2_000;
1557
1558    /// Walk the working directory, bounded, returning `(files, truncated)`.
1559    ///
1560    /// ONE walker. grep, files and project each need to enumerate the tree,
1561    /// and three copies of a bounded traversal is three places to get the
1562    /// ceiling, the skip-list, or the truncation report subtly different.
1563    ///
1564    /// Skips dotfiles, `target` and `node_modules`. That is NOT a gitignore
1565    /// implementation and does not pretend to be — a real ignore crate comes
1566    /// with the courier.
1567    fn walk_project(limit: usize) -> (Vec<std::path::PathBuf>, bool) {
1568        Self::walk_from(std::path::Path::new("."), limit)
1569    }
1570
1571    /// The same bounded walk, from an explicit root.
1572    ///
1573    /// `walk_project` is this with `.` — one traversal, two callers, rather
1574    /// than a second copy for "browse from somewhere else".
1575    fn walk_from(root: &std::path::Path, limit: usize) -> (Vec<std::path::PathBuf>, bool) {
1576        let mut out = Vec::new();
1577        let mut truncated = false;
1578        let mut stack = vec![root.to_path_buf()];
1579        while let Some(dir) = stack.pop() {
1580            let Ok(entries) = std::fs::read_dir(&dir) else {
1581                continue;
1582            };
1583            for entry in entries.flatten() {
1584                let name = entry.file_name();
1585                let name = name.to_string_lossy();
1586                if name.starts_with('.') || name == "target" || name == "node_modules" {
1587                    continue;
1588                }
1589                let path = entry.path();
1590                if entry.file_type().is_ok_and(|t| t.is_dir()) {
1591                    stack.push(path);
1592                    continue;
1593                }
1594                if out.len() >= limit {
1595                    truncated = true;
1596                    return (out, truncated);
1597                }
1598                out.push(path);
1599            }
1600        }
1601        (out, truncated)
1602    }
1603
1604    /// Say plainly when a bounded scan stopped short.
1605    ///
1606    /// A truncated list presented as complete is the failure this codebase
1607    /// keeps finding in itself; it does not get to ship one.
1608    fn report_truncation(&mut self, truncated: bool) {
1609        if truncated {
1610            self.messages
1611                .push("scan stopped at the limit — results are INCOMPLETE".to_string());
1612        }
1613    }
1614
1615    /// Scan the working directory for `pattern`, off the editor thread.
1616    ///
1617    /// This used to walk the tree inline, capped at 2,000 files and 500 hits
1618    /// because it ran on the thread that draws the screen — and it reported
1619    /// that truncation, honestly, as INCOMPLETE. Both ceilings are gone with
1620    /// the walk: the courier carries it, and results arrive in batches.
1621    ///
1622    /// The picker opens EMPTY and then projects the findings list. That is why
1623    /// there is no "no matches" message here any more — at dispatch time
1624    /// nothing is known yet, and guessing would mean reporting an empty result
1625    /// before the scan had read a single file.
1626    fn grep_project(&mut self, pattern: &str) {
1627        use escriba_ui::picker::{Picker, Source};
1628        if pattern.is_empty() {
1629            self.messages.push("grep: empty pattern".to_string());
1630            return;
1631        }
1632        // A fresh scan supersedes whatever was running, and clears the list so
1633        // the previous pattern's rows are not shown under the new one.
1634        self.bump_scan_gen();
1635        self.courier.cancel_all();
1636        self.results.clear(crate::scan::LIST);
1637
1638        let freight = escriba_madoguchi::errand::Freight::Scan {
1639            raw: pattern.to_string(),
1640            case: escriba_search::CaseMode::Smart,
1641            root: std::path::PathBuf::from("."),
1642        };
1643        let anchor = self.seal(&freight);
1644        self.courier.send(freight, anchor);
1645
1646        self.picker = Some(Picker::open(Source::Grep, Vec::new()));
1647        self.picker_projects = Some((true, Some(crate::scan::LIST.to_string())));
1648        self.bump_gen();
1649    }
1650
1651    /// Re-list a projecting picker after `published` changed.
1652    ///
1653    /// A picker over a live producer is a VIEW of the registry, not a snapshot
1654    /// taken when it opened — otherwise a scan's later batches would have
1655    /// nowhere to land, since `Picker` has no append.
1656    fn refresh_projected_picker(&mut self, published: &str) {
1657        let Some((workspace, ref list)) = self.picker_projects else {
1658            return;
1659        };
1660        // Only the list this picker is projecting. A diagnostics publish must
1661        // not redraw a grep picker.
1662        if list.as_deref().is_some_and(|l| l != published) {
1663            return;
1664        }
1665        let items = self.finding_items(workspace, list.as_deref());
1666        if let Some(p) = self.picker.as_mut() {
1667            if p.refresh_items(items) {
1668                self.bump_gen();
1669            }
1670        }
1671    }
1672
1673    /// Where accepting a finding should take the operator.
1674    ///
1675    /// Returns `None` for a finding whose site names neither a path nor a
1676    /// live buffer — that is a finding about nowhere, and offering it would
1677    /// give the operator a row that does nothing when pressed.
1678    fn finding_choice(&self, f: &escriba_shirube::Finding) -> Option<escriba_ui::picker::Choice> {
1679        use escriba_ui::picker::Choice;
1680        let line = f.site.range.start.line;
1681        if let Some(p) = &f.site.path {
1682            return Some(Choice::Location {
1683                path: p.clone(),
1684                line,
1685            });
1686        }
1687        let id = f.site.buffer?;
1688        let b = self.buffers.get(id)?;
1689        // A buffer WITH a path becomes a Location, so the line survives. A
1690        // scratch buffer has no path to name, so the best available answer
1691        // is the buffer itself — and the line is lost. Stated rather than
1692        // hidden: a `Choice` that carried a BufferId AND a line would be
1693        // the fix, and it belongs with the picker, not here.
1694        b.path.as_ref().map_or(Some(Choice::Buffer(id)), |p| {
1695            Some(Choice::Location {
1696                path: p.clone(),
1697                line,
1698            })
1699        })
1700    }
1701
1702    /// How a finding's location reads in a list row.
1703    fn finding_label(&self, f: &escriba_shirube::Finding) -> String {
1704        if let Some(p) = &f.site.path {
1705            return p.to_string_lossy().into_owned();
1706        }
1707        f.site
1708            .buffer
1709            .and_then(|id| self.buffers.get(id))
1710            .and_then(|b| b.path.as_ref())
1711            .map_or_else(
1712                || String::from("[scratch]"),
1713                |p| p.to_string_lossy().into_owned(),
1714            )
1715    }
1716
1717    /// Picker rows for every file under `root`.
1718    ///
1719    /// `picker.files` and `files.open-parent` differ only in the root, so
1720    /// they share this rather than carrying two copies of the same body —
1721    /// which is what they did for one commit, and what the line-count lint
1722    /// correctly complained about.
1723    fn file_items(
1724        &mut self,
1725        root: &std::path::Path,
1726    ) -> Vec<escriba_ui::picker::PickerItem<escriba_ui::picker::Choice>> {
1727        use escriba_ui::picker::{Choice, PickerItem};
1728        let (files, truncated) = Self::walk_from(root, Self::GREP_FILE_LIMIT);
1729        self.report_truncation(truncated);
1730        files
1731            .into_iter()
1732            .map(|p| {
1733                let label = p.to_string_lossy().into_owned();
1734                PickerItem::new(Choice::OpenFile(p), label)
1735            })
1736            .collect()
1737    }
1738
1739    /// Picker rows for the located findings the `trouble.*` verbs show.
1740    ///
1741    /// Freshness is asked of the registry, not assumed: `fresh` filters
1742    /// against the CURRENT world, so a list anchored to a revision the
1743    /// buffer has moved past contributes nothing rather than offering a
1744    /// line that has since shifted.
1745    fn finding_items(
1746        &self,
1747        workspace: bool,
1748        only: Option<&str>,
1749    ) -> Vec<escriba_ui::picker::PickerItem<escriba_ui::picker::Choice>> {
1750        use escriba_ui::picker::PickerItem;
1751        let world = self.world();
1752        let active = Some(self.active);
1753        let mut items = Vec::new();
1754        // `None` means every list — the trouble.* behaviour, unchanged.
1755        // `Some(n)` narrows to one producer, so a grep picker does not also
1756        // render LSP diagnostics and the marker scan.
1757        let names: Vec<&str> = only.map_or_else(|| self.results.names(), |n| vec![n]);
1758        for name in names {
1759            let Some(list) = self.results.get(name) else {
1760                continue;
1761            };
1762            for f in list.fresh(&world) {
1763                // `trouble.document` narrows to the buffer in front of the
1764                // operator. A finding that names only a path is
1765                // workspace-scoped by construction — it has no buffer to be
1766                // "this" one.
1767                if !workspace && f.site.buffer != active {
1768                    continue;
1769                }
1770                let Some(choice) = self.finding_choice(f) else {
1771                    continue;
1772                };
1773                let line = f.site.range.start.line;
1774                let mut label = String::with_capacity(64);
1775                label.push_str(f.severity.label());
1776                label.push_str("  ");
1777                label.push_str(&self.finding_label(f));
1778                label.push(':');
1779                label.push_str(&(line + 1).to_string());
1780                label.push_str("  ");
1781                label.push_str(&f.message);
1782                items.push(PickerItem::new(choice, label));
1783            }
1784        }
1785        items
1786    }
1787
1788    /// Build and open a picker over `source`.
1789    fn open_picker(&mut self, source: escriba_madoguchi::PickerSource) {
1790        use escriba_ui::picker::{Choice, Picker, PickerItem, Source};
1791        let (src, items) = match source {
1792            escriba_madoguchi::PickerSource::Buffers => (
1793                Source::Buffers,
1794                self.buffers
1795                    .ids()
1796                    .into_iter()
1797                    .filter_map(|id| {
1798                        let b = self.buffers.get(id)?;
1799                        let label = b.path.as_ref().map_or_else(
1800                            || String::from("[scratch]"),
1801                            |p| p.to_string_lossy().into_owned(),
1802                        );
1803                        Some(PickerItem::new(Choice::Buffer(id), label))
1804                    })
1805                    .collect::<Vec<_>>(),
1806            ),
1807            escriba_madoguchi::PickerSource::Help => (
1808                Source::Help,
1809                self.keymap
1810                    .entries_sorted()
1811                    .into_iter()
1812                    .map(|(mode, key, b)| {
1813                        // "NORMAL  gd   goto definition" — searchable by key,
1814                        // by mode, or by what it does, because a reader
1815                        // arrives from any of the three.
1816                        let mut label = String::with_capacity(48);
1817                        label.push_str(mode.as_str());
1818                        label.push_str("  ");
1819                        // `{key:?}` because there is no shared key FORMATTER
1820                        // in the fleet — awase owns the chord vocabulary but
1821                        // escriba-keymap's `Key` has no Display. That gap
1822                        // belongs to the keymap consolidation, not here, and
1823                        // inventing a fourth spelling would make it worse.
1824                        label.push_str(&format!("{key:?}"));
1825                        label.push_str("  ");
1826                        label.push_str(&b.description);
1827                        // Accepting runs the binding's action if it names a
1828                        // command; a typed Action has no name to run, so it
1829                        // reports rather than pretending.
1830                        let choice = match &b.action {
1831                            escriba_core::Action::Command { name, .. } => {
1832                                Choice::Command(name.clone())
1833                            }
1834                            other => Choice::Command(format!("{other:?}")),
1835                        };
1836                        PickerItem::new(choice, label)
1837                    })
1838                    .collect::<Vec<_>>(),
1839            ),
1840            escriba_madoguchi::PickerSource::Files => {
1841                (Source::Files, self.file_items(std::path::Path::new(".")))
1842            }
1843            escriba_madoguchi::PickerSource::Project => {
1844                // A project root is a directory carrying a marker. Derived
1845                // from the SAME walk rather than a second traversal — the
1846                // markers are files, so the walker already visited them.
1847                const MARKERS: &[&str] = &[
1848                    "Cargo.toml",
1849                    "flake.nix",
1850                    "package.json",
1851                    "go.mod",
1852                    "pyproject.toml",
1853                ];
1854                let (files, truncated) = Self::walk_project(Self::GREP_FILE_LIMIT);
1855                self.report_truncation(truncated);
1856                let mut roots: Vec<std::path::PathBuf> = files
1857                    .into_iter()
1858                    .filter(|p| {
1859                        p.file_name()
1860                            .is_some_and(|n| MARKERS.contains(&n.to_string_lossy().as_ref()))
1861                    })
1862                    .filter_map(|p| p.parent().map(std::path::Path::to_path_buf))
1863                    .collect();
1864                roots.sort();
1865                roots.dedup();
1866                (
1867                    Source::Project,
1868                    roots
1869                        .into_iter()
1870                        .map(|p| {
1871                            let label = p.to_string_lossy().into_owned();
1872                            PickerItem::new(Choice::OpenFile(p), label)
1873                        })
1874                        .collect::<Vec<_>>(),
1875                )
1876            }
1877            escriba_madoguchi::PickerSource::Commands => (
1878                Source::Commands,
1879                self.commands
1880                    .names()
1881                    .into_iter()
1882                    .map(|n| PickerItem::new(Choice::Command(n.to_string()), n.to_string()))
1883                    .collect::<Vec<_>>(),
1884            ),
1885            escriba_madoguchi::PickerSource::FilesUnder(root) => {
1886                (Source::Files, self.file_items(&root))
1887            }
1888            escriba_madoguchi::PickerSource::Findings { workspace } => {
1889                (Source::Findings, self.finding_items(workspace, None))
1890            }
1891        };
1892        if items.is_empty() {
1893            self.messages.push("nothing to pick from".to_string());
1894            return;
1895        }
1896        self.picker = Some(Picker::open(src, items));
1897        self.bump_gen();
1898    }
1899
1900    /// Read one key as operator-pending object selection.
1901    ///
1902    /// Returns `None` when the key is nothing to do with objects, so the
1903    /// ordinary path runs untouched.
1904    fn consume_object_key(&mut self, key: Key) -> Option<ObjectKey> {
1905        use escriba_core::TextObject as O;
1906        let Key::Char(c) = key else {
1907            // Esc (or anything non-printable) abandons a half-typed object
1908            // rather than leaving the editor silently armed.
1909            if self.pending_object.take().is_some() {
1910                self.op_pending
1911                    .dispatch((Action::ChangeMode(Mode::Normal), 1));
1912                return Some(ObjectKey::Consumed);
1913            }
1914            return None;
1915        };
1916
1917        // Second key: it names the object.
1918        if let Some(around) = self.pending_object.take() {
1919            let object = match c {
1920                'w' => Some(O::Word { around }),
1921                // vim's `b` and `B` aliases for the bracket pairs, plus the
1922                // brackets themselves in both directions.
1923                '(' | ')' | 'b' => Some(O::Delimited {
1924                    open: '(',
1925                    close: ')',
1926                    around,
1927                }),
1928                '{' | '}' | 'B' => Some(O::Delimited {
1929                    open: '{',
1930                    close: '}',
1931                    around,
1932                }),
1933                '[' | ']' => Some(O::Delimited {
1934                    open: '[',
1935                    close: ']',
1936                    around,
1937                }),
1938                '<' | '>' => Some(O::Delimited {
1939                    open: '<',
1940                    close: '>',
1941                    around,
1942                }),
1943                // Quotes: `open == close`, which is what tells the resolver
1944                // not to count nesting.
1945                '"' => Some(O::Delimited {
1946                    open: '"',
1947                    close: '"',
1948                    around,
1949                }),
1950                '\'' => Some(O::Delimited {
1951                    open: '\'',
1952                    close: '\'',
1953                    around,
1954                }),
1955                '`' => Some(O::Delimited {
1956                    open: '`',
1957                    close: '`',
1958                    around,
1959                }),
1960                _ => None,
1961            };
1962            let OpState::Awaiting { op, count } = *self.op_pending.state() else {
1963                return Some(ObjectKey::Consumed);
1964            };
1965            // Disarm either way: an unknown object key cancels the operator,
1966            // it does not leave it armed for the next unrelated keystroke.
1967            self.op_pending
1968                .dispatch((Action::ChangeMode(Mode::Normal), 1));
1969            let Some(object) = object else {
1970                return Some(ObjectKey::Consumed);
1971            };
1972            let composed = Action::ApplyOperatorObject { op, object };
1973            // `2diw` applies the object twice. The caller runs it once, so
1974            // the extra repeats happen here.
1975            for _ in 1..count {
1976                self.apply(&composed);
1977            }
1978            return Some(ObjectKey::Compose(composed));
1979        }
1980
1981        // First key: `i` or `a` while an operator waits.
1982        if matches!(c, 'i' | 'a') && matches!(self.op_pending.state(), OpState::Awaiting { .. }) {
1983            self.pending_object = Some(c == 'a');
1984            return Some(ObjectKey::Consumed);
1985        }
1986        None
1987    }
1988
1989    /// Claim the operand of a pending `f`/`F`/`t`/`T`, or arm one.
1990    ///
1991    /// Runs BEFORE the sequence stepper and before the keymap, for the same
1992    /// reason [`Self::consume_object_key`] does: the character is an OPERAND,
1993    /// not a binding. `dfx` is undecidable from actions — `x` would resolve as
1994    /// whatever `x` is bound to — and `f` then `f` has to reach here rather
1995    /// than resolve as a two-key sequence.
1996    ///
1997    /// Composition with an operator is free: the armed motion is emitted as an
1998    /// ordinary `Action::Move`, so the operator-pending FSM composes `dfx`
1999    /// exactly the way it composes `dw`.
2000    fn consume_find_key(&mut self, key: Key) -> Option<ObjectKey> {
2001        if let Some(spec) = self.pending_find.take() {
2002            let Key::Char(ch) = key else {
2003                // Esc (or any non-printable) abandons a half-typed find rather
2004                // than leaving the editor armed for the next keystroke.
2005                if matches!(self.op_pending.state(), OpState::Awaiting { .. }) {
2006                    self.op_pending
2007                        .dispatch((Action::ChangeMode(Mode::Normal), 1));
2008                }
2009                return Some(ObjectKey::Consumed);
2010            };
2011            let spec = FindSpec { ch, ..spec };
2012            self.last_find = Some(spec);
2013            return Some(ObjectKey::Compose(Action::Move(Motion::FindChar {
2014                ch,
2015                backward: spec.backward,
2016                till: spec.till,
2017            })));
2018        }
2019        if self.modal.mode() != Mode::Normal && self.modal.mode() != Mode::Visual {
2020            return None;
2021        }
2022        // A key that is CONTINUING a sequence belongs to the sequence.
2023        //
2024        // Without this, `zt` was unreachable: `z` starts a pending sequence,
2025        // then `t` was claimed here as a till-find and the sequence never
2026        // completed. The rule "an operand key outranks a binding" is right
2027        // for the FIRST key of a gesture and wrong for a later one — by then
2028        // the gesture has already been chosen. Note the operand branch above
2029        // runs before this guard, so `zt` and `ft` are both reachable.
2030        if !self.pending_keys.is_empty() {
2031            return None;
2032        }
2033        let Key::Char(c) = key else { return None };
2034        let (backward, till) = match c {
2035            'f' => (false, false),
2036            'F' => (true, false),
2037            't' => (false, true),
2038            'T' => (true, true),
2039            _ => return None,
2040        };
2041        self.pending_find = Some(FindSpec {
2042            ch: '\0',
2043            backward,
2044            till,
2045        });
2046        Some(ObjectKey::Consumed)
2047    }
2048
2049    /// Claim the operand of a pending `r`, or arm one.
2050    ///
2051    /// Same key-layer shape as [`Self::consume_find_key`], down to the
2052    /// mid-sequence guard: `r` is unbound in the keymap on purpose, because a
2053    /// binding on it would be a table entry no keypress can reach — which
2054    /// reads as configured and behaves as absent, the exact trap `f`/`t`
2055    /// documented.
2056    ///
2057    /// It runs AFTER the find capture and before the sequence stepper, and
2058    /// the relative order with find does not matter — the two arm on disjoint
2059    /// keys and neither can be pending while the other is.
2060    fn consume_replace_key(&mut self, key: Key) -> Option<ObjectKey> {
2061        if self.pending_replace {
2062            self.pending_replace = false;
2063            let Key::Char(ch) = key else {
2064                // Esc (or any non-printable) abandons a half-typed `r` rather
2065                // than replacing with something unprintable.
2066                return Some(ObjectKey::Consumed);
2067            };
2068            return Some(ObjectKey::Compose(Action::ReplaceChar(ch)));
2069        }
2070        if self.modal.mode() != Mode::Normal && self.modal.mode() != Mode::Visual {
2071            return None;
2072        }
2073        // A key CONTINUING a sequence belongs to the sequence — the `zt` rule.
2074        if !self.pending_keys.is_empty() {
2075            return None;
2076        }
2077        if key != Key::Char('r') {
2078            return None;
2079        }
2080        // `r` is not a motion, so `dr` is a typo — and vim treats it as one by
2081        // CANCELLING the operator. Falling through to the keymap instead is
2082        // not the same thing and is the worse reading: `r` is unbound (it has
2083        // to be, see above), so it resolves to `Action::Pending`, and the FSM
2084        // deliberately lets a stray `Pending` leave the operator armed for the
2085        // multi-key-sequence case. The next motion would then delete.
2086        if matches!(self.op_pending.state(), OpState::Awaiting { .. }) {
2087            self.op_pending
2088                .dispatch((Action::ChangeMode(Mode::Normal), 1));
2089            return Some(ObjectKey::Consumed);
2090        }
2091        self.pending_replace = true;
2092        Some(ObjectKey::Consumed)
2093    }
2094
2095    fn consume_splash_key(&mut self, key: &Key) -> SplashKey {
2096        let Some(splash) = self.splash.as_ref() else {
2097            return SplashKey::NotShowing;
2098        };
2099        let chosen = match key {
2100            Key::Char(c) => splash.entry_for(*c).map(|e| e.action.clone()),
2101            _ => None,
2102        };
2103        self.dismiss_splash();
2104        chosen.map_or(SplashKey::Dismissed, SplashKey::Ran)
2105    }
2106
2107    /// The current refresh generation. A renderer caches its products against
2108    /// this; equality is the freshness test (an unchanged generation ⇒ the
2109    /// last frame is still valid, so skip the re-highlight + re-shape).
2110    #[must_use]
2111    pub fn edit_gen(&self) -> EditGen {
2112        self.edit_gen
2113    }
2114
2115    /// Advance the refresh generation (a mutation happened).
2116    fn bump_gen(&mut self) {
2117        self.edit_gen = self.edit_gen.next();
2118    }
2119
2120    /// The accumulated dirty region (read-only). See [`take_damage`](Self::take_damage).
2121    #[must_use]
2122    pub fn damage(&self) -> Damage {
2123        self.damage
2124    }
2125
2126    /// Drain the accumulated dirty region, resetting to [`Damage::None`]. The
2127    /// renderer calls this once per frame to learn what to repaint, then the
2128    /// accumulator restarts — so damage never double-counts across frames.
2129    pub fn take_damage(&mut self) -> Damage {
2130        std::mem::replace(&mut self.damage, Damage::None)
2131    }
2132
2133    /// The line count of the active buffer (0 if none) — used to compute the
2134    /// [`Damage`] scope of a mutation.
2135    fn active_line_count(&self) -> u32 {
2136        self.buffers
2137            .get(self.active)
2138            .map_or(0, escriba_buffer::Buffer::line_count)
2139    }
2140
2141    /// Register a lazy USER plugin: its escriba entry is deferred until
2142    /// one of its `triggers` fires. Bundled defaults do NOT go through
2143    /// here — they are applied eagerly at boot. Empty `triggers` means
2144    /// the plugin never lazily activates (the binary applies eager
2145    /// plugins directly).
2146    pub fn register_lazy_plugin(
2147        &mut self,
2148        name: impl Into<String>,
2149        triggers: Vec<LazyTrigger>,
2150        entry_src: impl Into<String>,
2151    ) {
2152        self.plugin_host.register(name, triggers, entry_src);
2153    }
2154
2155    /// Apply a plugin entry's escriba-lisp to live state — the same
2156    /// keymap / command / option apply paths a user rc uses. Options are
2157    /// applied before keybinds so a plugin that sets `mapleader` resolves
2158    /// `<leader>` correctly. Returns the count of commands + keybinds it
2159    /// registered (best-effort; a malformed entry is skipped, not fatal).
2160    fn apply_plugin_entry(&mut self, entry_src: &str) -> usize {
2161        let Ok(plan) = escriba_lisp::apply_source(entry_src) else {
2162            return 0;
2163        };
2164        let cmd = escriba_lisp::apply_plan_to_commands(&plan, &mut self.commands);
2165        escriba_lisp::apply_plan_to_options(&plan, &mut self.options);
2166        if let Some(value) = self.options.get("mapleader") {
2167            if let Some(key) = escriba_lisp::parse_leader_key(value) {
2168                self.keymap.set_leader(key);
2169            }
2170        }
2171        let km = escriba_lisp::apply_plan_to_keymap(&plan, &mut self.keymap);
2172        (cmd.registered + km.keybinds_applied) as usize
2173    }
2174
2175    /// Fire any lazy plugin gated on a `FileType` trigger for `filetype`.
2176    /// Returns the number of plugins activated. Call when a buffer of a
2177    /// known filetype is opened.
2178    pub fn activate_filetype_plugins(&mut self, filetype: &str) -> usize {
2179        let pending = self.plugin_host.pending_for_filetype(filetype);
2180        let n = pending.len();
2181        for src in pending {
2182            self.apply_plugin_entry(&src);
2183        }
2184        n
2185    }
2186
2187    /// Fire any lazy plugin gated on an `Event` trigger for `event`.
2188    /// Returns the number of plugins activated.
2189    pub fn activate_event_plugins(&mut self, event: &str) -> usize {
2190        let pending = self.plugin_host.pending_for_event(event);
2191        let n = pending.len();
2192        for src in pending {
2193            self.apply_plugin_entry(&src);
2194        }
2195        n
2196    }
2197
2198    /// Advance one frame's worth of state given a raw madori event.
2199    ///
2200    /// Key events pass through the [`KeyRepeatGate`] first (see
2201    /// [`Self::tick_at`]); everything else is handled directly.
2202    pub fn tick(&mut self, event: &AppEvent) {
2203        self.tick_at(event, Instant::now());
2204    }
2205
2206    /// [`Self::tick`] with an explicit timestamp for the key-repeat gate —
2207    /// lets tests drive the debounce window without depending on the
2208    /// wall clock.
2209    pub fn tick_at(&mut self, event: &AppEvent, now: Instant) {
2210        match translate_app_event(event) {
2211            InputOutcome::Key(k) => {
2212                if self.gate_key(&k, now) {
2213                    self.on_key(&k);
2214                }
2215            }
2216            InputOutcome::Resized { .. } => {
2217                // Damage only. Each face owns its own geometry: the GPU
2218                // backend derives the grid in `RenderCallback::resize`, and
2219                // the ratatui face reads its area every frame. This arm used
2220                // to write `Window.rect`, which nothing ever read — so the
2221                // resize path was already doing no real work, it just looked
2222                // like it was.
2223                self.damage = self.damage.join(Damage::Viewport);
2224                self.bump_gen();
2225            }
2226            InputOutcome::Quit => self.quit_requested = true,
2227            InputOutcome::Focus(_) | InputOutcome::None => {}
2228        }
2229    }
2230
2231    /// Decide whether `key` survives the key-repeat gate at time `now`.
2232    ///
2233    /// Returns `true` when the key should be processed, `false` when it is
2234    /// an OS key-repeat storm tick that should be dropped. Gating applies
2235    /// ONLY in the navigation modes (Normal / Visual / VisualLine) — those
2236    /// are where a held `j`/`l` floods the motion path and thrashes the
2237    /// viewport. Insert and Command modes pass every key through ungated,
2238    /// because there "hold a key to repeat the character" is the intended
2239    /// behavior, not a storm to suppress.
2240    fn gate_key(&mut self, key: &Key, now: Instant) -> bool {
2241        match self.modal.mode() {
2242            Mode::Normal | Mode::Visual | Mode::VisualLine => {
2243                // The gate exists for HELD keys that flood the motion path and
2244                // thrash the viewport (`j`, `l`). It is wrong for the discrete
2245                // jumps: two `n` presses 10 ms apart mean two matches, and
2246                // swallowing the second is indistinguishable from a dead key —
2247                // the exact symptom the gate was added to prevent elsewhere.
2248                if is_repeat_storm_candidate(key) {
2249                    return self.repeat_gate.try_pass_at(*key, now);
2250                }
2251                true
2252            }
2253            Mode::Insert | Mode::Command => true,
2254        }
2255    }
2256
2257    /// Dispatch a single key through the keymap + apply the resulting action.
2258    pub fn on_key(&mut self, key: &Key) {
2259        // An open picker owns EVERY key while it is up — before the splash,
2260        // before the sequence stepper, before the keymap.
2261        match self.consume_picker_key(key) {
2262            escriba_ui::picker::Consumed::NotShowing => {}
2263            escriba_ui::picker::Consumed::Held | escriba_ui::picker::Consumed::Dismissed => return,
2264            escriba_ui::picker::Consumed::Chose(c) => {
2265                self.honour_choice(c);
2266                return;
2267            }
2268        }
2269        // The start screen owns the first keypress and nothing after it.
2270        match self.consume_splash_key(key) {
2271            SplashKey::NotShowing | SplashKey::Dismissed => {}
2272            SplashKey::Ran(action) => {
2273                self.apply(&action);
2274                return;
2275            }
2276        }
2277        // `m` / `` ` `` / `'` and their operand.
2278        //
2279        // BEFORE the object path, and `` d`a `` is why: the object path
2280        // claims `i` and `a` whenever an operator is armed, so it would have
2281        // eaten the mark LETTER. The two do not fight over the first key —
2282        // this arms only when `pending_object` is clear, so `di'` still
2283        // reaches the object path — they fight over the SECOND, and whichever
2284        // gesture is already half-typed must win it.
2285        if let Some(outcome) = self.consume_mark_key(key.clone()) {
2286            match outcome {
2287                ObjectKey::Consumed => return,
2288                ObjectKey::Compose(a) => {
2289                    let count = self.modal.pending_count().unwrap_or(1);
2290                    self.modal.clear_count();
2291                    self.apply_counted(&a, count);
2292                    return;
2293                }
2294            }
2295        }
2296        // Operator-pending OBJECT selection runs before EVERYTHING, because
2297        // `di(` must not be read as `d` then `i` (insert) then `(`.
2298        if let Some(action) = self.consume_object_key(*key) {
2299            match action {
2300                ObjectKey::Consumed => return,
2301                ObjectKey::Compose(a) => {
2302                    self.apply(&a);
2303                    return;
2304                }
2305            }
2306        }
2307        // `f`/`F`/`t`/`T` and their operand, for the same reason: the
2308        // character searched for is not a binding. Its result goes through
2309        // `apply_counted` — NOT `apply` — so a pending operator composes it
2310        // (`dfx`) and a count repeats it (`3fx`) on the one path every other
2311        // motion uses.
2312        if let Some(outcome) = self.consume_find_key(key.clone()) {
2313            match outcome {
2314                ObjectKey::Consumed => return,
2315                ObjectKey::Compose(a) => {
2316                    let count = self.modal.pending_count().unwrap_or(1);
2317                    self.modal.clear_count();
2318                    self.apply_counted(&a, count);
2319                    return;
2320                }
2321            }
2322        }
2323        // `r` and its operand, same shape and same reason as the find above:
2324        // the replacement character is not a binding. Through `apply_counted`
2325        // so `3ra` replaces three characters.
2326        if let Some(outcome) = self.consume_replace_key(key.clone()) {
2327            match outcome {
2328                ObjectKey::Consumed => return,
2329                ObjectKey::Compose(a) => {
2330                    let count = self.modal.pending_count().unwrap_or(1);
2331                    self.modal.clear_count();
2332                    self.apply_counted(&a, count);
2333                    return;
2334                }
2335            }
2336        }
2337        // Multi-key sequence resolution runs first: a key that begins or
2338        // continues a bound sequence (`<leader>ff`, `gg`) is held or
2339        // resolved here before the single-key path sees it.
2340        match self.step_sequence(key) {
2341            SeqStep::Pending => return,
2342            SeqStep::Resolved(action) => {
2343                let count = self.modal.pending_count().unwrap_or(1);
2344                self.modal.clear_count();
2345                for _ in 0..count {
2346                    self.apply(&action);
2347                    if self.quit_requested {
2348                        return;
2349                    }
2350                }
2351                return;
2352            }
2353            SeqStep::Passthrough => {}
2354        }
2355        let counted = self.keymap.dispatch(&self.modal, key);
2356        // Count prefixes accumulate into modal state.
2357        if matches!(counted.action, Action::Pending) {
2358            if let Key::Char(c) = key {
2359                if c.is_ascii_digit() {
2360                    let d = u32::from(*c as u8 - b'0');
2361                    self.modal.append_count(d);
2362                }
2363            }
2364            return;
2365        }
2366        // The count flows through the operator-pending FSM (apply_counted), which
2367        // owns repetition: a bare motion runs count× , an operator captures its
2368        // count, and an operated motion multiplies the two. No naive outer loop.
2369        self.apply_counted(&counted.action, counted.count);
2370        // After applying, reset pending count.
2371        self.modal.clear_count();
2372    }
2373
2374    /// Advance the multi-key pending-stroke state machine for `key`.
2375    ///
2376    /// Sequences only apply in normal / visual modes — insert and
2377    /// command modes treat keys as literal text. Rules:
2378    /// - Mid-sequence: extend the pending prefix. Exact match →
2379    ///   [`SeqStep::Resolved`]; still a live prefix → [`SeqStep::Pending`];
2380    ///   otherwise abort the sequence and re-process this key fresh.
2381    /// - Not mid-sequence: if `key` begins a bound sequence AND is not
2382    ///   itself a complete single binding (single bindings win, so no
2383    ///   chord timeout is needed) → start pending. Otherwise
2384    ///   [`SeqStep::Passthrough`] to the single-key dispatcher.
2385    fn step_sequence(&mut self, key: &Key) -> SeqStep {
2386        let mode = self.modal.mode();
2387        if !matches!(mode, Mode::Normal | Mode::Visual | Mode::VisualLine) {
2388            return SeqStep::Passthrough;
2389        }
2390        if !self.pending_keys.is_empty() {
2391            let mut seq = self.pending_keys.clone();
2392            seq.push(key.clone());
2393            if let Some(b) = self.keymap.lookup_sequence(mode, &seq) {
2394                let action = b.action.clone();
2395                self.pending_keys.clear();
2396                return SeqStep::Resolved(action);
2397            }
2398            if self.keymap.is_sequence_prefix(mode, &seq) {
2399                self.pending_keys = seq;
2400                return SeqStep::Pending;
2401            }
2402            // The key broke the in-progress sequence — abort it and let
2403            // the key be re-processed as a fresh stroke below.
2404            self.pending_keys.clear();
2405        }
2406        let start = [key.clone()];
2407        if self.keymap.is_sequence_prefix(mode, &start) && self.keymap.lookup(mode, key).is_none() {
2408            self.pending_keys = start.to_vec();
2409            return SeqStep::Pending;
2410        }
2411        SeqStep::Passthrough
2412    }
2413
2414    /// The primary cursor position. The single read accessor — every
2415    /// renderer + motion path goes through it, so the underlying
2416    /// representation (today a single-cursor [`Cursors`]) can grow to
2417    /// multi-caret without changing read sites.
2418    #[must_use]
2419    pub fn cursor(&self) -> Position {
2420        self.cursors.primary()
2421    }
2422
2423    /// The **single** cursor-mutation path. Clamp the requested position to
2424    /// the active buffer's bounds, then scroll the active window's viewport
2425    /// to contain it on BOTH axes. Routing every cursor change through this
2426    /// (and through [`Cursors::set_primary`]) makes "cursor outside its
2427    /// viewport" an unrepresentable state, AND keeps cursor state in ONE
2428    /// typed home — there is no code path that advances the cursor without
2429    /// re-deriving the viewport from it, and no second `Position` field to
2430    /// fall out of sync.
2431    /// Re-assert the cursor-visibility invariant against the CURRENT
2432    /// viewport.
2433    ///
2434    /// A resize changes how much a face can show without moving the cursor,
2435    /// so nothing would otherwise re-run `scroll_to_contain` — the cursor
2436    /// would sit off-screen until the operator happened to move it. Every
2437    /// face calls this after telling the runtime its new size.
2438    pub fn refollow_cursor(&mut self) {
2439        self.set_cursor(self.cursors.primary());
2440    }
2441
2442    fn set_cursor(&mut self, pos: Position) {
2443        self.place_cursor(pos, CursorRest::OnCharacter);
2444    }
2445
2446    /// The **single** cursor-mutation body. `rest` says what kind of place the
2447    /// caller is asking for — see [`CursorRest`].
2448    fn place_cursor(&mut self, pos: Position, rest: CursorRest) {
2449        let clamped = if let Some(buf) = self.buffers.get(self.active) {
2450            let on_buffer = buf.clamp(pos);
2451            // In Normal mode the cursor sits ON a character; only Insert may
2452            // park past the last one, because that is where the next typed
2453            // character goes.
2454            //
2455            // `Buffer::clamp` cannot make this call — it answers "is this
2456            // position inside the text", which is a question about the BUFFER,
2457            // and one-past-the-end legitimately is. Whether the cursor may
2458            // REST there is a question about the MODE, so it is asked here,
2459            // once, on the single cursor-mutation path. Every motion inherits
2460            // it: `w` onto the last word, `$`, `x` at end of line.
2461            if rest == CursorRest::OnCharacter && self.modal.mode() == Mode::Normal {
2462                Position::new(
2463                    on_buffer.line,
2464                    on_buffer
2465                        .column
2466                        .min(buf.line_len_chars(on_buffer.line).saturating_sub(1)),
2467                )
2468            } else {
2469                on_buffer
2470            }
2471        } else {
2472            pos
2473        };
2474        self.cursors.set_primary(clamped);
2475        if let Some(w) = self.layout.active_window_mut() {
2476            w.viewport = w.viewport.scroll_to_contain(self.cursors.primary(), 2);
2477        }
2478    }
2479
2480    /// Dispatch one resolved action at count 1. See [`apply_counted`](Self::apply_counted).
2481    fn apply(&mut self, action: &Action) {
2482        self.apply_counted(action, 1);
2483    }
2484
2485    /// Dispatch one resolved action with its count. Routes `(action, count)`
2486    /// through the operator-pending FSM ([`OperatorPending`], on `zenmai`): most
2487    /// actions pass straight to [`apply_resolved`](Self::apply_resolved) carrying
2488    /// their count (so `5j` runs the motion 5×), an operator key is held, and an
2489    /// operator-then-motion pair is rewritten into a counted
2490    /// [`Action::ApplyOperator`] (so `3dw` deletes 3 words). The FSM owns count
2491    /// composition — there is no naive outer repeat loop.
2492    fn apply_counted(&mut self, action: &Action, count: u32) {
2493        // An uncompilable pattern must not reach the operator machine.
2494        //
2495        // `SearchState::accept` puts the prompt BACK on a compile error so the
2496        // typed text is not lost — but the FSM had already transitioned out of
2497        // `AwaitingSearch` on the way in, so the prompt survived and the
2498        // OPERATOR did not, with nothing said about it. The `d` was simply
2499        // gone, and the corrected pattern then ran as a bare search.
2500        //
2501        // The machine is a pure `(State, Event) -> (State, effects)` and
2502        // cannot observe the result of an effect, so it cannot decide this
2503        // itself. The fix is to stop handing it an event it has no business
2504        // deciding: the runtime classifies the submit first, from state it
2505        // already holds. `prompt_error` returns `None` for an EMPTY prompt, so
2506        // the bare-`/<CR>` reuse path is untouched.
2507        //
2508        // Tier-honest: parse-rejected at the boundary, not
2509        // truly-unrepresentable.
2510        if matches!(action, Action::SubmitCommand) {
2511            if let Some(e) = self.search.prompt_error() {
2512                let mut m = String::from("E383: Invalid search string: ");
2513                m.push_str(&e.to_string());
2514                self.messages.push(m);
2515                return;
2516            }
2517        }
2518
2519        // `|` is the one motion whose count is an ARGUMENT rather than a
2520        // repetition: `40|` means column 40, not "column 1, forty times"
2521        // (which is column 1). Folded in before the FSM sees it, so the
2522        // machine keeps one rule — counts repeat — and the exception lives
2523        // where the exception is.
2524        let action = &match action {
2525            Action::Move(Motion::Column(_)) => Action::Move(Motion::Column(count)),
2526            a => a.clone(),
2527        };
2528        let count = match action {
2529            Action::Move(Motion::Column(_)) => 1,
2530            _ => count,
2531        };
2532        for (resolved, times) in self.op_pending.dispatch((action.clone(), count)) {
2533            // Two ways an action can carry a count, and the split is real:
2534            //
2535            //   REPEAT (`5j`) — run it `times` over. The default.
2536            //   ABSORB (`3dw`, `2dd`, `3p`) — ONE operation over an extent
2537            //     resolved `times` over.
2538            //
2539            // The distinction is not pedantry. Repeating an operator works by
2540            // accident for delete — the text vanishes, so the cursor lands
2541            // somewhere new each round — and is simply wrong for yank, which
2542            // does not move: `2yw` re-yanked the FIRST word twice and put
2543            // "one one " in the register. It is wrong for `2dd` in the same
2544            // shape (the register kept only the second line, so `2ddp` put
2545            // back half), and it would make `3p` three undo steps.
2546            //
2547            // Both kinds now go THROUGH `apply_resolved`, and that is the
2548            // load-bearing part. The absorbing three used to short-circuit
2549            // straight to their executors from here, skipping the damage
2550            // classification and the dot-register recording at that function's
2551            // tail — so `.` after `3p` or `dw` replayed nothing, and the
2552            // repaint span was whatever the previous action had asked for.
2553            let absorbs = absorbs_count(&resolved);
2554            let (reps, n) = if absorbs { (1, times) } else { (times, 1) };
2555            for _ in 0..reps {
2556                self.apply_resolved(&resolved, n);
2557                if self.quit_requested {
2558                    return;
2559                }
2560            }
2561        }
2562    }
2563
2564    /// The active buffer's text. Search is a pure function of it.
2565    /// The active buffer's text revision — the token an offset measured
2566    /// against it should carry.
2567    #[must_use]
2568    fn text_rev(&self) -> TextRev {
2569        self.buffers
2570            .get(self.active)
2571            .map_or_else(TextRev::default, escriba_buffer::Buffer::text_rev)
2572    }
2573
2574    fn active_text(&self) -> String {
2575        self.buffers
2576            .get(self.active)
2577            .map(escriba_buffer::Buffer::to_string)
2578            .unwrap_or_default()
2579    }
2580
2581    /// The cursor as a char offset — the coordinate search speaks.
2582    fn cursor_char(&self) -> usize {
2583        self.buffers
2584            .get(self.active)
2585            .and_then(|b| b.position_to_char(self.cursor()).ok())
2586            .unwrap_or(0)
2587    }
2588
2589    /// Move the cursor onto a match and report a wrap the way vim does.
2590    /// The status line as data — what every face draws.
2591    ///
2592    /// One model, so the two faces can only disagree about styling. Before
2593    /// this existed the GPU face built its own line from a fixed `format!()`
2594    /// and drew neither the prompt nor any message, which made a fully
2595    /// working `/` look like a dead key on escriba's default renderer.
2596    #[must_use]
2597    pub fn status_model(&self) -> StatusModel<'_> {
2598        let cursor = self.cursor();
2599        let prompt = self.search.prompt();
2600
2601        let kind = match prompt.map(|p| p.direction) {
2602            Some(escriba_search::Direction::Forward) => PromptKind::SearchForward,
2603            Some(escriba_search::Direction::Backward) => PromptKind::SearchBackward,
2604            // Command mode with no search prompt open is an ex-command; the
2605            // typed `Option<Prompt>` is the discriminator, never a mode flag.
2606            None if self.modal.mode() == Mode::Command => PromptKind::Ex,
2607            None => PromptKind::None,
2608        };
2609
2610        StatusModel {
2611            mode: self.modal.mode(),
2612            line: cursor.line.saturating_add(1) as usize,
2613            column: cursor.column.saturating_add(1) as usize,
2614            prompt: kind,
2615            prompt_text: prompt
2616                .map_or_else(|| self.modal.minibuffer(), escriba_search::Prompt::text),
2617            prompt_caret: prompt.map_or_else(
2618                || self.modal.minibuffer_caret(),
2619                escriba_search::Prompt::caret,
2620            ),
2621            count: self.match_count(),
2622            message: self.messages.last().map(String::as_str),
2623        }
2624    }
2625
2626    /// `[3/17]` for the current pattern.
2627    ///
2628    /// While a prompt is open the count describes the PREVIEW — the answer to
2629    /// "what would Enter do", which is the question being asked mid-typing.
2630    /// Once committed it describes where the cursor actually is.
2631    #[must_use]
2632    fn match_count(&self) -> MatchCount {
2633        if self.search.is_prompting() {
2634            let text = self.active_text();
2635            // ONE scan, four outcomes. `Incomplete` and `NoMatch` used to be
2636            // the same `None`, so a half-typed character class reported
2637            // `[0/0]` — telling the user their pattern matches nothing while
2638            // they are still writing it.
2639            return match self.search.preview(&text) {
2640                escriba_search::Preview::Landed { step, total } => {
2641                    MatchCount::new(step.index, total)
2642                }
2643                escriba_search::Preview::NoMatch => MatchCount::None,
2644                escriba_search::Preview::Incomplete | escriba_search::Preview::Idle => {
2645                    MatchCount::Idle
2646                }
2647            };
2648        }
2649        if self.search.pattern().is_none() {
2650            return MatchCount::Idle;
2651        }
2652        let total = self.search.matches().len();
2653        // Read THROUGH the anchor: an ordinal computed against text that has
2654        // since changed reads as absent, so a stale count cannot be displayed.
2655        let rev = self.text_rev();
2656        self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
2657            if total == 0 {
2658                MatchCount::None
2659            } else {
2660                MatchCount::Idle
2661            },
2662            |&i| MatchCount::new(i, total),
2663        )
2664    }
2665
2666    /// `.` — replay the last change at the cursor.
2667    ///
2668    /// Two steps, because a change can be two: run the action, then re-type
2669    /// whatever followed it. `cgn` + `.` is exactly this — change the next
2670    /// match, then repeat that whole gesture on the one after.
2671    fn repeat_last_change(&mut self) {
2672        let Some(change) = self.last_change.clone() else {
2673            self.messages
2674                .push("E32: No previous change to repeat".to_string());
2675            return;
2676        };
2677
2678        // Replayed the same way it ran: an absorbing action takes its count as
2679        // an argument, a repeating one takes it as a loop. Getting this
2680        // backwards makes `3dw` then `.` delete one word — which is what it
2681        // did while the recorded count was hardcoded to 1.
2682        let n = change.count.max(1);
2683        if absorbs_count(&change.action) {
2684            self.apply_resolved(&change.action, n);
2685        } else {
2686            for _ in 0..n {
2687                self.apply_resolved(&change.action, 1);
2688            }
2689        }
2690        for c in change.inserted.chars() {
2691            self.apply_resolved(&Action::InsertChar(c), 1);
2692        }
2693        if self.modal.mode() == Mode::Insert {
2694            // A replayed change must not leave the editor in Insert — the
2695            // original ended with an Esc the recording deliberately does not
2696            // store, since it is punctuation rather than part of the change.
2697            self.apply_resolved(&Action::ChangeMode(Mode::Normal), 1);
2698        }
2699        // The replay wrote through `apply_resolved`, which re-records
2700        // `last_change` from the inner action. Put the ORIGINAL back so a
2701        // second `.` repeats the same change rather than a fragment of it.
2702        self.last_change = Some(change);
2703        self.recording_insert = false;
2704    }
2705
2706    /// Resolve a text object to the range it names.
2707    ///
2708    /// `gn` uses the INCLUSIVE step, so a cursor already sitting inside a
2709    /// match operates on THAT match rather than skipping to the next — which
2710    /// is what makes `cgn` then `.` walk matches one at a time instead of
2711    /// every other one.
2712    /// `dd` — the current line INCLUDING its terminator.
2713    ///
2714    /// Taking the newline is what makes `dd` remove a line rather than blank
2715    /// it. On the last line there is no following newline to take, so it
2716    /// falls back to the preceding one — otherwise `dd` on the final line
2717    /// leaves an empty line behind, which is the one case a naive
2718    /// "start-of-line to start-of-next-line" range gets wrong.
2719    fn object_line(&self) -> Option<Range> {
2720        self.line_extent(1).map(|e| e.capture)
2721    }
2722
2723    /// `{n}dd` — `n` whole lines from the cursor down.
2724    ///
2725    /// A counted linewise operator is ONE operation over an `n`-line extent,
2726    /// not `n` operations over one line — the same rule `apply_operator_n`
2727    /// enforces for motions, and it broke here in exactly the way that note
2728    /// predicts. `2dd` ran the single-line object twice: the text came out
2729    /// right (deleting a line brings the next one under the cursor, so the
2730    /// repeat lands correctly by accident) and the REGISTER held only the
2731    /// second line, so `2ddp` silently put back half of what it took.
2732    ///
2733    /// Returns an [`Extent`], not a range, because a linewise CHANGE cuts
2734    /// something different from what a linewise DELETE cuts: `dd` takes the
2735    /// line and its terminator, `cc`/`S` clear the line's text and keep the
2736    /// line. Both put the same thing in the register.
2737    fn line_extent(&self, n: u32) -> Option<Extent> {
2738        let buf = self.buffers.get(self.active)?;
2739        let line = self.cursor().line;
2740        let last = buf.line_count().saturating_sub(1);
2741        // The last line the extent reaches, clamped so `999dd` near the end of
2742        // a file takes what is there rather than resolving to nothing.
2743        //
2744        // Clamped to `last_text_line`, NOT to `last`: on a file ending in `\n`
2745        // those differ by the phantom row the rope reports, and letting the
2746        // extent reach it sent the whole resolution down the "no following
2747        // newline" branch below — so `dd` on the last real line ate the file's
2748        // trailing newline instead of the line. It also makes a `dd` issued
2749        // FROM the phantom row resolve to an empty range (a no-op) rather than
2750        // to a destructive one.
2751        let end = line
2752            .saturating_add(n.max(1).saturating_sub(1))
2753            .min(last_text_line(buf));
2754        if line > last_text_line(buf) {
2755            // The phantom row. There is no line here to operate on.
2756            return None;
2757        }
2758        // What a CHANGE cuts: the text of the named lines, terminators intact.
2759        // Independent of which capture branch runs below, because the lines
2760        // named are the same in all three.
2761        let removal = Range::new(
2762            Position::new(line, 0),
2763            Position::new(end, buf.line_len_chars(end)),
2764        );
2765        let capture = if end < last {
2766            Range::new(Position::new(line, 0), Position::new(end + 1, 0))
2767        } else if line > 0 {
2768            // Final line of a file with NO trailing newline: there is no
2769            // following line start to take a terminator from, so swallow the
2770            // PRECEDING one — otherwise `dd` blanks the line and leaves it.
2771            Range::new(
2772                Position::new(line - 1, buf.line_len_chars(line - 1)),
2773                Position::new(end, buf.line_len_chars(end)),
2774            )
2775        } else {
2776            // The extent is the whole buffer and there is no terminator to
2777            // take at either end: clear the text, keep the line itself.
2778            removal
2779        };
2780        Some(Extent {
2781            capture,
2782            removal,
2783            kind: RegisterKind::Linewise,
2784        })
2785    }
2786
2787    /// `iw` / `aw` — the word under the cursor.
2788    ///
2789    /// vim's `w` classes are word / punctuation / whitespace, and a text
2790    /// object never crosses a line. `around` additionally takes the trailing
2791    /// whitespace run, falling back to LEADING whitespace when there is none
2792    /// after — which is what vim does at end of line.
2793    fn object_word(&self, around: bool) -> Option<Range> {
2794        let buf = self.buffers.get(self.active)?;
2795        let pos = self.cursor();
2796        let text: Vec<char> = buf.line(pos.line)?.chars().collect();
2797        if text.is_empty() {
2798            return None;
2799        }
2800        let col = (pos.column as usize).min(text.len().saturating_sub(1));
2801
2802        #[derive(PartialEq, Clone, Copy)]
2803        enum Class {
2804            Word,
2805            Punct,
2806            Space,
2807        }
2808        let class = |c: char| {
2809            if c.is_alphanumeric() || c == '_' {
2810                Class::Word
2811            } else if c.is_whitespace() {
2812                Class::Space
2813            } else {
2814                Class::Punct
2815            }
2816        };
2817
2818        let here = class(text[col]);
2819        let mut start = col;
2820        while start > 0 && class(text[start - 1]) == here {
2821            start -= 1;
2822        }
2823        let mut end = col + 1;
2824        while end < text.len() && class(text[end]) == here {
2825            end += 1;
2826        }
2827
2828        if around {
2829            let after = end;
2830            while end < text.len() && class(text[end]) == Class::Space {
2831                end += 1;
2832            }
2833            // No trailing run: take the leading one instead, as vim does.
2834            if end == after {
2835                while start > 0 && class(text[start - 1]) == Class::Space {
2836                    start -= 1;
2837                }
2838            }
2839        }
2840
2841        Some(Range::new(
2842            Position::new(pos.line, start as u32),
2843            Position::new(pos.line, end as u32),
2844        ))
2845    }
2846
2847    /// `i(` / `a"` … — the region between a matched pair, on one line.
2848    ///
2849    /// Brackets NEST and quotes do not, and that is the only difference:
2850    /// with `open == close` the scan cannot count depth, so it takes the
2851    /// nearest delimiter on each side instead.
2852    fn object_delimited(&self, open: char, close: char, around: bool) -> Option<Range> {
2853        let buf = self.buffers.get(self.active)?;
2854        let pos = self.cursor();
2855        let text: Vec<char> = buf.line(pos.line)?.chars().collect();
2856        if text.is_empty() {
2857            return None;
2858        }
2859        let col = (pos.column as usize).min(text.len().saturating_sub(1));
2860
2861        let (l, r) = if open == close {
2862            // Quotes: nearest on each side, no nesting to track.
2863            let l = (0..=col).rev().find(|&i| text[i] == open)?;
2864            let r = ((col.max(l) + 1)..text.len()).find(|&i| text[i] == close)?;
2865            (l, r)
2866        } else {
2867            // Brackets: walk out counting depth, so an inner pair does not
2868            // terminate the search for the enclosing one.
2869            let mut depth = 0i32;
2870            let l = (0..=col).rev().find(|&i| {
2871                if text[i] == close && i != col {
2872                    depth += 1;
2873                    false
2874                } else if text[i] == open {
2875                    if depth == 0 {
2876                        true
2877                    } else {
2878                        depth -= 1;
2879                        false
2880                    }
2881                } else {
2882                    false
2883                }
2884            })?;
2885            depth = 0;
2886            let r = ((l + 1)..text.len()).find(|&i| {
2887                if text[i] == open {
2888                    depth += 1;
2889                    false
2890                } else if text[i] == close {
2891                    if depth == 0 {
2892                        true
2893                    } else {
2894                        depth -= 1;
2895                        false
2896                    }
2897                } else {
2898                    false
2899                }
2900            })?;
2901            (l, r)
2902        };
2903
2904        // `i` is strictly between the delimiters; `a` includes them.
2905        let (s, e) = if around { (l, r + 1) } else { (l + 1, r) };
2906        Some(Range::new(
2907            Position::new(pos.line, s as u32),
2908            Position::new(pos.line, e as u32),
2909        ))
2910    }
2911
2912    fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
2913        use escriba_core::TextObject as O;
2914
2915        // The text-scanning objects resolve against the BUFFER; the two
2916        // search objects resolve against the match set. Splitting here keeps
2917        // the search logic below exactly as it was rather than threading a
2918        // second concern through it.
2919        match object {
2920            O::Line => return self.object_line(),
2921            O::Word { around } => return self.object_word(around),
2922            O::Delimited {
2923                open,
2924                close,
2925                around,
2926            } => return self.object_delimited(open, close, around),
2927            O::NextMatch | O::PrevMatch => {}
2928        }
2929
2930        let at = self.cursor_char();
2931        let matches = self.search.matches();
2932
2933        // A match CONTAINING the cursor wins outright, whichever direction the
2934        // object names.
2935        //
2936        // Comparing only against `m.start` — which is what a `starts`-vector
2937        // plus `Bound::Inclusive` does — is right only when the cursor sits on
2938        // a match's FIRST character. One column further in, `start < at` and
2939        // the match is rejected, so `cgn` skipped the very instance the
2940        // operator was standing in and the rename silently missed it. vim
2941        // operates on the containing match from every interior column, and the
2942        // `starts`-only comparison cannot express "contains" because it never
2943        // looks at `m.end`.
2944        let idx = matches.iter().position(|m| m.contains(at)).or_else(|| {
2945            let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
2946            match object {
2947                O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
2948                // Every other variant returned above; `NextMatch` is the only
2949                // one that can reach here besides `PrevMatch`.
2950                _ => Bound::Inclusive.first_matching(&starts, at, true),
2951            }
2952        })?;
2953
2954        let m = matches.get(idx)?;
2955        let buf = self.buffers.get(self.active)?;
2956        Some(Range {
2957            start: buf.char_to_position(m.start),
2958            end: buf.char_to_position(m.end),
2959        })
2960    }
2961
2962    fn land_on(&mut self, step: escriba_search::Step) {
2963        if let Some(buf) = self.buffers.get(self.active) {
2964            let pos = buf.char_to_position(step.target.start);
2965            self.set_cursor(pos);
2966        }
2967        // The `[3/17]` numerator. `Step` has carried this index since the
2968        // engine was written — `engine.rs` even names the counter as the
2969        // reason it exists — and every consumer discarded it until now.
2970        self.search_at = Some(Anchored::new(step.index, self.text_rev()));
2971    }
2972
2973    /// vim's "search hit BOTTOM, continuing at TOP".
2974    ///
2975    /// One reporter, called by the two places a search can wrap: the shared
2976    /// commit and `n`/`N`. `land_on` deliberately does NOT report, or the bare
2977    /// commit would say it twice.
2978    fn report_wrap(&mut self, step: &escriba_search::Step) {
2979        if let Some(msg) = escriba_search::wrap_message(step.wrapped) {
2980            self.messages.push(msg.to_string());
2981        }
2982    }
2983
2984    /// `n` / `N`. Reports vim's E486 when the pattern matches nothing, rather
2985    /// than failing silently — a search that appears to do nothing is
2986    /// indistinguishable from a dropped keystroke.
2987    fn jump_search(&mut self, reverse: bool) {
2988        // Using the matches re-lights them: `n` after an auto-clear shows you
2989        // what you are walking through.
2990        self.search.relight();
2991        // `n` is a far jump — record where we leave from so `<C-o>` works.
2992        self.jumps.push(self.spot());
2993        let at = self.cursor_char();
2994        match self.search.repeat(at, reverse) {
2995            Some(step) => {
2996                // `n` wrapping the file says so, same as a commit does.
2997                self.report_wrap(&step);
2998                self.land_on(step);
2999            }
3000            None => {
3001                let msg = self.search.pattern().map_or_else(
3002                    || "E35: No previous regular expression".to_string(),
3003                    |p| {
3004                        let mut m = String::from("E486: Pattern not found: ");
3005                        m.push_str(p.raw());
3006                        m
3007                    },
3008                );
3009                self.messages.push(msg);
3010            }
3011        }
3012    }
3013
3014    /// Move the cursor to where the in-progress pattern would land, without
3015    /// committing anything. vim's `incsearch`.
3016    ///
3017    /// A pattern that does not compile yet (`/a[`, mid-typing) previews
3018    /// nothing and reports nothing — an error toast on every keystroke of a
3019    /// character class would be unusable.
3020    fn preview_search(&mut self) {
3021        let text = self.active_text();
3022        let Some(origin) = self.search.prompt().map(|p| p.origin) else {
3023            return;
3024        };
3025        let target = match self.search.preview(&text) {
3026            escriba_search::Preview::Landed { step, .. } => step.target.start,
3027            // Nothing to show: back to where the search started. Covers a
3028            // half-typed pattern and a pattern that finds nothing alike —
3029            // both mean "there is no match to preview".
3030            escriba_search::Preview::Idle
3031            | escriba_search::Preview::Incomplete
3032            | escriba_search::Preview::NoMatch => origin,
3033        };
3034        // A pattern that STOPS matching returns the cursor to the origin.
3035        //
3036        // Preview used to only ever move forward, so typing `ch` (a match) and
3037        // then `chz` (none) left the cursor parked on the `ch` match — a
3038        // preview showing a position the pattern no longer justifies, while
3039        // the count beside it read `[0/0]`. Restoring is also what makes
3040        // Escape's promise legible: at every keystroke the cursor is either on
3041        // a real match or back where you started, never on a stale one.
3042        if let Some(buf) = self.buffers.get(self.active) {
3043            let pos = buf.char_to_position(target);
3044            self.set_cursor(pos);
3045        }
3046    }
3047
3048    /// `d/foo<CR>` — commit the prompt and operate from the prompt's origin to
3049    /// where the search lands, as ONE action.
3050    ///
3051    /// Split from [`Self::submit_search`] rather than sharing it because the
3052    /// two want opposite things from the commit: the bare `/` MOVES the cursor
3053    /// to the match, and an operated `/` must NOT — the cursor is the
3054    /// operator's start point, and moving it first would leave the operator
3055    /// with a zero-width range.
3056    /// Commit the open search prompt. The ONE copy of the sequence.
3057    ///
3058    /// Reports its own failures (E486 / E35) so neither caller has to carry a
3059    /// third copy of the message strings. `Accepted::Invalid` cannot reach
3060    /// here — `apply_counted` rejects an uncompilable pattern at the dispatch
3061    /// boundary before the FSM or this method ever sees the submit.
3062    fn commit_search_prompt(&mut self) -> CommitOutcome {
3063        let text = self.active_text();
3064        let Some((origin, skip)) = self.search.prompt().map(|p| (p.origin, p.preview_skip()))
3065        else {
3066            return CommitOutcome::NoPrompt;
3067        };
3068
3069        match self.search.accept(&text) {
3070            escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
3071                self.modal.clear_minibuffer();
3072                self.modal.enter(Mode::Normal);
3073                match self.search.commit_step_skipping(origin, skip) {
3074                    Some(step) => {
3075                        // The wrap notice belongs HERE, once, for both commit
3076                        // paths. Reporting it in each caller is what let the
3077                        // operated path lose it in the first place — and my
3078                        // first attempt at this refactor duplicated it again
3079                        // rather than moving it, which the red proof caught.
3080                        self.report_wrap(&step);
3081                        CommitOutcome::Landed { origin, step }
3082                    }
3083                    None => {
3084                        self.report_pattern_not_found();
3085                        CommitOutcome::NotFound
3086                    }
3087                }
3088            }
3089            escriba_search::Accepted::NothingToRepeat => {
3090                self.modal.clear_minibuffer();
3091                self.modal.enter(Mode::Normal);
3092                self.messages
3093                    .push("E35: No previous regular expression".to_string());
3094                CommitOutcome::NoPrevious
3095            }
3096            // Unreachable: the boundary guard in `apply_counted` returns early
3097            // on an uncompilable pattern, leaving the prompt open. Reported
3098            // rather than `unreachable!()` — a panic in the editor's commit
3099            // path is a worse failure than a duplicate message.
3100            escriba_search::Accepted::Invalid(e) => {
3101                let mut m = String::from("E383: Invalid search string: ");
3102                m.push_str(&e.to_string());
3103                self.messages.push(m);
3104                CommitOutcome::NoPrompt
3105            }
3106        }
3107    }
3108
3109    /// vim's E486, with the pattern named. One place, so every path that fails
3110    /// to find reports identically.
3111    fn report_pattern_not_found(&mut self) {
3112        let mut m = String::from("E486: Pattern not found");
3113        if let Some(p) = self.search.pattern() {
3114            m.push_str(": ");
3115            m.push_str(p.raw());
3116        }
3117        self.messages.push(m);
3118    }
3119
3120    /// Bare `/foo<CR>` — commit and MOVE the cursor to the match.
3121    ///
3122    /// The only difference from the operated path is that this one lands;
3123    /// everything else lives in `commit_search_prompt`.
3124    fn submit_search(&mut self) {
3125        match self.commit_search_prompt() {
3126            CommitOutcome::Landed { origin, step } => {
3127                if let Some(buf) = self.buffers.get(self.active) {
3128                    let from = buf.char_to_position(origin);
3129                    self.jumps.push(escriba_core::Spot::new(self.active, from));
3130                }
3131                self.land_on(step);
3132            }
3133            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
3134        }
3135    }
3136
3137    /// `d/foo<CR>` — commit, then operate from the prompt's origin to where the
3138    /// search lands, as ONE action.
3139    ///
3140    /// The cursor must NOT move to the match first: it is the operator's start
3141    /// point. That is the whole reason this differs from the bare path, and
3142    /// now the only reason.
3143    fn submit_search_operated(&mut self, op: Operator) {
3144        match self.commit_search_prompt() {
3145            CommitOutcome::Landed { origin, step } => {
3146                if let Some(buf) = self.buffers.get(self.active) {
3147                    let from = buf.char_to_position(origin);
3148                    let target = buf.char_to_position(step.target.start);
3149                    // Operating over a search is itself a far jump.
3150                    self.jumps.push(escriba_core::Spot::new(self.active, from));
3151                    self.set_cursor(from);
3152                    self.apply_operator_to(op, target);
3153                }
3154            }
3155            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
3156        }
3157    }
3158
3159    /// Execute one resolved action, with the count it ABSORBS.
3160    ///
3161    /// `count` is 1 for everything that repeats — the caller loops those — and
3162    /// is the gesture's full count for the arms listed in [`absorbs_count`].
3163    /// Every path lands here so the damage classification and dot-register
3164    /// recording at the tail run exactly once per gesture; the counted
3165    /// operators used to bypass this function and skipped both.
3166    fn apply_resolved(&mut self, action: &Action, count: u32) {
3167        // Snapshot the scope inputs before the mutation so the resulting
3168        // Damage covers the changed region (the S3 seal — conservative widen).
3169        let lines_before = self.active_line_count();
3170        // Snapshot for the dot register: the only reliable witness that this
3171        // action changed text is that the buffer's revision moved.
3172        let rev_before = self.text_rev();
3173        let cline_before = self.cursor().line;
3174        match action {
3175            // Every action with an exact slip equivalent goes through the
3176            // interpreter, so "undo" has ONE implementation rather than one
3177            // per entry point. These had already drifted: the executor
3178            // re-followed the viewport after undo and the M1 interpreter did
3179            // not, so `u` and `:undo` behaved differently within a milestone
3180            // of each other.
3181            // Listed EXPLICITLY rather than behind a `if lower(..).is_some()`
3182            // guard: a guard arm does not count toward exhaustiveness, so the
3183            // guarded form silently gave up the total match — the compiler
3184            // said so, and it was right. `lowering_and_dispatch_agree` pins
3185            // that this list and `lower` stay the same set.
3186            Action::Quit
3187            | Action::ClearSearchHighlight
3188            | Action::Save
3189            | Action::Undo
3190            | Action::Redo
3191            | Action::Edit(_) => {
3192                for slip in Self::lower(action, self.active).unwrap_or_default() {
3193                    self.honour_one(slip);
3194                }
3195            }
3196            Action::Move(m) => self.apply_motion(*m),
3197            Action::SearchOpen(dir) => {
3198                // vim's `/` is the command-line with a different prompt char,
3199                // so we reuse Command mode; `search.prompt` is what tells a
3200                // later <CR> this is a search and not an ex-command.
3201                let origin = self.cursor_char();
3202                self.search.open(*dir, origin);
3203                self.modal.enter(Mode::Command);
3204            }
3205            Action::SearchRepeat { reverse } => self.jump_search(*reverse),
3206            Action::SearchWord { reverse } => {
3207                let dir = if *reverse {
3208                    SearchDirection::Backward
3209                } else {
3210                    SearchDirection::Forward
3211                };
3212                let (text, at) = (self.active_text(), self.cursor_char());
3213                // `*` jumps, so it records too.
3214                self.jumps.push(self.spot());
3215                match self.search.search_word(&text, at, dir) {
3216                    Some(step) => self.land_on(step),
3217                    // vim beeps and stays put when there is no word under the
3218                    // cursor; a silent no-op would look like a broken key.
3219                    None => self
3220                        .messages
3221                        .push("E348: No string under cursor".to_string()),
3222                }
3223            }
3224            Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
3225            Action::TextObject(object) => {
3226                // Bare `gn` moves onto the match. vim additionally starts a
3227                // Visual selection of it; escriba's Visual plumbing does not
3228                // carry a selection an operator can consume yet, so this
3229                // stops at the jump rather than faking a selection that
3230                // nothing would honour.
3231                if let Some(range) = self.resolve_object(*object) {
3232                    self.jumps.push(self.spot());
3233                    self.set_cursor(range.start);
3234                } else {
3235                    self.report_pattern_not_found();
3236                }
3237            }
3238            // The linewise object is the one that can express an `n`-fold
3239            // extent, so it reads the count directly; every other object still
3240            // repeats (see `absorbs_count`).
3241            Action::ApplyOperatorObject {
3242                op,
3243                object: escriba_core::TextObject::Line,
3244            } => {
3245                if let Some(extent) = self.line_extent(count) {
3246                    self.apply_operator_over(*op, extent);
3247                }
3248            }
3249            Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
3250                // The kind comes from the OBJECT (`TextObject::register_kind`,
3251                // total over the enum), which is the only thing that knows:
3252                // `dd` on line 1 and a charwise `[(1,0), (2,0))` are the same
3253                // two positions.
3254                Some(range) => {
3255                    self.apply_operator_over(*op, Extent::from_object(range, object.register_kind()));
3256                }
3257                None => self.report_pattern_not_found(),
3258            },
3259            Action::Put { before } => self.put(*before, count),
3260            Action::ReplaceChar(ch) => self.replace_char(*ch, count),
3261            Action::JoinLines { space } => self.join_lines(*space, count),
3262            Action::RepeatLastChange => self.repeat_last_change(),
3263            Action::JumpBack => {
3264                let here = self.spot();
3265                if let Some(spot) = self.jumps.back(here) {
3266                    self.goto_spot(spot);
3267                } else {
3268                    self.messages
3269                        .push("E662: At start of changelist".to_string());
3270                }
3271            }
3272            Action::JumpForward => {
3273                if let Some(spot) = self.jumps.forward() {
3274                    self.goto_spot(spot);
3275                } else {
3276                    self.messages.push("E663: At end of changelist".to_string());
3277                }
3278            }
3279            Action::ChangeMode(m) => {
3280                // Leaving the cmdline abandons any open search prompt and
3281                // returns the cursor home. The COMMITTED pattern survives —
3282                // cancelling a new search must not erase the old highlights.
3283                if *m == Mode::Normal && self.search.is_prompting() {
3284                    if let Some(origin) = self.search.cancel() {
3285                        if let Some(buf) = self.buffers.get(self.active) {
3286                            let pos = buf.char_to_position(origin);
3287                            self.set_cursor(pos);
3288                        }
3289                    }
3290                }
3291                self.modal.enter(*m);
3292            }
3293            Action::EnterInsert(at) => self.enter_insert_at(*at),
3294            Action::InsertChar(c) => self.insert_char(*c),
3295
3296            Action::SubmitCommand => {
3297                if self.search.is_prompting() {
3298                    self.submit_search();
3299                } else {
3300                    self.submit_command();
3301                }
3302            }
3303            Action::Command { name, args } => self.run_command(name, args),
3304            Action::ApplyOperator { op, motion } => self.apply_operator_n(*op, *motion, count),
3305            // The operator-pending FSM consumes Operator keys (begins pending);
3306            // they never reach the executor. Defensive no-op for exhaustiveness.
3307            Action::Operator(_) => {}
3308            Action::PromptCaret { to } => {
3309                // Both prompts have a caret now, and the same keys move it.
3310                if self.search.is_prompting() {
3311                    self.search.move_caret(*to);
3312                } else {
3313                    self.modal.move_minibuffer_caret(*to);
3314                }
3315            }
3316            Action::SearchPreviewStep { forward } => {
3317                if self.search.is_prompting() {
3318                    self.search.preview_step(*forward);
3319                    self.preview_search();
3320                }
3321            }
3322            Action::DeleteForward => {
3323                if self.modal.mode() == Mode::Command {
3324                    if self.search.is_prompting() {
3325                        self.search.delete_at_caret();
3326                        self.preview_search();
3327                    } else {
3328                        self.modal.delete_minibuffer_at_caret();
3329                    }
3330                } else {
3331                    self.delete_after_cursor();
3332                }
3333            }
3334            Action::DeleteWordBefore => {
3335                if self.modal.mode() == Mode::Command {
3336                    if self.search.is_prompting() {
3337                        self.search.delete_word_before_caret();
3338                        self.preview_search();
3339                    }
3340                } else {
3341                    self.delete_word_before_cursor();
3342                }
3343            }
3344            Action::DeleteToLineStart => {
3345                if self.modal.mode() == Mode::Command {
3346                    if self.search.is_prompting() {
3347                        self.search.clear_before_caret();
3348                        self.preview_search();
3349                    }
3350                } else {
3351                    self.delete_to_line_start();
3352                }
3353            }
3354            Action::Backspace => {
3355                if self.modal.mode() == Mode::Command {
3356                    self.prompt_backspace();
3357                    // Shortening the pattern changes which matches exist, so
3358                    // the preview must re-run — otherwise the cursor sits on a
3359                    // match of a pattern that is no longer typed.
3360                    if self.search.is_prompting() {
3361                        self.preview_search();
3362                    }
3363                } else {
3364                    self.delete_before_cursor();
3365                }
3366            }
3367            Action::PromptHistory { back } => {
3368                if self.search.is_prompting() {
3369                    self.search.history_step(*back);
3370                    // No minibuffer resync: the shadow is the ex-line's store
3371                    // and nothing reads it while a search prompt is open, so
3372                    // rewriting it here was maintaining a copy for no reader.
3373                    self.preview_search();
3374                }
3375            }
3376            // `m{a-z}`. Only `a-z`: `A-Z` are vim's cross-file marks and this
3377            // map is per-editor, so accepting one would promise a jump back
3378            // to another FILE and deliver a jump to that line in this one.
3379            Action::SetMark(name) => {
3380                if name.is_ascii_lowercase() {
3381                    let at = self.cursor();
3382                    self.marks.insert(*name, at);
3383                } else {
3384                    self.messages
3385                        .push(format!("E191: mark `{name}` is not a-z"));
3386                }
3387            }
3388            Action::ScrollView(align) => self.scroll_view(*align),
3389            Action::Pending => {}
3390        }
3391        // Widen the dirty region by what this action touched (M1). Content
3392        // mutations that changed the line count run to end-of-document (every
3393        // line below shifted); an in-place edit or a cursor move is local;
3394        // arbitrary commands are conservatively Full. Never narrows.
3395        let lines_after = self.active_line_count();
3396        let cline_after = self.cursor().line;
3397        let d = match action {
3398            // A search repaints every highlight in the viewport, not just the
3399            // line the cursor left — so it must widen to Full. Treating it as a
3400            // cursor move would leave stale highlights on untouched lines.
3401            Action::SearchOpen(_)
3402            | Action::PromptHistory { .. }
3403            | Action::Backspace
3404            | Action::PromptCaret { .. }
3405            | Action::SearchPreviewStep { .. }
3406            | Action::DeleteForward
3407            | Action::DeleteWordBefore
3408            | Action::DeleteToLineStart
3409            | Action::SearchRepeat { .. }
3410            | Action::SearchWord { .. }
3411            | Action::ClearSearchHighlight
3412            | Action::SearchSubmitOperated { .. }
3413            // A replayed change can edit anywhere the original could, and a
3414            // match object can be anywhere in the document.
3415            | Action::RepeatLastChange
3416            | Action::TextObject(_)
3417            | Action::ApplyOperatorObject { .. }
3418            // A jump can land anywhere, so the viewport may scroll wholesale.
3419            | Action::JumpBack
3420            | Action::JumpForward
3421            // A re-frame repaints every row even though no byte changed —
3422            // which is exactly the case a line-scoped damage would miss.
3423            | Action::ScrollView(_) => Damage::Full,
3424            Action::InsertChar(_)
3425            | Action::Edit(_)
3426            | Action::Undo
3427            | Action::Redo
3428            // Insert-entry belongs in THIS group rather than beside
3429            // `ChangeMode` below, even though four of its six members only move
3430            // the caret: `o`/`O` add a line, and this arm's body is already the
3431            // one that asks whether the line COUNT changed. Grouping it with
3432            // the pure mode change would repaint a one-line span after `o` and
3433            // leave every line below the new one stale.
3434            | Action::EnterInsert(_)
3435            // Same reading as `EnterInsert`: a charwise put touches one line
3436            // and a linewise one adds several, and this arm's body is already
3437            // the one that asks which happened by comparing the line count.
3438            // `J` removes lines and `r` removes none — the same question.
3439            | Action::Put { .. }
3440            | Action::ReplaceChar(_)
3441            | Action::JoinLines { .. }
3442            | Action::ApplyOperator { .. } => {
3443                if lines_after == lines_before {
3444                    Damage::span(cline_before, cline_after)
3445                } else {
3446                    Damage::Lines {
3447                        from: cline_before.min(cline_after),
3448                        to: u32::MAX,
3449                    }
3450                }
3451            }
3452            Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
3453            Action::Save => Damage::Viewport,
3454            Action::Command { .. } | Action::SubmitCommand => Damage::Full,
3455            // Setting a mark changes no pixel — there is no gutter sign for
3456            // one yet. When one lands, this arm becomes `Damage::span`.
3457            Action::Quit | Action::Operator(_) | Action::SetMark(_) | Action::Pending => {
3458                Damage::None
3459            }
3460        };
3461        self.damage = self.damage.join(d);
3462        // Remember this change for `.`.
3463        //
3464        // Recorded from an OBSERVED MUTATION, not from the action's variant.
3465        // `text_effect()` is the wrong predicate here even though it looks
3466        // like the right one: it exists to decide cache invalidation, where
3467        // OVER-reporting is the safe direction, and the dot register needs the
3468        // opposite bias. Leaning on it meant `last_change` was set by actions
3469        // that changed no text at all, with two measured consequences:
3470        //
3471        //   `iZ<Esc>` then `/a<CR>` then `.`  — did nothing; the register held
3472        //       `SubmitCommand`, whose replay reads an already-cleared
3473        //       minibuffer.
3474        //   `iZ<Esc>` then `/q<Esc>` then `.` — TYPED `q` INTO THE BUFFER. An
3475        //       abandoned prompt left the register holding `InsertChar('q')`,
3476        //       and `.` in Normal mode routes that to the text. A corrupting
3477        //       register, not merely a lost one.
3478        //
3479        // Comparing the buffer's `TextRev` across the action answers the only
3480        // question that matters — did this actually change the text — and gets
3481        // the failed-operator case (`dgn` with no pattern) right for free.
3482        if self.recording_insert {
3483            match action {
3484                Action::InsertChar(c) => {
3485                    if let Some(lc) = self.last_change.as_mut() {
3486                        lc.inserted.push(*c);
3487                    }
3488                }
3489                // Leaving Insert ends the session; the change is now whole.
3490                Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
3491                _ => {}
3492            }
3493        } else if self.text_rev() != rev_before
3494            && !matches!(
3495                action,
3496                Action::RepeatLastChange | Action::Undo | Action::Redo
3497            )
3498        {
3499            self.last_change = Some(LastChange {
3500                // The count the gesture actually carried, not a hardcoded 1.
3501                // `.` replays it through the same absorb-or-repeat split the
3502                // original ran under (see `repeat_last_change`), so `3dw` then
3503                // `.` deletes three words rather than one.
3504                action: action.clone(),
3505                count,
3506                inserted: String::new(),
3507            });
3508            self.recording_insert = self.modal.mode() == Mode::Insert;
3509        }
3510
3511        // The search is over the moment you move on or edit — clear the
3512        // highlight rather than leaving the buffer as confetti until an
3513        // explicit `:noh`, which is the remap nearly every vimrc carries.
3514        // Clearing suppresses without forgetting, so `n` still works.
3515        if action.highlight_effect() == HighlightEffect::Clear {
3516            self.search.clear_highlight();
3517        }
3518        // Text changed ⇒ every match offset cached against the old text is
3519        // wrong. `SearchState::refresh` existed for exactly this and had ZERO
3520        // callers, so inserting four characters left both renderers painting
3521        // the highlight four columns off.
3522        //
3523        // Gated on the typed classifier rather than on `bump_gen` (which fires
3524        // for pure cursor moves too): re-scanning the document on every `j`
3525        // would be a per-keystroke full pass for no reason.
3526        if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
3527            let text = self.active_text();
3528            self.search.refresh(&text);
3529            // NO manual invalidation of `search_at` here, deliberately. It is
3530            // `Anchored` to the text revision, so an ordinal computed against
3531            // the old text now reads as `None` on its own. This is the line
3532            // that used to have to be remembered.
3533        }
3534        // An action reached the executor ⇒ visible state may have changed.
3535        // Advance the refresh generation so the renderer repaints (and
3536        // re-highlights) exactly once. A gated-out key never reaches here, so
3537        // a key-repeat storm does not spin the renderer.
3538        self.bump_gen();
3539    }
3540
3541    /// Resolve a [`Motion`] from `from` to its target [`Position`] against the
3542    /// active buffer — **pure**: no cursor mutation, no side effects. This is
3543    /// the single motion-resolution source of truth that both [`apply_motion`]
3544    /// (move the cursor *to* the target) and [`apply_operator`] (use the target
3545    /// as the *other end* of an operated range) stand on. `None` only if there
3546    /// is no active buffer.
3547    ///
3548    /// [`apply_motion`]: Self::apply_motion
3549    /// [`apply_operator`]: Self::apply_operator
3550    fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
3551        let buf = self.buffers.get(self.active)?;
3552        let pos = from;
3553        Some(match motion {
3554            // Search-as-motion: what makes `dn` / `d/foo<CR>` work. Resolved
3555            // against the committed match list, so it is `None` (motion fails,
3556            // operator aborts, buffer untouched) when nothing is committed —
3557            // never a silent move to 0, which would delete to the file start.
3558            Motion::SearchNext | Motion::SearchPrev => {
3559                let at = buf.position_to_char(pos).ok()?;
3560                let step = self
3561                    .search
3562                    .repeat(at, matches!(motion, Motion::SearchPrev))?;
3563                buf.char_to_position(step.target.start)
3564            }
3565            Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
3566            // Clamped to the line, which is what makes `x` (`dl`) safe to
3567            // express as a composition. Unclamped, an operator range built
3568            // over `Right` crosses the line TERMINATOR on an empty line — so
3569            // `x` there would join the next line onto this one instead of
3570            // doing nothing. The cursor path is unaffected: `place_cursor`
3571            // was already pulling `l` back onto the last character.
3572            Motion::Right => Position::new(
3573                pos.line,
3574                pos.column
3575                    .saturating_add(1)
3576                    .min(buf.line_len_chars(pos.line)),
3577            ),
3578            Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
3579            Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
3580            Motion::LineStart => Position::new(pos.line, 0),
3581            Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
3582            Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
3583            // `g_` — the last non-blank. Inclusive, so the operator widens it;
3584            // the resolver names the CHARACTER, which is where `$` differs.
3585            Motion::LineLastNonBlank => {
3586                let chars = line_chars(buf, pos.line);
3587                let col = chars
3588                    .iter()
3589                    .rposition(|c| !c.is_whitespace())
3590                    .and_then(|i| u32::try_from(i).ok())
3591                    .unwrap_or(0);
3592                Position::new(pos.line, col)
3593            }
3594            // `|` is 1-based, and clamped to the line rather than refused —
3595            // vim puts `500|` on the last character.
3596            Motion::Column(n) => Position::new(
3597                pos.line,
3598                n.saturating_sub(1).min(buf.line_len_chars(pos.line)),
3599            ),
3600            Motion::LineDownFirstNonBlank => {
3601                first_non_blank(buf, pos.line.saturating_add(1).min(last_text_line(buf)))
3602            }
3603            Motion::LineUpFirstNonBlank => first_non_blank(buf, pos.line.saturating_sub(1)),
3604            Motion::DocStart => Position::ZERO,
3605            Motion::DocEnd => Position::new(
3606                buf.line_count().saturating_sub(1),
3607                buf.line_len_chars(buf.line_count().saturating_sub(1)),
3608            ),
3609            Motion::WordStartNext => word_next(buf, pos, Width::Small),
3610            Motion::WordEndNext => word_end(buf, pos, Width::Small),
3611            Motion::WordStartPrev => word_prev(buf, pos, Width::Small),
3612            Motion::WordEndPrev => word_end_prev(buf, pos, Width::Small),
3613            Motion::BigWordStartNext => word_next(buf, pos, Width::Big),
3614            Motion::BigWordEndNext => word_end(buf, pos, Width::Big),
3615            Motion::BigWordStartPrev => word_prev(buf, pos, Width::Big),
3616            Motion::BigWordEndPrev => word_end_prev(buf, pos, Width::Big),
3617            Motion::FindChar { ch, backward, till } => find_char(buf, pos, ch, backward, till)?,
3618            // `;` / `,` resolve through the LAST `f`/`t`, which is runtime
3619            // state — the same shape as the search motions above, and the
3620            // reason neither can be resolved by the enum alone.
3621            Motion::RepeatFind { reverse } => {
3622                let last = self.last_find?;
3623                let backward = last.backward != reverse;
3624                find_char(buf, pos, last.ch, backward, last.till)?
3625            }
3626            Motion::MatchPair => self.resolve_match(buf, pos)?,
3627            // A mark that was never set is a FAILED motion, not a move to the
3628            // origin: `` `q `` with no `q` must leave the cursor alone, and
3629            // ``d`q`` must not delete to the top of the file.
3630            Motion::MarkExact(name) => {
3631                let at = *self.marks.get(&name)?;
3632                Position::new(
3633                    at.line.min(last_text_line(buf)),
3634                    at.column
3635                        .min(buf.line_len_chars(at.line.min(last_text_line(buf)))),
3636                )
3637            }
3638            Motion::MarkLine(name) => {
3639                let at = *self.marks.get(&name)?;
3640                first_non_blank(buf, at.line.min(last_text_line(buf)))
3641            }
3642            Motion::ParagraphNext => paragraph(buf, pos, true),
3643            Motion::ParagraphPrev => paragraph(buf, pos, false),
3644            Motion::SentenceNext => sentence(buf, pos, true),
3645            Motion::SentencePrev => sentence(buf, pos, false),
3646            // `H` / `M` / `L` are about the VIEWPORT, not the buffer — which
3647            // is what makes them the only motions whose target changes when
3648            // nothing in the text did.
3649            Motion::ScreenTop | Motion::ScreenMiddle | Motion::ScreenBottom => {
3650                let vp = self.layout.active_window().map_or(
3651                    Viewport {
3652                        top_line: 0,
3653                        left_column: 0,
3654                        visible_lines: 1,
3655                        visible_columns: 1,
3656                    },
3657                    |w| w.viewport,
3658                );
3659                let last = last_text_line(buf);
3660                let bottom = vp
3661                    .top_line
3662                    .saturating_add(vp.visible_lines.saturating_sub(1))
3663                    .min(last);
3664                let line = match motion {
3665                    Motion::ScreenTop => vp.top_line.min(last),
3666                    Motion::ScreenBottom => bottom,
3667                    _ => vp.top_line.min(last) + (bottom - vp.top_line.min(last)) / 2,
3668                };
3669                first_non_blank(buf, line)
3670            }
3671            Motion::PageDown | Motion::HalfPageDown => {
3672                Position::new(pos.line.saturating_add(10), pos.column)
3673            }
3674            Motion::PageUp | Motion::HalfPageUp => {
3675                Position::new(pos.line.saturating_sub(10), pos.column)
3676            }
3677            Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
3678            // Structural Lisp motions — stubs for phase 1.B; full paredit
3679            // semantics land when caixa-ast is wired to the active buffer.
3680            Motion::ForwardSexp
3681            | Motion::BackwardSexp
3682            | Motion::UpList
3683            | Motion::DownList
3684            | Motion::BeginningOfDefun
3685            | Motion::EndOfDefun
3686            | Motion::BeginningOfSexp
3687            | Motion::EndOfSexp => pos,
3688        })
3689    }
3690
3691    /// `zt` / `zz` / `zb` — re-frame the window around the cursor's line
3692    /// WITHOUT moving the cursor.
3693    ///
3694    /// The cursor is deliberately untouched: `zz` is what you press when you
3695    /// are already where you want to be and only the framing is wrong. Note
3696    /// that `set_cursor` would undo this — it scrolls the viewport to contain
3697    /// the cursor with a 2-line margin — so this must not route through it,
3698    /// and the next motion legitimately re-frames again.
3699    fn scroll_view(&mut self, align: escriba_core::ViewAlign) {
3700        use escriba_core::ViewAlign;
3701        let line = self.cursor().line;
3702        let Some(w) = self.layout.active_window_mut() else {
3703            return;
3704        };
3705        let h = w.viewport.visible_lines.max(1);
3706        w.viewport.top_line = match align {
3707            ViewAlign::Top => line,
3708            ViewAlign::Center => line.saturating_sub(h / 2),
3709            ViewAlign::Bottom => line.saturating_sub(h.saturating_sub(1)),
3710        };
3711        self.damage = self.damage.join(Damage::Full);
3712        self.bump_gen();
3713    }
3714
3715    /// Claim the operand of a pending `m` / `` ` `` / `'`, or arm one.
3716    ///
3717    /// Same key-layer shape as [`Self::consume_find_key`] and for the same
3718    /// reason: `ma` is `m` plus an OPERAND, and `a` is bound (append). Without
3719    /// claiming it first, `ma` would set no mark and enter Insert mode.
3720    ///
3721    /// Runs BEFORE `consume_object_key`, because `` d`a `` needs it: the
3722    /// object path claims `i` and `a` whenever an operator is armed, and the
3723    /// mark LETTER can be either of them.
3724    ///
3725    /// The two do not fight over the first key. This arms only while
3726    /// `pending_object` is clear, so `di'` — where `'` is a text-object
3727    /// delimiter rather than a mark jump — still reaches the object path. The
3728    /// guard states that dependency locally instead of leaving it implied by
3729    /// call order.
3730    fn consume_mark_key(&mut self, key: Key) -> Option<ObjectKey> {
3731        if let Some(kind) = self.pending_mark.take() {
3732            let Key::Char(name) = key else {
3733                if matches!(self.op_pending.state(), OpState::Awaiting { .. }) {
3734                    self.op_pending
3735                        .dispatch((Action::ChangeMode(Mode::Normal), 1));
3736                }
3737                return Some(ObjectKey::Consumed);
3738            };
3739            return Some(ObjectKey::Compose(match kind {
3740                MarkKey::Set => Action::SetMark(name),
3741                MarkKey::GotoExact => Action::Move(Motion::MarkExact(name)),
3742                MarkKey::GotoLine => Action::Move(Motion::MarkLine(name)),
3743            }));
3744        }
3745        if !matches!(self.modal.mode(), Mode::Normal | Mode::Visual) {
3746            return None;
3747        }
3748        // Half-typed text object (`di` waiting for its `'`) belongs to the
3749        // object path, not here; a key continuing a sequence belongs to the
3750        // sequence (see `consume_find_key` for the `zt` case that proves it).
3751        if self.pending_object.is_some() || !self.pending_keys.is_empty() {
3752            return None;
3753        }
3754        let Key::Char(c) = key else { return None };
3755        let kind = match c {
3756            'm' => MarkKey::Set,
3757            '`' => MarkKey::GotoExact,
3758            '\'' => MarkKey::GotoLine,
3759            _ => return None,
3760        };
3761        self.pending_mark = Some(kind);
3762        Some(ObjectKey::Consumed)
3763    }
3764
3765    /// `%` — brackets, plus this buffer's language word pairs if it has any.
3766    ///
3767    /// When both are candidates the NEARER one on the line wins, because that
3768    /// is the one under the operator's eye: on `if foo() then`, `%` on the
3769    /// `if` means the block and `%` on the `(` means the call. Deciding by
3770    /// distance rather than by precedence is what keeps both usable from the
3771    /// same key without a mode.
3772    fn resolve_match(&self, buf: &escriba_buffer::Buffer, pos: Position) -> Option<Position> {
3773        let Some(pairs) = self.word_pairs_for_active() else {
3774            return match_pair(buf, pos);
3775        };
3776        let bracket_col = line_chars(buf, pos.line)
3777            .into_iter()
3778            .enumerate()
3779            .skip(pos.column as usize)
3780            .find(|(_, c)| MATCH_PAIRS.iter().any(|&(o, cl)| *c == o || *c == cl))
3781            .and_then(|(i, _)| u32::try_from(i).ok());
3782        let word_col = word_hits(buf, pos.line, pairs)
3783            .into_iter()
3784            .find(|h| h.end > pos.column)
3785            .map(|h| h.col);
3786        match (bracket_col, word_col) {
3787            (Some(b), Some(w)) if w < b => match_word_pair(buf, pos, pairs),
3788            (Some(_), _) => match_pair(buf, pos),
3789            (None, Some(_)) => match_word_pair(buf, pos, pairs),
3790            (None, None) => None,
3791        }
3792    }
3793
3794    /// The word pairs for the active buffer's filetype, if the language has
3795    /// any. `None` for brace languages — Rust's `%` is bracket-only, and that
3796    /// is correct rather than missing.
3797    fn word_pairs_for_active(&self) -> Option<WordPairs> {
3798        let path = self.buffers.get(self.active)?.path.as_deref()?;
3799        let name = &self.filetypes.resolve(path)?.name;
3800        WORD_PAIRS
3801            .iter()
3802            .find(|(ft, _)| ft == name)
3803            .map(|(_, pairs)| *pairs)
3804    }
3805
3806    fn apply_motion(&mut self, motion: Motion) {
3807        // A bare search motion is a FAR JUMP and it REPORTS — it records into
3808        // the jumplist, prints vim's "hit BOTTOM" on a wrap, and says E486
3809        // when nothing matches. `resolve_motion` can do none of that: it is
3810        // deliberately pure because the OPERATOR path calls it to find a range
3811        // without moving the cursor. So `n` routes to the one executor that
3812        // owns those side effects, and `Action::SearchRepeat` routes to the
3813        // same place — one code path, two spellings.
3814        if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
3815            self.jump_search(matches!(motion, Motion::SearchPrev));
3816            return;
3817        }
3818        let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
3819            return;
3820        };
3821        // The single cursor-mutation path clamps to the buffer and scrolls
3822        // the viewport to contain the cursor on both axes.
3823        self.set_cursor(pos);
3824    }
3825
3826    /// Apply an operator over a motion — the vim `{operator}{motion}` verbs
3827    /// (`dw` delete-word, `c$` change-to-line-end, `y0` yank-to-line-start).
3828    /// Composition is explicit: the motion resolves a target via
3829    /// [`resolve_motion`](Self::resolve_motion); the operator acts over the
3830    /// `[cursor, target)` range. Register-leaving operators
3831    /// ([`Operator::leaves_register`]) capture the text first.
3832    /// Apply `op` over `motion` resolved `n` times from the cursor.
3833    ///
3834    /// `n == 1` is the ordinary path. Larger `n` walks the motion forward
3835    /// first and operates over the whole span in one go, which is what vim
3836    /// means by `3dw` — and the only way a non-moving operator like yank can
3837    /// honour a count at all.
3838    fn apply_operator_n(&mut self, op: Operator, motion: Motion, n: u32) {
3839        if n <= 1 {
3840            self.apply_operator(op, motion);
3841            return;
3842        }
3843        let from = self.cursor();
3844        let mut to = from;
3845        for _ in 0..n {
3846            match self.resolve_motion(to, motion) {
3847                Some(next) if next != to => to = next,
3848                // The motion stopped making progress (start/end of buffer):
3849                // operate over what we reached rather than aborting, which is
3850                // what vim does for `999dw` near the end of a file.
3851                _ => break,
3852            }
3853        }
3854        if to == from {
3855            // Nothing to operate over. Fall through to the single-step path
3856            // so its error reporting (E35, pattern-not-found) still runs.
3857            self.apply_operator(op, motion);
3858            return;
3859        }
3860        self.apply_operator_to(op, self.operated_end(motion, to));
3861    }
3862
3863    /// Widen an INCLUSIVE motion's target to the exclusive end an operator
3864    /// range needs. See [`Motion::is_inclusive`].
3865    ///
3866    /// Applied at the OPERATOR, never inside `resolve_motion`: the same
3867    /// resolution has to serve the cursor path, where `e` must land ON the
3868    /// last character, and the range path, where the range must end after it.
3869    /// One target, two readings — putting the widening in the resolver would
3870    /// move `e` itself one character too far.
3871    fn operated_end(&self, motion: Motion, to: Position) -> Position {
3872        // `;` inherits the inclusiveness of the find it repeats — resolve it
3873        // to that concrete motion rather than teaching `is_inclusive` about
3874        // state it cannot see. `d;` after `fx` must delete THROUGH the `x`.
3875        let motion = match motion {
3876            Motion::RepeatFind { reverse } => match self.last_find {
3877                Some(f) => Motion::FindChar {
3878                    ch: f.ch,
3879                    backward: f.backward != reverse,
3880                    till: f.till,
3881                },
3882                None => return to,
3883            },
3884            m => m,
3885        };
3886        if !motion.is_inclusive() {
3887            return to;
3888        }
3889        let line_len = self
3890            .buffers
3891            .get(self.active)
3892            .map_or(to.column, |b| b.line_len_chars(to.line));
3893        Position::new(to.line, to.column.saturating_add(1).min(line_len))
3894    }
3895
3896    fn apply_operator(&mut self, op: Operator, motion: Motion) {
3897        let from = self.cursor();
3898        let Some(to) = self.resolve_motion(from, motion) else {
3899            // A motion that cannot resolve aborts the operator with the buffer
3900            // untouched. A search motion says WHY — `dn` with no pattern armed
3901            // is otherwise indistinguishable from a dropped keystroke, which
3902            // is the same complaint that motivated E486 on the bare path.
3903            if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
3904                if self.search.pattern().is_none() {
3905                    self.messages
3906                        .push("E35: No previous regular expression".to_string());
3907                } else {
3908                    self.report_pattern_not_found();
3909                }
3910            }
3911            return;
3912        };
3913        self.apply_operator_to(op, self.operated_end(motion, to));
3914    }
3915
3916    /// Apply `op` over `[cursor, to)`.
3917    ///
3918    /// Split out of [`Self::apply_operator`] so the operated-search path can
3919    /// reach the same range machinery with a target it resolved itself — the
3920    /// alternative was a second copy of the delete/yank/register logic, which
3921    /// is how the two would drift.
3922    fn apply_operator_to(&mut self, op: Operator, to: Position) {
3923        let from = self.cursor();
3924        // A motion-shaped operation is charwise by construction: it acts over
3925        // `[cursor, point)`, which is a run of characters even when that run
3926        // happens to span a line break (`d}`).
3927        self.apply_operator_over(
3928            op,
3929            Extent::charwise(Range {
3930                start: from,
3931                end: to,
3932            }),
3933        );
3934    }
3935
3936    /// Apply `op` over an explicit range, capturing it as `kind`.
3937    ///
3938    /// The object path needs this: `gn`'s extent need not begin at the cursor,
3939    /// so it cannot go through the `[cursor, target)` shape the motion path
3940    /// uses. One implementation of the delete/yank/register logic, reached two
3941    /// ways.
3942    ///
3943    /// `kind` is a PARAMETER rather than something inferred from the range,
3944    /// and it has to be: `[(1,0), (2,0))` is the range `dd` produces on line 1
3945    /// AND the range `dj`-ish charwise motions produce, and nothing about the
3946    /// two positions distinguishes them. Only the caller knows which gesture
3947    /// it was. It travels to the register, and the register is what a later
3948    /// `p` reads to decide between splicing and opening a line.
3949    fn apply_operator_over(&mut self, op: Operator, extent: Extent) {
3950        let Extent {
3951            capture,
3952            removal,
3953            kind,
3954        } = extent.normalized();
3955        if capture.is_empty() {
3956            return;
3957        }
3958        // Capture the operated text (for the register) before mutating.
3959        let text = self
3960            .buffers
3961            .get(self.active)
3962            .and_then(|buf| buf.slice(capture).ok());
3963        if op.leaves_register() {
3964            if let Some(t) = &text {
3965                let captured = match kind {
3966                    RegisterKind::Charwise => t.clone(),
3967                    RegisterKind::Linewise => as_linewise_capture(t),
3968                };
3969                self.register = Some(Register::new(captured, kind));
3970            }
3971        }
3972        match op {
3973            // Delete + Change remove the range; Change then enters Insert so
3974            // the operator pairs with immediate typing (`ciw`, `c$`).
3975            //
3976            // They remove DIFFERENT ranges for a linewise extent, which is the
3977            // whole reason `Extent` carries two: `dd` takes the line and its
3978            // terminator, `cc` clears the line's text and KEEPS the line,
3979            // because you are changing its contents rather than removing it.
3980            // Both leave the same thing in the register.
3981            Operator::Delete | Operator::Change => {
3982                let cut = if op == Operator::Change {
3983                    removal
3984                } else {
3985                    capture
3986                };
3987                if cut.is_empty() {
3988                    // `cc` on an already-empty line: nothing to clear, but the
3989                    // gesture still means "type here".
3990                    self.rest_after_operator(kind, cut.start);
3991                    self.modal.enter(Mode::Insert);
3992                    return;
3993                }
3994                if let Some(buf) = self.buffers.get_mut(self.active) {
3995                    let _ = buf.apply(&Edit::delete(cut));
3996                }
3997                self.rest_after_operator(kind, cut.start);
3998                if op == Operator::Change {
3999                    self.modal.enter(Mode::Insert);
4000                }
4001            }
4002            // Yank copies to the register without mutating the buffer, so it
4003            // gets its OWN resting rule rather than the delete rule above: the
4004            // line is still there, and vim moves the cursor only when the yank
4005            // reached BACKWARDS past it.
4006            //
4007            // Keyed on the kind for the same reason everything else here is.
4008            // A linewise yank compares LINES — `yy` and `3yy` both start on
4009            // the cursor's own line, so neither moves, which is why comparing
4010            // POSITIONS was wrong: `yy`'s range starts at column 0, so it read
4011            // as "backwards" and knocked the cursor to the left margin every
4012            // time you copied a line. Invisible for `yw`, whose range starts
4013            // exactly at the cursor, so the move was a no-op there.
4014            Operator::Yank => {
4015                let here = self.cursor();
4016                match kind {
4017                    RegisterKind::Linewise if capture.start.line < here.line => {
4018                        // Keep the column: a backwards linewise yank rests on
4019                        // the first line taken, not at its margin.
4020                        self.set_cursor(Position::new(capture.start.line, here.column));
4021                    }
4022                    RegisterKind::Charwise
4023                        if (capture.start.line, capture.start.column)
4024                            < (here.line, here.column) =>
4025                    {
4026                        self.set_cursor(capture.start);
4027                    }
4028                    _ => {}
4029                }
4030            }
4031            // Indent/Format/structural operators are not yet wired — named,
4032            // not faked (no buffer mutation, register already captured for the
4033            // register-leaving ones above).
4034            _ => {
4035                self.messages
4036                    .push("operator not yet implemented".to_owned());
4037            }
4038        }
4039    }
4040
4041    /// `r{char}` — overwrite `count` characters from the cursor with `char`.
4042    ///
4043    /// Three things it deliberately is NOT, each of which a `Change`-operator
4044    /// composition would get wrong: it does not enter Insert, it does not
4045    /// touch the register, and it REFUSES rather than truncating when the
4046    /// count runs past the end of the line. vim's rule is that `5rx` on a
4047    /// three-character tail does nothing at all — a partial replace would
4048    /// silently destroy two characters you did not mean to name.
4049    fn replace_char(&mut self, ch: char, count: u32) {
4050        let n = count.max(1);
4051        let here = self.cursor();
4052        let Some(buf) = self.buffers.get(self.active) else {
4053            return;
4054        };
4055        let len = buf.line_len_chars(here.line);
4056        if here.column.saturating_add(n) > len {
4057            // Silent, like vim. The line is short — there is nothing to say
4058            // that the unchanged text does not already say.
4059            return;
4060        }
4061        let end = Position::new(here.line, here.column + n);
4062        let mut text = String::with_capacity(n as usize);
4063        for _ in 0..n {
4064            text.push(ch);
4065        }
4066        let Some(buf) = self.buffers.get_mut(self.active) else {
4067            return;
4068        };
4069        if buf
4070            .apply(&Edit::replace(Range::new(here, end), text))
4071            .is_err()
4072        {
4073            return;
4074        }
4075        // vim leaves the cursor on the LAST character replaced, not after it.
4076        self.set_cursor(Position::new(here.line, here.column + n - 1));
4077    }
4078
4079    /// `J` / `gJ` — join `count` lines into one.
4080    ///
4081    /// One `Edit::replace` over the whole span rather than `n` splices, so a
4082    /// `3J` is one `u` away from gone and the damage classifier sees a single
4083    /// line-count change.
4084    ///
4085    /// `space: true` (`J`) drops the next line's leading whitespace and puts a
4086    /// single space in the newline's place, with vim's two exceptions: no
4087    /// space is added when the line already ends in one, or when the next line
4088    /// starts with `)`. `space: false` (`gJ`) splices verbatim — the reason to
4089    /// reach for it is that `J` is lossy.
4090    fn join_lines(&mut self, space: bool, count: u32) {
4091        // `J` and `2J` both mean "join ONE following line": vim counts LINES
4092        // involved, not joins performed, so the join count is `count - 1`
4093        // floored at 1.
4094        let joins = count.max(2) - 1;
4095        let here = self.cursor();
4096        let Some(buf) = self.buffers.get(self.active) else {
4097            return;
4098        };
4099        let last = last_text_line(buf);
4100        if here.line >= last {
4101            // Nothing below to join. vim beeps; escriba says so, because a key
4102            // that silently does nothing is indistinguishable from an unbound
4103            // one — which is how `<C-h>` hid for a month.
4104            self.messages
4105                .push("E36: Not enough lines to join".to_string());
4106            return;
4107        }
4108        let end_line = here.line.saturating_add(joins).min(last);
4109        // `Buffer::line` INCLUDES the trailing newline and `line_len_chars`
4110        // excludes it — a mismatch that made the first cut of this splice the
4111        // terminators back in and then leave the originals behind, so `J`
4112        // produced the file unchanged plus a blank line. `line_chars` is the
4113        // newline-free reading every motion already uses.
4114        let line_text = |l: u32| line_chars(buf, l).into_iter().collect::<String>();
4115        let mut joined = line_text(here.line);
4116        // Where the cursor lands: vim puts it ON the join — the position the
4117        // newline used to occupy, which is the space it inserted.
4118        let mut caret = u32::try_from(joined.chars().count()).unwrap_or(0);
4119        for l in (here.line + 1)..=end_line {
4120            let next = line_text(l);
4121            caret = u32::try_from(joined.chars().count()).unwrap_or(0);
4122            if space {
4123                let trimmed = next.trim_start();
4124                let needs_space = !joined.is_empty()
4125                    && !joined.ends_with(char::is_whitespace)
4126                    && !trimmed.starts_with(')')
4127                    && !trimmed.is_empty();
4128                if needs_space {
4129                    joined.push(' ');
4130                }
4131                joined.push_str(trimmed);
4132            } else {
4133                joined.push_str(&next);
4134            }
4135        }
4136        let span = Range::new(
4137            Position::new(here.line, 0),
4138            Position::new(end_line, buf.line_len_chars(end_line)),
4139        );
4140        let Some(buf) = self.buffers.get_mut(self.active) else {
4141            return;
4142        };
4143        if buf.apply(&Edit::replace(span, joined)).is_err() {
4144            return;
4145        }
4146        self.set_cursor(Position::new(here.line, caret));
4147    }
4148
4149    /// Where the cursor rests once an operator has finished.
4150    ///
4151    /// Keyed on the operated KIND rather than on the operator, because that is
4152    /// what vim keys it on: every linewise operation lands the cursor the same
4153    /// way regardless of which operator produced it.
4154    ///
4155    /// The charwise arm is the old unconditional behaviour — the range start,
4156    /// which is where the text used to begin.
4157    fn rest_after_operator(&mut self, kind: RegisterKind, start: Position) {
4158        match kind {
4159            RegisterKind::Charwise => self.set_cursor(start),
4160            RegisterKind::Linewise => {
4161                // vim's linewise rule: the cursor lands on the FIRST NON-BLANK
4162                // of the line that now occupies the operated line's index, and
4163                // never past the last line that holds text.
4164                //
4165                // Both halves were wrong, and each in a way no unit test could
4166                // see, because both are about WHERE THE CURSOR IS rather than
4167                // what the text says — and every `dd` test asserted the text.
4168                //
4169                //   - Column 0 instead of the first non-blank is untidy on flat
4170                //     prose and actively wrong on indented code: `dd` inside a
4171                //     nested block dropped the cursor into the indentation, so
4172                //     the next `i` typed at the margin.
4173                //   - Landing past the last line of text was worse. A file
4174                //     ending in `\n` makes the rope report a phantom final
4175                //     line (see `last_text_line`); `dd` on the last REAL line
4176                //     parked the cursor on that phantom row, where `x` and `i`
4177                //     had nothing to act on and the next `dd` deleted the
4178                //     file's trailing NEWLINE rather than a line.
4179                let at = match self.buffers.get(self.active) {
4180                    Some(buf) => first_non_blank(buf, start.line.min(last_text_line(buf))),
4181                    None => return,
4182                };
4183                self.set_cursor(at);
4184            }
4185        }
4186    }
4187
4188    /// `p` / `P` — put `count` copies of the register back into the buffer.
4189    ///
4190    /// **The register's [`RegisterKind`] chooses the operation, not the key.**
4191    /// `p` after `dw` splices characters in at a column; `p` after `dd` opens
4192    /// a whole line below. That is why the capture had to become typed before
4193    /// this could exist at all: a `String` register leaves `p` guessing, and
4194    /// the only guess available — splice — drops a whole line, terminator and
4195    /// all, into the middle of whatever line the cursor is on.
4196    ///
4197    /// One [`Edit`] regardless of `count`, so `3p` is one `u` away from gone.
4198    fn put(&mut self, before: bool, count: u32) {
4199        let Some(reg) = self.register.clone() else {
4200            // vim says nothing for a put with an empty register, and neither
4201            // does this — but it must not fall through to an insert of `""`
4202            // either, which would record a `last_change` that `.` then
4203            // replays as a no-op edit.
4204            return;
4205        };
4206        let text = reg.replayed(count);
4207        if text.is_empty() {
4208            return;
4209        }
4210        let Some(buf) = self.buffers.get(self.active) else {
4211            return;
4212        };
4213        let here = self.cursor();
4214        let (at, rest) = match reg.kind {
4215            RegisterKind::Linewise => {
4216                // `p` opens BELOW the cursor's line, `P` above. The insertion
4217                // point is the start of a line either way, and the text ends
4218                // in a newline (`Register::replayed` guarantees it), so the
4219                // splice pushes the existing line down rather than joining it.
4220                //
4221                // `line + 1` is a valid insertion point even on the last line:
4222                // a file ending in `\n` has the phantom row there, and one
4223                // that does not gets the newline from `replayed`.
4224                let line = if before {
4225                    here.line
4226                } else {
4227                    here.line.saturating_add(1)
4228                };
4229                let at = Position::new(line.min(buf.line_count()), 0);
4230                // vim rests on the first non-blank of the FIRST line put.
4231                (at, PutRest::LineStart(at.line))
4232            }
4233            RegisterKind::Charwise => {
4234                // `p` lands AFTER the character under the cursor, `P` on it.
4235                // Appending past the end of the line is legal here — that is
4236                // what makes `p` on the last character of a line work — so
4237                // this clamps to the line length, not to the last character.
4238                let col = if before {
4239                    here.column
4240                } else {
4241                    here.column
4242                        .saturating_add(1)
4243                        .min(buf.line_len_chars(here.line))
4244                };
4245                (Position::new(here.line, col), PutRest::LastCharPut)
4246            }
4247        };
4248        let Some(buf) = self.buffers.get_mut(self.active) else {
4249            return;
4250        };
4251        if buf.apply(&Edit::insert(at, text.clone())).is_err() {
4252            return;
4253        }
4254        match rest {
4255            PutRest::LineStart(line) => {
4256                let to = match self.buffers.get(self.active) {
4257                    Some(b) => first_non_blank(b, line.min(last_text_line(b))),
4258                    None => return,
4259                };
4260                self.set_cursor(to);
4261            }
4262            // vim leaves the cursor ON the last character put, not after it —
4263            // which is what makes `p` then `.`-less repeated puts stack rather
4264            // than march right. Routed through `set_cursor` (an `OnCharacter`
4265            // rest) so Normal mode's on-a-character invariant still applies.
4266            PutRest::LastCharPut => {
4267                let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
4268                let end = if let Some(nl) = text.rfind('\n') {
4269                    let tail = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
4270                    Position::new(at.line + added_lines, tail)
4271                } else {
4272                    let n = u32::try_from(text.chars().count()).unwrap_or(0);
4273                    Position::new(at.line, at.column.saturating_add(n))
4274                };
4275                self.set_cursor(Position::new(end.line, end.column.saturating_sub(1)));
4276            }
4277        }
4278    }
4279
4280    /// The text last yanked or deleted into the unnamed register, if any.
4281    /// `p`/`P` read this — through [`Register`], so they can tell a captured
4282    /// LINE from a captured run of characters.
4283    #[must_use]
4284    pub fn register(&self) -> Option<&Register> {
4285        self.register.as_ref()
4286    }
4287
4288    /// The register's raw text, for callers that only want the characters.
4289    #[must_use]
4290    pub fn register_text(&self) -> Option<&str> {
4291        self.register.as_ref().map(|r| r.text.as_str())
4292    }
4293
4294    fn insert_char(&mut self, c: char) {
4295        if self.modal.mode() == Mode::Command {
4296            // A search prompt and an ex-command share Command mode (vim's
4297            // cmdline). `search.is_prompting()` is the typed discriminator —
4298            // it can only be true when `/` or `?` actually opened a prompt.
4299            if self.search.is_prompting() {
4300                // The search prompt is the SOLE store while it is open.
4301                //
4302                // This used to also `push_minibuffer(c)`, and the two stores
4303                // insert differently — `search.push` at the caret, the
4304                // minibuffer always at the end — so `/fo<Left>X` left them
4305                // reading `fXo` and `foX`. That was one of FIVE desync paths;
4306                // the caret moves, forward-delete, delete-word and
4307                // clear-to-start never touched the shadow at all.
4308                //
4309                // Deleting the write costs nothing because `status_model`
4310                // already selects the minibuffer only on the `prompt == None`
4311                // branch — the shadow is the EX-LINE's store, and while a
4312                // search prompt is open nothing reads it.
4313                self.search.push(c);
4314                self.preview_search();
4315            } else {
4316                self.modal.push_minibuffer(c);
4317            }
4318            return;
4319        }
4320        let cursor = self.cursor();
4321        let Some(buf) = self.buffers.get_mut(self.active) else {
4322            return;
4323        };
4324        let edit = Edit::insert(cursor, c.to_string());
4325        if buf.apply(&edit).is_ok() {
4326            let next = if c == '\n' {
4327                Position::new(cursor.line.saturating_add(1), 0)
4328            } else {
4329                cursor.shift_right(1)
4330            };
4331            // Route through the single cursor-mutation path so the viewport
4332            // follows the cursor (both axes) and the cursor stays clamped.
4333            self.place_cursor(next, CursorRest::AtInsertPoint);
4334        }
4335    }
4336
4337    /// Enter Insert mode at `at` — the ONE body behind `i` `I` `a` `A` `o` `O`.
4338    ///
4339    /// # What lets `A` park past the last character
4340    ///
4341    /// [`Self::place_cursor`] pulls a caret back to `len - 1` — but only when
4342    /// **both** halves of its guard hold: `rest == CursorRest::OnCharacter`
4343    /// *and* the mode is `Normal`. `A` and `a`-at-end-of-line need that clamp
4344    /// lifted, and this function lifts it twice over: it enters Insert before
4345    /// placing anything, and it asks for `CursorRest::AtInsertPoint`.
4346    ///
4347    /// **Either one alone is sufficient**, which is worth writing down because
4348    /// it is the opposite of what it looks like. An earlier version of this
4349    /// comment claimed the ORDER was load-bearing on its own; the red run
4350    /// refuted it — reversing the order while keeping `AtInsertPoint` stays
4351    /// green, and so does `OnCharacter` while entering Insert first. Only
4352    /// removing BOTH goes red, and then `a` on the `o` of "hello" reports
4353    /// column 4 instead of 5: the caret sits back on the character it was meant
4354    /// to append after. Belt and braces here is deliberate — the two guards
4355    /// answer different questions ("what kind of place is this?" and "what mode
4356    /// are we in?") and a later refactor is free to change one.
4357    ///
4358    /// `o`/`O` are in this function rather than in an `Edit` action because
4359    /// they are ONE gesture: vim's `o` is not "insert a newline, then enter
4360    /// insert" — the caret must land on the new line, and an operator watching
4361    /// two separate actions would record two dot-repeat entries for one press.
4362    fn enter_insert_at(&mut self, at: InsertAt) {
4363        self.modal.enter_insert();
4364        let cursor = self.cursor();
4365        // Resolve everything that needs the buffer BEFORE mutating, so the
4366        // immutable borrow ends before `place_cursor`/`apply` want `&mut self`.
4367        let Some(buf) = self.buffers.get(self.active) else {
4368            return;
4369        };
4370        let line_len = buf.line_len_chars(cursor.line);
4371        let target = match at {
4372            // `i` — the caret is already the insert point.
4373            InsertAt::Caret => Some(cursor),
4374            // One past the last char is a legal insert point, which is what
4375            // lets `a` on the final character append rather than stall.
4376            InsertAt::AfterCaret => Some(Position::new(
4377                cursor.line,
4378                cursor.column.saturating_add(1).min(line_len),
4379            )),
4380            InsertAt::LineEnd => Some(Position::new(cursor.line, line_len)),
4381            InsertAt::FirstNonBlank => Some(first_non_blank(buf, cursor.line)),
4382            // Handled below — these two edit the buffer first.
4383            InsertAt::OpenBelow | InsertAt::OpenAbove => None,
4384        };
4385        if let Some(pos) = target {
4386            self.place_cursor(pos, CursorRest::AtInsertPoint);
4387            return;
4388        }
4389        // `o`/`O` — open a line by inserting the terminator at the boundary the
4390        // direction names, then land on the fresh line. Expressed as an
4391        // `Edit::insert` through `Buffer::apply` so it joins the undo history
4392        // the same way typed text does.
4393        let (at_pos, land_on) = match at {
4394            InsertAt::OpenBelow => (
4395                Position::new(cursor.line, line_len),
4396                Position::new(cursor.line.saturating_add(1), 0),
4397            ),
4398            // Inserting at column 0 pushes the current line DOWN, so the fresh
4399            // line takes the caret's own line number.
4400            _ => (Position::new(cursor.line, 0), Position::new(cursor.line, 0)),
4401        };
4402        let Some(buf) = self.buffers.get_mut(self.active) else {
4403            return;
4404        };
4405        if buf.apply(&Edit::insert(at_pos, "\n")).is_ok() {
4406            self.place_cursor(land_on, CursorRest::AtInsertPoint);
4407        }
4408    }
4409
4410    /// `<BS>` against the BUFFER — the Insert-mode arm of [`Action::Backspace`].
4411    ///
4412    /// Deletes `[target, cursor)` where `target` is the previous character
4413    /// position, so column 0 JOINS with the line above rather than stopping
4414    /// dead: the range spans the newline and one `Edit::delete` removes it.
4415    /// `Motion::Left` cannot express that — it saturates at column 0, which is
4416    /// why this does not route through `apply_operator`.
4417    ///
4418    /// The other reason it does not: `Operator::Delete` captures the unnamed
4419    /// register, and vim's insert-mode backspace does not. Erasing a typo
4420    /// should not silently overwrite what you yanked to paste.
4421    fn delete_before_cursor(&mut self) {
4422        let cursor = self.cursor();
4423        let Some(buf) = self.buffers.get(self.active) else {
4424            return;
4425        };
4426        let target = if cursor.column > 0 {
4427            Position::new(cursor.line, cursor.column.saturating_sub(1))
4428        } else if cursor.line > 0 {
4429            let above = cursor.line.saturating_sub(1);
4430            Position::new(above, buf.line_len_chars(above))
4431        } else {
4432            // Start of the document — nothing to the left. A no-op, not a
4433            // clamp onto something else.
4434            return;
4435        };
4436        self.erase_back_to(target);
4437    }
4438
4439    /// Delete `[target, cursor)` and park the caret on `target`.
4440    ///
4441    /// The shared body of every BACKWARD erase against the buffer — `<BS>`,
4442    /// `<C-w>`, `<C-u>`. They differ only in how far back they reach, so the
4443    /// two properties that must hold for all three live here once rather than
4444    /// three times: the edit does NOT route through `apply_operator` (see
4445    /// [`Self::delete_before_cursor`] for both reasons), and the caret lands
4446    /// via `set_cursor` so the viewport follows and the clamp still runs.
4447    ///
4448    /// A `target` at or after the cursor is a no-op. That is the guard that
4449    /// makes the callers safe to write as "resolve a position, hand it over":
4450    /// `word_prev` returns the cursor unchanged at column 0 and
4451    /// `first_non_blank` returns a position AHEAD of the cursor inside an
4452    /// indent, and a reversed `Range` would be a delete of unknown extent
4453    /// rather than nothing.
4454    fn erase_back_to(&mut self, target: Position) {
4455        let cursor = self.cursor();
4456        if (target.line, target.column) >= (cursor.line, cursor.column) {
4457            return;
4458        }
4459        let edit = Edit::delete(Range {
4460            start: target,
4461            end: cursor,
4462        });
4463        if let Some(buf) = self.buffers.get_mut(self.active) {
4464            if buf.apply(&edit).is_ok() {
4465                self.set_cursor(target);
4466            }
4467        }
4468    }
4469
4470    /// `<C-w>` against the BUFFER — the Insert-mode arm of
4471    /// [`Action::DeleteWordBefore`].
4472    ///
4473    /// Reaches back over `Motion::WordStartPrev`, the SAME resolver the cursor
4474    /// move and the operator range already stand on, so `<C-w>` and `db` agree
4475    /// on where a word starts by construction instead of by two hand-written
4476    /// scans that drift.
4477    ///
4478    /// `word_prev` is single-line and returns the cursor unchanged at column 0,
4479    /// which would make `<C-w>` a dead key at the start of a line. vim erases
4480    /// the line break there, so the zero-width case falls through to
4481    /// [`Self::delete_before_cursor`] — one character back, which at column 0
4482    /// IS the newline.
4483    fn delete_word_before_cursor(&mut self) {
4484        let cursor = self.cursor();
4485        let Some(target) = self.resolve_motion(cursor, Motion::WordStartPrev) else {
4486            return;
4487        };
4488        if (target.line, target.column) >= (cursor.line, cursor.column) {
4489            self.delete_before_cursor();
4490            return;
4491        }
4492        self.erase_back_to(target);
4493    }
4494
4495    /// `<C-u>` against the BUFFER — the Insert-mode arm of
4496    /// [`Action::DeleteToLineStart`].
4497    ///
4498    /// Two-step, as vim is: the first press erases back to the first non-blank
4499    /// (what you typed), and a second press — now sitting ON the first
4500    /// non-blank, so that target is no longer behind the cursor — erases the
4501    /// indent. Collapsing the two into "always column 0" would destroy
4502    /// alignment on the first press, which is the one the hands reach for.
4503    ///
4504    /// Never joins with the line above: `<C-u>` is a line-scoped verb, and at
4505    /// column 0 it is a no-op rather than a silent line-merge.
4506    fn delete_to_line_start(&mut self) {
4507        let cursor = self.cursor();
4508        let Some(indent) = self.resolve_motion(cursor, Motion::LineFirstNonBlank) else {
4509            return;
4510        };
4511        let target = if (indent.line, indent.column) < (cursor.line, cursor.column) {
4512            indent
4513        } else {
4514            Position::new(cursor.line, 0)
4515        };
4516        self.erase_back_to(target);
4517    }
4518
4519    /// `<Del>` against the BUFFER — the Insert-mode arm of
4520    /// [`Action::DeleteForward`]. The cursor does NOT move: forward-delete
4521    /// pulls the rest of the line leftwards under a stationary caret.
4522    fn delete_after_cursor(&mut self) {
4523        let cursor = self.cursor();
4524        let Some(buf) = self.buffers.get(self.active) else {
4525            return;
4526        };
4527        let target = if cursor.column < buf.line_len_chars(cursor.line) {
4528            Position::new(cursor.line, cursor.column.saturating_add(1))
4529        } else if cursor.line.saturating_add(1) < buf.line_count() {
4530            // At end-of-line the character ahead IS the newline, so this
4531            // joins the line below — the mirror of `delete_before_cursor`.
4532            Position::new(cursor.line.saturating_add(1), 0)
4533        } else {
4534            return;
4535        };
4536        let edit = Edit::delete(Range {
4537            start: cursor,
4538            end: target,
4539        });
4540        if let Some(buf) = self.buffers.get_mut(self.active) {
4541            let _ = buf.apply(&edit);
4542        }
4543    }
4544
4545    /// Backspace inside a prompt. Keeps the search buffer and the displayed
4546    /// minibuffer in lockstep — if only one shrank, the pattern submitted
4547    /// would differ from the text on screen.
4548    fn prompt_backspace(&mut self) -> bool {
4549        if self.modal.mode() != Mode::Command {
4550            return false;
4551        }
4552        if self.search.is_prompting() {
4553            // Backspacing past the `/` closes the prompt, as vim does. No
4554            // `pop_minibuffer` here for the same reason as `insert_char`: the
4555            // shadow is the ex-line's, and popping its TAIL when the caret is
4556            // mid-pattern was another desync path.
4557            if self.search.backspace() {
4558                self.modal.clear_minibuffer();
4559                self.modal.enter(Mode::Normal);
4560            }
4561            // Never `pop_minibuffer` on the search path: it pops the TAIL,
4562            // while `search.backspace()` removes the char before the CARET.
4563            return true;
4564        }
4565        self.modal.pop_minibuffer();
4566        true
4567    }
4568
4569    fn submit_command(&mut self) {
4570        // Read the command line BEFORE leaving Command mode — the minibuffer
4571        // exists only in the `Command` variant, so the escape must come
4572        // after the capture.
4573        let line = self.modal.minibuffer().to_string();
4574        self.modal.escape();
4575        // The ex-name grammar — vim's abbreviations and its `!` — lives in
4576        // `escriba_command::ex` and NOT here. It used to be three arms in a
4577        // `match` at the bottom of this file (`"w" => "save"`, …), which is
4578        // why `:wq` reported "command not found" while `:w` and `:q` both
4579        // worked: there was nowhere for a compound spelling to be known.
4580        let Some(inv) = escriba_command::ex::parse(&line) else {
4581            return;
4582        };
4583        self.run_command(&inv.command, &inv.args);
4584    }
4585
4586    fn run_command(&mut self, name: &str, args: &[String]) {
4587        // Bound the command -> RunCommand slip -> command cycle. Refused and
4588        // reported, never a stack overflow: an editor that dies under the
4589        // operator loses their buffer, and a script that loops is a mistake
4590        // they should be told about, not punished for.
4591        if self.dispatch_depth >= Self::MAX_DISPATCH_DEPTH {
4592            let mut m = String::from("command recursion too deep at `");
4593            m.push_str(name);
4594            m.push_str("` — refusing");
4595            self.messages.push(m);
4596            self.damage = self.damage.join(Damage::Viewport);
4597            self.bump_gen();
4598            return;
4599        }
4600        self.dispatch_depth += 1;
4601        self.run_command_inner(name, args);
4602        self.dispatch_depth -= 1;
4603    }
4604
4605    /// How many nested command dispatches are allowed. Deep enough that no
4606    /// legitimate script notices, shallow enough to fail fast.
4607    const MAX_DISPATCH_DEPTH: u8 = 8;
4608
4609    fn run_command_inner(&mut self, name: &str, args: &[String]) {
4610        // Lazy-activation seam (lazy.nvim `cmd =` model): a user plugin
4611        // gated on `Command: <name>` has its entry applied the first time
4612        // that command runs, BEFORE dispatch — so the activated plugin
4613        // can register the very command being invoked and it resolves on
4614        // this same call.
4615        if self.plugin_host.pending() > 0 {
4616            let pending = self.plugin_host.pending_for_command(name);
4617            for src in pending {
4618                self.apply_plugin_entry(&src);
4619            }
4620        }
4621        // Read through the counter, then interpret. Two immutable borrows of
4622        // `self` (the window and the registry) coexist; the `&mut` comes
4623        // afterwards, once the outcome is owned. That sequencing IS the
4624        // seam: there is no moment where a command body and `&mut self` are
4625        // live at the same time.
4626        let outcome = {
4627            let window = self.window();
4628            self.commands.run(name, &window, args)
4629        };
4630        match outcome {
4631            Ok(o) => self.interpret(o),
4632            // Reported, never fatal (Phase 0). A failed command must not
4633            // take the editor down, but it must not be invisible either.
4634            Err(e) => {
4635                self.messages.push(describe_command_failure(name, &e));
4636                self.damage = self.damage.join(Damage::Viewport);
4637                self.bump_gen();
4638            }
4639        }
4640    }
4641
4642    // ── tatara-lisp runtime bridge (imperative programmability tier) ──
4643
4644    /// Capture a read snapshot of the editor for the tatara-lisp host.
4645    /// Lisp reads (`cursor-line`, `current-line`, …) answer from this.
4646    #[must_use]
4647    pub fn snapshot(&self) -> EditorSnapshot {
4648        let current_line = self
4649            .buffers
4650            .get(self.active)
4651            .and_then(|b| b.line(self.cursor().line))
4652            .map(|s| s.trim_end_matches('\n').to_string())
4653            .unwrap_or_default();
4654        let buffer_name = self
4655            .buffers
4656            .get(self.active)
4657            .and_then(|b| b.path.as_ref())
4658            .map(|p| p.display().to_string())
4659            .unwrap_or_else(|| "[scratch]".to_string());
4660        EditorSnapshot {
4661            cursor_line: i64::from(self.cursor().line),
4662            cursor_column: i64::from(self.cursor().column),
4663            current_line,
4664            mode: self.modal.mode().as_str().to_string(),
4665            buffer_name,
4666        }
4667    }
4668
4669    /// Evaluate tatara-lisp `src` against this editor: capture a
4670    /// snapshot, run it in the embedded VM, then apply the typed effects
4671    /// the program emitted. This is the imperative programmability tier
4672    /// — live Lisp that reads state and drives the editor through the
4673    /// sandboxed effect boundary.
4674    ///
4675    /// **Snapshot semantics:** the read snapshot is captured ONCE before
4676    /// eval, and effects are applied AFTER the program returns. So within
4677    /// a single `run_lisp` call a program cannot observe its own writes —
4678    /// `(insert "x") (cursor-column)` reads the pre-insert column. This
4679    /// snapshot-isolation is deliberate (it's what makes the effect
4680    /// boundary a clean sandbox seam); a program that must read its own
4681    /// effects splits the work across calls. The VM is cached
4682    /// ([`Self::lisp_vm`]) so the stdlib is installed once and top-level
4683    /// `define`s persist across calls (REPL-like).
4684    pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
4685        let mut host = EscribaHost::with_snapshot(self.snapshot());
4686        let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
4687        vm.eval(src, &mut host)?;
4688        let effects = host.take_effects();
4689        self.apply_host_effects(effects);
4690        Ok(())
4691    }
4692
4693    /// Apply tatara-lisp effects to live editor state.
4694    ///
4695    /// A thin adapter now. It used to be `apply_host_effects`, a THIRD
4696    /// implementation of message-push / option-insert / insert-text beside
4697    /// the Action executor and the slip interpreter — the same duplication
4698    /// that let `u` and `:undo` drift apart in M3. The VM emits slips; this
4699    /// hands them to the one interpreter.
4700    pub fn apply_host_effects(&mut self, effects: Vec<Negai>) {
4701        self.interpret(Outcome::did(effects));
4702    }
4703
4704    /// Insert a (possibly multi-line) string at the cursor and advance
4705    /// the cursor past it. Used by the `(insert …)` effect.
4706    fn insert_text(&mut self, text: &str) {
4707        if text.is_empty() {
4708            return;
4709        }
4710        let cursor = self.cursor();
4711        let Some(buf) = self.buffers.get_mut(self.active) else {
4712            return;
4713        };
4714        let edit = Edit::insert(cursor, text.to_string());
4715        if buf.apply(&edit).is_ok() {
4716            let next = if let Some(nl) = text.rfind('\n') {
4717                let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
4718                let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
4719                Position::new(cursor.line + added_lines, last_line_len)
4720            } else {
4721                let n = u32::try_from(text.chars().count()).unwrap_or(0);
4722                cursor.shift_right(n)
4723            };
4724            // Route through the single cursor-mutation path so the viewport
4725            // follows the cursor (both axes) and the cursor stays clamped.
4726            self.place_cursor(next, CursorRest::AtInsertPoint);
4727        }
4728    }
4729}
4730
4731fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
4732    let Some(text) = buf.line(line) else {
4733        return Position::new(line, 0);
4734    };
4735    let col = text
4736        .chars()
4737        .take_while(|c| c.is_whitespace() && *c != '\n')
4738        .count();
4739    Position::new(line, u32::try_from(col).unwrap_or(0))
4740}
4741
4742/// A character search: which character, which direction, and whether it stops
4743/// ON it (`f`/`F`) or just BEFORE it (`t`/`T`).
4744///
4745/// The same value serves the pending operand and the `;`/`,` memory, so the
4746/// thing repeated is the thing that ran.
4747#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4748struct FindSpec {
4749    ch: char,
4750    backward: bool,
4751    till: bool,
4752}
4753
4754/// What the next keystroke means after `m`, `` ` `` or `'`.
4755#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4756enum MarkKey {
4757    /// `m{a-z}` — set.
4758    Set,
4759    /// `` `{a-z} `` — jump to the exact position.
4760    GotoExact,
4761    /// `'{a-z}` — jump to the line's first non-blank.
4762    GotoLine,
4763}
4764
4765/// What kind of place a cursor move is asking for.
4766///
4767/// The Normal-mode rule "the cursor sits ON a character" is about where the
4768/// cursor comes to REST. It is not about where text goes next: a write that
4769/// appends `abc` leaves the cursor after the `c`, and that position is one
4770/// past the last character by construction — clamping it back would make the
4771/// next append land inside the text just written. The lisp `(insert …)`
4772/// effect is the case that proves it, because it runs in Normal mode.
4773///
4774/// A parameter rather than two functions, so both readings stay in front of
4775/// whoever changes the clamp.
4776#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4777enum CursorRest {
4778    /// A motion's destination — Normal mode pulls it onto a character.
4779    OnCharacter,
4780    /// Where the next character goes — never pulled back.
4781    AtInsertPoint,
4782}
4783
4784/// What an operator acts over — a CAPTURE range, a REMOVAL range, and the
4785/// kind they were resolved as.
4786///
4787/// Two ranges because for a linewise extent they genuinely differ, and every
4788/// attempt to derive one from the other re-decides which branch produced it:
4789///
4790///   - `dd` removes the line AND its terminator; `cc` clears the line's text
4791///     and KEEPS the line, because you are changing its contents rather than
4792///     removing it. Same lines, same register content, different cut.
4793///   - On the last line of a file with no trailing newline the removal has to
4794///     swallow the PRECEDING newline (there is none following), so it starts
4795///     on a different LINE than the extent names.
4796///
4797/// Charwise extents have `capture == removal`, which is why the old
4798/// single-range signature was right for everything except the linewise change
4799/// and wrong there — `cc` deleted the line.
4800#[derive(Clone, Copy, Debug)]
4801struct Extent {
4802    /// What goes in the register, and what a delete removes.
4803    capture: Range,
4804    /// What a CHANGE removes. Equal to `capture` unless the kind is linewise.
4805    removal: Range,
4806    kind: RegisterKind,
4807}
4808
4809impl Extent {
4810    /// A run of characters: one range, both roles.
4811    const fn charwise(r: Range) -> Self {
4812        Self {
4813            capture: r,
4814            removal: r,
4815            kind: RegisterKind::Charwise,
4816        }
4817    }
4818
4819    /// An extent resolved by a text object, keyed on what the object says it
4820    /// is. The linewise case needs the explicit constructor below, so this is
4821    /// the charwise-or-nothing door.
4822    fn from_object(r: Range, kind: RegisterKind) -> Self {
4823        match kind {
4824            RegisterKind::Charwise => Self::charwise(r),
4825            // A caller that has only a range cannot supply the text-only
4826            // removal, so the two coincide — which is the pre-`cc` behaviour
4827            // and is correct for every linewise object except a change. The
4828            // `Line` object goes through `line_extent` instead.
4829            RegisterKind::Linewise => Self {
4830                capture: r,
4831                removal: r,
4832                kind,
4833            },
4834        }
4835    }
4836
4837    fn normalized(self) -> Self {
4838        Self {
4839            capture: self.capture.normalized(),
4840            removal: self.removal.normalized(),
4841            kind: self.kind,
4842        }
4843    }
4844}
4845
4846/// Normalize a linewise capture: newline-TERMINATED, never newline-LED.
4847///
4848/// The removal range and the register capture are two different views of one
4849/// gesture, and the last line of a file with no trailing newline is where they
4850/// come apart. There is no following terminator to take, so `dd` has to
4851/// swallow the PRECEDING one — the right thing to REMOVE, and the wrong thing
4852/// to put back: the raw slice reads `"\nbravo"`, so `yyp` opened a blank line
4853/// and then a `bravo` with no terminator of its own.
4854///
4855/// Stated once, here, where the kind is known. `Register::replayed` handles
4856/// the other half (a capture that ends without a newline).
4857fn as_linewise_capture(slice: &str) -> String {
4858    match slice.strip_prefix('\n') {
4859        Some(rest) => {
4860            let mut s = String::with_capacity(slice.len());
4861            s.push_str(rest);
4862            s.push('\n');
4863            s
4864        }
4865        None => slice.to_owned(),
4866    }
4867}
4868
4869/// Does this action ABSORB its count into one operation, or REPEAT?
4870///
4871/// A free function rather than a method on `Action` deliberately: the answer
4872/// is a property of THIS EXECUTOR's arms, not of the action's meaning. An arm
4873/// absorbs its count exactly when it takes one, and a name listed here that no
4874/// arm reads is worse than no list — it reads as handled and behaves as
4875/// repeated. Keep the two in step; the tests below pin every member.
4876fn absorbs_count(action: &Action) -> bool {
4877    matches!(
4878        action,
4879        Action::ApplyOperator { .. }
4880            | Action::Put { .. }
4881            // `3ra` is one replace of three characters (and refuses if there
4882            // are not three), `3J` is one join of three lines. Repeating
4883            // either would walk the cursor and do the wrong thing three times.
4884            | Action::ReplaceChar(_)
4885            | Action::JoinLines { .. }
4886            // Only the LINEWISE object can express an `n`-fold extent today.
4887            // `2diw` still repeats, which is the same over-count-a-yank defect
4888            // waiting on a general "resolve this object n times" — named here
4889            // rather than half-fixed.
4890            | Action::ApplyOperatorObject {
4891                object: escriba_core::TextObject::Line,
4892                ..
4893            }
4894    )
4895}
4896
4897/// Where a put leaves the cursor.
4898///
4899/// Decided BEFORE the insert (from the register's kind) and consumed after,
4900/// because the two arms need different information and only one of them
4901/// survives the edit: the linewise arm needs the line it opened, which the
4902/// pre-edit position names, while the charwise arm needs the extent of the
4903/// text it wrote. Computing either from the post-edit buffer alone means
4904/// re-deriving which gesture happened, which is exactly what
4905/// [`escriba_core::RegisterKind`] exists to stop.
4906#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4907enum PutRest {
4908    /// Linewise: the first non-blank of the first line put.
4909    LineStart(u32),
4910    /// Charwise: ON the last character put — vim's rule, and the one that
4911    /// makes a following `p` stack the copies rather than walk rightward.
4912    LastCharPut,
4913}
4914
4915/// vim's three character classes — the whole of what "a word" means to `w`,
4916/// `b`, `e` and `iw`.
4917///
4918/// One classifier, not four. `object_word` grew its own copy while the word
4919/// MOTIONS were still splitting on whitespace alone, so `diw` on `foo.bar`
4920/// took `foo` and `dw` took `foo.bar` — two answers to "where does this word
4921/// end" from one editor, on the same keystroke's worth of text.
4922#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4923enum WordClass {
4924    Word,
4925    Punct,
4926    Space,
4927}
4928
4929fn word_class(c: char) -> WordClass {
4930    if c.is_alphanumeric() || c == '_' {
4931        WordClass::Word
4932    } else if c.is_whitespace() {
4933        WordClass::Space
4934    } else {
4935        WordClass::Punct
4936    }
4937}
4938
4939/// vim's two word WIDTHS. `w` splits on the three [`WordClass`]es; `W` splits
4940/// on whitespace alone, so `foo.bar` is three words and one WORD.
4941///
4942/// A parameter on the scanners rather than a second family of them: `w` and
4943/// `W` differ in exactly one place — how a character is classified — and two
4944/// copies of the cross-line, empty-line and end-of-buffer rules is how they
4945/// would drift.
4946#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4947enum Width {
4948    /// `w` / `e` / `b` / `ge` — alphanumeric, punctuation and space.
4949    Small,
4950    /// `W` / `E` / `B` / `gE` — non-space and space, nothing else.
4951    Big,
4952}
4953
4954fn class_at(c: char, width: Width) -> WordClass {
4955    match (width, word_class(c)) {
4956        (Width::Big, WordClass::Punct) => WordClass::Word,
4957        (_, k) => k,
4958    }
4959}
4960
4961/// A line's characters WITHOUT its terminator.
4962///
4963/// The newline is not a character the cursor can sit on, and every word scan
4964/// wants the line's own text; `line_len_chars` already strips it for exactly
4965/// this reason, so the two agree on where a line ends by construction.
4966fn line_chars(buf: &escriba_buffer::Buffer, line: u32) -> Vec<char> {
4967    let Some(text) = buf.line(line) else {
4968        return Vec::new();
4969    };
4970    let len = buf.line_len_chars(line) as usize;
4971    text.chars().take(len).collect()
4972}
4973
4974/// The last line that HOLDS text.
4975///
4976/// A file ending in `\n` is one line of text plus a terminator, but the rope
4977/// reports two lines, the second empty — so `line_count() - 1` names a line
4978/// that is not there. A forward word motion walking onto it moves the cursor
4979/// off the end of the file onto a row with nothing on it, which is what `w`
4980/// on the last word of an ordinary file did.
4981///
4982/// Scoped to the word motions on purpose. That phantom row is also DRAWN — it
4983/// gets a gutter number in every face — and hiding it is a buffer-model change
4984/// with a much wider blast radius than a motion fix; it is a separate defect,
4985/// named rather than half-fixed here. What is fixed here is the claim these
4986/// motions make: there is no next word after the last character of the text.
4987fn last_text_line(buf: &escriba_buffer::Buffer) -> u32 {
4988    let last = buf.line_count().saturating_sub(1);
4989    if last > 0 && buf.line_len_chars(last) == 0 {
4990        last - 1
4991    } else {
4992        last
4993    }
4994}
4995
4996/// Where a forward word motion runs out of text — the EXCLUSIVE end, so an
4997/// operator reaches the final character. See [`word_next`].
4998fn buffer_end(buf: &escriba_buffer::Buffer) -> Position {
4999    let line = last_text_line(buf);
5000    Position::new(line, buf.line_len_chars(line))
5001}
5002
5003/// `w` — to the start of the next word.
5004///
5005/// Three vim behaviours this had to grow, each of which was a visible wrong
5006/// answer before:
5007///
5008/// - **Punctuation starts a word.** `w` on `foo.bar` stops at `.` and again
5009///   at `b`; the whitespace-only scan sailed past both to the end.
5010/// - **It crosses lines onto the first non-blank**, not onto column 0. Landing
5011///   on the indent means the next `w` is spent walking out of it.
5012/// - **An empty line is a word.** vim stops on one, and that is what makes `w`
5013///   usable for walking paragraphs.
5014///
5015/// When there is no next word it returns the position PAST the last character
5016/// — not the last character itself. That looks like the bug it is next to and
5017/// is the opposite: an operator needs the exclusive end (`dw` on the final
5018/// word must delete the whole word), and it is the Normal-mode cursor that
5019/// must not sit there. So the clamp lives in [`EditorState::set_cursor`],
5020/// which knows the mode, and this stays a pure range endpoint.
5021fn word_next(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5022    let mut line = pos.line;
5023    let mut chars = line_chars(buf, line);
5024    let mut col = (pos.column as usize).min(chars.len());
5025
5026    // Leave the run the cursor is standing in. Starting on a blank skips this
5027    // — there is no run to leave, only blanks to cross.
5028    if col < chars.len() {
5029        let start = class_at(chars[col], width);
5030        if start != WordClass::Space {
5031            while col < chars.len() && class_at(chars[col], width) == start {
5032                col += 1;
5033            }
5034        }
5035    }
5036
5037    loop {
5038        while col < chars.len() && class_at(chars[col], width) == WordClass::Space {
5039            col += 1;
5040        }
5041        if col < chars.len() {
5042            return Position::new(line, u32::try_from(col).unwrap_or(pos.column));
5043        }
5044        if line >= last_text_line(buf) {
5045            // Out of text: the exclusive end of the last word.
5046            return Position::new(line, u32::try_from(chars.len()).unwrap_or(pos.column));
5047        }
5048        line += 1;
5049        col = 0;
5050        chars = line_chars(buf, line);
5051        if chars.is_empty() {
5052            return Position::new(line, 0);
5053        }
5054    }
5055}
5056
5057/// `b` — back to the start of the current or previous word.
5058///
5059/// Class-aware like [`word_next`], so `b` and `w` agree on where a word
5060/// begins; a disagreement between them is felt as `dw` and `db` deleting
5061/// different things from the same spot.
5062///
5063/// Single-line, and that is load-bearing: `<C-w>` reaches back over this
5064/// motion and relies on it returning the cursor UNCHANGED at column 0, which
5065/// is what makes the insert-mode erase fall through to `delete_before_cursor`
5066/// and join with the line above. Teaching this to cross lines would silently
5067/// change that key.
5068fn word_prev(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5069    let chars = line_chars(buf, pos.line);
5070    let mut i = (pos.column as usize).min(chars.len());
5071    while i > 0 && class_at(chars[i - 1], width) == WordClass::Space {
5072        i -= 1;
5073    }
5074    if i > 0 {
5075        let run = class_at(chars[i - 1], width);
5076        while i > 0 && class_at(chars[i - 1], width) == run {
5077            i -= 1;
5078        }
5079    }
5080    Position::new(pos.line, u32::try_from(i).unwrap_or(0))
5081}
5082
5083/// `ge` / `gE` — back to the LAST character of the previous word.
5084///
5085/// The mirror of [`word_end`], and INCLUSIVE like it: `dge` deletes through
5086/// the character it lands on. Single-line for the same reason [`word_prev`]
5087/// is — the backward scanners are what the insert-mode erases stand on, and
5088/// teaching them to cross lines changes those keys silently.
5089fn word_end_prev(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5090    let chars = line_chars(buf, pos.line);
5091    let start = (pos.column as usize).min(chars.len());
5092    // `ge` always retreats at least one character before it starts looking,
5093    // so standing on the last character of a word does not stand still.
5094    let Some(mut i) = start.checked_sub(1) else {
5095        return pos;
5096    };
5097    // Leave the run the cursor is standing in FIRST. Without this, `ge` from
5098    // the middle (or the end) of a word lands one character to its left —
5099    // inside the same word, which is the one place `ge` must never stop.
5100    if let Some(&here) = chars.get(start) {
5101        let run = class_at(here, width);
5102        if run != WordClass::Space {
5103            while i > 0 && class_at(chars[i], width) == run {
5104                i -= 1;
5105            }
5106        }
5107    }
5108    while i > 0 && class_at(chars[i], width) == WordClass::Space {
5109        i -= 1;
5110    }
5111    Position::new(pos.line, u32::try_from(i).unwrap_or(0))
5112}
5113
5114/// `e` — to the LAST character of the current or next word.
5115///
5116/// Always moves, which is what separates it from "the end of this word": on
5117/// the last character of a word, `e` goes to the last character of the NEXT
5118/// one rather than standing still.
5119///
5120/// This motion is INCLUSIVE — it names a character to act on, not a boundary
5121/// to stop before — see [`Motion::is_inclusive`]. `WordEndNext` used to
5122/// resolve through [`word_next`], so `e` and `w` were the same key with two
5123/// names.
5124fn word_end(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5125    let mut line = pos.line;
5126    let mut chars = line_chars(buf, line);
5127    // `e` always advances at least one character before it starts looking.
5128    let mut col = (pos.column as usize).saturating_add(1);
5129
5130    loop {
5131        while col < chars.len() && class_at(chars[col], width) == WordClass::Space {
5132            col += 1;
5133        }
5134        if col < chars.len() {
5135            break;
5136        }
5137        if line >= last_text_line(buf) {
5138            return buffer_end(buf);
5139        }
5140        line += 1;
5141        col = 0;
5142        chars = line_chars(buf, line);
5143    }
5144
5145    let run = class_at(chars[col], width);
5146    while col + 1 < chars.len() && class_at(chars[col + 1], width) == run {
5147        col += 1;
5148    }
5149    Position::new(line, u32::try_from(col).unwrap_or(pos.column))
5150}
5151
5152/// `f` / `F` / `t` / `T` — the character search, resolved on ONE line.
5153///
5154/// vim's character search never crosses a line, which is what makes it safe
5155/// to compose with an operator: `df;` can only ever delete within the line.
5156/// `None` when the character is not there — the motion fails and the operator
5157/// aborts with the buffer untouched, rather than deleting to the line edge.
5158fn find_char(
5159    buf: &escriba_buffer::Buffer,
5160    pos: Position,
5161    ch: char,
5162    backward: bool,
5163    till: bool,
5164) -> Option<Position> {
5165    let chars = line_chars(buf, pos.line);
5166    let cur = (pos.column as usize).min(chars.len());
5167    let hit = if backward {
5168        // `T` stops AFTER the character, so it has to start one further back
5169        // or a repeated `T` would never leave the spot it already reached.
5170        let from = if till { cur.checked_sub(1)? } else { cur };
5171        (0..from).rev().find(|&i| chars[i] == ch)?
5172    } else {
5173        let from = if till { cur.saturating_add(2) } else { cur + 1 };
5174        (from.min(chars.len())..chars.len()).find(|&i| chars[i] == ch)?
5175    };
5176    let col = match (backward, till) {
5177        (false, true) => hit - 1,
5178        (true, true) => hit + 1,
5179        _ => hit,
5180    };
5181    Some(Position::new(pos.line, u32::try_from(col).ok()?))
5182}
5183
5184/// The four bracket pairs `%` knows.
5185const MATCH_PAIRS: [(char, char); 4] = [('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')];
5186
5187/// A language's WORD pairs for `%` — vim's `matchit`, typed.
5188///
5189/// `(open, middles, close)`. A middle (`else`, `elif`, `when`) is a word `%`
5190/// steps THROUGH on its way round the group; without them `%` on a shell `if`
5191/// jumps straight past `elif` to `fi`, which is right for a scanner and wrong
5192/// for a reader.
5193///
5194/// A TABLE keyed by filetype name, not a per-language scanner: every entry is
5195/// the same depth-counting walk over a different word list, so a new language
5196/// is a row. Deliberately small — these are the languages whose blocks are
5197/// words rather than braces, which is exactly the set where bracket-only `%`
5198/// is useless.
5199type WordPairs = &'static [(&'static str, &'static [&'static str], &'static str)];
5200
5201const WORD_PAIRS: &[(&str, WordPairs)] = &[
5202    (
5203        "lua",
5204        &[
5205            ("if", &["elseif", "else"], "end"),
5206            ("for", &[], "end"),
5207            ("while", &[], "end"),
5208            ("function", &[], "end"),
5209            ("do", &[], "end"),
5210            ("repeat", &[], "until"),
5211        ],
5212    ),
5213    (
5214        "ruby",
5215        &[
5216            ("if", &["elsif", "else"], "end"),
5217            ("unless", &["else"], "end"),
5218            ("case", &["when", "else"], "end"),
5219            ("begin", &["rescue", "ensure", "else"], "end"),
5220            ("def", &[], "end"),
5221            ("class", &[], "end"),
5222            ("module", &[], "end"),
5223            ("do", &[], "end"),
5224            ("while", &[], "end"),
5225        ],
5226    ),
5227    (
5228        "sh",
5229        &[
5230            ("if", &["elif", "else"], "fi"),
5231            ("case", &[], "esac"),
5232            ("do", &[], "done"),
5233        ],
5234    ),
5235    (
5236        "bash",
5237        &[
5238            ("if", &["elif", "else"], "fi"),
5239            ("case", &[], "esac"),
5240            ("do", &[], "done"),
5241        ],
5242    ),
5243    (
5244        "elixir",
5245        &[
5246            ("do", &["else", "rescue", "after", "catch"], "end"),
5247            ("fn", &[], "end"),
5248        ],
5249    ),
5250    (
5251        "vim",
5252        &[
5253            ("if", &["elseif", "else"], "endif"),
5254            ("function", &[], "endfunction"),
5255            ("while", &[], "endwhile"),
5256            ("for", &[], "endfor"),
5257            ("try", &["catch", "finally"], "endtry"),
5258        ],
5259    ),
5260];
5261
5262/// A word occurrence: its position, and which group + role it plays.
5263#[derive(Clone, Copy)]
5264struct WordHit {
5265    line: u32,
5266    col: u32,
5267    end: u32,
5268    group: usize,
5269    /// `0` = opener, `1` = middle, `2` = closer.
5270    role: u8,
5271}
5272
5273/// `%` — to the match of the bracket under the cursor, or of the first
5274/// bracket to its right on the same line (vim scans forward to find one).
5275///
5276/// Depth-counting and buffer-wide, because a brace pair that fits on one line
5277/// is the case `%` is least needed for.
5278fn match_pair(buf: &escriba_buffer::Buffer, pos: Position) -> Option<Position> {
5279    let chars = line_chars(buf, pos.line);
5280    let start = (pos.column as usize).min(chars.len());
5281    let (col, open, close, forward) = (start..chars.len()).find_map(|i| {
5282        MATCH_PAIRS.iter().find_map(|&(o, c)| {
5283            if chars[i] == o {
5284                Some((i, o, c, true))
5285            } else if chars[i] == c {
5286                Some((i, o, c, false))
5287            } else {
5288                None
5289            }
5290        })
5291    })?;
5292
5293    let last = buf.line_count().saturating_sub(1);
5294    let mut depth = 0i32;
5295    let (mut line, mut i) = (pos.line, col);
5296    let mut text = chars;
5297    loop {
5298        let c = text[i];
5299        if c == open {
5300            depth += if forward { 1 } else { -1 };
5301        } else if c == close {
5302            depth += if forward { -1 } else { 1 };
5303        }
5304        if depth == 0 {
5305            return Some(Position::new(line, u32::try_from(i).ok()?));
5306        }
5307        if forward {
5308            i += 1;
5309            while i >= text.len() {
5310                if line >= last {
5311                    return None;
5312                }
5313                line += 1;
5314                text = line_chars(buf, line);
5315                i = 0;
5316            }
5317        } else {
5318            while i == 0 {
5319                if line == 0 {
5320                    return None;
5321                }
5322                line -= 1;
5323                text = line_chars(buf, line);
5324                i = text.len();
5325            }
5326            i -= 1;
5327        }
5328    }
5329}
5330
5331/// Every word-pair keyword on `line`, in column order.
5332///
5333/// Word-bounded on both sides, so `endif` is not read as `end`, `define` is
5334/// not read as `def`, and a `do` inside `window` is not a block opener. That
5335/// boundary check is the whole difference between matchit and a substring
5336/// search, and skipping it is worse than having no word pairs at all — a `%`
5337/// that jumps to the middle of an identifier is a silent wrong answer.
5338fn word_hits(buf: &escriba_buffer::Buffer, line: u32, pairs: WordPairs) -> Vec<WordHit> {
5339    let chars = line_chars(buf, line);
5340    let mut out = Vec::new();
5341    let mut i = 0usize;
5342    while i < chars.len() {
5343        if word_class(chars[i]) != WordClass::Word {
5344            i += 1;
5345            continue;
5346        }
5347        let start = i;
5348        while i < chars.len() && word_class(chars[i]) == WordClass::Word {
5349            i += 1;
5350        }
5351        let word: String = chars[start..i].iter().collect();
5352        for (group, (open, middles, close)) in pairs.iter().enumerate() {
5353            let role = if word == *open {
5354                0
5355            } else if word == *close {
5356                2
5357            } else if middles.contains(&word.as_str()) {
5358                1
5359            } else {
5360                continue;
5361            };
5362            out.push(WordHit {
5363                line,
5364                col: u32::try_from(start).unwrap_or(0),
5365                end: u32::try_from(i).unwrap_or(0),
5366                group,
5367                role,
5368            });
5369            break;
5370        }
5371    }
5372    out
5373}
5374
5375/// `%` over WORD pairs — matchit's half of the motion.
5376///
5377/// Finds the keyword at (or right of) the cursor and walks to the next member
5378/// of its group at the same depth: opener → first middle → … → closer →
5379/// opener. Cycling rather than jumping straight to the closer is what makes
5380/// `%` usable for reading an `if`/`elif`/`else`/`fi` chain.
5381fn match_word_pair(
5382    buf: &escriba_buffer::Buffer,
5383    pos: Position,
5384    pairs: WordPairs,
5385) -> Option<Position> {
5386    let here = word_hits(buf, pos.line, pairs)
5387        .into_iter()
5388        .find(|h| h.end > pos.column)?;
5389    let last = last_text_line(buf);
5390    let forward = here.role != 2;
5391    let mut depth = 0i32;
5392    let mut line = here.line;
5393    loop {
5394        let hits = word_hits(buf, line, pairs);
5395        // Only the hits strictly beyond the starting keyword on its own line.
5396        let scan: Vec<WordHit> = if line == here.line {
5397            let mut v: Vec<WordHit> = hits
5398                .into_iter()
5399                .filter(|h| {
5400                    if forward {
5401                        h.col > here.col
5402                    } else {
5403                        h.col < here.col
5404                    }
5405                })
5406                .collect();
5407            if !forward {
5408                v.reverse();
5409            }
5410            v
5411        } else {
5412            let mut v = hits;
5413            if !forward {
5414                v.reverse();
5415            }
5416            v
5417        };
5418        for h in scan {
5419            if h.group != here.group {
5420                continue;
5421            }
5422            match (h.role, forward) {
5423                (0, true) | (2, false) => depth += 1,
5424                (2, true) | (0, false) => {
5425                    if depth == 0 {
5426                        return Some(Position::new(h.line, h.col));
5427                    }
5428                    depth -= 1;
5429                }
5430                // A middle at the SAME depth is the next stop; nested ones are
5431                // somebody else's `else`.
5432                (1, _) if depth == 0 => return Some(Position::new(h.line, h.col)),
5433                _ => {}
5434            }
5435        }
5436        if forward {
5437            if line >= last {
5438                return None;
5439            }
5440            line += 1;
5441        } else {
5442            if line == 0 {
5443                return None;
5444            }
5445            line -= 1;
5446        }
5447    }
5448}
5449
5450/// `{` / `}` — to the nearest blank line in `dir`, or the buffer edge.
5451///
5452/// vim's paragraph boundary is an EMPTY line, not an indentation change; a
5453/// line of spaces is not one. `line_len_chars` already excludes the
5454/// terminator, so "empty" is exactly `len == 0`.
5455fn paragraph(buf: &escriba_buffer::Buffer, pos: Position, forward: bool) -> Position {
5456    let last = last_text_line(buf);
5457    let mut line = pos.line;
5458    loop {
5459        if forward {
5460            if line >= last {
5461                return buffer_end(buf);
5462            }
5463            line += 1;
5464        } else {
5465            if line == 0 {
5466                return Position::ZERO;
5467            }
5468            line -= 1;
5469        }
5470        if buf.line_len_chars(line) == 0 {
5471            return Position::new(line, 0);
5472        }
5473    }
5474}
5475
5476/// `(` / `)` — to the start of the adjacent sentence.
5477///
5478/// A sentence ends at `.`/`!`/`?` followed by whitespace or end-of-line; the
5479/// next one starts at the following non-blank. A paragraph boundary is also a
5480/// sentence boundary, which is what stops `)` at the end of a block of prose
5481/// instead of sailing into the next one.
5482fn sentence(buf: &escriba_buffer::Buffer, pos: Position, forward: bool) -> Position {
5483    let starts = sentence_starts(buf);
5484    let here = (pos.line, pos.column);
5485    if forward {
5486        starts
5487            .iter()
5488            .find(|&&(l, c)| (l, c) > here)
5489            .map_or_else(|| buffer_end(buf), |&(l, c)| Position::new(l, c))
5490    } else {
5491        starts
5492            .iter()
5493            .rev()
5494            .find(|&&(l, c)| (l, c) < here)
5495            .map_or(Position::ZERO, |&(l, c)| Position::new(l, c))
5496    }
5497}
5498
5499/// Every sentence start in the buffer, in order.
5500///
5501/// Computed wholesale rather than scanned directionally: the backward and
5502/// forward cases are then the same list read two ways, so `(` and `)` cannot
5503/// disagree about where a sentence begins.
5504fn sentence_starts(buf: &escriba_buffer::Buffer) -> Vec<(u32, u32)> {
5505    let mut out = vec![(0u32, 0u32)];
5506    let mut ended = false;
5507    for line in 0..=last_text_line(buf) {
5508        let chars = line_chars(buf, line);
5509        if chars.is_empty() {
5510            // A blank line is a paragraph break, and so a sentence break.
5511            out.push((line, 0));
5512            ended = false;
5513            continue;
5514        }
5515        for (i, &c) in chars.iter().enumerate() {
5516            if ended && !c.is_whitespace() {
5517                out.push((line, u32::try_from(i).unwrap_or(0)));
5518                ended = false;
5519            }
5520            if matches!(c, '.' | '!' | '?') {
5521                ended = true;
5522            } else if !matches!(c, ')' | ']' | '"' | '\'') && !c.is_whitespace() {
5523                ended = false;
5524            }
5525        }
5526    }
5527    out.sort_unstable();
5528    out.dedup();
5529    out
5530}
5531
5532#[cfg(test)]
5533mod tests {
5534    use super::*;
5535    use madori::event::{KeyCode, KeyEvent, Modifiers};
5536
5537    // ── search wiring (escriba-search integration) ────────────────────
5538    //
5539    // The engine is proven in escriba-search's own 61 tests. These prove the
5540    // WIRING: that keys reach it, that the cursor lands where it says, and
5541    // that a search prompt and an ex-command can share Command mode without
5542    // being confused for one another.
5543
5544    fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
5545        st.apply(&Action::SearchOpen(dir));
5546        for c in pat.chars() {
5547            st.apply(&Action::InsertChar(c));
5548        }
5549        st.apply(&Action::SubmitCommand);
5550    }
5551
5552    #[test]
5553    fn slash_search_moves_the_cursor_to_the_match() {
5554        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
5555        type_search(&mut st, SearchDirection::Forward, "charlie");
5556        assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
5557        assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
5558        assert_eq!(st.search.matches().len(), 1);
5559    }
5560
5561    #[test]
5562    // `N` is a DIFFERENT vim key from `n` — see escriba-search.
5563    #[allow(non_snake_case)]
5564    fn n_and_N_walk_matches_in_both_directions() {
5565        let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
5566        type_search(&mut st, SearchDirection::Forward, "foo");
5567        let first = st.cursor().line;
5568        st.apply(&Action::SearchRepeat { reverse: false });
5569        let second = st.cursor().line;
5570        assert!(second > first, "n advances ({first} -> {second})");
5571        st.apply(&Action::SearchRepeat { reverse: true });
5572        assert_eq!(st.cursor().line, first, "N comes back");
5573    }
5574
5575    #[test]
5576    fn star_searches_the_word_under_the_cursor() {
5577        let mut st = new_state_with("needle\nhaystack\nneedle\n");
5578        st.apply(&Action::SearchWord { reverse: false });
5579        assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
5580        assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
5581    }
5582
5583    #[test]
5584    fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
5585        let mut st = new_state_with("foo\nbar\nfoo\n");
5586        type_search(&mut st, SearchDirection::Forward, "foo");
5587        let matches_before = st.search.matches().len();
5588
5589        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5590        st.apply(&Action::InsertChar('z'));
5591        st.apply(&Action::ChangeMode(Mode::Normal));
5592
5593        assert!(!st.search.is_prompting(), "prompt gone");
5594        assert_eq!(
5595            st.search.pattern().unwrap().raw(),
5596            "foo",
5597            "old pattern survives"
5598        );
5599        assert_eq!(
5600            st.search.matches().len(),
5601            matches_before,
5602            "old highlights survive"
5603        );
5604    }
5605
5606    #[test]
5607    fn a_search_prompt_and_an_ex_command_are_not_confused() {
5608        let mut st = new_state_with("foo\n");
5609        // No `/` pressed: Command mode belongs to the ex-command line.
5610        st.apply(&Action::ChangeMode(Mode::Command));
5611        assert!(!st.search.is_prompting(), "`:` must not open a search");
5612        st.apply(&Action::InsertChar('w'));
5613        assert!(
5614            st.search.prompt().is_none(),
5615            "typed char went to the ex line"
5616        );
5617    }
5618
5619    #[test]
5620    fn a_missing_pattern_reports_instead_of_failing_silently() {
5621        let mut st = new_state_with("alpha\nbravo\n");
5622        type_search(&mut st, SearchDirection::Forward, "zzz");
5623        assert!(
5624            st.messages.iter().any(|m| m.contains("E486")),
5625            "must report not-found, got {:?}",
5626            st.messages
5627        );
5628    }
5629
5630    #[test]
5631    fn n_without_any_search_reports_rather_than_moving() {
5632        let mut st = new_state_with("alpha\nbravo\n");
5633        let before = st.cursor();
5634        st.apply(&Action::SearchRepeat { reverse: false });
5635        assert_eq!(st.cursor(), before, "cursor must not move");
5636        assert!(
5637            st.messages.iter().any(|m| m.contains("E35")),
5638            "got {:?}",
5639            st.messages
5640        );
5641    }
5642
5643    #[test]
5644    fn search_as_a_motion_composes_with_an_operator() {
5645        // The point of Motion::SearchNext: `d` + search deletes to the match.
5646        let mut st = new_state_with("alpha bravo charlie\n");
5647        type_search(&mut st, SearchDirection::Forward, "charlie");
5648        st.set_cursor(Position::new(0, 0));
5649        let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
5650        assert!(target.is_some(), "search must resolve as a motion");
5651        assert_eq!(target.unwrap().column, 12, "at `charlie`");
5652    }
5653
5654    #[test]
5655    fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
5656        // A silent fallback to offset 0 would make `d` + search delete to the
5657        // start of the file — the worst possible failure for an operator.
5658        let st = new_state_with("alpha bravo\n");
5659        assert!(
5660            st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
5661                .is_none()
5662        );
5663    }
5664
5665    #[test]
5666    fn clear_highlight_keeps_the_pattern_usable() {
5667        let mut st = new_state_with("foo\nbar\nfoo\n");
5668        type_search(&mut st, SearchDirection::Forward, "foo");
5669        st.apply(&Action::ClearSearchHighlight);
5670        assert!(st.search.highlights().is_empty(), "nothing lit");
5671        st.apply(&Action::SearchRepeat { reverse: false });
5672        assert!(st.search.pattern().is_some(), "but n still works");
5673    }
5674
5675    #[test]
5676    fn typing_previews_incrementally_before_commit() {
5677        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
5678        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5679        for c in "charlie".chars() {
5680            st.apply(&Action::InsertChar(c));
5681        }
5682        // incsearch: the cursor has already moved, with nothing committed.
5683        assert_eq!(st.cursor().line, 2, "preview moved the cursor");
5684        assert!(st.search.pattern().is_none(), "but nothing is committed");
5685    }
5686
5687    #[test]
5688    fn backspace_corrects_the_prompt_and_reruns_the_preview() {
5689        let mut st = new_state_with("alpha\nbravo\n");
5690        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5691        for c in "bravox".chars() {
5692            st.apply(&Action::InsertChar(c));
5693        }
5694        assert_eq!(st.search.prompt().unwrap().text(), "bravox");
5695        st.apply(&Action::Backspace);
5696        assert_eq!(
5697            st.search.prompt().unwrap().text(),
5698            "bravo",
5699            "typo corrected"
5700        );
5701        assert_eq!(
5702            st.status_model().prompt_text,
5703            "bravo",
5704            "the model reads the PROMPT — the minibuffer is the ex-line's store",
5705        );
5706        assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
5707    }
5708
5709    #[test]
5710    fn backspacing_past_the_slash_closes_the_prompt() {
5711        let mut st = new_state_with("alpha\n");
5712        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5713        st.apply(&Action::InsertChar('a'));
5714        st.apply(&Action::Backspace);
5715        st.apply(&Action::Backspace);
5716        assert!(!st.search.is_prompting(), "prompt closed");
5717        assert_eq!(st.modal.mode(), Mode::Normal);
5718    }
5719
5720    #[test]
5721    fn noh_clears_highlights_and_keeps_the_pattern() {
5722        let mut st = new_state_with("foo\nbar\nfoo\n");
5723        type_search(&mut st, SearchDirection::Forward, "foo");
5724        assert!(!st.search.highlights().is_empty());
5725        st.run_command("noh", &[]);
5726        assert!(st.search.highlights().is_empty(), ":noh turns them off");
5727        assert!(st.search.pattern().is_some(), "but n still works");
5728    }
5729
5730    #[test]
5731    fn noh_accepts_the_vim_aliases() {
5732        for name in ["noh", "nohl", "nohlsearch"] {
5733            let mut st = new_state_with("foo\nfoo\n");
5734            type_search(&mut st, SearchDirection::Forward, "foo");
5735            st.run_command(name, &[]);
5736            assert!(st.search.highlights().is_empty(), "{name} must clear");
5737        }
5738    }
5739
5740    #[test]
5741    fn backspace_on_the_ex_line_does_not_touch_search_state() {
5742        let mut st = new_state_with("foo\n");
5743        st.apply(&Action::ChangeMode(Mode::Command));
5744        st.apply(&Action::InsertChar('w'));
5745        st.apply(&Action::InsertChar('q'));
5746        st.apply(&Action::Backspace);
5747        assert_eq!(st.status_model().prompt_text, "w");
5748        assert!(st.search.prompt().is_none(), "no search was involved");
5749    }
5750
5751    #[test]
5752    fn up_arrow_recalls_the_previous_search() {
5753        let mut st = new_state_with("alpha\nbravo\n");
5754        type_search(&mut st, SearchDirection::Forward, "bravo");
5755        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5756        st.apply(&Action::PromptHistory { back: true });
5757        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
5758        assert_eq!(
5759            st.status_model().prompt_text,
5760            "bravo",
5761            "display follows the prompt"
5762        );
5763    }
5764
5765    #[test]
5766    fn arrowing_back_down_restores_the_half_typed_pattern() {
5767        let mut st = new_state_with("alpha\nbravo\n");
5768        type_search(&mut st, SearchDirection::Forward, "bravo");
5769        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5770        st.apply(&Action::InsertChar('a'));
5771        st.apply(&Action::PromptHistory { back: true });
5772        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
5773        st.apply(&Action::PromptHistory { back: false });
5774        assert_eq!(
5775            st.search.prompt().unwrap().text(),
5776            "a",
5777            "the draft comes back"
5778        );
5779        assert_eq!(st.status_model().prompt_text, "a");
5780    }
5781
5782    #[test]
5783    fn history_arrows_do_nothing_on_the_ex_line() {
5784        let mut st = new_state_with("alpha\n");
5785        st.apply(&Action::ChangeMode(Mode::Command));
5786        st.apply(&Action::InsertChar('w'));
5787        st.apply(&Action::PromptHistory { back: true });
5788        assert_eq!(st.status_model().prompt_text, "w", "ex line untouched");
5789    }
5790
5791    // ── trouble.* — the findings view ────────────────────────────────
5792    //
5793    // These assert on the ROWS the picker would be built from, not on the
5794    // registry: the registry is already tested, and what could be wrong
5795    // here is the projection — scoping, freshness, and whether a row goes
5796    // anywhere when pressed.
5797
5798    fn finding_at(buffer: BufferId, line: u32, msg: &str) -> escriba_shirube::Finding {
5799        use escriba_core::{Position, Range};
5800        escriba_shirube::Finding::new(
5801            escriba_shirube::Site::in_buffer(
5802                buffer,
5803                Range::new(Position::new(line, 0), Position::new(line, 1)),
5804            ),
5805            escriba_shirube::Severity::Error,
5806            msg.to_string(),
5807            escriba_shirube::Origin::Text("test"),
5808        )
5809    }
5810
5811    #[test]
5812    fn published_findings_become_picker_rows() {
5813        let mut st = new_state_with("a\nb\nc\n");
5814        let world = st.world();
5815        st.results.publish(
5816            "test",
5817            escriba_shirube::ResultList::new(vec![finding_at(st.active, 1, "boom")], world),
5818        );
5819        let rows = st.finding_items(true, None);
5820        assert_eq!(rows.len(), 1, "the published finding produces a row");
5821        // The row must SAY something an operator can act on: severity,
5822        // 1-based line, and the message.
5823        let label = &rows[0].label;
5824        assert!(label.contains("ERROR"), "{label}");
5825        assert!(label.contains(":2"), "lines are 1-based on screen: {label}");
5826        assert!(label.contains("boom"), "{label}");
5827    }
5828
5829    #[test]
5830    fn a_stale_list_contributes_no_rows() {
5831        // THE load-bearing one. A list anchored to a revision the buffer has
5832        // moved past must vanish from the view rather than offer a line that
5833        // has since shifted — which is the whole reason findings carry an
5834        // anchor instead of just a position.
5835        let mut st = new_state_with("a\nb\nc\n");
5836        let world = st.world();
5837        st.results.publish(
5838            "test",
5839            escriba_shirube::ResultList::new(vec![finding_at(st.active, 1, "boom")], world),
5840        );
5841        assert_eq!(st.finding_items(true, None).len(), 1, "fresh to begin with");
5842
5843        st.apply(&Action::InsertChar('x'));
5844        assert!(
5845            st.finding_items(true, None).is_empty(),
5846            "an edit moved the text on; the list is stale and must not be shown"
5847        );
5848    }
5849
5850    #[test]
5851    fn document_scope_excludes_another_buffer() {
5852        // `trouble.document` vs `trouble.workspace` is one bool, so this is
5853        // the only thing that can distinguish them.
5854        let mut st = new_state_with("a\nb\n");
5855        let other = st.buffers.scratch("z\n");
5856        let world = st.world();
5857        st.results.publish(
5858            "test",
5859            escriba_shirube::ResultList::new(
5860                vec![
5861                    finding_at(st.active, 0, "mine"),
5862                    finding_at(other, 0, "theirs"),
5863                ],
5864                world,
5865            ),
5866        );
5867        let ws = st.finding_items(true, None);
5868        assert_eq!(ws.len(), 2, "workspace scope shows both");
5869        let doc = st.finding_items(false, None);
5870        assert_eq!(doc.len(), 1, "document scope shows only the active buffer");
5871        assert!(doc[0].label.contains("mine"), "{}", doc[0].label);
5872    }
5873
5874    #[test]
5875    fn files_under_a_root_produces_rows() {
5876        // `files.open-parent` differs from `files.open` only in the root, so
5877        // what must hold is that a root is actually honoured.
5878        let mut st = new_state_with("");
5879        let rows = st.file_items(std::path::Path::new("."));
5880        assert!(!rows.is_empty(), "the working directory has files");
5881    }
5882
5883    // ── vim text objects ─────────────────────────────────────────────
5884    //
5885    // Asserted through `apply` on real buffer text, so a wrong RANGE shows
5886    // up as wrong text rather than as a range that merely looks plausible.
5887
5888    fn after(text: &str, line: u32, col: u32, act: Action) -> String {
5889        let mut st = new_state_with(text);
5890        st.set_cursor(Position::new(line, col));
5891        st.apply(&act);
5892        st.buffers
5893            .get(st.active)
5894            .map(|b| b.to_string())
5895            .unwrap_or_default()
5896    }
5897
5898    fn del_obj(o: escriba_core::TextObject) -> Action {
5899        Action::ApplyOperatorObject {
5900            op: escriba_core::Operator::Delete,
5901            object: o,
5902        }
5903    }
5904
5905    #[test]
5906    fn dd_removes_the_line_not_just_its_contents() {
5907        // The distinction the newline makes: without it, `dd` blanks a line
5908        // and leaves it behind.
5909        let got = after("a\nb\nc\n", 1, 0, del_obj(escriba_core::TextObject::Line));
5910        assert_eq!(got, "a\nc\n");
5911    }
5912
5913    #[test]
5914    fn dd_on_the_last_line_leaves_no_blank_behind() {
5915        // The case a naive start-of-line..start-of-next range gets wrong:
5916        // there is no following newline to take, so it must take the
5917        // preceding one.
5918        let got = after("a\nb\nc\n", 2, 0, del_obj(escriba_core::TextObject::Line));
5919        assert_eq!(got, "a\nb\n", "no trailing empty line: {got:?}");
5920    }
5921
5922    #[test]
5923    fn dd_on_the_only_line_clears_it_but_keeps_the_line() {
5924        let got = after("solo\n", 0, 2, del_obj(escriba_core::TextObject::Line));
5925        assert!(got.starts_with('\n') || got.is_empty(), "{got:?}");
5926    }
5927
5928    #[test]
5929    fn diw_takes_the_word_and_daw_takes_its_trailing_space() {
5930        let inner = after(
5931            "one two three\n",
5932            0,
5933            5,
5934            del_obj(escriba_core::TextObject::Word { around: false }),
5935        );
5936        assert_eq!(inner, "one  three\n", "iw leaves both spaces");
5937        let around = after(
5938            "one two three\n",
5939            0,
5940            5,
5941            del_obj(escriba_core::TextObject::Word { around: true }),
5942        );
5943        assert_eq!(around, "one three\n", "aw takes the trailing space");
5944    }
5945
5946    #[test]
5947    fn iw_from_any_column_inside_the_word_takes_the_whole_word() {
5948        for col in 4..=6 {
5949            let got = after(
5950                "one two three\n",
5951                0,
5952                col,
5953                del_obj(escriba_core::TextObject::Word { around: false }),
5954            );
5955            assert_eq!(got, "one  three\n", "from column {col}");
5956        }
5957    }
5958
5959    #[test]
5960    fn iw_on_punctuation_takes_the_punctuation_run() {
5961        // vim's three classes: word / punctuation / whitespace. A `::` is a
5962        // run of punctuation, not part of either identifier.
5963        let got = after(
5964            "foo::bar\n",
5965            0,
5966            3,
5967            del_obj(escriba_core::TextObject::Word { around: false }),
5968        );
5969        assert_eq!(got, "foobar\n");
5970    }
5971
5972    #[test]
5973    fn i_paren_takes_the_inside_and_a_paren_takes_the_brackets_too() {
5974        let inner = after(
5975            "f(a, b)\n",
5976            0,
5977            3,
5978            del_obj(escriba_core::TextObject::Delimited {
5979                open: '(',
5980                close: ')',
5981                around: false,
5982            }),
5983        );
5984        assert_eq!(inner, "f()\n");
5985        let around = after(
5986            "f(a, b)\n",
5987            0,
5988            3,
5989            del_obj(escriba_core::TextObject::Delimited {
5990                open: '(',
5991                close: ')',
5992                around: true,
5993            }),
5994        );
5995        assert_eq!(around, "f\n");
5996    }
5997
5998    #[test]
5999    fn nested_brackets_resolve_to_the_enclosing_pair() {
6000        // THE reason the bracket scan counts depth: an inner pair must not
6001        // terminate the search for the one the cursor is actually inside.
6002        let got = after(
6003            "f(g(x), y)\n",
6004            0,
6005            8,
6006            del_obj(escriba_core::TextObject::Delimited {
6007                open: '(',
6008                close: ')',
6009                around: false,
6010            }),
6011        );
6012        assert_eq!(got, "f()\n", "took the outer pair");
6013    }
6014
6015    #[test]
6016    fn quotes_do_not_nest_so_the_nearest_pair_wins() {
6017        let got = after(
6018            r#"say "hi there" ok"#,
6019            0,
6020            7,
6021            del_obj(escriba_core::TextObject::Delimited {
6022                open: '"',
6023                close: '"',
6024                around: false,
6025            }),
6026        );
6027        assert_eq!(got, "say \"\" ok");
6028    }
6029
6030    #[test]
6031    fn an_unmatched_delimiter_resolves_to_nothing_rather_than_guessing() {
6032        let mut st = new_state_with("f(a, b\n");
6033        st.set_cursor(Position::new(0, 3));
6034        let before = st
6035            .buffers
6036            .get(st.active)
6037            .map(|b| b.to_string())
6038            .unwrap_or_default();
6039        st.apply(&del_obj(escriba_core::TextObject::Delimited {
6040            open: '(',
6041            close: ')',
6042            around: false,
6043        }));
6044        let got_after = st
6045            .buffers
6046            .get(st.active)
6047            .map(|b| b.to_string())
6048            .unwrap_or_default();
6049        assert_eq!(got_after, before, "no closing bracket: change nothing");
6050    }
6051
6052    fn new_state_with(text: &str) -> EditorState {
6053        let mut bufs = BufferSet::new();
6054        let id = bufs.scratch(text);
6055        EditorState::new_with_buffer(bufs, id)
6056    }
6057
6058    /// A breakpoint toggle reaches the GPU face's rebuild gate.
6059    ///
6060    /// ## What this does and does not claim
6061    ///
6062    /// The GPU face is the only one that CACHES its gutter: it shapes a
6063    /// glyphon buffer and rebuilds it only when `s.edit_gen() != self.last_gen`
6064    /// (`escriba-render/src/gpu.rs:260`). Both testable faces repaint from
6065    /// scratch every draw, so no rendered-cells test can see this — measured
6066    /// 2026-08-12 by removing the bump and watching all eight breakpoint
6067    /// render tests stay green.
6068    ///
6069    /// The guarantee is STRUCTURAL, not local: [`EditorState::honour`] widens
6070    /// the damage and bumps the generation after every slip, so the property
6071    /// holds for `ToggleBreakpoint` the way it holds for the other thirty.
6072    /// This pins the INSTANCE, and says so rather than pretending to gate a
6073    /// line inside `toggle_breakpoint` — there is no such line, deliberately.
6074    ///
6075    /// RED RUN (2026-08-12): deleting `self.bump_gen()` from `honour` fails
6076    /// this (and much else, which is the honest shape of a structural
6077    /// guarantee). The evidence is the generation counter itself — the exact
6078    /// value the GPU gate compares — not a restatement of "was a method
6079    /// called".
6080    #[test]
6081    fn setting_a_breakpoint_repaints() {
6082        let mut s = new_state_with("alpha\nbravo\ncharlie\n");
6083        let before = s.edit_gen();
6084        s.run_command("dap.toggle-breakpoint", &[]);
6085        assert!(
6086            s.breakpoints().is_set(s.active, 0),
6087            "precondition: the toggle ran",
6088        );
6089        assert_ne!(
6090            s.edit_gen(),
6091            before,
6092            "the GPU face rebuilds its cached gutter ONLY on a generation \
6093             change — without this the mark never reaches that screen",
6094        );
6095        assert!(
6096            !s.damage().is_none(),
6097            "and a scoped-repaint face has to be told the viewport moved",
6098        );
6099    }
6100
6101    #[test]
6102    fn a_breakpoint_toggle_with_no_open_buffer_marks_nothing() {
6103        // A mark on a buffer that does not exist is one no future DAP client
6104        // could ever name, and the honest report is silence rather than a
6105        // confirmation of something that did not happen. `active` names no
6106        // open buffer here, which is the state a `--no-defaults` boot and a
6107        // just-closed buffer both pass through.
6108        let mut s = new_state_with("alpha\n");
6109        s.active = BufferId(9_999);
6110        s.run_command("dap.toggle-breakpoint", &[]);
6111        assert!(!s.breakpoints().is_set(s.active, 0), "nothing was marked");
6112        assert!(
6113            !s.messages.iter().any(|m| m.contains("breakpoint")),
6114            "and nothing was claimed: {:?}",
6115            s.messages,
6116        );
6117    }
6118
6119    /// The refresh-seal driver (theory/ESCRIBA.md §Refresh-Seal): an applied
6120    /// action advances `edit_gen` (so the renderer repaints), and merely
6121    /// reading the generation does not. This is what lets `gpu.rs` gate the
6122    /// re-highlight/re-shape on a generation change — an idle frame observes an
6123    /// unchanged generation and reuses its cached buffer.
6124    #[test]
6125    fn edit_gen_advances_on_applied_action_not_on_read() {
6126        let mut s = new_state_with("hello\nworld\n");
6127        let g0 = s.edit_gen();
6128        s.apply(&Action::InsertChar('X'));
6129        assert_ne!(
6130            s.edit_gen(),
6131            g0,
6132            "an applied action must advance the refresh generation",
6133        );
6134        // Reading the generation is not a mutation — idle frames stay put.
6135        let g1 = s.edit_gen();
6136        assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
6137    }
6138
6139    /// The M1 refresh node (theory/ESCRIBA.md §X): a mutation widens the typed
6140    /// `Damage` to cover exactly what changed — local for an in-place edit,
6141    /// to-end-of-document when the line count shifts — and the renderer drains
6142    /// it per frame. `Damage ⊇ changed` by construction; it never narrows.
6143    #[test]
6144    fn damage_tracks_edit_scope_and_drains() {
6145        let mut s = new_state_with("hello\nworld\n");
6146        assert!(s.damage().is_none(), "a fresh state has no damage");
6147
6148        s.apply(&Action::InsertChar('X')); // in-place edit on line 0
6149        assert_eq!(
6150            s.damage(),
6151            Damage::Lines { from: 0, to: 0 },
6152            "a local edit damages just its line",
6153        );
6154
6155        let drained = s.take_damage();
6156        assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
6157        assert!(s.damage().is_none(), "take_damage drains to None");
6158
6159        s.apply(&Action::InsertChar('\n')); // splits line 0 → line count grows
6160        assert_eq!(
6161            s.damage(),
6162            Damage::Lines {
6163                from: 0,
6164                to: u32::MAX,
6165            },
6166            "a line-count change damages to end-of-document",
6167        );
6168    }
6169
6170    /// A state whose active window is a deliberately tiny viewport
6171    /// (`visible_lines` × `visible_columns`) so the scroll-to-contain
6172    /// invariant is exercised on small inputs.
6173    fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
6174        let mut s = new_state_with(text);
6175        for w in s.layout.windows_mut() {
6176            w.viewport.visible_lines = vis_lines;
6177            w.viewport.visible_columns = vis_cols;
6178        }
6179        s
6180    }
6181
6182    /// The core regression invariant: the active window's viewport CONTAINS
6183    /// the cursor on BOTH axes. This is the operator's exact complaint —
6184    /// "typing past the bottom (or right) leaves the cursor off-screen" —
6185    /// made into a checkable property.
6186    fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
6187        let w = s.layout.active_window().expect("active window");
6188        let v = w.viewport;
6189        let c = s.cursor();
6190        assert!(
6191            v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
6192            "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
6193            c.line,
6194            v.top_line,
6195            v.top_line + v.visible_lines,
6196        );
6197        assert!(
6198            v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
6199            "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
6200            c.column,
6201            v.left_column,
6202            v.left_column + v.visible_columns,
6203        );
6204    }
6205
6206    /// `dd` from the KEYBOARD, not from a synthesized action.
6207    ///
6208    /// The FSM composition is unit-tested, but what an operator actually
6209    /// does is press `d` twice — and that path goes through the keymap and
6210    /// the sequence stepper, either of which could swallow the second `d`.
6211    #[test]
6212    fn pressing_d_twice_deletes_the_line() {
6213        let mut st = new_state_with("alpha\nbeta\ngamma\n");
6214        st.set_cursor(Position::new(1, 0));
6215        st.tick(&press(KeyCode::Char('d')));
6216        st.tick(&press(KeyCode::Char('d')));
6217        let got = st
6218            .buffers
6219            .get(st.active)
6220            .map(|b| b.to_string())
6221            .unwrap_or_default();
6222        assert_eq!(got, "alpha\ngamma\n", "dd from the keyboard");
6223    }
6224
6225    #[test]
6226    fn pressing_2_d_d_deletes_two_lines() {
6227        let mut st = new_state_with("a\nb\nc\nd\n");
6228        st.set_cursor(Position::new(0, 0));
6229        for k in ['2', 'd', 'd'] {
6230            st.tick(&press(KeyCode::Char(k)));
6231        }
6232        let got = st
6233            .buffers
6234            .get(st.active)
6235            .map(|b| b.to_string())
6236            .unwrap_or_default();
6237        assert_eq!(got, "c\nd\n", "count applies to the doubled operator");
6238    }
6239
6240    // ── The insert-entry family: `i` `I` `a` `A` `o` `O` ─────────────────
6241    //
6242    // Measured before the family existed (escriba 0.1.71, live 80×24 TUI):
6243    // pressing `A` moved nothing, changed no mode and printed nothing, because
6244    // an unbound Normal key resolves to `Action::Pending`. Only `i` was bound.
6245
6246    /// Press one key on `text` from `at`, and report (mode, cursor, buffer).
6247    ///
6248    /// The buffer is part of the tuple on purpose: four of the six entries must
6249    /// leave it byte-identical, and a caret-only assertion cannot see a stray
6250    /// edit — which is the exact shape of the phantom-space report that started
6251    /// this work.
6252    fn entry(text: &str, at: Position, key: char) -> (Mode, Position, String) {
6253        let mut st = new_state_with(text);
6254        st.set_cursor(at);
6255        st.tick(&press(KeyCode::Char(key)));
6256        (
6257            st.modal.mode(),
6258            st.cursor(),
6259            st.buffers
6260                .get(st.active)
6261                .map(|b| b.to_string())
6262                .unwrap_or_default(),
6263        )
6264    }
6265
6266    /// The whole family, one row per entry — vim's caret placement exactly.
6267    ///
6268    /// A matrix rather than six tests so the ★★ CLOSED-LOOP MASS-SYNTHESIS
6269    /// rule has something to bite on: `every_insert_entry_has_a_key` below
6270    /// fails the build when a seventh `InsertAt` variant lands without a row.
6271    #[test]
6272    fn the_insert_entry_family_places_the_caret_like_vim() {
6273        // "  hello" — two leading blanks, so `I` and `0` differ, and 7 chars,
6274        // so "one past the end" is column 7.
6275        const TEXT: &str = "  hello\nworld\n";
6276        let from = Position::new(0, 4); // on the first `l`
6277        for (key, want_cursor, want_text, why) in [
6278            (
6279                'i',
6280                Position::new(0, 4),
6281                TEXT,
6282                "`i` inserts before the caret",
6283            ),
6284            (
6285                'I',
6286                Position::new(0, 2),
6287                TEXT,
6288                "`I` goes to the first NON-BLANK, not to column 0",
6289            ),
6290            (
6291                'a',
6292                Position::new(0, 5),
6293                TEXT,
6294                "`a` appends after the caret",
6295            ),
6296            (
6297                'A',
6298                Position::new(0, 7),
6299                TEXT,
6300                "`A` parks one PAST the last char — the whole point of the key",
6301            ),
6302            (
6303                'o',
6304                Position::new(1, 0),
6305                "  hello\n\nworld\n",
6306                "`o` opens below and lands on the new line",
6307            ),
6308            (
6309                'O',
6310                Position::new(0, 0),
6311                "\n  hello\nworld\n",
6312                "`O` opens above; the fresh line takes the caret's line number",
6313            ),
6314        ] {
6315            let (mode, cursor, text) = entry(TEXT, from, key);
6316            assert_eq!(mode, Mode::Insert, "`{key}` must enter Insert");
6317            assert_eq!(cursor, want_cursor, "{why}");
6318            assert_eq!(text, want_text, "`{key}`: {why}");
6319        }
6320    }
6321
6322    /// Every `InsertAt` has a Normal-mode key, and every one of those keys
6323    /// actually resolves to it.
6324    ///
6325    /// The forcing function. Adding a variant to `InsertAt` without binding it
6326    /// fails here rather than shipping a key that silently does nothing — which
6327    /// is precisely how `a`, `A`, `I`, `o` and `O` were missing for so long
6328    /// without any test noticing.
6329    #[test]
6330    fn every_insert_entry_has_a_key() {
6331        let km = escriba_keymap::Keymap::default_vim();
6332        let bound: Vec<InsertAt> = km
6333            .entries_sorted()
6334            .into_iter()
6335            .filter_map(|(mode, _, b)| match (mode, &b.action) {
6336                (Mode::Normal, Action::EnterInsert(at)) => Some(*at),
6337                _ => None,
6338            })
6339            .collect();
6340        for at in InsertAt::ALL {
6341            assert!(
6342                bound.contains(&at),
6343                "InsertAt::{at:?} ({}) has no Normal-mode key",
6344                at.as_str()
6345            );
6346        }
6347        assert_eq!(
6348            bound.len(),
6349            InsertAt::ALL.len(),
6350            "one key per entry, no duplicates: {bound:?}"
6351        );
6352    }
6353
6354    /// `A` then typing appends at the end — the end-to-end gesture, not just
6355    /// the caret placement.
6356    ///
6357    /// The caret assertion above would still pass if Insert mode refused to
6358    /// write at a column past the last character; this is what proves the
6359    /// `CursorRest::AtInsertPoint` rest actually holds through a keystroke.
6360    #[test]
6361    fn shift_a_then_typing_appends_at_the_end_of_the_line() {
6362        let mut st = new_state_with("hello\nworld\n");
6363        st.set_cursor(Position::new(0, 0));
6364        st.tick(&press(KeyCode::Char('A')));
6365        for c in "!!".chars() {
6366            st.tick(&press(KeyCode::Char(c)));
6367        }
6368        assert_eq!(
6369            st.buffers
6370                .get(st.active)
6371                .map(|b| b.to_string())
6372                .unwrap_or_default(),
6373            "hello!!\nworld\n"
6374        );
6375    }
6376
6377    /// `a` on the LAST character still appends, rather than stalling.
6378    ///
6379    /// The case the Normal-mode clamp would break, and the test that measured
6380    /// how. RED RUN 2026-08-12: `place_cursor`'s clamp needs BOTH
6381    /// `CursorRest::OnCharacter` and `Mode::Normal`, so this stays green if
6382    /// either guard is removed and goes red only when both are — reporting
6383    /// `column: 4` (back on the `o`) instead of 5. See `enter_insert_at`, whose
6384    /// doc comment originally over-claimed that the ordering alone carried it.
6385    #[test]
6386    fn a_on_the_last_character_appends_after_it() {
6387        let mut st = new_state_with("hello\n");
6388        st.set_cursor(Position::new(0, 4)); // the `o`
6389        st.tick(&press(KeyCode::Char('a')));
6390        assert_eq!(st.cursor(), Position::new(0, 5), "one past the `o`");
6391        st.tick(&press(KeyCode::Char('?')));
6392        assert_eq!(
6393            st.buffers
6394                .get(st.active)
6395                .map(|b| b.to_string())
6396                .unwrap_or_default(),
6397            "hello?\n"
6398        );
6399    }
6400
6401    /// No insert-entry key touches the buffer except `o`/`O`.
6402    ///
6403    /// The direct gate on the reported symptom: "hitting insert creates a
6404    /// space". It never did — the space was a RENDER defect (see
6405    /// `escriba-tui`'s `entering_insert_does_not_widen_the_rendered_line`) —
6406    /// and this test is what keeps the two explanations from being confused
6407    /// again, by pinning that the text really is untouched.
6408    #[test]
6409    fn entering_insert_types_nothing() {
6410        const TEXT: &str = "  hello\nworld\n";
6411        for key in ['i', 'I', 'a', 'A'] {
6412            let (_, _, text) = entry(TEXT, Position::new(0, 4), key);
6413            assert_eq!(text, TEXT, "`{key}` must not write a character");
6414        }
6415        for key in ['o', 'O'] {
6416            let (_, _, text) = entry(TEXT, Position::new(0, 4), key);
6417            assert_eq!(
6418                text.chars().filter(|c| *c == '\n').count(),
6419                3,
6420                "`{key}` adds exactly one line terminator and no other char"
6421            );
6422            assert!(
6423                text.contains("  hello") && text.contains("world"),
6424                "`{key}` must not disturb the existing lines: {text:?}"
6425            );
6426        }
6427    }
6428
6429    /// Binding bare `a` and `i` must NOT shadow the text objects.
6430    ///
6431    /// The regression this whole family risked. `escriba-keymap`'s rule is that
6432    /// a single binding beats a sequence prefix, so a naive `a` binding would
6433    /// have made `daw` mean "delete, then append". It does not, because
6434    /// `consume_object_key` runs before both and claims `i`/`a` only while an
6435    /// operator is armed — this test is the evidence for that sentence.
6436    #[test]
6437    fn the_insert_entry_keys_do_not_shadow_text_objects() {
6438        assert_eq!(keys("one two three\n", 0, 5, "daw"), "one three\n");
6439        assert_eq!(keys("one two three\n", 0, 5, "diw"), "one  three\n");
6440        assert_eq!(keys("f(a, b)\n", 0, 3, "di("), "f()\n");
6441        // And the operator-free path still reaches the new bindings.
6442        let (mode, cursor, _) = entry("one two\n", Position::new(0, 0), 'a');
6443        assert_eq!(mode, Mode::Insert);
6444        assert_eq!(cursor, Position::new(0, 1), "no operator ⇒ `a` appends");
6445    }
6446
6447    /// Text objects FROM THE KEYBOARD.
6448    ///
6449    /// Every bracket is unbound, and `i`/`a` are claimed by
6450    /// `consume_object_key` only while an operator waits, so all of this is
6451    /// decided on the KEY rather than in the binding table. (Until 2026-08-12
6452    /// this comment read "`i` is `ChangeMode(Insert)` in Normal and `a` … are
6453    /// unbound" — true when written, and made false by the insert-entry family
6454    /// above.)
6455
6456    fn keys(text: &str, line: u32, col: u32, seq: &str) -> String {
6457        let mut st = new_state_with(text);
6458        st.set_cursor(Position::new(line, col));
6459        for c in seq.chars() {
6460            st.tick(&press(KeyCode::Char(c)));
6461        }
6462        st.buffers
6463            .get(st.active)
6464            .map(|b| b.to_string())
6465            .unwrap_or_default()
6466    }
6467
6468    #[test]
6469    fn diw_from_the_keyboard() {
6470        assert_eq!(keys("one two three\n", 0, 5, "diw"), "one  three\n");
6471    }
6472
6473    #[test]
6474    fn daw_from_the_keyboard_takes_the_space() {
6475        assert_eq!(keys("one two three\n", 0, 5, "daw"), "one three\n");
6476    }
6477
6478    #[test]
6479    fn ciw_deletes_and_enters_insert() {
6480        let mut st = new_state_with("one two\n");
6481        st.set_cursor(Position::new(0, 5));
6482        for c in "ciw".chars() {
6483            st.tick(&press(KeyCode::Char(c)));
6484        }
6485        assert_eq!(st.modal.mode(), Mode::Insert, "change leaves you inserting");
6486        let got = st
6487            .buffers
6488            .get(st.active)
6489            .map(|b| b.to_string())
6490            .unwrap_or_default();
6491        assert_eq!(got, "one \n");
6492    }
6493
6494    #[test]
6495    fn di_paren_and_da_paren_from_the_keyboard() {
6496        assert_eq!(keys("f(a, b)\n", 0, 3, "di("), "f()\n");
6497        assert_eq!(keys("f(a, b)\n", 0, 3, "da("), "f\n");
6498    }
6499
6500    #[test]
6501    fn the_closing_bracket_and_b_are_aliases() {
6502        // vim accepts `i(`, `i)` and `ib` for the same object.
6503        for sel in ["di(", "di)", "dib"] {
6504            assert_eq!(keys("f(a, b)\n", 0, 3, sel), "f()\n", "{sel}");
6505        }
6506    }
6507
6508    #[test]
6509    fn di_quote_from_the_keyboard() {
6510        assert_eq!(keys("say \"hi\" ok\n", 0, 6, "di\""), "say \"\" ok\n");
6511    }
6512
6513    #[test]
6514    fn i_alone_still_enters_insert_when_no_operator_is_pending() {
6515        // The load-bearing negative: the object layer must not steal `i`
6516        // from ordinary use.
6517        let mut st = new_state_with("abc\n");
6518        st.tick(&press(KeyCode::Char('i')));
6519        assert_eq!(st.modal.mode(), Mode::Insert);
6520    }
6521
6522    #[test]
6523    fn an_unknown_object_key_cancels_rather_than_staying_armed() {
6524        // `diz` is not an object. The operator must disarm, and the buffer
6525        // must be untouched — not left waiting to eat the next keystroke.
6526        let mut st = new_state_with("one two\n");
6527        st.set_cursor(Position::new(0, 5));
6528        for c in "diz".chars() {
6529            st.tick(&press(KeyCode::Char(c)));
6530        }
6531        let got = st
6532            .buffers
6533            .get(st.active)
6534            .map(|b| b.to_string())
6535            .unwrap_or_default();
6536        assert_eq!(got, "one two\n", "nothing was deleted");
6537        assert_eq!(*st.op_pending.state(), OpState::Resting, "and it disarmed");
6538    }
6539
6540    // ── the register under a count ───────────────────────────────────
6541
6542    #[test]
6543    fn a_counted_delete_puts_ALL_of_it_in_the_register() {
6544        // `3dw` is one delete of three words as far as the register is
6545        // concerned. Each repetition emits its own Yank, and each used to
6546        // overwrite — so `3dwP` put back only the third word and silently
6547        // lost two.
6548        let mut st = new_state_with("one two three four\n");
6549        st.set_cursor(Position::new(0, 0));
6550        for c in "3dw".chars() {
6551            st.tick(&press(KeyCode::Char(c)));
6552        }
6553        assert_eq!(
6554            st.register_text(),
6555            Some("one two three "),
6556            "all three words, in the order they were deleted"
6557        );
6558    }
6559
6560    #[test]
6561    fn an_uncounted_delete_still_replaces_the_register() {
6562        // The combining flag must not leak: a later single delete replaces.
6563        let mut st = new_state_with("alpha beta\n");
6564        st.set_cursor(Position::new(0, 0));
6565        for c in "3dw".chars() {
6566            st.tick(&press(KeyCode::Char(c)));
6567        }
6568        let mut st2 = new_state_with("gamma delta\n");
6569        st2.set_cursor(Position::new(0, 0));
6570        for c in "dw".chars() {
6571            st2.tick(&press(KeyCode::Char(c)));
6572        }
6573        assert_eq!(st2.register_text(), Some("gamma "));
6574    }
6575
6576    #[test]
6577    fn two_separate_counted_deletes_do_not_accumulate_into_each_other() {
6578        // The flag is cleared after each group, so the second `2dw` starts
6579        // from empty rather than appending to the first.
6580        let mut st = new_state_with("a b c d e f\n");
6581        st.set_cursor(Position::new(0, 0));
6582        for c in "2dw".chars() {
6583            st.tick(&press(KeyCode::Char(c)));
6584        }
6585        let first = st.register_text().map(str::to_owned);
6586        for c in "2dw".chars() {
6587            st.tick(&press(KeyCode::Char(c)));
6588        }
6589        assert_eq!(first.as_deref(), Some("a b "));
6590        assert_eq!(st.register_text(), Some("c d "), "not \"a b c d \"");
6591    }
6592
6593    #[test]
6594    fn a_counted_yank_accumulates_without_changing_the_buffer() {
6595        let mut st = new_state_with("one two three\n");
6596        st.set_cursor(Position::new(0, 0));
6597        let before = st
6598            .buffers
6599            .get(st.active)
6600            .map(|b| b.to_string())
6601            .unwrap_or_default();
6602        for c in "2yw".chars() {
6603            st.tick(&press(KeyCode::Char(c)));
6604        }
6605        assert_eq!(st.register_text(), Some("one two "));
6606        let after = st
6607            .buffers
6608            .get(st.active)
6609            .map(|b| b.to_string())
6610            .unwrap_or_default();
6611        assert_eq!(after, before, "yank does not edit");
6612    }
6613
6614    // ── the anchored reply (Negai::ErrandReply) ──────────────────────
6615    //
6616    // Landed BEFORE the courier that will produce these. The class being
6617    // closed: a reply computed off the tick, applied against a world that
6618    // has since moved, and RESEALED as fresh by the interpreter — which is
6619    // what every synchronous slip correctly does and what an async one must
6620    // never do.
6621
6622    fn a_finding(buffer: BufferId, line: u32) -> escriba_shirube::Finding {
6623        use escriba_core::{Position, Range};
6624        escriba_shirube::Finding::new(
6625            escriba_shirube::Site::in_buffer(
6626                buffer,
6627                Range::new(Position::new(line, 0), Position::new(line, 1)),
6628            ),
6629            escriba_shirube::Severity::Error,
6630            "computed off the tick".to_string(),
6631            escriba_shirube::Origin::Text("test"),
6632        )
6633    }
6634
6635    #[test]
6636    fn a_fresh_errand_reply_is_honoured() {
6637        let mut st = new_state_with("a\nb\nc\n");
6638        let anchor = st.world();
6639        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
6640            anchor,
6641            then: Box::new(escriba_madoguchi::Negai::PublishFindings {
6642                list: "lsp".to_string(),
6643                findings: vec![a_finding(st.active, 1)],
6644            }),
6645        });
6646        assert_eq!(
6647            st.finding_items(true, None).len(),
6648            1,
6649            "the world had not moved"
6650        );
6651    }
6652
6653    /// THE red run. Without the freshness check this passes findings
6654    /// straight through, and `PublishFindings` reseals them with the
6655    /// CURRENT world — so they are reported fresh at columns that moved.
6656    #[test]
6657    fn a_stale_errand_reply_is_dropped_not_resealed() {
6658        let mut st = new_state_with("a\nb\nc\n");
6659        // Capture the world the "server" computed against...
6660        let anchor = st.world();
6661        // ...then let the operator keep typing, which is the whole point.
6662        st.apply(&Action::InsertChar('x'));
6663
6664        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
6665            anchor,
6666            then: Box::new(escriba_madoguchi::Negai::PublishFindings {
6667                list: "lsp".to_string(),
6668                findings: vec![a_finding(st.active, 1)],
6669            }),
6670        });
6671        assert!(
6672            st.finding_items(true, None).is_empty(),
6673            "a reply computed against an older text revision must be DROPPED, \
6674             not resealed against the current one"
6675        );
6676    }
6677
6678    /// The failure the wrapper exists for, and the reason it wraps a slip
6679    /// rather than adding an anchor field to PublishFindings: a stale EDIT
6680    /// corrupts the file, where a stale diagnostic merely mis-decorates it.
6681    #[test]
6682    fn a_stale_errand_reply_cannot_edit_the_buffer() {
6683        let mut st = new_state_with("hello\n");
6684        let anchor = st.world();
6685        st.apply(&Action::InsertChar('!'));
6686        let before = st
6687            .buffers
6688            .get(st.active)
6689            .map(|b| b.to_string())
6690            .unwrap_or_default();
6691
6692        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
6693            anchor,
6694            then: Box::new(escriba_madoguchi::Negai::Edit {
6695                buffer: st.active,
6696                edit: escriba_core::Edit {
6697                    range: Range::new(Position::new(0, 0), Position::new(0, 0)),
6698                    kind: escriba_core::EditKind::Insert {
6699                        text: "FORMATTED".to_string(),
6700                    },
6701                },
6702            }),
6703        });
6704        let after = st
6705            .buffers
6706            .get(st.active)
6707            .map(|b| b.to_string())
6708            .unwrap_or_default();
6709        assert_eq!(
6710            after, before,
6711            "a stale formatter reply must not touch the text"
6712        );
6713    }
6714
6715    fn press(kc: KeyCode) -> AppEvent {
6716        AppEvent::Key(KeyEvent {
6717            key: kc,
6718            pressed: true,
6719            modifiers: Modifiers::default(),
6720            text: None,
6721        })
6722    }
6723
6724    // ── operator-over-motion (the `dw`/`c$`/`y0` verbs) ──────────────
6725
6726    fn line0_len(s: &EditorState) -> u32 {
6727        s.buffers.get(s.active).unwrap().line_len_chars(0)
6728    }
6729
6730    #[test]
6731    fn delete_to_line_end_clears_line_and_fills_register() {
6732        let mut s = new_state_with("hello world");
6733        s.apply(&Action::ApplyOperator {
6734            op: Operator::Delete,
6735            motion: Motion::LineEnd,
6736        });
6737        assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
6738        assert_eq!(
6739            s.register_text(),
6740            Some("hello world"),
6741            "delete fills the register"
6742        );
6743        assert_eq!(
6744            s.cursor(),
6745            Position::ZERO,
6746            "cursor lands at the range start"
6747        );
6748    }
6749
6750    #[test]
6751    fn delete_over_right_motion_removes_one_char() {
6752        let mut s = new_state_with("abc");
6753        s.apply(&Action::ApplyOperator {
6754            op: Operator::Delete,
6755            motion: Motion::Right,
6756        });
6757        assert_eq!(
6758            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6759            Some("bc")
6760        );
6761        assert_eq!(s.register_text(), Some("a"));
6762    }
6763
6764    #[test]
6765    fn change_to_line_end_deletes_and_enters_insert() {
6766        let mut s = new_state_with("hello world");
6767        assert_eq!(s.modal.mode(), Mode::Normal);
6768        s.apply(&Action::ApplyOperator {
6769            op: Operator::Change,
6770            motion: Motion::LineEnd,
6771        });
6772        assert_eq!(line0_len(&s), 0, "c$ deletes the range");
6773        assert_eq!(
6774            s.modal.mode(),
6775            Mode::Insert,
6776            "change enters Insert to type the replacement"
6777        );
6778        assert_eq!(
6779            s.register_text(),
6780            Some("hello world"),
6781            "change fills the register"
6782        );
6783    }
6784
6785    #[test]
6786    fn yank_to_line_end_fills_register_without_mutating() {
6787        let mut s = new_state_with("hello world");
6788        s.apply(&Action::ApplyOperator {
6789            op: Operator::Yank,
6790            motion: Motion::LineEnd,
6791        });
6792        assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
6793        assert_eq!(s.register_text(), Some("hello world"), "yank fills the register");
6794        assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
6795    }
6796
6797    #[test]
6798    fn resolve_motion_is_the_shared_target_for_move_and_operator() {
6799        // The encapsulation proof: apply_motion (cursor move) and
6800        // apply_operator (range end) BOTH stand on resolve_motion.
6801        //
6802        // They read its answer differently AT THE BUFFER EDGE, and the
6803        // difference is vim's: `d$` deletes the last character, so the RANGE
6804        // ends after it; `$` puts the cursor ON it, because Normal mode has
6805        // nowhere past the last character to stand. One resolver, one target,
6806        // two readings — the reading is the mode's, not the motion's, which
6807        // is why the rest rule lives in `place_cursor` and not in here.
6808        let mut s = new_state_with("hello world");
6809        let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
6810        assert_eq!(target, Position::new(0, 11), "the exclusive range end");
6811
6812        s.apply_motion(Motion::LineEnd);
6813        assert_eq!(
6814            s.cursor(),
6815            Position::new(0, 10),
6816            "`$` rests on the last character, not past it",
6817        );
6818
6819        let mut d = new_state_with("hello world");
6820        d.apply(&Action::ApplyOperator {
6821            op: Operator::Delete,
6822            motion: Motion::LineEnd,
6823        });
6824        assert_eq!(
6825            line0_len(&d),
6826            0,
6827            "`d$` deletes through the last character — the range ends where \
6828             resolve_motion said, not where the cursor may rest",
6829        );
6830    }
6831
6832    #[test]
6833    fn empty_motion_range_is_a_no_op() {
6834        // An operator over a zero-width motion (cursor already at line start)
6835        // mutates nothing and leaves the register untouched.
6836        let mut s = new_state_with("abc");
6837        s.apply(&Action::ApplyOperator {
6838            op: Operator::Delete,
6839            motion: Motion::LineStart,
6840        });
6841        assert_eq!(
6842            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6843            Some("abc")
6844        );
6845        assert_eq!(s.register_text(), None);
6846    }
6847
6848    #[test]
6849    fn operator_then_motion_composes_through_the_pending_fsm() {
6850        // The full keymap→FSM→engine path: dispatching the `d` operator action
6851        // then a `$` motion composes `d$` via the zenmai operator-pending FSM —
6852        // the operator key alone does nothing until the motion arrives.
6853        let mut s = new_state_with("hello world");
6854        s.apply(&Action::Operator(Operator::Delete));
6855        assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
6856        s.apply(&Action::Move(Motion::LineEnd));
6857        assert_eq!(
6858            line0_len(&s),
6859            0,
6860            "d then $ composes d$ and deletes the line"
6861        );
6862        assert_eq!(s.register_text(), Some("hello world"));
6863    }
6864
6865    #[test]
6866    fn change_operator_through_fsm_enters_insert() {
6867        let mut s = new_state_with("hello world");
6868        s.apply(&Action::Operator(Operator::Change));
6869        s.apply(&Action::Move(Motion::LineEnd));
6870        assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
6871    }
6872
6873    #[test]
6874    fn lone_motion_after_no_operator_just_moves() {
6875        // Without a preceding operator the motion passes through unchanged —
6876        // and comes to rest on the last character, as Normal mode requires.
6877        let mut s = new_state_with("hello world");
6878        s.apply(&Action::Move(Motion::LineEnd));
6879        assert_eq!(s.cursor(), Position::new(0, 10));
6880        assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
6881    }
6882
6883    #[test]
6884    fn counted_operator_deletes_count_times() {
6885        // `3d` + a right-motion = `3dl` = delete 3 chars. The operator's count
6886        // flows through the FSM to the composed motion (the bug fix: previously
6887        // the count repeated the operator key and toggled the FSM).
6888        let mut s = new_state_with("abcdef");
6889        s.apply_counted(&Action::Operator(Operator::Delete), 3);
6890        assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
6891        s.apply(&Action::Move(Motion::Right));
6892        assert_eq!(
6893            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6894            Some("def")
6895        );
6896    }
6897
6898    #[test]
6899    fn operator_and_motion_counts_multiply_end_to_end() {
6900        // `2d3l` = delete 2×3 = 6 chars.
6901        let mut s = new_state_with("abcdefgh");
6902        s.apply_counted(&Action::Operator(Operator::Delete), 2);
6903        s.apply_counted(&Action::Move(Motion::Right), 3);
6904        assert_eq!(
6905            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6906            Some("gh")
6907        );
6908    }
6909
6910    #[test]
6911    fn bare_counted_motion_still_repeats_no_regression() {
6912        // `3j` still moves down 3 lines — the count passes through the FSM
6913        // unchanged when no operator is pending.
6914        let mut s = new_state_with("a\nb\nc\nd\ne");
6915        s.apply_counted(&Action::Move(Motion::Down), 3);
6916        assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
6917    }
6918
6919    /// A monotonic clock for the key-repeat gate in tests — each `next()`
6920    /// jumps a full second past the previous, so every press it stamps is
6921    /// well outside the 80ms debounce window and therefore an INTENTIONAL
6922    /// press (never a storm tick). Used by tests that fire the *same*
6923    /// navigation key twice and assert editor logic, not debounce timing.
6924    struct SpacedClock(std::time::Instant);
6925    impl SpacedClock {
6926        fn new() -> Self {
6927            Self(std::time::Instant::now())
6928        }
6929        fn next(&mut self) -> std::time::Instant {
6930            self.0 += std::time::Duration::from_secs(1);
6931            self.0
6932        }
6933    }
6934
6935    #[test]
6936    fn hjkl_moves_cursor() {
6937        let mut s = new_state_with("hello\nworld");
6938        s.tick(&press(KeyCode::Char('l')));
6939        assert_eq!(s.cursor().column, 1);
6940        s.tick(&press(KeyCode::Char('j')));
6941        assert_eq!(s.cursor().line, 1);
6942        s.tick(&press(KeyCode::Char('h')));
6943        assert_eq!(s.cursor().column, 0);
6944    }
6945
6946    #[test]
6947    fn insert_mode_inserts_chars() {
6948        let mut s = new_state_with("");
6949        s.tick(&press(KeyCode::Char('i')));
6950        assert_eq!(s.modal.mode(), Mode::Insert);
6951        s.tick(&press(KeyCode::Char('h')));
6952        s.tick(&press(KeyCode::Char('i')));
6953        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
6954        assert_eq!(s.cursor().column, 2);
6955    }
6956
6957    #[test]
6958    fn esc_returns_to_normal() {
6959        let mut s = new_state_with("");
6960        s.tick(&press(KeyCode::Char('i')));
6961        s.tick(&press(KeyCode::Escape));
6962        assert_eq!(s.modal.mode(), Mode::Normal);
6963    }
6964
6965    #[test]
6966    fn count_prefix_repeats_motion() {
6967        let mut s = new_state_with("abcdefghij");
6968        s.tick(&press(KeyCode::Char('5')));
6969        s.tick(&press(KeyCode::Char('l')));
6970        assert_eq!(s.cursor().column, 5);
6971    }
6972
6973    #[test]
6974    fn close_event_requests_quit() {
6975        let mut s = new_state_with("");
6976        s.tick(&AppEvent::CloseRequested);
6977        assert!(s.quit_requested);
6978    }
6979
6980    #[test]
6981    fn word_next_jumps_past_whitespace() {
6982        let mut s = new_state_with("foo bar baz");
6983        // Two INTENTIONAL `w` presses, spaced past the key-repeat window so
6984        // the gate passes both (a real user's two taps are ≥80ms apart).
6985        let mut clk = SpacedClock::new();
6986        s.tick_at(&press(KeyCode::Char('w')), clk.next());
6987        assert_eq!(s.cursor().column, 4);
6988        s.tick_at(&press(KeyCode::Char('w')), clk.next());
6989        assert_eq!(s.cursor().column, 8);
6990    }
6991
6992    // ── Multi-key / leader pending-stroke ───────────────────────────
6993
6994    #[test]
6995    fn leader_sequence_holds_then_resolves() {
6996        let mut s = new_state_with("a\nbb\nccc");
6997        s.keymap.bind_sequence(
6998            Mode::Normal,
6999            vec![Key::Char(','), Key::Char('g')],
7000            Action::Move(Motion::DocEnd),
7001            "doc end",
7002        );
7003        // `,` begins the sequence — held pending, nothing applied yet.
7004        s.on_key(&Key::Char(','));
7005        assert_eq!(s.pending_keys, vec![Key::Char(',')]);
7006        assert_eq!(s.cursor(), Position::ZERO);
7007        // `g` completes `<leader>g` → DocEnd; pending clears.
7008        s.on_key(&Key::Char('g'));
7009        assert!(s.pending_keys.is_empty());
7010        assert_eq!(s.cursor().line, 2);
7011    }
7012
7013    #[test]
7014    fn two_key_gg_jumps_doc_start() {
7015        let mut s = new_state_with("a\nbb\nccc");
7016        s.keymap.bind_sequence(
7017            Mode::Normal,
7018            vec![Key::Char('g'), Key::Char('g')],
7019            Action::Move(Motion::DocStart),
7020            "doc start",
7021        );
7022        let mut clk = SpacedClock::new();
7023        s.tick_at(&press(KeyCode::Char('j')), clk.next());
7024        s.tick_at(&press(KeyCode::Char('j')), clk.next());
7025        assert_eq!(s.cursor().line, 2);
7026        s.on_key(&Key::Char('g')); // pending
7027        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7028        s.on_key(&Key::Char('g')); // resolve
7029        assert_eq!(s.cursor(), Position::ZERO);
7030    }
7031
7032    #[test]
7033    fn broken_sequence_aborts_and_clears_pending() {
7034        let mut s = new_state_with("hello");
7035        s.keymap.bind_sequence(
7036            Mode::Normal,
7037            vec![Key::Char('g'), Key::Char('g')],
7038            Action::Move(Motion::DocEnd),
7039            "doc end",
7040        );
7041        s.on_key(&Key::Char('g')); // pending [g]
7042        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7043        s.on_key(&Key::Char('x')); // breaks gg → abort; x is unbound → no-op
7044        assert!(s.pending_keys.is_empty());
7045        assert_eq!(s.cursor(), Position::ZERO);
7046    }
7047
7048    #[test]
7049    fn single_binding_wins_over_sequence_prefix() {
7050        // A key that is BOTH a complete single binding and the start of
7051        // a sequence fires the single binding immediately (no chord
7052        // timeout needed). Here `h` (move-left) also prefixes `hz`.
7053        let mut s = new_state_with("abcde");
7054        let mut clk = SpacedClock::new();
7055        s.tick_at(&press(KeyCode::Char('l')), clk.next());
7056        s.tick_at(&press(KeyCode::Char('l')), clk.next());
7057        assert_eq!(s.cursor().column, 2);
7058        s.keymap.bind_sequence(
7059            Mode::Normal,
7060            vec![Key::Char('h'), Key::Char('z')],
7061            Action::Move(Motion::DocEnd),
7062            "shadowed",
7063        );
7064        s.on_key(&Key::Char('h'));
7065        assert!(s.pending_keys.is_empty(), "single binding should not pend");
7066        assert_eq!(s.cursor().column, 1, "h moved left immediately");
7067    }
7068
7069    // ── tatara-lisp runtime bridge (imperative programmability) ─────
7070
7071    #[test]
7072    fn lisp_set_option_writes_live_options() {
7073        let mut s = new_state_with("");
7074        s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
7075        assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
7076    }
7077
7078    #[test]
7079    fn lisp_insert_modifies_buffer_and_advances_cursor() {
7080        let mut s = new_state_with("");
7081        s.run_lisp(r#"(insert "abc")"#).unwrap();
7082        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
7083        assert_eq!(s.cursor(), Position::new(0, 3));
7084    }
7085
7086    #[test]
7087    fn lisp_message_appends_to_messages() {
7088        let mut s = new_state_with("");
7089        s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
7090        assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
7091    }
7092
7093    #[test]
7094    fn lisp_reads_snapshot_and_branches_to_effect() {
7095        // Genuine programmability: Lisp reads the live cursor line and
7096        // an `if` decides which option to set.
7097        let mut s = new_state_with("one\ntwo\nthree");
7098        // cursor at line 0 → "top" branch
7099        s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
7100            .unwrap();
7101        assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
7102    }
7103
7104    #[test]
7105    fn lisp_run_command_effect_drives_registry() {
7106        // `(run-command "undo")` reaches the live command registry and
7107        // reverts a prior Lisp-driven insert — proving the RunCommand
7108        // effect dispatches through real editor commands.
7109        let mut s = new_state_with("");
7110        s.run_lisp(r#"(insert "abc")"#).unwrap();
7111        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
7112        s.run_lisp(r#"(run-command "undo")"#).unwrap();
7113        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
7114    }
7115
7116    #[test]
7117    fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
7118        // The full imperative-quit path: (run-command "quit") routes
7119        // through the registry's typed `quit_requested` signal — no string
7120        // sentinel, and no minibuffer pollution (the editor stays in a
7121        // clean Normal state, which has no minibuffer at all).
7122        let mut s = new_state_with("");
7123        s.run_lisp(r#"(run-command "quit")"#).unwrap();
7124        assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
7125        assert_eq!(
7126            s.modal.minibuffer(),
7127            "",
7128            "quit must not pollute any command line — Normal mode has no minibuffer",
7129        );
7130    }
7131
7132    // ── Lazy plugin activation (PluginHost) ────────────────────────
7133
7134    #[test]
7135    fn lazy_plugin_activates_on_command_trigger() {
7136        // A user plugin gated on `Command: LazyGo` has its entry applied
7137        // the first time that command runs — proving the lazy.nvim
7138        // `cmd =` model works end-to-end against live editor state.
7139        let mut s = new_state_with("");
7140        s.register_lazy_plugin(
7141            "user-lazy",
7142            vec![LazyTrigger::Command("LazyGo".into())],
7143            r#"(defoption :name "lazy-loaded" :value "yes")
7144               (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
7145        );
7146        assert_eq!(s.plugin_host.pending(), 1);
7147        assert!(
7148            s.options.get("lazy-loaded").is_none(),
7149            "entry not applied yet"
7150        );
7151
7152        // Drive the command through the public imperative path.
7153        s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
7154
7155        assert_eq!(
7156            s.options.get("lazy-loaded").map(String::as_str),
7157            Some("yes"),
7158            "the command trigger applied the plugin's entry",
7159        );
7160        assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
7161    }
7162
7163    #[test]
7164    fn lazy_plugin_activates_on_filetype() {
7165        let mut s = new_state_with("");
7166        s.register_lazy_plugin(
7167            "user-rust",
7168            vec![LazyTrigger::FileType("rust".into())],
7169            r#"(defoption :name "rust-plugin" :value "on")"#,
7170        );
7171        let n = s.activate_filetype_plugins("rust");
7172        assert_eq!(n, 1);
7173        assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
7174        // A second open of the same filetype is a no-op (one-shot).
7175        assert_eq!(s.activate_filetype_plugins("rust"), 0);
7176    }
7177
7178    #[test]
7179    fn cached_vm_serves_multiple_run_lisp_calls() {
7180        let mut s = new_state_with("");
7181        s.run_lisp(r#"(message "one")"#).unwrap();
7182        assert!(
7183            s.lisp_vm.is_some(),
7184            "VM should be cached after first run_lisp"
7185        );
7186        s.run_lisp(r#"(message "two")"#).unwrap();
7187        assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
7188    }
7189
7190    #[test]
7191    fn lisp_define_persists_across_run_lisp_calls() {
7192        // The cached VM's top-level env persists across calls (REPL
7193        // semantics): a `define` in one call is visible in the next.
7194        let mut s = new_state_with("");
7195        s.run_lisp(r#"(define greeting "hi")"#).unwrap();
7196        s.run_lisp(r#"(message greeting)"#).unwrap();
7197        assert_eq!(s.messages, vec!["hi".to_string()]);
7198    }
7199
7200    #[test]
7201    fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
7202        // Within ONE call a program cannot observe its own writes — the
7203        // read snapshot is captured before eval, effects apply after. A
7204        // later call sees the refreshed snapshot.
7205        let mut s = new_state_with("");
7206        s.run_lisp(
7207            r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
7208        )
7209        .unwrap();
7210        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
7211        assert_eq!(
7212            s.options.get("col").map(String::as_str),
7213            Some("stale-zero"),
7214            "cursor-column within the same call reads the pre-eval snapshot",
7215        );
7216        // After the first call the cursor advanced to column 2; the next
7217        // call's snapshot reflects it.
7218        s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
7219            .unwrap();
7220        assert_eq!(
7221            s.options.get("col2").map(String::as_str),
7222            Some("live-two"),
7223            "a later call sees the refreshed snapshot",
7224        );
7225    }
7226
7227    #[test]
7228    fn insert_text_effect_multiline_lands_cursor_on_last_line() {
7229        let mut s = new_state_with("");
7230        s.apply_host_effects(vec![Negai::InsertText("foo\nbar".to_string())]);
7231        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
7232        assert_eq!(s.cursor(), Position::new(1, 3));
7233    }
7234
7235    #[test]
7236    fn visual_mode_sequence_resolves() {
7237        let mut s = new_state_with("abc");
7238        s.modal.enter(Mode::Visual);
7239        s.keymap.bind_sequence(
7240            Mode::Visual,
7241            vec![Key::Char('g'), Key::Char('e')],
7242            Action::Move(Motion::DocEnd),
7243            "ge",
7244        );
7245        s.on_key(&Key::Char('g'));
7246        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7247        s.on_key(&Key::Char('e'));
7248        assert!(s.pending_keys.is_empty());
7249        assert_eq!(
7250            s.cursor().column,
7251            3,
7252            "ge resolved to doc-end in visual mode"
7253        );
7254    }
7255
7256    #[test]
7257    fn sequence_abort_with_bound_breaking_key_redispatches() {
7258        // gg is a sequence; `l` (move-right) is a bound single key. After
7259        // `g` pends, `l` breaks gg, aborts, and is re-dispatched fresh.
7260        let mut s = new_state_with("abcde");
7261        s.keymap.bind_sequence(
7262            Mode::Normal,
7263            vec![Key::Char('g'), Key::Char('g')],
7264            Action::Move(Motion::DocEnd),
7265            "gg",
7266        );
7267        s.on_key(&Key::Char('g'));
7268        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7269        s.on_key(&Key::Char('l'));
7270        assert!(s.pending_keys.is_empty());
7271        assert_eq!(
7272            s.cursor().column,
7273            1,
7274            "the breaking key l should re-dispatch as move-right",
7275        );
7276    }
7277
7278    // ── Viewport-follows-cursor invariant (both axes) ───────────────
7279
7280    #[test]
7281    fn viewport_contains_cursor_after_every_op() {
7282        // Tiny window: 5 visible lines × 10 visible columns. Drive a
7283        // representative scripted sequence and assert the viewport contains
7284        // the cursor after EVERY mutating step.
7285        let mut s = new_state_small_viewport("", 5, 10);
7286        assert_cursor_in_viewport(&s, "initial");
7287
7288        // Enter insert mode and type 30 newline-separated lines — this is
7289        // the exact "type past the bottom" complaint.
7290        s.tick(&press(KeyCode::Char('i')));
7291        assert_eq!(s.modal.mode(), Mode::Insert);
7292        for line in 0..30u32 {
7293            for c in "line".chars() {
7294                s.tick(&press(KeyCode::Char(c)));
7295                assert_cursor_in_viewport(&s, "typing chars");
7296            }
7297            s.tick(&press(KeyCode::Enter));
7298            assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
7299        }
7300
7301        // Type a long (200-char) line — the "type past the right edge"
7302        // complaint. The cursor must stay horizontally visible the whole way.
7303        for i in 0..200u32 {
7304            s.tick(&press(KeyCode::Char('x')));
7305            assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
7306        }
7307
7308        // Multi-line insert_text effect (the `(insert …)` Lisp path).
7309        s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
7310        assert_cursor_in_viewport(&s, "insert_text multiline");
7311
7312        // Back to normal mode and move in all directions / to extremes.
7313        s.tick(&press(KeyCode::Escape));
7314        assert_eq!(s.modal.mode(), Mode::Normal);
7315        for m in [
7316            Motion::DocStart,
7317            Motion::DocEnd,
7318            Motion::Down,
7319            Motion::Down,
7320            Motion::Up,
7321            Motion::Right,
7322            Motion::Right,
7323            Motion::Left,
7324            Motion::LineEnd,
7325            Motion::LineStart,
7326            Motion::GotoLine(1),
7327            Motion::GotoLine(40),
7328            Motion::PageDown,
7329            Motion::PageUp,
7330        ] {
7331            s.apply_motion(m);
7332            assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
7333        }
7334
7335        // Undo many times — the buffer shrinks; the viewport must re-follow
7336        // the (now clamped) cursor.
7337        for i in 0..50u32 {
7338            s.apply(&Action::Undo);
7339            assert_cursor_in_viewport(&s, &format!("undo {i}"));
7340        }
7341        // Redo back up.
7342        for i in 0..50u32 {
7343            s.apply(&Action::Redo);
7344            assert_cursor_in_viewport(&s, &format!("redo {i}"));
7345        }
7346    }
7347
7348    #[test]
7349    fn insert_at_eof_keeps_cursor_in_bounds() {
7350        // Inserting at the end of the buffer must leave the cursor clamped
7351        // to a valid position (and inside the viewport).
7352        let mut s = new_state_small_viewport("abc", 5, 10);
7353        s.apply_motion(Motion::DocEnd);
7354        s.tick(&press(KeyCode::Char('i')));
7355        s.tick(&press(KeyCode::Char('d')));
7356        let buf = s.buffers.get(s.active).unwrap();
7357        let clamped = buf.clamp(s.cursor());
7358        assert_eq!(
7359            s.cursor(),
7360            clamped,
7361            "cursor must be clamped in-bounds at EOF"
7362        );
7363        assert_cursor_in_viewport(&s, "insert at eof");
7364    }
7365
7366    #[test]
7367    fn count_prefix_then_sequence_repeats() {
7368        // `2` then `gj` (→ move-down) repeats the resolved action twice.
7369        let mut s = new_state_with("a\nb\nc\nd\ne");
7370        s.keymap.bind_sequence(
7371            Mode::Normal,
7372            vec![Key::Char('g'), Key::Char('j')],
7373            Action::Move(Motion::Down),
7374            "gj",
7375        );
7376        s.on_key(&Key::Char('2'));
7377        s.on_key(&Key::Char('g'));
7378        s.on_key(&Key::Char('j'));
7379        assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
7380    }
7381
7382    // ── Key-repeat gate (awase::KeyRepeatGate) ──────────────────────────
7383
7384    #[test]
7385    fn held_key_repeat_storm_is_debounced_in_normal_mode() {
7386        // The audit's exact complaint: holding `j` floods motion events
7387        // and thrashes the viewport. Simulate an OS key-repeat storm — 20
7388        // identical `j` KeyDowns at 50ms intervals (typical repeat cadence)
7389        // — and assert only the gated subset (one per 80ms window) actually
7390        // moves the cursor.
7391        let mut s = new_state_with(&"x\n".repeat(40));
7392        let t0 = std::time::Instant::now();
7393        let mut delivered = 0u32;
7394        for i in 0..20u32 {
7395            let before = s.cursor().line;
7396            s.tick_at(
7397                &press(KeyCode::Char('j')),
7398                t0 + std::time::Duration::from_millis(u64::from(i) * 50),
7399            );
7400            if s.cursor().line != before {
7401                delivered += 1;
7402            }
7403        }
7404        // 20 events over ~1s at 50ms spacing, 80ms gate ⇒ ~13 pass — far
7405        // fewer than the 20 the ungated path would have applied.
7406        assert!(
7407            (10..=14).contains(&delivered),
7408            "expected the storm debounced to ~13 moves, got {delivered}",
7409        );
7410        assert!(
7411            delivered < 20,
7412            "the gate must drop SOME storm ticks, not pass all 20",
7413        );
7414    }
7415
7416    #[test]
7417    fn spaced_intentional_taps_all_pass() {
7418        // Intentional taps spaced past the debounce window must ALL reach
7419        // the editor — the gate filters storms, never deliberate input.
7420        let mut s = new_state_with(&"x\n".repeat(10));
7421        let t0 = std::time::Instant::now();
7422        for i in 0..5u32 {
7423            s.tick_at(
7424                &press(KeyCode::Char('j')),
7425                // 100ms apart — comfortably past the 80ms window.
7426                t0 + std::time::Duration::from_millis(u64::from(i) * 100),
7427            );
7428        }
7429        assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
7430    }
7431
7432    #[test]
7433    fn distinct_keys_have_independent_clocks() {
7434        // Holding `j` must not block a simultaneous `l` — the gate keys on
7435        // the Key, so independent keys have independent windows.
7436        let mut s = new_state_with("abc\ndef\nghi");
7437        let t = std::time::Instant::now();
7438        s.tick_at(&press(KeyCode::Char('j')), t);
7439        // `j` again within the window is dropped…
7440        s.tick_at(
7441            &press(KeyCode::Char('j')),
7442            t + std::time::Duration::from_millis(10),
7443        );
7444        assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
7445        // …but `l` at the same instant passes (its own clock).
7446        s.tick_at(
7447            &press(KeyCode::Char('l')),
7448            t + std::time::Duration::from_millis(10),
7449        );
7450        assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
7451    }
7452
7453    // ── Cursors newtype is the single cursor home ──────────────────────
7454
7455    #[test]
7456    fn cursor_home_preserves_single_cursor_behavior() {
7457        // The typed `Cursors` wrapper behaves exactly like the old bare
7458        // `Position` field for single-cursor editing: the read accessor
7459        // tracks every mutation routed through `set_cursor`, and there is
7460        // exactly one caret.
7461        let mut s = new_state_with("hello\nworld\nthere");
7462        assert_eq!(s.cursor(), Position::ZERO);
7463        assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
7464
7465        s.apply_motion(Motion::Down);
7466        s.apply_motion(Motion::Right);
7467        s.apply_motion(Motion::Right);
7468        assert_eq!(s.cursor(), Position::new(1, 2));
7469        // Still a single caret after a sequence of motions.
7470        assert_eq!(s.cursors.count(), 1);
7471
7472        // The accessor is the SAME value the viewport-follow path read.
7473        let w = s.layout.active_window().unwrap();
7474        assert!(w.viewport.top_line <= s.cursor().line);
7475    }
7476
7477    #[test]
7478    fn insert_mode_is_ungated_so_repeat_typing_works() {
7479        // Holding a key to repeat-type a character is intended in Insert
7480        // mode — the gate must NOT suppress it. 10 rapid identical `x`
7481        // keystrokes at the same instant must all land as text.
7482        let mut s = new_state_with("");
7483        s.tick(&press(KeyCode::Char('i')));
7484        assert_eq!(s.modal.mode(), Mode::Insert);
7485        let t = std::time::Instant::now();
7486        for _ in 0..10 {
7487            s.tick_at(&press(KeyCode::Char('x')), t);
7488        }
7489        assert_eq!(
7490            s.buffers.get(s.active).unwrap().to_string(),
7491            "xxxxxxxxxx",
7492            "insert-mode repeat typing is ungated",
7493        );
7494    }
7495
7496    // ── the courier seam (denrei) ────────────────────────────────────
7497    //
7498    // What these pin is not "work happens off-thread" — that is the runner's
7499    // business. It is that a reply computed against one world cannot be
7500    // applied against a different one, and that the machinery says so out loud
7501    // when it declines to do something.
7502
7503    mod courier_seam {
7504        use super::new_state_with;
7505        use escriba_madoguchi::Negai;
7506        use escriba_madoguchi::errand::{Crew, Errand, Freight, Parcel, Runner};
7507        use escriba_shirube::{Anchor, Axis, ResultList, SessionKind};
7508        use std::sync::Arc;
7509        use std::sync::atomic::AtomicBool;
7510        use std::sync::mpsc::Sender;
7511
7512        fn a_scan() -> Freight {
7513            Freight::Scan {
7514                raw: "needle".into(),
7515                case: escriba_search::CaseMode::Smart,
7516                root: ".".into(),
7517            }
7518        }
7519
7520        /// Replies with whatever slip it was built with, immediately and on the
7521        /// calling thread — so these tests assert the SEAM, not thread timing.
7522        struct Says(Negai);
7523        impl Runner for Says {
7524            fn start(&self, e: Errand, _c: Arc<AtomicBool>, reply: Sender<Parcel>) {
7525                let _ = reply.send(Parcel {
7526                    id: e.id,
7527                    slip: self.0.clone(),
7528                });
7529            }
7530        }
7531
7532        /// Replies by wrapping its payload in the anchor the DISPATCHER sealed
7533        /// — which is what a real runner does: it echoes back the seal it was
7534        /// handed, because it has no way to mint its own.
7535        struct EchoesSeal(Negai);
7536        impl Runner for EchoesSeal {
7537            fn start(&self, e: Errand, _c: Arc<AtomicBool>, reply: Sender<Parcel>) {
7538                let _ = reply.send(Parcel {
7539                    id: e.id,
7540                    slip: Negai::ErrandReply {
7541                        anchor: e.anchor.into_anchor(),
7542                        then: Box::new(self.0.clone()),
7543                    },
7544                });
7545            }
7546        }
7547
7548        fn crew_with_scan(r: impl Runner + 'static) -> Crew {
7549            Crew {
7550                scan: Box::new(r),
7551                diagnostics: Box::new(escriba_madoguchi::errand::Idle("t")),
7552                format: Box::new(escriba_madoguchi::errand::Idle("t")),
7553            }
7554        }
7555
7556        /// The whole path in one test: a handler names a class of work, the
7557        /// dispatcher seals it, a runner answers, and the reply is applied at a
7558        /// tick boundary.
7559        #[test]
7560        fn an_errand_is_dispatched_sealed_and_its_reply_applied_at_the_drain() {
7561            let mut st = new_state_with("x\n");
7562            st.hire(crew_with_scan(EchoesSeal(Negai::Message("done".into()))));
7563
7564            st.honour_one(Negai::Errand(Box::new(a_scan())));
7565            assert!(
7566                !st.messages.iter().any(|m| m == "done"),
7567                "nothing is applied before the drain"
7568            );
7569
7570            st.deliver();
7571            assert!(
7572                st.messages.iter().any(|m| m == "done"),
7573                "the reply lands at the drain: {:?}",
7574                st.messages
7575            );
7576        }
7577
7578        /// **The reason the whole seam exists.** A reply sealed against the
7579        /// world at dispatch must be discarded once that world has moved.
7580        #[test]
7581        fn a_reply_whose_world_moved_is_dropped() {
7582            let mut st = new_state_with("x\n");
7583            st.hire(crew_with_scan(EchoesSeal(Negai::Message("late".into()))));
7584
7585            st.honour_one(Negai::Errand(Box::new(a_scan())));
7586            // The surface the scan feeds closed while it was running.
7587            st.bump_scan_gen();
7588            st.deliver();
7589
7590            assert!(
7591                !st.messages.iter().any(|m| m == "late"),
7592                "a superseded reply must not be applied: {:?}",
7593                st.messages
7594            );
7595        }
7596
7597        /// The converse, so the test above is not passing because nothing ever
7598        /// applies.
7599        #[test]
7600        fn a_reply_whose_world_held_is_applied() {
7601            let mut st = new_state_with("x\n");
7602            st.hire(crew_with_scan(EchoesSeal(Negai::Message("ok".into()))));
7603            st.honour_one(Negai::Errand(Box::new(a_scan())));
7604            st.deliver();
7605            assert!(st.messages.iter().any(|m| m == "ok"));
7606        }
7607
7608        /// A scan must NOT be staled by typing. It reads the filesystem; no
7609        /// text revision has anything to say about it, and anchoring one on the
7610        /// buffers would kill every result on the next keystroke.
7611        #[test]
7612        fn typing_does_not_stale_a_scan_reply() {
7613            let mut st = new_state_with("x\n");
7614            st.hire(crew_with_scan(EchoesSeal(Negai::Message("rows".into()))));
7615            st.honour_one(Negai::Errand(Box::new(a_scan())));
7616
7617            st.insert_text("hello");
7618            st.deliver();
7619            assert!(
7620                st.messages.iter().any(|m| m == "rows"),
7621                "a scan does not depend on buffer text: {:?}",
7622                st.messages
7623            );
7624        }
7625
7626        /// The seal's OWN anchor becomes the list's seal. Re-sealing at the
7627        /// arrival world would widen a one-axis claim into an every-buffer one,
7628        /// so the findings would die on the next unrelated edit.
7629        #[test]
7630        fn findings_from_an_errand_keep_the_narrow_seal_they_were_computed_with() {
7631            let mut st = new_state_with("x\n");
7632            st.hire(crew_with_scan(EchoesSeal(Negai::PublishFindings {
7633                list: "grep".into(),
7634                findings: vec![],
7635            })));
7636            st.honour_one(Negai::Errand(Box::new(a_scan())));
7637            st.deliver();
7638
7639            let sealed_with = st.results.get("grep").expect("published").anchor().clone();
7640            let axes = sealed_with.axes();
7641            assert_eq!(axes.len(), 1, "narrow, not the whole world: {axes:?}");
7642            assert!(
7643                matches!(axes[0], Axis::Session(SessionKind::Scan, _)),
7644                "sealed on the scan session: {axes:?}"
7645            );
7646
7647            // …and the consequence that makes it worth doing: an edit
7648            // elsewhere does not discard it.
7649            st.insert_text("more");
7650            assert!(
7651                !st.results
7652                    .get("grep")
7653                    .expect("still there")
7654                    .is_stale(&st.world()),
7655                "an unrelated edit must not stale a scan list"
7656            );
7657        }
7658
7659        /// A directly-dispatched `PublishFindings` — an on-tick producer like
7660        /// the marker scan — still seals at the world, which is correct for it.
7661        /// The special case must not have changed that.
7662        #[test]
7663        fn a_direct_publish_still_seals_at_the_world() {
7664            let mut st = new_state_with("x\n");
7665            st.honour_one(Negai::PublishFindings {
7666                list: "todo".into(),
7667                findings: vec![],
7668            });
7669            let axes = st.results.get("todo").expect("published").anchor().axes();
7670            assert!(
7671                axes.len() > 1,
7672                "the on-tick path anchors on the whole world: {axes:?}"
7673            );
7674        }
7675
7676        /// An empty anchor is fresh against every world, so a forged reply
7677        /// carrying one bypasses the gate entirely. The courier cannot produce
7678        /// this — `seal` returns a `NonEmptyAnchor` — and the test exists to
7679        /// document why that type is not decoration.
7680        #[test]
7681        fn an_empty_anchor_would_bypass_the_gate_which_is_why_seal_cannot_mint_one() {
7682            let mut st = new_state_with("x\n");
7683            st.bump_scan_gen();
7684            st.bump_lsp_gen();
7685            st.insert_text("moved a long way");
7686
7687            st.honour_one(Negai::ErrandReply {
7688                anchor: Anchor::new(),
7689                then: Box::new(Negai::Message("forged".into())),
7690            });
7691            assert!(
7692                st.messages.iter().any(|m| m == "forged"),
7693                "an empty anchor passes any world — the hazard NonEmptyAnchor removes"
7694            );
7695        }
7696
7697        /// Closing the picker supersedes the scan feeding it. Both closing
7698        /// paths must do it — choosing a row closes the overlay exactly as Esc
7699        /// does, and only handling Esc leaves a scan running after every pick.
7700        #[test]
7701        fn closing_the_picker_supersedes_the_scan_it_was_feeding() {
7702            let mut st = new_state_with("x\n");
7703            st.hire(crew_with_scan(EchoesSeal(Negai::Message("rows".into()))));
7704            st.honour_one(Negai::Errand(Box::new(a_scan())));
7705
7706            st.close_picker();
7707            st.deliver();
7708            assert!(
7709                !st.messages.iter().any(|m| m == "rows"),
7710                "rows must not reopen a picker the operator closed: {:?}",
7711                st.messages
7712            );
7713        }
7714
7715        /// The default state. An errand with nobody hired must report that it
7716        /// went nowhere — a request that silently does nothing is the exact
7717        /// failure the pre-courier stub had.
7718        #[test]
7719        fn an_errand_with_no_crew_hired_says_so() {
7720            let mut st = new_state_with("x\n");
7721            st.honour_one(Negai::Errand(Box::new(a_scan())));
7722            st.deliver();
7723            assert!(
7724                st.messages.iter().any(|m| m.contains("scan")),
7725                "the inert crew announces: {:?}",
7726                st.messages
7727            );
7728        }
7729
7730        /// A quiet tick must be free — `deliver` is called on every frame.
7731        #[test]
7732        fn delivering_nothing_does_not_repaint() {
7733            let mut st = new_state_with("x\n");
7734            let before = st.edit_gen();
7735            st.deliver();
7736            assert_eq!(st.edit_gen(), before, "an empty drain is not a change");
7737        }
7738
7739        /// …and a tick that DID deliver must repaint, or the result sits in
7740        /// state that nothing draws.
7741        #[test]
7742        fn delivering_something_repaints() {
7743            let mut st = new_state_with("x\n");
7744            st.hire(crew_with_scan(Says(Negai::Message("hi".into()))));
7745            st.honour_one(Negai::Errand(Box::new(a_scan())));
7746            let before = st.edit_gen();
7747            st.deliver();
7748            assert_ne!(st.edit_gen(), before, "a delivered reply repaints");
7749        }
7750
7751        /// The two session kinds must not alias at the runtime level either: an
7752        /// LSP restart must not discard scan results, and vice versa.
7753        #[test]
7754        fn the_two_session_generations_are_independent() {
7755            let mut st = new_state_with("x\n");
7756            let scan_sealed = ResultList::new(
7757                vec![],
7758                Anchor::new().on(Axis::Session(SessionKind::Scan, st.scan_gen)),
7759            );
7760            st.bump_lsp_gen();
7761            assert!(
7762                !scan_sealed.is_stale(&st.world()),
7763                "an LSP restart must not discard scan results"
7764            );
7765            st.bump_scan_gen();
7766            assert!(scan_sealed.is_stale(&st.world()), "…but a scan bump does");
7767        }
7768
7769        #[test]
7770        fn every_freight_class_seals_on_something() {
7771            let mut st = new_state_with("x\n");
7772            let active = st.active;
7773            for freight in [
7774                a_scan(),
7775                Freight::Diagnostics {
7776                    buffer: active,
7777                    path: "a.nix".into(),
7778                    language: None,
7779                    text: String::new(),
7780                },
7781                Freight::Format {
7782                    buffer: active,
7783                    path: "a.nix".into(),
7784                    language: None,
7785                    text: String::new(),
7786                },
7787            ] {
7788                let sealed = st.seal(&freight);
7789                assert!(
7790                    !sealed.as_anchor().is_empty(),
7791                    "{} sealed on nothing",
7792                    freight.label()
7793                );
7794            }
7795            let _ = &mut st;
7796        }
7797    }
7798}