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        // ── OPERAND CAPTURE — the keys that are ARGUMENTS, not bindings ──
2278        //
2279        // `di(`, `fx`, `` `a ``, `rZ`: in each, the second keystroke is an
2280        // operand of a half-typed gesture and must be claimed before the
2281        // sequence stepper and before the keymap, or it resolves as whatever
2282        // it happens to be bound to (`i` enters Insert, `w` moves a word).
2283        //
2284        // This was four near-identical inlined blocks. It is a TABLE now
2285        // because **the order is the correctness property**, and an order that
2286        // lives in the arrangement of code is protected by nothing —
2287        // `operand_capture_order.rs` asserts this list, which the four blocks
2288        // could not be. Each adjacency below is a real dependency, not a
2289        // preference; see that test for the failure each one prevents.
2290        for cap in OPERAND_CHAIN {
2291            let Some(outcome) = (cap.claim)(self, key.clone()) else {
2292                continue;
2293            };
2294            match outcome {
2295                ObjectKey::Consumed => return,
2296                ObjectKey::Compose(a) => {
2297                    match cap.count {
2298                        // The object path applies its own repeats before
2299                        // returning (`2diw`), so re-counting here would square
2300                        // the count.
2301                        OperandCount::SelfCounted => self.apply(&a),
2302                        OperandCount::Drained => {
2303                            let n = self.modal.pending_count().unwrap_or(1);
2304                            self.modal.clear_count();
2305                            self.apply_counted(&a, n);
2306                        }
2307                    }
2308                    return;
2309                }
2310            }
2311        }
2312        // Multi-key sequence resolution runs first: a key that begins or
2313        // continues a bound sequence (`<leader>ff`, `gg`) is held or
2314        // resolved here before the single-key path sees it.
2315        match self.step_sequence(key) {
2316            SeqStep::Pending => return,
2317            SeqStep::Resolved(action) => {
2318                let count = self.modal.pending_count().unwrap_or(1);
2319                self.modal.clear_count();
2320                for _ in 0..count {
2321                    self.apply(&action);
2322                    if self.quit_requested {
2323                        return;
2324                    }
2325                }
2326                return;
2327            }
2328            SeqStep::Passthrough => {}
2329        }
2330        let counted = self.keymap.dispatch(&self.modal, key);
2331        // Count prefixes accumulate into modal state.
2332        if matches!(counted.action, Action::Pending) {
2333            if let Key::Char(c) = key {
2334                if c.is_ascii_digit() {
2335                    let d = u32::from(*c as u8 - b'0');
2336                    self.modal.append_count(d);
2337                }
2338            }
2339            return;
2340        }
2341        // The count flows through the operator-pending FSM (apply_counted), which
2342        // owns repetition: a bare motion runs count× , an operator captures its
2343        // count, and an operated motion multiplies the two. No naive outer loop.
2344        self.apply_counted(&counted.action, counted.count);
2345        // After applying, reset pending count.
2346        self.modal.clear_count();
2347    }
2348
2349    /// Advance the multi-key pending-stroke state machine for `key`.
2350    ///
2351    /// Sequences only apply in normal / visual modes — insert and
2352    /// command modes treat keys as literal text. Rules:
2353    /// - Mid-sequence: extend the pending prefix. Exact match →
2354    ///   [`SeqStep::Resolved`]; still a live prefix → [`SeqStep::Pending`];
2355    ///   otherwise abort the sequence and re-process this key fresh.
2356    /// - Not mid-sequence: if `key` begins a bound sequence AND is not
2357    ///   itself a complete single binding (single bindings win, so no
2358    ///   chord timeout is needed) → start pending. Otherwise
2359    ///   [`SeqStep::Passthrough`] to the single-key dispatcher.
2360    fn step_sequence(&mut self, key: &Key) -> SeqStep {
2361        let mode = self.modal.mode();
2362        if !matches!(mode, Mode::Normal | Mode::Visual | Mode::VisualLine) {
2363            return SeqStep::Passthrough;
2364        }
2365        if !self.pending_keys.is_empty() {
2366            let mut seq = self.pending_keys.clone();
2367            seq.push(key.clone());
2368            if let Some(b) = self.keymap.lookup_sequence(mode, &seq) {
2369                let action = b.action.clone();
2370                self.pending_keys.clear();
2371                return SeqStep::Resolved(action);
2372            }
2373            if self.keymap.is_sequence_prefix(mode, &seq) {
2374                self.pending_keys = seq;
2375                return SeqStep::Pending;
2376            }
2377            // The key broke the in-progress sequence — abort it and let
2378            // the key be re-processed as a fresh stroke below.
2379            self.pending_keys.clear();
2380        }
2381        let start = [key.clone()];
2382        if self.keymap.is_sequence_prefix(mode, &start) && self.keymap.lookup(mode, key).is_none() {
2383            self.pending_keys = start.to_vec();
2384            return SeqStep::Pending;
2385        }
2386        SeqStep::Passthrough
2387    }
2388
2389    /// The primary cursor position. The single read accessor — every
2390    /// renderer + motion path goes through it, so the underlying
2391    /// representation (today a single-cursor [`Cursors`]) can grow to
2392    /// multi-caret without changing read sites.
2393    #[must_use]
2394    pub fn cursor(&self) -> Position {
2395        self.cursors.primary()
2396    }
2397
2398    /// The **single** cursor-mutation path. Clamp the requested position to
2399    /// the active buffer's bounds, then scroll the active window's viewport
2400    /// to contain it on BOTH axes. Routing every cursor change through this
2401    /// (and through [`Cursors::set_primary`]) makes "cursor outside its
2402    /// viewport" an unrepresentable state, AND keeps cursor state in ONE
2403    /// typed home — there is no code path that advances the cursor without
2404    /// re-deriving the viewport from it, and no second `Position` field to
2405    /// fall out of sync.
2406    /// Re-assert the cursor-visibility invariant against the CURRENT
2407    /// viewport.
2408    ///
2409    /// A resize changes how much a face can show without moving the cursor,
2410    /// so nothing would otherwise re-run `scroll_to_contain` — the cursor
2411    /// would sit off-screen until the operator happened to move it. Every
2412    /// face calls this after telling the runtime its new size.
2413    pub fn refollow_cursor(&mut self) {
2414        self.set_cursor(self.cursors.primary());
2415    }
2416
2417    fn set_cursor(&mut self, pos: Position) {
2418        self.place_cursor(pos, CursorRest::OnCharacter);
2419    }
2420
2421    /// The **single** cursor-mutation body. `rest` says what kind of place the
2422    /// caller is asking for — see [`CursorRest`].
2423    fn place_cursor(&mut self, pos: Position, rest: CursorRest) {
2424        let clamped = if let Some(buf) = self.buffers.get(self.active) {
2425            let on_buffer = buf.clamp(pos);
2426            // In Normal mode the cursor sits ON a character; only Insert may
2427            // park past the last one, because that is where the next typed
2428            // character goes.
2429            //
2430            // `Buffer::clamp` cannot make this call — it answers "is this
2431            // position inside the text", which is a question about the BUFFER,
2432            // and one-past-the-end legitimately is. Whether the cursor may
2433            // REST there is a question about the MODE, so it is asked here,
2434            // once, on the single cursor-mutation path. Every motion inherits
2435            // it: `w` onto the last word, `$`, `x` at end of line.
2436            if rest == CursorRest::OnCharacter && self.modal.mode() == Mode::Normal {
2437                Position::new(
2438                    on_buffer.line,
2439                    on_buffer
2440                        .column
2441                        .min(buf.line_len_chars(on_buffer.line).saturating_sub(1)),
2442                )
2443            } else {
2444                on_buffer
2445            }
2446        } else {
2447            pos
2448        };
2449        self.cursors.set_primary(clamped);
2450        if let Some(w) = self.layout.active_window_mut() {
2451            w.viewport = w.viewport.scroll_to_contain(self.cursors.primary(), 2);
2452        }
2453    }
2454
2455    /// Dispatch one resolved action at count 1. See [`apply_counted`](Self::apply_counted).
2456    fn apply(&mut self, action: &Action) {
2457        self.apply_counted(action, 1);
2458    }
2459
2460    /// Dispatch one resolved action with its count. Routes `(action, count)`
2461    /// through the operator-pending FSM ([`OperatorPending`], on `zenmai`): most
2462    /// actions pass straight to [`apply_resolved`](Self::apply_resolved) carrying
2463    /// their count (so `5j` runs the motion 5×), an operator key is held, and an
2464    /// operator-then-motion pair is rewritten into a counted
2465    /// [`Action::ApplyOperator`] (so `3dw` deletes 3 words). The FSM owns count
2466    /// composition — there is no naive outer repeat loop.
2467    fn apply_counted(&mut self, action: &Action, count: u32) {
2468        // An uncompilable pattern must not reach the operator machine.
2469        //
2470        // `SearchState::accept` puts the prompt BACK on a compile error so the
2471        // typed text is not lost — but the FSM had already transitioned out of
2472        // `AwaitingSearch` on the way in, so the prompt survived and the
2473        // OPERATOR did not, with nothing said about it. The `d` was simply
2474        // gone, and the corrected pattern then ran as a bare search.
2475        //
2476        // The machine is a pure `(State, Event) -> (State, effects)` and
2477        // cannot observe the result of an effect, so it cannot decide this
2478        // itself. The fix is to stop handing it an event it has no business
2479        // deciding: the runtime classifies the submit first, from state it
2480        // already holds. `prompt_error` returns `None` for an EMPTY prompt, so
2481        // the bare-`/<CR>` reuse path is untouched.
2482        //
2483        // Tier-honest: parse-rejected at the boundary, not
2484        // truly-unrepresentable.
2485        if matches!(action, Action::SubmitCommand) {
2486            if let Some(e) = self.search.prompt_error() {
2487                let mut m = String::from("E383: Invalid search string: ");
2488                m.push_str(&e.to_string());
2489                self.messages.push(m);
2490                return;
2491            }
2492        }
2493
2494        // `|` is the one motion whose count is an ARGUMENT rather than a
2495        // repetition: `40|` means column 40, not "column 1, forty times"
2496        // (which is column 1). Folded in before the FSM sees it, so the
2497        // machine keeps one rule — counts repeat — and the exception lives
2498        // where the exception is.
2499        let action = &match action {
2500            Action::Move(Motion::Column(_)) => Action::Move(Motion::Column(count)),
2501            a => a.clone(),
2502        };
2503        let count = match action {
2504            Action::Move(Motion::Column(_)) => 1,
2505            _ => count,
2506        };
2507        for (resolved, times) in self.op_pending.dispatch((action.clone(), count)) {
2508            // Two ways an action can carry a count, and the split is real:
2509            //
2510            //   REPEAT (`5j`) — run it `times` over. The default.
2511            //   ABSORB (`3dw`, `2dd`, `3p`) — ONE operation over an extent
2512            //     resolved `times` over.
2513            //
2514            // The distinction is not pedantry. Repeating an operator works by
2515            // accident for delete — the text vanishes, so the cursor lands
2516            // somewhere new each round — and is simply wrong for yank, which
2517            // does not move: `2yw` re-yanked the FIRST word twice and put
2518            // "one one " in the register. It is wrong for `2dd` in the same
2519            // shape (the register kept only the second line, so `2ddp` put
2520            // back half), and it would make `3p` three undo steps.
2521            //
2522            // Both kinds now go THROUGH `apply_resolved`, and that is the
2523            // load-bearing part. The absorbing three used to short-circuit
2524            // straight to their executors from here, skipping the damage
2525            // classification and the dot-register recording at that function's
2526            // tail — so `.` after `3p` or `dw` replayed nothing, and the
2527            // repaint span was whatever the previous action had asked for.
2528            let absorbs = absorbs_count(&resolved);
2529            let (reps, n) = if absorbs { (1, times) } else { (times, 1) };
2530            for _ in 0..reps {
2531                self.apply_resolved(&resolved, n);
2532                if self.quit_requested {
2533                    return;
2534                }
2535            }
2536        }
2537    }
2538
2539    /// The active buffer's text. Search is a pure function of it.
2540    /// The active buffer's text revision — the token an offset measured
2541    /// against it should carry.
2542    #[must_use]
2543    fn text_rev(&self) -> TextRev {
2544        self.buffers
2545            .get(self.active)
2546            .map_or_else(TextRev::default, escriba_buffer::Buffer::text_rev)
2547    }
2548
2549    fn active_text(&self) -> String {
2550        self.buffers
2551            .get(self.active)
2552            .map(escriba_buffer::Buffer::to_string)
2553            .unwrap_or_default()
2554    }
2555
2556    /// The cursor as a char offset — the coordinate search speaks.
2557    fn cursor_char(&self) -> usize {
2558        self.buffers
2559            .get(self.active)
2560            .and_then(|b| b.position_to_char(self.cursor()).ok())
2561            .unwrap_or(0)
2562    }
2563
2564    /// Move the cursor onto a match and report a wrap the way vim does.
2565    /// The status line as data — what every face draws.
2566    ///
2567    /// One model, so the two faces can only disagree about styling. Before
2568    /// this existed the GPU face built its own line from a fixed `format!()`
2569    /// and drew neither the prompt nor any message, which made a fully
2570    /// working `/` look like a dead key on escriba's default renderer.
2571    #[must_use]
2572    pub fn status_model(&self) -> StatusModel<'_> {
2573        let cursor = self.cursor();
2574        let prompt = self.search.prompt();
2575
2576        let kind = match prompt.map(|p| p.direction) {
2577            Some(escriba_search::Direction::Forward) => PromptKind::SearchForward,
2578            Some(escriba_search::Direction::Backward) => PromptKind::SearchBackward,
2579            // Command mode with no search prompt open is an ex-command; the
2580            // typed `Option<Prompt>` is the discriminator, never a mode flag.
2581            None if self.modal.mode() == Mode::Command => PromptKind::Ex,
2582            None => PromptKind::None,
2583        };
2584
2585        StatusModel {
2586            mode: self.modal.mode(),
2587            line: cursor.line.saturating_add(1) as usize,
2588            column: cursor.column.saturating_add(1) as usize,
2589            prompt: kind,
2590            prompt_text: prompt
2591                .map_or_else(|| self.modal.minibuffer(), escriba_search::Prompt::text),
2592            prompt_caret: prompt.map_or_else(
2593                || self.modal.minibuffer_caret(),
2594                escriba_search::Prompt::caret,
2595            ),
2596            count: self.match_count(),
2597            message: self.messages.last().map(String::as_str),
2598        }
2599    }
2600
2601    /// `[3/17]` for the current pattern.
2602    ///
2603    /// While a prompt is open the count describes the PREVIEW — the answer to
2604    /// "what would Enter do", which is the question being asked mid-typing.
2605    /// Once committed it describes where the cursor actually is.
2606    #[must_use]
2607    fn match_count(&self) -> MatchCount {
2608        if self.search.is_prompting() {
2609            let text = self.active_text();
2610            // ONE scan, four outcomes. `Incomplete` and `NoMatch` used to be
2611            // the same `None`, so a half-typed character class reported
2612            // `[0/0]` — telling the user their pattern matches nothing while
2613            // they are still writing it.
2614            return match self.search.preview(&text) {
2615                escriba_search::Preview::Landed { step, total } => {
2616                    MatchCount::new(step.index, total)
2617                }
2618                escriba_search::Preview::NoMatch => MatchCount::None,
2619                escriba_search::Preview::Incomplete | escriba_search::Preview::Idle => {
2620                    MatchCount::Idle
2621                }
2622            };
2623        }
2624        if self.search.pattern().is_none() {
2625            return MatchCount::Idle;
2626        }
2627        let total = self.search.matches().len();
2628        // Read THROUGH the anchor: an ordinal computed against text that has
2629        // since changed reads as absent, so a stale count cannot be displayed.
2630        let rev = self.text_rev();
2631        self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
2632            if total == 0 {
2633                MatchCount::None
2634            } else {
2635                MatchCount::Idle
2636            },
2637            |&i| MatchCount::new(i, total),
2638        )
2639    }
2640
2641    /// `.` — replay the last change at the cursor.
2642    ///
2643    /// Two steps, because a change can be two: run the action, then re-type
2644    /// whatever followed it. `cgn` + `.` is exactly this — change the next
2645    /// match, then repeat that whole gesture on the one after.
2646    fn repeat_last_change(&mut self) {
2647        let Some(change) = self.last_change.clone() else {
2648            self.messages
2649                .push("E32: No previous change to repeat".to_string());
2650            return;
2651        };
2652
2653        // Replayed the same way it ran: an absorbing action takes its count as
2654        // an argument, a repeating one takes it as a loop. Getting this
2655        // backwards makes `3dw` then `.` delete one word — which is what it
2656        // did while the recorded count was hardcoded to 1.
2657        let n = change.count.max(1);
2658        if absorbs_count(&change.action) {
2659            self.apply_resolved(&change.action, n);
2660        } else {
2661            for _ in 0..n {
2662                self.apply_resolved(&change.action, 1);
2663            }
2664        }
2665        for c in change.inserted.chars() {
2666            self.apply_resolved(&Action::InsertChar(c), 1);
2667        }
2668        if self.modal.mode() == Mode::Insert {
2669            // A replayed change must not leave the editor in Insert — the
2670            // original ended with an Esc the recording deliberately does not
2671            // store, since it is punctuation rather than part of the change.
2672            self.apply_resolved(&Action::ChangeMode(Mode::Normal), 1);
2673        }
2674        // The replay wrote through `apply_resolved`, which re-records
2675        // `last_change` from the inner action. Put the ORIGINAL back so a
2676        // second `.` repeats the same change rather than a fragment of it.
2677        self.last_change = Some(change);
2678        self.recording_insert = false;
2679    }
2680
2681    /// Resolve a text object to the range it names.
2682    ///
2683    /// `gn` uses the INCLUSIVE step, so a cursor already sitting inside a
2684    /// match operates on THAT match rather than skipping to the next — which
2685    /// is what makes `cgn` then `.` walk matches one at a time instead of
2686    /// every other one.
2687    /// `dd` — the current line INCLUDING its terminator.
2688    ///
2689    /// Taking the newline is what makes `dd` remove a line rather than blank
2690    /// it. On the last line there is no following newline to take, so it
2691    /// falls back to the preceding one — otherwise `dd` on the final line
2692    /// leaves an empty line behind, which is the one case a naive
2693    /// "start-of-line to start-of-next-line" range gets wrong.
2694    fn object_line(&self) -> Option<Range> {
2695        self.line_extent(1).map(|e| e.capture)
2696    }
2697
2698    /// `{n}dd` — `n` whole lines from the cursor down.
2699    ///
2700    /// A counted linewise operator is ONE operation over an `n`-line extent,
2701    /// not `n` operations over one line — the same rule `apply_operator_n`
2702    /// enforces for motions, and it broke here in exactly the way that note
2703    /// predicts. `2dd` ran the single-line object twice: the text came out
2704    /// right (deleting a line brings the next one under the cursor, so the
2705    /// repeat lands correctly by accident) and the REGISTER held only the
2706    /// second line, so `2ddp` silently put back half of what it took.
2707    ///
2708    /// Returns an [`Extent`], not a range, because a linewise CHANGE cuts
2709    /// something different from what a linewise DELETE cuts: `dd` takes the
2710    /// line and its terminator, `cc`/`S` clear the line's text and keep the
2711    /// line. Both put the same thing in the register.
2712    fn line_extent(&self, n: u32) -> Option<Extent> {
2713        let buf = self.buffers.get(self.active)?;
2714        let line = self.cursor().line;
2715        let last = buf.line_count().saturating_sub(1);
2716        // The last line the extent reaches, clamped so `999dd` near the end of
2717        // a file takes what is there rather than resolving to nothing.
2718        //
2719        // Clamped to `last_text_line`, NOT to `last`: on a file ending in `\n`
2720        // those differ by the phantom row the rope reports, and letting the
2721        // extent reach it sent the whole resolution down the "no following
2722        // newline" branch below — so `dd` on the last real line ate the file's
2723        // trailing newline instead of the line. It also makes a `dd` issued
2724        // FROM the phantom row resolve to an empty range (a no-op) rather than
2725        // to a destructive one.
2726        let end = line
2727            .saturating_add(n.max(1).saturating_sub(1))
2728            .min(last_text_line(buf));
2729        if line > last_text_line(buf) {
2730            // The phantom row. There is no line here to operate on.
2731            return None;
2732        }
2733        // What a CHANGE cuts: the text of the named lines, terminators intact.
2734        // Independent of which capture branch runs below, because the lines
2735        // named are the same in all three.
2736        let removal = Range::new(
2737            Position::new(line, 0),
2738            Position::new(end, buf.line_len_chars(end)),
2739        );
2740        let capture = if end < last {
2741            Range::new(Position::new(line, 0), Position::new(end + 1, 0))
2742        } else if line > 0 {
2743            // Final line of a file with NO trailing newline: there is no
2744            // following line start to take a terminator from, so swallow the
2745            // PRECEDING one — otherwise `dd` blanks the line and leaves it.
2746            Range::new(
2747                Position::new(line - 1, buf.line_len_chars(line - 1)),
2748                Position::new(end, buf.line_len_chars(end)),
2749            )
2750        } else {
2751            // The extent is the whole buffer and there is no terminator to
2752            // take at either end: clear the text, keep the line itself.
2753            removal
2754        };
2755        Some(Extent {
2756            capture,
2757            removal,
2758            kind: RegisterKind::Linewise,
2759        })
2760    }
2761
2762    /// `iw` / `aw` — the word under the cursor.
2763    ///
2764    /// vim's `w` classes are word / punctuation / whitespace, and a text
2765    /// object never crosses a line. `around` additionally takes the trailing
2766    /// whitespace run, falling back to LEADING whitespace when there is none
2767    /// after — which is what vim does at end of line.
2768    fn object_word(&self, around: bool) -> Option<Range> {
2769        let buf = self.buffers.get(self.active)?;
2770        let pos = self.cursor();
2771        let text: Vec<char> = buf.line(pos.line)?.chars().collect();
2772        if text.is_empty() {
2773            return None;
2774        }
2775        let col = (pos.column as usize).min(text.len().saturating_sub(1));
2776
2777        #[derive(PartialEq, Clone, Copy)]
2778        enum Class {
2779            Word,
2780            Punct,
2781            Space,
2782        }
2783        let class = |c: char| {
2784            if c.is_alphanumeric() || c == '_' {
2785                Class::Word
2786            } else if c.is_whitespace() {
2787                Class::Space
2788            } else {
2789                Class::Punct
2790            }
2791        };
2792
2793        let here = class(text[col]);
2794        let mut start = col;
2795        while start > 0 && class(text[start - 1]) == here {
2796            start -= 1;
2797        }
2798        let mut end = col + 1;
2799        while end < text.len() && class(text[end]) == here {
2800            end += 1;
2801        }
2802
2803        if around {
2804            let after = end;
2805            while end < text.len() && class(text[end]) == Class::Space {
2806                end += 1;
2807            }
2808            // No trailing run: take the leading one instead, as vim does.
2809            if end == after {
2810                while start > 0 && class(text[start - 1]) == Class::Space {
2811                    start -= 1;
2812                }
2813            }
2814        }
2815
2816        Some(Range::new(
2817            Position::new(pos.line, start as u32),
2818            Position::new(pos.line, end as u32),
2819        ))
2820    }
2821
2822    /// `i(` / `a"` … — the region between a matched pair, on one line.
2823    ///
2824    /// Brackets NEST and quotes do not, and that is the only difference:
2825    /// with `open == close` the scan cannot count depth, so it takes the
2826    /// nearest delimiter on each side instead.
2827    fn object_delimited(&self, open: char, close: char, around: bool) -> Option<Range> {
2828        let buf = self.buffers.get(self.active)?;
2829        let pos = self.cursor();
2830        let text: Vec<char> = buf.line(pos.line)?.chars().collect();
2831        if text.is_empty() {
2832            return None;
2833        }
2834        let col = (pos.column as usize).min(text.len().saturating_sub(1));
2835
2836        let (l, r) = if open == close {
2837            // Quotes: nearest on each side, no nesting to track.
2838            let l = (0..=col).rev().find(|&i| text[i] == open)?;
2839            let r = ((col.max(l) + 1)..text.len()).find(|&i| text[i] == close)?;
2840            (l, r)
2841        } else {
2842            // Brackets: walk out counting depth, so an inner pair does not
2843            // terminate the search for the enclosing one.
2844            let mut depth = 0i32;
2845            let l = (0..=col).rev().find(|&i| {
2846                if text[i] == close && i != col {
2847                    depth += 1;
2848                    false
2849                } else if text[i] == open {
2850                    if depth == 0 {
2851                        true
2852                    } else {
2853                        depth -= 1;
2854                        false
2855                    }
2856                } else {
2857                    false
2858                }
2859            })?;
2860            depth = 0;
2861            let r = ((l + 1)..text.len()).find(|&i| {
2862                if text[i] == open {
2863                    depth += 1;
2864                    false
2865                } else if text[i] == close {
2866                    if depth == 0 {
2867                        true
2868                    } else {
2869                        depth -= 1;
2870                        false
2871                    }
2872                } else {
2873                    false
2874                }
2875            })?;
2876            (l, r)
2877        };
2878
2879        // `i` is strictly between the delimiters; `a` includes them.
2880        let (s, e) = if around { (l, r + 1) } else { (l + 1, r) };
2881        Some(Range::new(
2882            Position::new(pos.line, s as u32),
2883            Position::new(pos.line, e as u32),
2884        ))
2885    }
2886
2887    fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
2888        use escriba_core::TextObject as O;
2889
2890        // The text-scanning objects resolve against the BUFFER; the two
2891        // search objects resolve against the match set. Splitting here keeps
2892        // the search logic below exactly as it was rather than threading a
2893        // second concern through it.
2894        match object {
2895            O::Line => return self.object_line(),
2896            O::Word { around } => return self.object_word(around),
2897            O::Delimited {
2898                open,
2899                close,
2900                around,
2901            } => return self.object_delimited(open, close, around),
2902            O::NextMatch | O::PrevMatch => {}
2903        }
2904
2905        let at = self.cursor_char();
2906        let matches = self.search.matches();
2907
2908        // A match CONTAINING the cursor wins outright, whichever direction the
2909        // object names.
2910        //
2911        // Comparing only against `m.start` — which is what a `starts`-vector
2912        // plus `Bound::Inclusive` does — is right only when the cursor sits on
2913        // a match's FIRST character. One column further in, `start < at` and
2914        // the match is rejected, so `cgn` skipped the very instance the
2915        // operator was standing in and the rename silently missed it. vim
2916        // operates on the containing match from every interior column, and the
2917        // `starts`-only comparison cannot express "contains" because it never
2918        // looks at `m.end`.
2919        let idx = matches.iter().position(|m| m.contains(at)).or_else(|| {
2920            let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
2921            match object {
2922                O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
2923                // Every other variant returned above; `NextMatch` is the only
2924                // one that can reach here besides `PrevMatch`.
2925                _ => Bound::Inclusive.first_matching(&starts, at, true),
2926            }
2927        })?;
2928
2929        let m = matches.get(idx)?;
2930        let buf = self.buffers.get(self.active)?;
2931        Some(Range {
2932            start: buf.char_to_position(m.start),
2933            end: buf.char_to_position(m.end),
2934        })
2935    }
2936
2937    fn land_on(&mut self, step: escriba_search::Step) {
2938        if let Some(buf) = self.buffers.get(self.active) {
2939            let pos = buf.char_to_position(step.target.start);
2940            self.set_cursor(pos);
2941        }
2942        // The `[3/17]` numerator. `Step` has carried this index since the
2943        // engine was written — `engine.rs` even names the counter as the
2944        // reason it exists — and every consumer discarded it until now.
2945        self.search_at = Some(Anchored::new(step.index, self.text_rev()));
2946    }
2947
2948    /// vim's "search hit BOTTOM, continuing at TOP".
2949    ///
2950    /// One reporter, called by the two places a search can wrap: the shared
2951    /// commit and `n`/`N`. `land_on` deliberately does NOT report, or the bare
2952    /// commit would say it twice.
2953    fn report_wrap(&mut self, step: &escriba_search::Step) {
2954        if let Some(msg) = escriba_search::wrap_message(step.wrapped) {
2955            self.messages.push(msg.to_string());
2956        }
2957    }
2958
2959    /// `n` / `N`. Reports vim's E486 when the pattern matches nothing, rather
2960    /// than failing silently — a search that appears to do nothing is
2961    /// indistinguishable from a dropped keystroke.
2962    fn jump_search(&mut self, reverse: bool) {
2963        // Using the matches re-lights them: `n` after an auto-clear shows you
2964        // what you are walking through.
2965        self.search.relight();
2966        // `n` is a far jump — record where we leave from so `<C-o>` works.
2967        self.jumps.push(self.spot());
2968        let at = self.cursor_char();
2969        match self.search.repeat(at, reverse) {
2970            Some(step) => {
2971                // `n` wrapping the file says so, same as a commit does.
2972                self.report_wrap(&step);
2973                self.land_on(step);
2974            }
2975            None => {
2976                let msg = self.search.pattern().map_or_else(
2977                    || "E35: No previous regular expression".to_string(),
2978                    |p| {
2979                        let mut m = String::from("E486: Pattern not found: ");
2980                        m.push_str(p.raw());
2981                        m
2982                    },
2983                );
2984                self.messages.push(msg);
2985            }
2986        }
2987    }
2988
2989    /// Move the cursor to where the in-progress pattern would land, without
2990    /// committing anything. vim's `incsearch`.
2991    ///
2992    /// A pattern that does not compile yet (`/a[`, mid-typing) previews
2993    /// nothing and reports nothing — an error toast on every keystroke of a
2994    /// character class would be unusable.
2995    fn preview_search(&mut self) {
2996        let text = self.active_text();
2997        let Some(origin) = self.search.prompt().map(|p| p.origin) else {
2998            return;
2999        };
3000        let target = match self.search.preview(&text) {
3001            escriba_search::Preview::Landed { step, .. } => step.target.start,
3002            // Nothing to show: back to where the search started. Covers a
3003            // half-typed pattern and a pattern that finds nothing alike —
3004            // both mean "there is no match to preview".
3005            escriba_search::Preview::Idle
3006            | escriba_search::Preview::Incomplete
3007            | escriba_search::Preview::NoMatch => origin,
3008        };
3009        // A pattern that STOPS matching returns the cursor to the origin.
3010        //
3011        // Preview used to only ever move forward, so typing `ch` (a match) and
3012        // then `chz` (none) left the cursor parked on the `ch` match — a
3013        // preview showing a position the pattern no longer justifies, while
3014        // the count beside it read `[0/0]`. Restoring is also what makes
3015        // Escape's promise legible: at every keystroke the cursor is either on
3016        // a real match or back where you started, never on a stale one.
3017        if let Some(buf) = self.buffers.get(self.active) {
3018            let pos = buf.char_to_position(target);
3019            self.set_cursor(pos);
3020        }
3021    }
3022
3023    /// `d/foo<CR>` — commit the prompt and operate from the prompt's origin to
3024    /// where the search lands, as ONE action.
3025    ///
3026    /// Split from [`Self::submit_search`] rather than sharing it because the
3027    /// two want opposite things from the commit: the bare `/` MOVES the cursor
3028    /// to the match, and an operated `/` must NOT — the cursor is the
3029    /// operator's start point, and moving it first would leave the operator
3030    /// with a zero-width range.
3031    /// Commit the open search prompt. The ONE copy of the sequence.
3032    ///
3033    /// Reports its own failures (E486 / E35) so neither caller has to carry a
3034    /// third copy of the message strings. `Accepted::Invalid` cannot reach
3035    /// here — `apply_counted` rejects an uncompilable pattern at the dispatch
3036    /// boundary before the FSM or this method ever sees the submit.
3037    fn commit_search_prompt(&mut self) -> CommitOutcome {
3038        let text = self.active_text();
3039        let Some((origin, skip)) = self.search.prompt().map(|p| (p.origin, p.preview_skip()))
3040        else {
3041            return CommitOutcome::NoPrompt;
3042        };
3043
3044        match self.search.accept(&text) {
3045            escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
3046                self.modal.clear_minibuffer();
3047                self.modal.enter(Mode::Normal);
3048                match self.search.commit_step_skipping(origin, skip) {
3049                    Some(step) => {
3050                        // The wrap notice belongs HERE, once, for both commit
3051                        // paths. Reporting it in each caller is what let the
3052                        // operated path lose it in the first place — and my
3053                        // first attempt at this refactor duplicated it again
3054                        // rather than moving it, which the red proof caught.
3055                        self.report_wrap(&step);
3056                        CommitOutcome::Landed { origin, step }
3057                    }
3058                    None => {
3059                        self.report_pattern_not_found();
3060                        CommitOutcome::NotFound
3061                    }
3062                }
3063            }
3064            escriba_search::Accepted::NothingToRepeat => {
3065                self.modal.clear_minibuffer();
3066                self.modal.enter(Mode::Normal);
3067                self.messages
3068                    .push("E35: No previous regular expression".to_string());
3069                CommitOutcome::NoPrevious
3070            }
3071            // Unreachable: the boundary guard in `apply_counted` returns early
3072            // on an uncompilable pattern, leaving the prompt open. Reported
3073            // rather than `unreachable!()` — a panic in the editor's commit
3074            // path is a worse failure than a duplicate message.
3075            escriba_search::Accepted::Invalid(e) => {
3076                let mut m = String::from("E383: Invalid search string: ");
3077                m.push_str(&e.to_string());
3078                self.messages.push(m);
3079                CommitOutcome::NoPrompt
3080            }
3081        }
3082    }
3083
3084    /// vim's E486, with the pattern named. One place, so every path that fails
3085    /// to find reports identically.
3086    fn report_pattern_not_found(&mut self) {
3087        let mut m = String::from("E486: Pattern not found");
3088        if let Some(p) = self.search.pattern() {
3089            m.push_str(": ");
3090            m.push_str(p.raw());
3091        }
3092        self.messages.push(m);
3093    }
3094
3095    /// Bare `/foo<CR>` — commit and MOVE the cursor to the match.
3096    ///
3097    /// The only difference from the operated path is that this one lands;
3098    /// everything else lives in `commit_search_prompt`.
3099    fn submit_search(&mut self) {
3100        match self.commit_search_prompt() {
3101            CommitOutcome::Landed { origin, step } => {
3102                if let Some(buf) = self.buffers.get(self.active) {
3103                    let from = buf.char_to_position(origin);
3104                    self.jumps.push(escriba_core::Spot::new(self.active, from));
3105                }
3106                self.land_on(step);
3107            }
3108            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
3109        }
3110    }
3111
3112    /// `d/foo<CR>` — commit, then operate from the prompt's origin to where the
3113    /// search lands, as ONE action.
3114    ///
3115    /// The cursor must NOT move to the match first: it is the operator's start
3116    /// point. That is the whole reason this differs from the bare path, and
3117    /// now the only reason.
3118    fn submit_search_operated(&mut self, op: Operator) {
3119        match self.commit_search_prompt() {
3120            CommitOutcome::Landed { origin, step } => {
3121                if let Some(buf) = self.buffers.get(self.active) {
3122                    let from = buf.char_to_position(origin);
3123                    let target = buf.char_to_position(step.target.start);
3124                    // Operating over a search is itself a far jump.
3125                    self.jumps.push(escriba_core::Spot::new(self.active, from));
3126                    self.set_cursor(from);
3127                    self.apply_operator_to(op, target);
3128                }
3129            }
3130            CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
3131        }
3132    }
3133
3134    /// Execute one resolved action, with the count it ABSORBS.
3135    ///
3136    /// `count` is 1 for everything that repeats — the caller loops those — and
3137    /// is the gesture's full count for the arms listed in [`absorbs_count`].
3138    /// Every path lands here so the damage classification and dot-register
3139    /// recording at the tail run exactly once per gesture; the counted
3140    /// operators used to bypass this function and skipped both.
3141    fn apply_resolved(&mut self, action: &Action, count: u32) {
3142        // Snapshot the scope inputs before the mutation so the resulting
3143        // Damage covers the changed region (the S3 seal — conservative widen).
3144        let lines_before = self.active_line_count();
3145        // Snapshot for the dot register: the only reliable witness that this
3146        // action changed text is that the buffer's revision moved.
3147        let rev_before = self.text_rev();
3148        let cline_before = self.cursor().line;
3149        match action {
3150            // Every action with an exact slip equivalent goes through the
3151            // interpreter, so "undo" has ONE implementation rather than one
3152            // per entry point. These had already drifted: the executor
3153            // re-followed the viewport after undo and the M1 interpreter did
3154            // not, so `u` and `:undo` behaved differently within a milestone
3155            // of each other.
3156            // Listed EXPLICITLY rather than behind a `if lower(..).is_some()`
3157            // guard: a guard arm does not count toward exhaustiveness, so the
3158            // guarded form silently gave up the total match — the compiler
3159            // said so, and it was right. `lowering_and_dispatch_agree` pins
3160            // that this list and `lower` stay the same set.
3161            Action::Quit
3162            | Action::ClearSearchHighlight
3163            | Action::Save
3164            | Action::Undo
3165            | Action::Redo
3166            | Action::Edit(_) => {
3167                for slip in Self::lower(action, self.active).unwrap_or_default() {
3168                    self.honour_one(slip);
3169                }
3170            }
3171            Action::Move(m) => self.apply_motion(*m),
3172            Action::SearchOpen(dir) => {
3173                // vim's `/` is the command-line with a different prompt char,
3174                // so we reuse Command mode; `search.prompt` is what tells a
3175                // later <CR> this is a search and not an ex-command.
3176                let origin = self.cursor_char();
3177                self.search.open(*dir, origin);
3178                self.modal.enter(Mode::Command);
3179            }
3180            Action::SearchRepeat { reverse } => self.jump_search(*reverse),
3181            Action::SearchWord { reverse } => {
3182                let dir = if *reverse {
3183                    SearchDirection::Backward
3184                } else {
3185                    SearchDirection::Forward
3186                };
3187                let (text, at) = (self.active_text(), self.cursor_char());
3188                // `*` jumps, so it records too.
3189                self.jumps.push(self.spot());
3190                match self.search.search_word(&text, at, dir) {
3191                    Some(step) => self.land_on(step),
3192                    // vim beeps and stays put when there is no word under the
3193                    // cursor; a silent no-op would look like a broken key.
3194                    None => self
3195                        .messages
3196                        .push("E348: No string under cursor".to_string()),
3197                }
3198            }
3199            Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
3200            Action::TextObject(object) => {
3201                // Bare `gn` moves onto the match. vim additionally starts a
3202                // Visual selection of it; escriba's Visual plumbing does not
3203                // carry a selection an operator can consume yet, so this
3204                // stops at the jump rather than faking a selection that
3205                // nothing would honour.
3206                if let Some(range) = self.resolve_object(*object) {
3207                    self.jumps.push(self.spot());
3208                    self.set_cursor(range.start);
3209                } else {
3210                    self.report_pattern_not_found();
3211                }
3212            }
3213            // The linewise object is the one that can express an `n`-fold
3214            // extent, so it reads the count directly; every other object still
3215            // repeats (see `absorbs_count`).
3216            Action::ApplyOperatorObject {
3217                op,
3218                object: escriba_core::TextObject::Line,
3219            } => {
3220                if let Some(extent) = self.line_extent(count) {
3221                    self.apply_operator_over(*op, extent);
3222                }
3223            }
3224            Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
3225                // The kind comes from the OBJECT (`TextObject::register_kind`,
3226                // total over the enum), which is the only thing that knows:
3227                // `dd` on line 1 and a charwise `[(1,0), (2,0))` are the same
3228                // two positions.
3229                Some(range) => {
3230                    self.apply_operator_over(
3231                        *op,
3232                        Extent::from_object(range, object.register_kind()),
3233                    );
3234                }
3235                None => self.report_pattern_not_found(),
3236            },
3237            Action::Put { before } => self.put(*before, count),
3238            Action::ReplaceChar(ch) => self.replace_char(*ch, count),
3239            Action::JoinLines { space } => self.join_lines(*space, count),
3240            Action::RepeatLastChange => self.repeat_last_change(),
3241            Action::JumpBack => {
3242                let here = self.spot();
3243                if let Some(spot) = self.jumps.back(here) {
3244                    self.goto_spot(spot);
3245                } else {
3246                    self.messages
3247                        .push("E662: At start of changelist".to_string());
3248                }
3249            }
3250            Action::JumpForward => {
3251                if let Some(spot) = self.jumps.forward() {
3252                    self.goto_spot(spot);
3253                } else {
3254                    self.messages.push("E663: At end of changelist".to_string());
3255                }
3256            }
3257            Action::ChangeMode(m) => {
3258                // Leaving the cmdline abandons any open search prompt and
3259                // returns the cursor home. The COMMITTED pattern survives —
3260                // cancelling a new search must not erase the old highlights.
3261                if *m == Mode::Normal && self.search.is_prompting() {
3262                    if let Some(origin) = self.search.cancel() {
3263                        if let Some(buf) = self.buffers.get(self.active) {
3264                            let pos = buf.char_to_position(origin);
3265                            self.set_cursor(pos);
3266                        }
3267                    }
3268                }
3269                self.modal.enter(*m);
3270            }
3271            Action::EnterInsert(at) => self.enter_insert_at(*at),
3272            Action::InsertChar(c) => self.insert_char(*c),
3273
3274            Action::SubmitCommand => {
3275                if self.search.is_prompting() {
3276                    self.submit_search();
3277                } else {
3278                    self.submit_command();
3279                }
3280            }
3281            Action::Command { name, args } => self.run_command(name, args),
3282            Action::ApplyOperator { op, motion } => self.apply_operator_n(*op, *motion, count),
3283            // The operator-pending FSM consumes Operator keys (begins pending);
3284            // they never reach the executor. Defensive no-op for exhaustiveness.
3285            Action::Operator(_) => {}
3286            Action::PromptCaret { to } => {
3287                // Both prompts have a caret now, and the same keys move it.
3288                if self.search.is_prompting() {
3289                    self.search.move_caret(*to);
3290                } else {
3291                    self.modal.move_minibuffer_caret(*to);
3292                }
3293            }
3294            Action::SearchPreviewStep { forward } => {
3295                if self.search.is_prompting() {
3296                    self.search.preview_step(*forward);
3297                    self.preview_search();
3298                }
3299            }
3300            Action::DeleteForward => {
3301                if self.modal.mode() == Mode::Command {
3302                    if self.search.is_prompting() {
3303                        self.search.delete_at_caret();
3304                        self.preview_search();
3305                    } else {
3306                        self.modal.delete_minibuffer_at_caret();
3307                    }
3308                } else {
3309                    self.delete_after_cursor();
3310                }
3311            }
3312            Action::DeleteWordBefore => {
3313                if self.modal.mode() == Mode::Command {
3314                    if self.search.is_prompting() {
3315                        self.search.delete_word_before_caret();
3316                        self.preview_search();
3317                    }
3318                } else {
3319                    self.delete_word_before_cursor();
3320                }
3321            }
3322            Action::DeleteToLineStart => {
3323                if self.modal.mode() == Mode::Command {
3324                    if self.search.is_prompting() {
3325                        self.search.clear_before_caret();
3326                        self.preview_search();
3327                    }
3328                } else {
3329                    self.delete_to_line_start();
3330                }
3331            }
3332            Action::Backspace => {
3333                if self.modal.mode() == Mode::Command {
3334                    self.prompt_backspace();
3335                    // Shortening the pattern changes which matches exist, so
3336                    // the preview must re-run — otherwise the cursor sits on a
3337                    // match of a pattern that is no longer typed.
3338                    if self.search.is_prompting() {
3339                        self.preview_search();
3340                    }
3341                } else {
3342                    self.delete_before_cursor();
3343                }
3344            }
3345            Action::PromptHistory { back } => {
3346                if self.search.is_prompting() {
3347                    self.search.history_step(*back);
3348                    // No minibuffer resync: the shadow is the ex-line's store
3349                    // and nothing reads it while a search prompt is open, so
3350                    // rewriting it here was maintaining a copy for no reader.
3351                    self.preview_search();
3352                }
3353            }
3354            // `m{a-z}`. Only `a-z`: `A-Z` are vim's cross-file marks and this
3355            // map is per-editor, so accepting one would promise a jump back
3356            // to another FILE and deliver a jump to that line in this one.
3357            Action::SetMark(name) => {
3358                if name.is_ascii_lowercase() {
3359                    let at = self.cursor();
3360                    self.marks.insert(*name, at);
3361                } else {
3362                    self.messages
3363                        .push(format!("E191: mark `{name}` is not a-z"));
3364                }
3365            }
3366            Action::ScrollView(align) => self.scroll_view(*align),
3367            Action::Pending => {}
3368        }
3369        // Widen the dirty region by what this action touched (M1). Content
3370        // mutations that changed the line count run to end-of-document (every
3371        // line below shifted); an in-place edit or a cursor move is local;
3372        // arbitrary commands are conservatively Full. Never narrows.
3373        let lines_after = self.active_line_count();
3374        let cline_after = self.cursor().line;
3375        let d = match action {
3376            // A search repaints every highlight in the viewport, not just the
3377            // line the cursor left — so it must widen to Full. Treating it as a
3378            // cursor move would leave stale highlights on untouched lines.
3379            Action::SearchOpen(_)
3380            | Action::PromptHistory { .. }
3381            | Action::Backspace
3382            | Action::PromptCaret { .. }
3383            | Action::SearchPreviewStep { .. }
3384            | Action::DeleteForward
3385            | Action::DeleteWordBefore
3386            | Action::DeleteToLineStart
3387            | Action::SearchRepeat { .. }
3388            | Action::SearchWord { .. }
3389            | Action::ClearSearchHighlight
3390            | Action::SearchSubmitOperated { .. }
3391            // A replayed change can edit anywhere the original could, and a
3392            // match object can be anywhere in the document.
3393            | Action::RepeatLastChange
3394            | Action::TextObject(_)
3395            | Action::ApplyOperatorObject { .. }
3396            // A jump can land anywhere, so the viewport may scroll wholesale.
3397            | Action::JumpBack
3398            | Action::JumpForward
3399            // A re-frame repaints every row even though no byte changed —
3400            // which is exactly the case a line-scoped damage would miss.
3401            | Action::ScrollView(_) => Damage::Full,
3402            Action::InsertChar(_)
3403            | Action::Edit(_)
3404            | Action::Undo
3405            | Action::Redo
3406            // Insert-entry belongs in THIS group rather than beside
3407            // `ChangeMode` below, even though four of its six members only move
3408            // the caret: `o`/`O` add a line, and this arm's body is already the
3409            // one that asks whether the line COUNT changed. Grouping it with
3410            // the pure mode change would repaint a one-line span after `o` and
3411            // leave every line below the new one stale.
3412            | Action::EnterInsert(_)
3413            // Same reading as `EnterInsert`: a charwise put touches one line
3414            // and a linewise one adds several, and this arm's body is already
3415            // the one that asks which happened by comparing the line count.
3416            // `J` removes lines and `r` removes none — the same question.
3417            | Action::Put { .. }
3418            | Action::ReplaceChar(_)
3419            | Action::JoinLines { .. }
3420            | Action::ApplyOperator { .. } => {
3421                if lines_after == lines_before {
3422                    Damage::span(cline_before, cline_after)
3423                } else {
3424                    Damage::Lines {
3425                        from: cline_before.min(cline_after),
3426                        to: u32::MAX,
3427                    }
3428                }
3429            }
3430            Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
3431            Action::Save => Damage::Viewport,
3432            Action::Command { .. } | Action::SubmitCommand => Damage::Full,
3433            // Setting a mark changes no pixel — there is no gutter sign for
3434            // one yet. When one lands, this arm becomes `Damage::span`.
3435            Action::Quit | Action::Operator(_) | Action::SetMark(_) | Action::Pending => {
3436                Damage::None
3437            }
3438        };
3439        self.damage = self.damage.join(d);
3440        // Remember this change for `.`.
3441        //
3442        // Recorded from an OBSERVED MUTATION, not from the action's variant.
3443        // `text_effect()` is the wrong predicate here even though it looks
3444        // like the right one: it exists to decide cache invalidation, where
3445        // OVER-reporting is the safe direction, and the dot register needs the
3446        // opposite bias. Leaning on it meant `last_change` was set by actions
3447        // that changed no text at all, with two measured consequences:
3448        //
3449        //   `iZ<Esc>` then `/a<CR>` then `.`  — did nothing; the register held
3450        //       `SubmitCommand`, whose replay reads an already-cleared
3451        //       minibuffer.
3452        //   `iZ<Esc>` then `/q<Esc>` then `.` — TYPED `q` INTO THE BUFFER. An
3453        //       abandoned prompt left the register holding `InsertChar('q')`,
3454        //       and `.` in Normal mode routes that to the text. A corrupting
3455        //       register, not merely a lost one.
3456        //
3457        // Comparing the buffer's `TextRev` across the action answers the only
3458        // question that matters — did this actually change the text — and gets
3459        // the failed-operator case (`dgn` with no pattern) right for free.
3460        if self.recording_insert {
3461            match action {
3462                Action::InsertChar(c) => {
3463                    if let Some(lc) = self.last_change.as_mut() {
3464                        lc.inserted.push(*c);
3465                    }
3466                }
3467                // Leaving Insert ends the session; the change is now whole.
3468                Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
3469                _ => {}
3470            }
3471        } else if self.text_rev() != rev_before
3472            && !matches!(
3473                action,
3474                Action::RepeatLastChange | Action::Undo | Action::Redo
3475            )
3476        {
3477            self.last_change = Some(LastChange {
3478                // The count the gesture actually carried, not a hardcoded 1.
3479                // `.` replays it through the same absorb-or-repeat split the
3480                // original ran under (see `repeat_last_change`), so `3dw` then
3481                // `.` deletes three words rather than one.
3482                action: action.clone(),
3483                count,
3484                inserted: String::new(),
3485            });
3486            self.recording_insert = self.modal.mode() == Mode::Insert;
3487        }
3488
3489        // The search is over the moment you move on or edit — clear the
3490        // highlight rather than leaving the buffer as confetti until an
3491        // explicit `:noh`, which is the remap nearly every vimrc carries.
3492        // Clearing suppresses without forgetting, so `n` still works.
3493        if action.highlight_effect() == HighlightEffect::Clear {
3494            self.search.clear_highlight();
3495        }
3496        // Text changed ⇒ every match offset cached against the old text is
3497        // wrong. `SearchState::refresh` existed for exactly this and had ZERO
3498        // callers, so inserting four characters left both renderers painting
3499        // the highlight four columns off.
3500        //
3501        // Gated on the typed classifier rather than on `bump_gen` (which fires
3502        // for pure cursor moves too): re-scanning the document on every `j`
3503        // would be a per-keystroke full pass for no reason.
3504        if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
3505            let text = self.active_text();
3506            self.search.refresh(&text);
3507            // NO manual invalidation of `search_at` here, deliberately. It is
3508            // `Anchored` to the text revision, so an ordinal computed against
3509            // the old text now reads as `None` on its own. This is the line
3510            // that used to have to be remembered.
3511        }
3512        // An action reached the executor ⇒ visible state may have changed.
3513        // Advance the refresh generation so the renderer repaints (and
3514        // re-highlights) exactly once. A gated-out key never reaches here, so
3515        // a key-repeat storm does not spin the renderer.
3516        self.bump_gen();
3517    }
3518
3519    /// Resolve a [`Motion`] from `from` to its target [`Position`] against the
3520    /// active buffer — **pure**: no cursor mutation, no side effects. This is
3521    /// the single motion-resolution source of truth that both [`apply_motion`]
3522    /// (move the cursor *to* the target) and [`apply_operator`] (use the target
3523    /// as the *other end* of an operated range) stand on. `None` only if there
3524    /// is no active buffer.
3525    ///
3526    /// [`apply_motion`]: Self::apply_motion
3527    /// [`apply_operator`]: Self::apply_operator
3528    fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
3529        let buf = self.buffers.get(self.active)?;
3530        let pos = from;
3531        Some(match motion {
3532            // Search-as-motion: what makes `dn` / `d/foo<CR>` work. Resolved
3533            // against the committed match list, so it is `None` (motion fails,
3534            // operator aborts, buffer untouched) when nothing is committed —
3535            // never a silent move to 0, which would delete to the file start.
3536            Motion::SearchNext | Motion::SearchPrev => {
3537                let at = buf.position_to_char(pos).ok()?;
3538                let step = self
3539                    .search
3540                    .repeat(at, matches!(motion, Motion::SearchPrev))?;
3541                buf.char_to_position(step.target.start)
3542            }
3543            Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
3544            // Clamped to the line, which is what makes `x` (`dl`) safe to
3545            // express as a composition. Unclamped, an operator range built
3546            // over `Right` crosses the line TERMINATOR on an empty line — so
3547            // `x` there would join the next line onto this one instead of
3548            // doing nothing. The cursor path is unaffected: `place_cursor`
3549            // was already pulling `l` back onto the last character.
3550            Motion::Right => Position::new(
3551                pos.line,
3552                pos.column
3553                    .saturating_add(1)
3554                    .min(buf.line_len_chars(pos.line)),
3555            ),
3556            Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
3557            Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
3558            Motion::LineStart => Position::new(pos.line, 0),
3559            Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
3560            Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
3561            // `g_` — the last non-blank. Inclusive, so the operator widens it;
3562            // the resolver names the CHARACTER, which is where `$` differs.
3563            Motion::LineLastNonBlank => {
3564                let chars = line_chars(buf, pos.line);
3565                let col = chars
3566                    .iter()
3567                    .rposition(|c| !c.is_whitespace())
3568                    .and_then(|i| u32::try_from(i).ok())
3569                    .unwrap_or(0);
3570                Position::new(pos.line, col)
3571            }
3572            // `|` is 1-based, and clamped to the line rather than refused —
3573            // vim puts `500|` on the last character.
3574            Motion::Column(n) => Position::new(
3575                pos.line,
3576                n.saturating_sub(1).min(buf.line_len_chars(pos.line)),
3577            ),
3578            Motion::LineDownFirstNonBlank => {
3579                first_non_blank(buf, pos.line.saturating_add(1).min(last_text_line(buf)))
3580            }
3581            Motion::LineUpFirstNonBlank => first_non_blank(buf, pos.line.saturating_sub(1)),
3582            Motion::DocStart => Position::ZERO,
3583            Motion::DocEnd => Position::new(
3584                buf.line_count().saturating_sub(1),
3585                buf.line_len_chars(buf.line_count().saturating_sub(1)),
3586            ),
3587            Motion::WordStartNext => word_next(buf, pos, Width::Small),
3588            Motion::WordEndNext => word_end(buf, pos, Width::Small),
3589            Motion::WordStartPrev => word_prev(buf, pos, Width::Small),
3590            Motion::WordEndPrev => word_end_prev(buf, pos, Width::Small),
3591            Motion::BigWordStartNext => word_next(buf, pos, Width::Big),
3592            Motion::BigWordEndNext => word_end(buf, pos, Width::Big),
3593            Motion::BigWordStartPrev => word_prev(buf, pos, Width::Big),
3594            Motion::BigWordEndPrev => word_end_prev(buf, pos, Width::Big),
3595            Motion::FindChar { ch, backward, till } => find_char(buf, pos, ch, backward, till)?,
3596            // `;` / `,` resolve through the LAST `f`/`t`, which is runtime
3597            // state — the same shape as the search motions above, and the
3598            // reason neither can be resolved by the enum alone.
3599            Motion::RepeatFind { reverse } => {
3600                let last = self.last_find?;
3601                let backward = last.backward != reverse;
3602                find_char(buf, pos, last.ch, backward, last.till)?
3603            }
3604            Motion::MatchPair => self.resolve_match(buf, pos)?,
3605            // A mark that was never set is a FAILED motion, not a move to the
3606            // origin: `` `q `` with no `q` must leave the cursor alone, and
3607            // ``d`q`` must not delete to the top of the file.
3608            Motion::MarkExact(name) => {
3609                let at = *self.marks.get(&name)?;
3610                Position::new(
3611                    at.line.min(last_text_line(buf)),
3612                    at.column
3613                        .min(buf.line_len_chars(at.line.min(last_text_line(buf)))),
3614                )
3615            }
3616            Motion::MarkLine(name) => {
3617                let at = *self.marks.get(&name)?;
3618                first_non_blank(buf, at.line.min(last_text_line(buf)))
3619            }
3620            Motion::ParagraphNext => paragraph(buf, pos, true),
3621            Motion::ParagraphPrev => paragraph(buf, pos, false),
3622            Motion::SentenceNext => sentence(buf, pos, true),
3623            Motion::SentencePrev => sentence(buf, pos, false),
3624            // `H` / `M` / `L` are about the VIEWPORT, not the buffer — which
3625            // is what makes them the only motions whose target changes when
3626            // nothing in the text did.
3627            Motion::ScreenTop | Motion::ScreenMiddle | Motion::ScreenBottom => {
3628                let vp = self.layout.active_window().map_or(
3629                    Viewport {
3630                        top_line: 0,
3631                        left_column: 0,
3632                        visible_lines: 1,
3633                        visible_columns: 1,
3634                    },
3635                    |w| w.viewport,
3636                );
3637                let last = last_text_line(buf);
3638                let bottom = vp
3639                    .top_line
3640                    .saturating_add(vp.visible_lines.saturating_sub(1))
3641                    .min(last);
3642                let line = match motion {
3643                    Motion::ScreenTop => vp.top_line.min(last),
3644                    Motion::ScreenBottom => bottom,
3645                    _ => vp.top_line.min(last) + (bottom - vp.top_line.min(last)) / 2,
3646                };
3647                first_non_blank(buf, line)
3648            }
3649            Motion::PageDown | Motion::HalfPageDown => {
3650                Position::new(pos.line.saturating_add(10), pos.column)
3651            }
3652            Motion::PageUp | Motion::HalfPageUp => {
3653                Position::new(pos.line.saturating_sub(10), pos.column)
3654            }
3655            Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
3656            // Structural Lisp motions — stubs for phase 1.B; full paredit
3657            // semantics land when caixa-ast is wired to the active buffer.
3658            Motion::ForwardSexp
3659            | Motion::BackwardSexp
3660            | Motion::UpList
3661            | Motion::DownList
3662            | Motion::BeginningOfDefun
3663            | Motion::EndOfDefun
3664            | Motion::BeginningOfSexp
3665            | Motion::EndOfSexp => pos,
3666        })
3667    }
3668
3669    /// `zt` / `zz` / `zb` — re-frame the window around the cursor's line
3670    /// WITHOUT moving the cursor.
3671    ///
3672    /// The cursor is deliberately untouched: `zz` is what you press when you
3673    /// are already where you want to be and only the framing is wrong. Note
3674    /// that `set_cursor` would undo this — it scrolls the viewport to contain
3675    /// the cursor with a 2-line margin — so this must not route through it,
3676    /// and the next motion legitimately re-frames again.
3677    fn scroll_view(&mut self, align: escriba_core::ViewAlign) {
3678        use escriba_core::ViewAlign;
3679        let line = self.cursor().line;
3680        let Some(w) = self.layout.active_window_mut() else {
3681            return;
3682        };
3683        let h = w.viewport.visible_lines.max(1);
3684        w.viewport.top_line = match align {
3685            ViewAlign::Top => line,
3686            ViewAlign::Center => line.saturating_sub(h / 2),
3687            ViewAlign::Bottom => line.saturating_sub(h.saturating_sub(1)),
3688        };
3689        self.damage = self.damage.join(Damage::Full);
3690        self.bump_gen();
3691    }
3692
3693    /// Claim the operand of a pending `m` / `` ` `` / `'`, or arm one.
3694    ///
3695    /// Same key-layer shape as [`Self::consume_find_key`] and for the same
3696    /// reason: `ma` is `m` plus an OPERAND, and `a` is bound (append). Without
3697    /// claiming it first, `ma` would set no mark and enter Insert mode.
3698    ///
3699    /// Runs BEFORE `consume_object_key`, because `` d`a `` needs it: the
3700    /// object path claims `i` and `a` whenever an operator is armed, and the
3701    /// mark LETTER can be either of them.
3702    ///
3703    /// The two do not fight over the first key. This arms only while
3704    /// `pending_object` is clear, so `di'` — where `'` is a text-object
3705    /// delimiter rather than a mark jump — still reaches the object path. The
3706    /// guard states that dependency locally instead of leaving it implied by
3707    /// call order.
3708    fn consume_mark_key(&mut self, key: Key) -> Option<ObjectKey> {
3709        if let Some(kind) = self.pending_mark.take() {
3710            let Key::Char(name) = key else {
3711                if matches!(self.op_pending.state(), OpState::Awaiting { .. }) {
3712                    self.op_pending
3713                        .dispatch((Action::ChangeMode(Mode::Normal), 1));
3714                }
3715                return Some(ObjectKey::Consumed);
3716            };
3717            return Some(ObjectKey::Compose(match kind {
3718                MarkKey::Set => Action::SetMark(name),
3719                MarkKey::GotoExact => Action::Move(Motion::MarkExact(name)),
3720                MarkKey::GotoLine => Action::Move(Motion::MarkLine(name)),
3721            }));
3722        }
3723        if !matches!(self.modal.mode(), Mode::Normal | Mode::Visual) {
3724            return None;
3725        }
3726        // Half-typed text object (`di` waiting for its `'`) belongs to the
3727        // object path, not here; a key continuing a sequence belongs to the
3728        // sequence (see `consume_find_key` for the `zt` case that proves it).
3729        if self.pending_object.is_some() || !self.pending_keys.is_empty() {
3730            return None;
3731        }
3732        let Key::Char(c) = key else { return None };
3733        let kind = match c {
3734            'm' => MarkKey::Set,
3735            '`' => MarkKey::GotoExact,
3736            '\'' => MarkKey::GotoLine,
3737            _ => return None,
3738        };
3739        self.pending_mark = Some(kind);
3740        Some(ObjectKey::Consumed)
3741    }
3742
3743    /// `%` — brackets, plus this buffer's language word pairs if it has any.
3744    ///
3745    /// When both are candidates the NEARER one on the line wins, because that
3746    /// is the one under the operator's eye: on `if foo() then`, `%` on the
3747    /// `if` means the block and `%` on the `(` means the call. Deciding by
3748    /// distance rather than by precedence is what keeps both usable from the
3749    /// same key without a mode.
3750    fn resolve_match(&self, buf: &escriba_buffer::Buffer, pos: Position) -> Option<Position> {
3751        let Some(pairs) = self.word_pairs_for_active() else {
3752            return match_pair(buf, pos);
3753        };
3754        let bracket_col = line_chars(buf, pos.line)
3755            .into_iter()
3756            .enumerate()
3757            .skip(pos.column as usize)
3758            .find(|(_, c)| MATCH_PAIRS.iter().any(|&(o, cl)| *c == o || *c == cl))
3759            .and_then(|(i, _)| u32::try_from(i).ok());
3760        let word_col = word_hits(buf, pos.line, pairs)
3761            .into_iter()
3762            .find(|h| h.end > pos.column)
3763            .map(|h| h.col);
3764        match (bracket_col, word_col) {
3765            (Some(b), Some(w)) if w < b => match_word_pair(buf, pos, pairs),
3766            (Some(_), _) => match_pair(buf, pos),
3767            (None, Some(_)) => match_word_pair(buf, pos, pairs),
3768            (None, None) => None,
3769        }
3770    }
3771
3772    /// The word pairs for the active buffer's filetype, if the language has
3773    /// any. `None` for brace languages — Rust's `%` is bracket-only, and that
3774    /// is correct rather than missing.
3775    fn word_pairs_for_active(&self) -> Option<WordPairs> {
3776        let path = self.buffers.get(self.active)?.path.as_deref()?;
3777        let name = &self.filetypes.resolve(path)?.name;
3778        WORD_PAIRS
3779            .iter()
3780            .find(|(ft, _)| ft == name)
3781            .map(|(_, pairs)| *pairs)
3782    }
3783
3784    fn apply_motion(&mut self, motion: Motion) {
3785        // A bare search motion is a FAR JUMP and it REPORTS — it records into
3786        // the jumplist, prints vim's "hit BOTTOM" on a wrap, and says E486
3787        // when nothing matches. `resolve_motion` can do none of that: it is
3788        // deliberately pure because the OPERATOR path calls it to find a range
3789        // without moving the cursor. So `n` routes to the one executor that
3790        // owns those side effects, and `Action::SearchRepeat` routes to the
3791        // same place — one code path, two spellings.
3792        if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
3793            self.jump_search(matches!(motion, Motion::SearchPrev));
3794            return;
3795        }
3796        let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
3797            return;
3798        };
3799        // The single cursor-mutation path clamps to the buffer and scrolls
3800        // the viewport to contain the cursor on both axes.
3801        self.set_cursor(pos);
3802    }
3803
3804    /// Apply an operator over a motion — the vim `{operator}{motion}` verbs
3805    /// (`dw` delete-word, `c$` change-to-line-end, `y0` yank-to-line-start).
3806    /// Composition is explicit: the motion resolves a target via
3807    /// [`resolve_motion`](Self::resolve_motion); the operator acts over the
3808    /// `[cursor, target)` range. Register-leaving operators
3809    /// ([`Operator::leaves_register`]) capture the text first.
3810    /// Apply `op` over `motion` resolved `n` times from the cursor.
3811    ///
3812    /// `n == 1` is the ordinary path. Larger `n` walks the motion forward
3813    /// first and operates over the whole span in one go, which is what vim
3814    /// means by `3dw` — and the only way a non-moving operator like yank can
3815    /// honour a count at all.
3816    fn apply_operator_n(&mut self, op: Operator, motion: Motion, n: u32) {
3817        if n <= 1 {
3818            self.apply_operator(op, motion);
3819            return;
3820        }
3821        let from = self.cursor();
3822        let mut to = from;
3823        for _ in 0..n {
3824            match self.resolve_motion(to, motion) {
3825                Some(next) if next != to => to = next,
3826                // The motion stopped making progress (start/end of buffer):
3827                // operate over what we reached rather than aborting, which is
3828                // what vim does for `999dw` near the end of a file.
3829                _ => break,
3830            }
3831        }
3832        if to == from {
3833            // Nothing to operate over. Fall through to the single-step path
3834            // so its error reporting (E35, pattern-not-found) still runs.
3835            self.apply_operator(op, motion);
3836            return;
3837        }
3838        self.apply_operator_to(op, self.operated_end(motion, to));
3839    }
3840
3841    /// Widen an INCLUSIVE motion's target to the exclusive end an operator
3842    /// range needs. See [`Motion::is_inclusive`].
3843    ///
3844    /// Applied at the OPERATOR, never inside `resolve_motion`: the same
3845    /// resolution has to serve the cursor path, where `e` must land ON the
3846    /// last character, and the range path, where the range must end after it.
3847    /// One target, two readings — putting the widening in the resolver would
3848    /// move `e` itself one character too far.
3849    fn operated_end(&self, motion: Motion, to: Position) -> Position {
3850        // `;` inherits the inclusiveness of the find it repeats — resolve it
3851        // to that concrete motion rather than teaching `is_inclusive` about
3852        // state it cannot see. `d;` after `fx` must delete THROUGH the `x`.
3853        let motion = match motion {
3854            Motion::RepeatFind { reverse } => match self.last_find {
3855                Some(f) => Motion::FindChar {
3856                    ch: f.ch,
3857                    backward: f.backward != reverse,
3858                    till: f.till,
3859                },
3860                None => return to,
3861            },
3862            m => m,
3863        };
3864        if !motion.is_inclusive() {
3865            return to;
3866        }
3867        let line_len = self
3868            .buffers
3869            .get(self.active)
3870            .map_or(to.column, |b| b.line_len_chars(to.line));
3871        Position::new(to.line, to.column.saturating_add(1).min(line_len))
3872    }
3873
3874    fn apply_operator(&mut self, op: Operator, motion: Motion) {
3875        let from = self.cursor();
3876        let Some(to) = self.resolve_motion(from, motion) else {
3877            // A motion that cannot resolve aborts the operator with the buffer
3878            // untouched. A search motion says WHY — `dn` with no pattern armed
3879            // is otherwise indistinguishable from a dropped keystroke, which
3880            // is the same complaint that motivated E486 on the bare path.
3881            if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
3882                if self.search.pattern().is_none() {
3883                    self.messages
3884                        .push("E35: No previous regular expression".to_string());
3885                } else {
3886                    self.report_pattern_not_found();
3887                }
3888            }
3889            return;
3890        };
3891        self.apply_operator_to(op, self.operated_end(motion, to));
3892    }
3893
3894    /// Apply `op` over `[cursor, to)`.
3895    ///
3896    /// Split out of [`Self::apply_operator`] so the operated-search path can
3897    /// reach the same range machinery with a target it resolved itself — the
3898    /// alternative was a second copy of the delete/yank/register logic, which
3899    /// is how the two would drift.
3900    fn apply_operator_to(&mut self, op: Operator, to: Position) {
3901        let from = self.cursor();
3902        // A motion-shaped operation is charwise by construction: it acts over
3903        // `[cursor, point)`, which is a run of characters even when that run
3904        // happens to span a line break (`d}`).
3905        self.apply_operator_over(
3906            op,
3907            Extent::charwise(Range {
3908                start: from,
3909                end: to,
3910            }),
3911        );
3912    }
3913
3914    /// Apply `op` over an explicit range, capturing it as `kind`.
3915    ///
3916    /// The object path needs this: `gn`'s extent need not begin at the cursor,
3917    /// so it cannot go through the `[cursor, target)` shape the motion path
3918    /// uses. One implementation of the delete/yank/register logic, reached two
3919    /// ways.
3920    ///
3921    /// `kind` is a PARAMETER rather than something inferred from the range,
3922    /// and it has to be: `[(1,0), (2,0))` is the range `dd` produces on line 1
3923    /// AND the range `dj`-ish charwise motions produce, and nothing about the
3924    /// two positions distinguishes them. Only the caller knows which gesture
3925    /// it was. It travels to the register, and the register is what a later
3926    /// `p` reads to decide between splicing and opening a line.
3927    fn apply_operator_over(&mut self, op: Operator, extent: Extent) {
3928        let Extent {
3929            capture,
3930            removal,
3931            kind,
3932        } = extent.normalized();
3933        if capture.is_empty() {
3934            return;
3935        }
3936        // Capture the operated text (for the register) before mutating.
3937        let text = self
3938            .buffers
3939            .get(self.active)
3940            .and_then(|buf| buf.slice(capture).ok());
3941        if op.leaves_register() {
3942            if let Some(t) = &text {
3943                let captured = match kind {
3944                    RegisterKind::Charwise => t.clone(),
3945                    RegisterKind::Linewise => as_linewise_capture(t),
3946                };
3947                self.register = Some(Register::new(captured, kind));
3948            }
3949        }
3950        match op {
3951            // Delete + Change remove the range; Change then enters Insert so
3952            // the operator pairs with immediate typing (`ciw`, `c$`).
3953            //
3954            // They remove DIFFERENT ranges for a linewise extent, which is the
3955            // whole reason `Extent` carries two: `dd` takes the line and its
3956            // terminator, `cc` clears the line's text and KEEPS the line,
3957            // because you are changing its contents rather than removing it.
3958            // Both leave the same thing in the register.
3959            Operator::Delete | Operator::Change => {
3960                let cut = if op == Operator::Change {
3961                    removal
3962                } else {
3963                    capture
3964                };
3965                if cut.is_empty() {
3966                    // `cc` on an already-empty line: nothing to clear, but the
3967                    // gesture still means "type here".
3968                    self.rest_after_operator(kind, cut.start);
3969                    self.modal.enter(Mode::Insert);
3970                    return;
3971                }
3972                if let Some(buf) = self.buffers.get_mut(self.active) {
3973                    let _ = buf.apply(&Edit::delete(cut));
3974                }
3975                self.rest_after_operator(kind, cut.start);
3976                if op == Operator::Change {
3977                    self.modal.enter(Mode::Insert);
3978                }
3979            }
3980            // Yank copies to the register without mutating the buffer, so it
3981            // gets its OWN resting rule rather than the delete rule above: the
3982            // line is still there, and vim moves the cursor only when the yank
3983            // reached BACKWARDS past it.
3984            //
3985            // Keyed on the kind for the same reason everything else here is.
3986            // A linewise yank compares LINES — `yy` and `3yy` both start on
3987            // the cursor's own line, so neither moves, which is why comparing
3988            // POSITIONS was wrong: `yy`'s range starts at column 0, so it read
3989            // as "backwards" and knocked the cursor to the left margin every
3990            // time you copied a line. Invisible for `yw`, whose range starts
3991            // exactly at the cursor, so the move was a no-op there.
3992            Operator::Yank => {
3993                let here = self.cursor();
3994                match kind {
3995                    RegisterKind::Linewise if capture.start.line < here.line => {
3996                        // Keep the column: a backwards linewise yank rests on
3997                        // the first line taken, not at its margin.
3998                        self.set_cursor(Position::new(capture.start.line, here.column));
3999                    }
4000                    RegisterKind::Charwise
4001                        if (capture.start.line, capture.start.column)
4002                            < (here.line, here.column) =>
4003                    {
4004                        self.set_cursor(capture.start);
4005                    }
4006                    _ => {}
4007                }
4008            }
4009            // Indent/Format/structural operators are not yet wired — named,
4010            // not faked (no buffer mutation, register already captured for the
4011            // register-leaving ones above).
4012            _ => {
4013                self.messages
4014                    .push("operator not yet implemented".to_owned());
4015            }
4016        }
4017    }
4018
4019    /// `r{char}` — overwrite `count` characters from the cursor with `char`.
4020    ///
4021    /// Three things it deliberately is NOT, each of which a `Change`-operator
4022    /// composition would get wrong: it does not enter Insert, it does not
4023    /// touch the register, and it REFUSES rather than truncating when the
4024    /// count runs past the end of the line. vim's rule is that `5rx` on a
4025    /// three-character tail does nothing at all — a partial replace would
4026    /// silently destroy two characters you did not mean to name.
4027    fn replace_char(&mut self, ch: char, count: u32) {
4028        let n = count.max(1);
4029        let here = self.cursor();
4030        let Some(buf) = self.buffers.get(self.active) else {
4031            return;
4032        };
4033        let len = buf.line_len_chars(here.line);
4034        if here.column.saturating_add(n) > len {
4035            // Silent, like vim. The line is short — there is nothing to say
4036            // that the unchanged text does not already say.
4037            return;
4038        }
4039        let end = Position::new(here.line, here.column + n);
4040        let mut text = String::with_capacity(n as usize);
4041        for _ in 0..n {
4042            text.push(ch);
4043        }
4044        let Some(buf) = self.buffers.get_mut(self.active) else {
4045            return;
4046        };
4047        if buf
4048            .apply(&Edit::replace(Range::new(here, end), text))
4049            .is_err()
4050        {
4051            return;
4052        }
4053        // vim leaves the cursor on the LAST character replaced, not after it.
4054        self.set_cursor(Position::new(here.line, here.column + n - 1));
4055    }
4056
4057    /// `J` / `gJ` — join `count` lines into one.
4058    ///
4059    /// One `Edit::replace` over the whole span rather than `n` splices, so a
4060    /// `3J` is one `u` away from gone and the damage classifier sees a single
4061    /// line-count change.
4062    ///
4063    /// `space: true` (`J`) drops the next line's leading whitespace and puts a
4064    /// single space in the newline's place, with vim's two exceptions: no
4065    /// space is added when the line already ends in one, or when the next line
4066    /// starts with `)`. `space: false` (`gJ`) splices verbatim — the reason to
4067    /// reach for it is that `J` is lossy.
4068    fn join_lines(&mut self, space: bool, count: u32) {
4069        // `J` and `2J` both mean "join ONE following line": vim counts LINES
4070        // involved, not joins performed, so the join count is `count - 1`
4071        // floored at 1.
4072        let joins = count.max(2) - 1;
4073        let here = self.cursor();
4074        let Some(buf) = self.buffers.get(self.active) else {
4075            return;
4076        };
4077        let last = last_text_line(buf);
4078        if here.line >= last {
4079            // Nothing below to join. vim beeps; escriba says so, because a key
4080            // that silently does nothing is indistinguishable from an unbound
4081            // one — which is how `<C-h>` hid for a month.
4082            self.messages
4083                .push("E36: Not enough lines to join".to_string());
4084            return;
4085        }
4086        let end_line = here.line.saturating_add(joins).min(last);
4087        // `Buffer::line` INCLUDES the trailing newline and `line_len_chars`
4088        // excludes it — a mismatch that made the first cut of this splice the
4089        // terminators back in and then leave the originals behind, so `J`
4090        // produced the file unchanged plus a blank line. `line_chars` is the
4091        // newline-free reading every motion already uses.
4092        let line_text = |l: u32| line_chars(buf, l).into_iter().collect::<String>();
4093        let mut joined = line_text(here.line);
4094        // Where the cursor lands: vim puts it ON the join — the position the
4095        // newline used to occupy, which is the space it inserted.
4096        let mut caret = u32::try_from(joined.chars().count()).unwrap_or(0);
4097        for l in (here.line + 1)..=end_line {
4098            let next = line_text(l);
4099            caret = u32::try_from(joined.chars().count()).unwrap_or(0);
4100            if space {
4101                let trimmed = next.trim_start();
4102                let needs_space = !joined.is_empty()
4103                    && !joined.ends_with(char::is_whitespace)
4104                    && !trimmed.starts_with(')')
4105                    && !trimmed.is_empty();
4106                if needs_space {
4107                    joined.push(' ');
4108                }
4109                joined.push_str(trimmed);
4110            } else {
4111                joined.push_str(&next);
4112            }
4113        }
4114        let span = Range::new(
4115            Position::new(here.line, 0),
4116            Position::new(end_line, buf.line_len_chars(end_line)),
4117        );
4118        let Some(buf) = self.buffers.get_mut(self.active) else {
4119            return;
4120        };
4121        if buf.apply(&Edit::replace(span, joined)).is_err() {
4122            return;
4123        }
4124        self.set_cursor(Position::new(here.line, caret));
4125    }
4126
4127    /// Where the cursor rests once an operator has finished.
4128    ///
4129    /// Keyed on the operated KIND rather than on the operator, because that is
4130    /// what vim keys it on: every linewise operation lands the cursor the same
4131    /// way regardless of which operator produced it.
4132    ///
4133    /// The charwise arm is the old unconditional behaviour — the range start,
4134    /// which is where the text used to begin.
4135    fn rest_after_operator(&mut self, kind: RegisterKind, start: Position) {
4136        match kind {
4137            RegisterKind::Charwise => self.set_cursor(start),
4138            RegisterKind::Linewise => {
4139                // vim's linewise rule: the cursor lands on the FIRST NON-BLANK
4140                // of the line that now occupies the operated line's index, and
4141                // never past the last line that holds text.
4142                //
4143                // Both halves were wrong, and each in a way no unit test could
4144                // see, because both are about WHERE THE CURSOR IS rather than
4145                // what the text says — and every `dd` test asserted the text.
4146                //
4147                //   - Column 0 instead of the first non-blank is untidy on flat
4148                //     prose and actively wrong on indented code: `dd` inside a
4149                //     nested block dropped the cursor into the indentation, so
4150                //     the next `i` typed at the margin.
4151                //   - Landing past the last line of text was worse. A file
4152                //     ending in `\n` makes the rope report a phantom final
4153                //     line (see `last_text_line`); `dd` on the last REAL line
4154                //     parked the cursor on that phantom row, where `x` and `i`
4155                //     had nothing to act on and the next `dd` deleted the
4156                //     file's trailing NEWLINE rather than a line.
4157                let at = match self.buffers.get(self.active) {
4158                    Some(buf) => first_non_blank(buf, start.line.min(last_text_line(buf))),
4159                    None => return,
4160                };
4161                self.set_cursor(at);
4162            }
4163        }
4164    }
4165
4166    /// `p` / `P` — put `count` copies of the register back into the buffer.
4167    ///
4168    /// **The register's [`RegisterKind`] chooses the operation, not the key.**
4169    /// `p` after `dw` splices characters in at a column; `p` after `dd` opens
4170    /// a whole line below. That is why the capture had to become typed before
4171    /// this could exist at all: a `String` register leaves `p` guessing, and
4172    /// the only guess available — splice — drops a whole line, terminator and
4173    /// all, into the middle of whatever line the cursor is on.
4174    ///
4175    /// One [`Edit`] regardless of `count`, so `3p` is one `u` away from gone.
4176    fn put(&mut self, before: bool, count: u32) {
4177        let Some(reg) = self.register.clone() else {
4178            // vim says nothing for a put with an empty register, and neither
4179            // does this — but it must not fall through to an insert of `""`
4180            // either, which would record a `last_change` that `.` then
4181            // replays as a no-op edit.
4182            return;
4183        };
4184        let text = reg.replayed(count);
4185        if text.is_empty() {
4186            return;
4187        }
4188        let Some(buf) = self.buffers.get(self.active) else {
4189            return;
4190        };
4191        let here = self.cursor();
4192        let (at, rest) = match reg.kind {
4193            RegisterKind::Linewise => {
4194                // `p` opens BELOW the cursor's line, `P` above. The insertion
4195                // point is the start of a line either way, and the text ends
4196                // in a newline (`Register::replayed` guarantees it), so the
4197                // splice pushes the existing line down rather than joining it.
4198                //
4199                // `line + 1` is a valid insertion point even on the last line:
4200                // a file ending in `\n` has the phantom row there, and one
4201                // that does not gets the newline from `replayed`.
4202                let line = if before {
4203                    here.line
4204                } else {
4205                    here.line.saturating_add(1)
4206                };
4207                let at = Position::new(line.min(buf.line_count()), 0);
4208                // vim rests on the first non-blank of the FIRST line put.
4209                (at, PutRest::LineStart(at.line))
4210            }
4211            RegisterKind::Charwise => {
4212                // `p` lands AFTER the character under the cursor, `P` on it.
4213                // Appending past the end of the line is legal here — that is
4214                // what makes `p` on the last character of a line work — so
4215                // this clamps to the line length, not to the last character.
4216                let col = if before {
4217                    here.column
4218                } else {
4219                    here.column
4220                        .saturating_add(1)
4221                        .min(buf.line_len_chars(here.line))
4222                };
4223                (Position::new(here.line, col), PutRest::LastCharPut)
4224            }
4225        };
4226        let Some(buf) = self.buffers.get_mut(self.active) else {
4227            return;
4228        };
4229        if buf.apply(&Edit::insert(at, text.clone())).is_err() {
4230            return;
4231        }
4232        match rest {
4233            PutRest::LineStart(line) => {
4234                let to = match self.buffers.get(self.active) {
4235                    Some(b) => first_non_blank(b, line.min(last_text_line(b))),
4236                    None => return,
4237                };
4238                self.set_cursor(to);
4239            }
4240            // vim leaves the cursor ON the last character put, not after it —
4241            // which is what makes `p` then `.`-less repeated puts stack rather
4242            // than march right. Routed through `set_cursor` (an `OnCharacter`
4243            // rest) so Normal mode's on-a-character invariant still applies.
4244            PutRest::LastCharPut => {
4245                let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
4246                let end = if let Some(nl) = text.rfind('\n') {
4247                    let tail = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
4248                    Position::new(at.line + added_lines, tail)
4249                } else {
4250                    let n = u32::try_from(text.chars().count()).unwrap_or(0);
4251                    Position::new(at.line, at.column.saturating_add(n))
4252                };
4253                self.set_cursor(Position::new(end.line, end.column.saturating_sub(1)));
4254            }
4255        }
4256    }
4257
4258    /// The text last yanked or deleted into the unnamed register, if any.
4259    /// `p`/`P` read this — through [`Register`], so they can tell a captured
4260    /// LINE from a captured run of characters.
4261    #[must_use]
4262    pub fn register(&self) -> Option<&Register> {
4263        self.register.as_ref()
4264    }
4265
4266    /// The register's raw text, for callers that only want the characters.
4267    #[must_use]
4268    pub fn register_text(&self) -> Option<&str> {
4269        self.register.as_ref().map(|r| r.text.as_str())
4270    }
4271
4272    fn insert_char(&mut self, c: char) {
4273        if self.modal.mode() == Mode::Command {
4274            // A search prompt and an ex-command share Command mode (vim's
4275            // cmdline). `search.is_prompting()` is the typed discriminator —
4276            // it can only be true when `/` or `?` actually opened a prompt.
4277            if self.search.is_prompting() {
4278                // The search prompt is the SOLE store while it is open.
4279                //
4280                // This used to also `push_minibuffer(c)`, and the two stores
4281                // insert differently — `search.push` at the caret, the
4282                // minibuffer always at the end — so `/fo<Left>X` left them
4283                // reading `fXo` and `foX`. That was one of FIVE desync paths;
4284                // the caret moves, forward-delete, delete-word and
4285                // clear-to-start never touched the shadow at all.
4286                //
4287                // Deleting the write costs nothing because `status_model`
4288                // already selects the minibuffer only on the `prompt == None`
4289                // branch — the shadow is the EX-LINE's store, and while a
4290                // search prompt is open nothing reads it.
4291                self.search.push(c);
4292                self.preview_search();
4293            } else {
4294                self.modal.push_minibuffer(c);
4295            }
4296            return;
4297        }
4298        let cursor = self.cursor();
4299        let Some(buf) = self.buffers.get_mut(self.active) else {
4300            return;
4301        };
4302        let edit = Edit::insert(cursor, c.to_string());
4303        if buf.apply(&edit).is_ok() {
4304            let next = if c == '\n' {
4305                Position::new(cursor.line.saturating_add(1), 0)
4306            } else {
4307                cursor.shift_right(1)
4308            };
4309            // Route through the single cursor-mutation path so the viewport
4310            // follows the cursor (both axes) and the cursor stays clamped.
4311            self.place_cursor(next, CursorRest::AtInsertPoint);
4312        }
4313    }
4314
4315    /// Enter Insert mode at `at` — the ONE body behind `i` `I` `a` `A` `o` `O`.
4316    ///
4317    /// # What lets `A` park past the last character
4318    ///
4319    /// [`Self::place_cursor`] pulls a caret back to `len - 1` — but only when
4320    /// **both** halves of its guard hold: `rest == CursorRest::OnCharacter`
4321    /// *and* the mode is `Normal`. `A` and `a`-at-end-of-line need that clamp
4322    /// lifted, and this function lifts it twice over: it enters Insert before
4323    /// placing anything, and it asks for `CursorRest::AtInsertPoint`.
4324    ///
4325    /// **Either one alone is sufficient**, which is worth writing down because
4326    /// it is the opposite of what it looks like. An earlier version of this
4327    /// comment claimed the ORDER was load-bearing on its own; the red run
4328    /// refuted it — reversing the order while keeping `AtInsertPoint` stays
4329    /// green, and so does `OnCharacter` while entering Insert first. Only
4330    /// removing BOTH goes red, and then `a` on the `o` of "hello" reports
4331    /// column 4 instead of 5: the caret sits back on the character it was meant
4332    /// to append after. Belt and braces here is deliberate — the two guards
4333    /// answer different questions ("what kind of place is this?" and "what mode
4334    /// are we in?") and a later refactor is free to change one.
4335    ///
4336    /// `o`/`O` are in this function rather than in an `Edit` action because
4337    /// they are ONE gesture: vim's `o` is not "insert a newline, then enter
4338    /// insert" — the caret must land on the new line, and an operator watching
4339    /// two separate actions would record two dot-repeat entries for one press.
4340    fn enter_insert_at(&mut self, at: InsertAt) {
4341        self.modal.enter_insert();
4342        let cursor = self.cursor();
4343        // Resolve everything that needs the buffer BEFORE mutating, so the
4344        // immutable borrow ends before `place_cursor`/`apply` want `&mut self`.
4345        let Some(buf) = self.buffers.get(self.active) else {
4346            return;
4347        };
4348        let line_len = buf.line_len_chars(cursor.line);
4349        let target = match at {
4350            // `i` — the caret is already the insert point.
4351            InsertAt::Caret => Some(cursor),
4352            // One past the last char is a legal insert point, which is what
4353            // lets `a` on the final character append rather than stall.
4354            InsertAt::AfterCaret => Some(Position::new(
4355                cursor.line,
4356                cursor.column.saturating_add(1).min(line_len),
4357            )),
4358            InsertAt::LineEnd => Some(Position::new(cursor.line, line_len)),
4359            InsertAt::FirstNonBlank => Some(first_non_blank(buf, cursor.line)),
4360            // Handled below — these two edit the buffer first.
4361            InsertAt::OpenBelow | InsertAt::OpenAbove => None,
4362        };
4363        if let Some(pos) = target {
4364            self.place_cursor(pos, CursorRest::AtInsertPoint);
4365            return;
4366        }
4367        // `o`/`O` — open a line by inserting the terminator at the boundary the
4368        // direction names, then land on the fresh line. Expressed as an
4369        // `Edit::insert` through `Buffer::apply` so it joins the undo history
4370        // the same way typed text does.
4371        let (at_pos, land_on) = match at {
4372            InsertAt::OpenBelow => (
4373                Position::new(cursor.line, line_len),
4374                Position::new(cursor.line.saturating_add(1), 0),
4375            ),
4376            // Inserting at column 0 pushes the current line DOWN, so the fresh
4377            // line takes the caret's own line number.
4378            _ => (Position::new(cursor.line, 0), Position::new(cursor.line, 0)),
4379        };
4380        let Some(buf) = self.buffers.get_mut(self.active) else {
4381            return;
4382        };
4383        if buf.apply(&Edit::insert(at_pos, "\n")).is_ok() {
4384            self.place_cursor(land_on, CursorRest::AtInsertPoint);
4385        }
4386    }
4387
4388    /// `<BS>` against the BUFFER — the Insert-mode arm of [`Action::Backspace`].
4389    ///
4390    /// Deletes `[target, cursor)` where `target` is the previous character
4391    /// position, so column 0 JOINS with the line above rather than stopping
4392    /// dead: the range spans the newline and one `Edit::delete` removes it.
4393    /// `Motion::Left` cannot express that — it saturates at column 0, which is
4394    /// why this does not route through `apply_operator`.
4395    ///
4396    /// The other reason it does not: `Operator::Delete` captures the unnamed
4397    /// register, and vim's insert-mode backspace does not. Erasing a typo
4398    /// should not silently overwrite what you yanked to paste.
4399    fn delete_before_cursor(&mut self) {
4400        let cursor = self.cursor();
4401        let Some(buf) = self.buffers.get(self.active) else {
4402            return;
4403        };
4404        let target = if cursor.column > 0 {
4405            Position::new(cursor.line, cursor.column.saturating_sub(1))
4406        } else if cursor.line > 0 {
4407            let above = cursor.line.saturating_sub(1);
4408            Position::new(above, buf.line_len_chars(above))
4409        } else {
4410            // Start of the document — nothing to the left. A no-op, not a
4411            // clamp onto something else.
4412            return;
4413        };
4414        self.erase_back_to(target);
4415    }
4416
4417    /// Delete `[target, cursor)` and park the caret on `target`.
4418    ///
4419    /// The shared body of every BACKWARD erase against the buffer — `<BS>`,
4420    /// `<C-w>`, `<C-u>`. They differ only in how far back they reach, so the
4421    /// two properties that must hold for all three live here once rather than
4422    /// three times: the edit does NOT route through `apply_operator` (see
4423    /// [`Self::delete_before_cursor`] for both reasons), and the caret lands
4424    /// via `set_cursor` so the viewport follows and the clamp still runs.
4425    ///
4426    /// A `target` at or after the cursor is a no-op. That is the guard that
4427    /// makes the callers safe to write as "resolve a position, hand it over":
4428    /// `word_prev` returns the cursor unchanged at column 0 and
4429    /// `first_non_blank` returns a position AHEAD of the cursor inside an
4430    /// indent, and a reversed `Range` would be a delete of unknown extent
4431    /// rather than nothing.
4432    fn erase_back_to(&mut self, target: Position) {
4433        let cursor = self.cursor();
4434        if (target.line, target.column) >= (cursor.line, cursor.column) {
4435            return;
4436        }
4437        let edit = Edit::delete(Range {
4438            start: target,
4439            end: cursor,
4440        });
4441        if let Some(buf) = self.buffers.get_mut(self.active) {
4442            if buf.apply(&edit).is_ok() {
4443                self.set_cursor(target);
4444            }
4445        }
4446    }
4447
4448    /// `<C-w>` against the BUFFER — the Insert-mode arm of
4449    /// [`Action::DeleteWordBefore`].
4450    ///
4451    /// Reaches back over `Motion::WordStartPrev`, the SAME resolver the cursor
4452    /// move and the operator range already stand on, so `<C-w>` and `db` agree
4453    /// on where a word starts by construction instead of by two hand-written
4454    /// scans that drift.
4455    ///
4456    /// `word_prev` is single-line and returns the cursor unchanged at column 0,
4457    /// which would make `<C-w>` a dead key at the start of a line. vim erases
4458    /// the line break there, so the zero-width case falls through to
4459    /// [`Self::delete_before_cursor`] — one character back, which at column 0
4460    /// IS the newline.
4461    fn delete_word_before_cursor(&mut self) {
4462        let cursor = self.cursor();
4463        let Some(target) = self.resolve_motion(cursor, Motion::WordStartPrev) else {
4464            return;
4465        };
4466        if (target.line, target.column) >= (cursor.line, cursor.column) {
4467            self.delete_before_cursor();
4468            return;
4469        }
4470        self.erase_back_to(target);
4471    }
4472
4473    /// `<C-u>` against the BUFFER — the Insert-mode arm of
4474    /// [`Action::DeleteToLineStart`].
4475    ///
4476    /// Two-step, as vim is: the first press erases back to the first non-blank
4477    /// (what you typed), and a second press — now sitting ON the first
4478    /// non-blank, so that target is no longer behind the cursor — erases the
4479    /// indent. Collapsing the two into "always column 0" would destroy
4480    /// alignment on the first press, which is the one the hands reach for.
4481    ///
4482    /// Never joins with the line above: `<C-u>` is a line-scoped verb, and at
4483    /// column 0 it is a no-op rather than a silent line-merge.
4484    fn delete_to_line_start(&mut self) {
4485        let cursor = self.cursor();
4486        let Some(indent) = self.resolve_motion(cursor, Motion::LineFirstNonBlank) else {
4487            return;
4488        };
4489        let target = if (indent.line, indent.column) < (cursor.line, cursor.column) {
4490            indent
4491        } else {
4492            Position::new(cursor.line, 0)
4493        };
4494        self.erase_back_to(target);
4495    }
4496
4497    /// `<Del>` against the BUFFER — the Insert-mode arm of
4498    /// [`Action::DeleteForward`]. The cursor does NOT move: forward-delete
4499    /// pulls the rest of the line leftwards under a stationary caret.
4500    fn delete_after_cursor(&mut self) {
4501        let cursor = self.cursor();
4502        let Some(buf) = self.buffers.get(self.active) else {
4503            return;
4504        };
4505        let target = if cursor.column < buf.line_len_chars(cursor.line) {
4506            Position::new(cursor.line, cursor.column.saturating_add(1))
4507        } else if cursor.line.saturating_add(1) < buf.line_count() {
4508            // At end-of-line the character ahead IS the newline, so this
4509            // joins the line below — the mirror of `delete_before_cursor`.
4510            Position::new(cursor.line.saturating_add(1), 0)
4511        } else {
4512            return;
4513        };
4514        let edit = Edit::delete(Range {
4515            start: cursor,
4516            end: target,
4517        });
4518        if let Some(buf) = self.buffers.get_mut(self.active) {
4519            let _ = buf.apply(&edit);
4520        }
4521    }
4522
4523    /// Backspace inside a prompt. Keeps the search buffer and the displayed
4524    /// minibuffer in lockstep — if only one shrank, the pattern submitted
4525    /// would differ from the text on screen.
4526    fn prompt_backspace(&mut self) -> bool {
4527        if self.modal.mode() != Mode::Command {
4528            return false;
4529        }
4530        if self.search.is_prompting() {
4531            // Backspacing past the `/` closes the prompt, as vim does. No
4532            // `pop_minibuffer` here for the same reason as `insert_char`: the
4533            // shadow is the ex-line's, and popping its TAIL when the caret is
4534            // mid-pattern was another desync path.
4535            if self.search.backspace() {
4536                self.modal.clear_minibuffer();
4537                self.modal.enter(Mode::Normal);
4538            }
4539            // Never `pop_minibuffer` on the search path: it pops the TAIL,
4540            // while `search.backspace()` removes the char before the CARET.
4541            return true;
4542        }
4543        self.modal.pop_minibuffer();
4544        true
4545    }
4546
4547    fn submit_command(&mut self) {
4548        // Read the command line BEFORE leaving Command mode — the minibuffer
4549        // exists only in the `Command` variant, so the escape must come
4550        // after the capture.
4551        let line = self.modal.minibuffer().to_string();
4552        self.modal.escape();
4553        // The ex-name grammar — vim's abbreviations and its `!` — lives in
4554        // `escriba_command::ex` and NOT here. It used to be three arms in a
4555        // `match` at the bottom of this file (`"w" => "save"`, …), which is
4556        // why `:wq` reported "command not found" while `:w` and `:q` both
4557        // worked: there was nowhere for a compound spelling to be known.
4558        let Some(inv) = escriba_command::ex::parse(&line) else {
4559            return;
4560        };
4561        self.run_command(&inv.command, &inv.args);
4562    }
4563
4564    fn run_command(&mut self, name: &str, args: &[String]) {
4565        // Bound the command -> RunCommand slip -> command cycle. Refused and
4566        // reported, never a stack overflow: an editor that dies under the
4567        // operator loses their buffer, and a script that loops is a mistake
4568        // they should be told about, not punished for.
4569        if self.dispatch_depth >= Self::MAX_DISPATCH_DEPTH {
4570            let mut m = String::from("command recursion too deep at `");
4571            m.push_str(name);
4572            m.push_str("` — refusing");
4573            self.messages.push(m);
4574            self.damage = self.damage.join(Damage::Viewport);
4575            self.bump_gen();
4576            return;
4577        }
4578        self.dispatch_depth += 1;
4579        self.run_command_inner(name, args);
4580        self.dispatch_depth -= 1;
4581    }
4582
4583    /// How many nested command dispatches are allowed. Deep enough that no
4584    /// legitimate script notices, shallow enough to fail fast.
4585    const MAX_DISPATCH_DEPTH: u8 = 8;
4586
4587    fn run_command_inner(&mut self, name: &str, args: &[String]) {
4588        // Lazy-activation seam (lazy.nvim `cmd =` model): a user plugin
4589        // gated on `Command: <name>` has its entry applied the first time
4590        // that command runs, BEFORE dispatch — so the activated plugin
4591        // can register the very command being invoked and it resolves on
4592        // this same call.
4593        if self.plugin_host.pending() > 0 {
4594            let pending = self.plugin_host.pending_for_command(name);
4595            for src in pending {
4596                self.apply_plugin_entry(&src);
4597            }
4598        }
4599        // Read through the counter, then interpret. Two immutable borrows of
4600        // `self` (the window and the registry) coexist; the `&mut` comes
4601        // afterwards, once the outcome is owned. That sequencing IS the
4602        // seam: there is no moment where a command body and `&mut self` are
4603        // live at the same time.
4604        let outcome = {
4605            let window = self.window();
4606            self.commands.run(name, &window, args)
4607        };
4608        match outcome {
4609            Ok(o) => self.interpret(o),
4610            // Reported, never fatal (Phase 0). A failed command must not
4611            // take the editor down, but it must not be invisible either.
4612            Err(e) => {
4613                self.messages.push(describe_command_failure(name, &e));
4614                self.damage = self.damage.join(Damage::Viewport);
4615                self.bump_gen();
4616            }
4617        }
4618    }
4619
4620    // ── tatara-lisp runtime bridge (imperative programmability tier) ──
4621
4622    /// Capture a read snapshot of the editor for the tatara-lisp host.
4623    /// Lisp reads (`cursor-line`, `current-line`, …) answer from this.
4624    #[must_use]
4625    pub fn snapshot(&self) -> EditorSnapshot {
4626        let current_line = self
4627            .buffers
4628            .get(self.active)
4629            .and_then(|b| b.line(self.cursor().line))
4630            .map(|s| s.trim_end_matches('\n').to_string())
4631            .unwrap_or_default();
4632        let buffer_name = self
4633            .buffers
4634            .get(self.active)
4635            .and_then(|b| b.path.as_ref())
4636            .map(|p| p.display().to_string())
4637            .unwrap_or_else(|| "[scratch]".to_string());
4638        EditorSnapshot {
4639            cursor_line: i64::from(self.cursor().line),
4640            cursor_column: i64::from(self.cursor().column),
4641            current_line,
4642            mode: self.modal.mode().as_str().to_string(),
4643            buffer_name,
4644        }
4645    }
4646
4647    /// Evaluate tatara-lisp `src` against this editor: capture a
4648    /// snapshot, run it in the embedded VM, then apply the typed effects
4649    /// the program emitted. This is the imperative programmability tier
4650    /// — live Lisp that reads state and drives the editor through the
4651    /// sandboxed effect boundary.
4652    ///
4653    /// **Snapshot semantics:** the read snapshot is captured ONCE before
4654    /// eval, and effects are applied AFTER the program returns. So within
4655    /// a single `run_lisp` call a program cannot observe its own writes —
4656    /// `(insert "x") (cursor-column)` reads the pre-insert column. This
4657    /// snapshot-isolation is deliberate (it's what makes the effect
4658    /// boundary a clean sandbox seam); a program that must read its own
4659    /// effects splits the work across calls. The VM is cached
4660    /// ([`Self::lisp_vm`]) so the stdlib is installed once and top-level
4661    /// `define`s persist across calls (REPL-like).
4662    pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
4663        let mut host = EscribaHost::with_snapshot(self.snapshot());
4664        let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
4665        vm.eval(src, &mut host)?;
4666        let effects = host.take_effects();
4667        self.apply_host_effects(effects);
4668        Ok(())
4669    }
4670
4671    /// Apply tatara-lisp effects to live editor state.
4672    ///
4673    /// A thin adapter now. It used to be `apply_host_effects`, a THIRD
4674    /// implementation of message-push / option-insert / insert-text beside
4675    /// the Action executor and the slip interpreter — the same duplication
4676    /// that let `u` and `:undo` drift apart in M3. The VM emits slips; this
4677    /// hands them to the one interpreter.
4678    pub fn apply_host_effects(&mut self, effects: Vec<Negai>) {
4679        self.interpret(Outcome::did(effects));
4680    }
4681
4682    /// Insert a (possibly multi-line) string at the cursor and advance
4683    /// the cursor past it. Used by the `(insert …)` effect.
4684    fn insert_text(&mut self, text: &str) {
4685        if text.is_empty() {
4686            return;
4687        }
4688        let cursor = self.cursor();
4689        let Some(buf) = self.buffers.get_mut(self.active) else {
4690            return;
4691        };
4692        let edit = Edit::insert(cursor, text.to_string());
4693        if buf.apply(&edit).is_ok() {
4694            let next = if let Some(nl) = text.rfind('\n') {
4695                let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
4696                let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
4697                Position::new(cursor.line + added_lines, last_line_len)
4698            } else {
4699                let n = u32::try_from(text.chars().count()).unwrap_or(0);
4700                cursor.shift_right(n)
4701            };
4702            // Route through the single cursor-mutation path so the viewport
4703            // follows the cursor (both axes) and the cursor stays clamped.
4704            self.place_cursor(next, CursorRest::AtInsertPoint);
4705        }
4706    }
4707}
4708
4709fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
4710    let Some(text) = buf.line(line) else {
4711        return Position::new(line, 0);
4712    };
4713    let col = text
4714        .chars()
4715        .take_while(|c| c.is_whitespace() && *c != '\n')
4716        .count();
4717    Position::new(line, u32::try_from(col).unwrap_or(0))
4718}
4719
4720/// A character search: which character, which direction, and whether it stops
4721/// ON it (`f`/`F`) or just BEFORE it (`t`/`T`).
4722///
4723/// The same value serves the pending operand and the `;`/`,` memory, so the
4724/// thing repeated is the thing that ran.
4725#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4726struct FindSpec {
4727    ch: char,
4728    backward: bool,
4729    till: bool,
4730}
4731
4732/// What the next keystroke means after `m`, `` ` `` or `'`.
4733#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4734enum MarkKey {
4735    /// `m{a-z}` — set.
4736    Set,
4737    /// `` `{a-z} `` — jump to the exact position.
4738    GotoExact,
4739    /// `'{a-z}` — jump to the line's first non-blank.
4740    GotoLine,
4741}
4742
4743/// What kind of place a cursor move is asking for.
4744///
4745/// The Normal-mode rule "the cursor sits ON a character" is about where the
4746/// cursor comes to REST. It is not about where text goes next: a write that
4747/// appends `abc` leaves the cursor after the `c`, and that position is one
4748/// past the last character by construction — clamping it back would make the
4749/// next append land inside the text just written. The lisp `(insert …)`
4750/// effect is the case that proves it, because it runs in Normal mode.
4751///
4752/// A parameter rather than two functions, so both readings stay in front of
4753/// whoever changes the clamp.
4754#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4755enum CursorRest {
4756    /// A motion's destination — Normal mode pulls it onto a character.
4757    OnCharacter,
4758    /// Where the next character goes — never pulled back.
4759    AtInsertPoint,
4760}
4761
4762/// What an operator acts over — a CAPTURE range, a REMOVAL range, and the
4763/// kind they were resolved as.
4764///
4765/// Two ranges because for a linewise extent they genuinely differ, and every
4766/// attempt to derive one from the other re-decides which branch produced it:
4767///
4768///   - `dd` removes the line AND its terminator; `cc` clears the line's text
4769///     and KEEPS the line, because you are changing its contents rather than
4770///     removing it. Same lines, same register content, different cut.
4771///   - On the last line of a file with no trailing newline the removal has to
4772///     swallow the PRECEDING newline (there is none following), so it starts
4773///     on a different LINE than the extent names.
4774///
4775/// Charwise extents have `capture == removal`, which is why the old
4776/// single-range signature was right for everything except the linewise change
4777/// and wrong there — `cc` deleted the line.
4778#[derive(Clone, Copy, Debug)]
4779struct Extent {
4780    /// What goes in the register, and what a delete removes.
4781    capture: Range,
4782    /// What a CHANGE removes. Equal to `capture` unless the kind is linewise.
4783    removal: Range,
4784    kind: RegisterKind,
4785}
4786
4787impl Extent {
4788    /// A run of characters: one range, both roles.
4789    const fn charwise(r: Range) -> Self {
4790        Self {
4791            capture: r,
4792            removal: r,
4793            kind: RegisterKind::Charwise,
4794        }
4795    }
4796
4797    /// An extent resolved by a text object, keyed on what the object says it
4798    /// is. The linewise case needs the explicit constructor below, so this is
4799    /// the charwise-or-nothing door.
4800    fn from_object(r: Range, kind: RegisterKind) -> Self {
4801        match kind {
4802            RegisterKind::Charwise => Self::charwise(r),
4803            // A caller that has only a range cannot supply the text-only
4804            // removal, so the two coincide — which is the pre-`cc` behaviour
4805            // and is correct for every linewise object except a change. The
4806            // `Line` object goes through `line_extent` instead.
4807            RegisterKind::Linewise => Self {
4808                capture: r,
4809                removal: r,
4810                kind,
4811            },
4812        }
4813    }
4814
4815    fn normalized(self) -> Self {
4816        Self {
4817            capture: self.capture.normalized(),
4818            removal: self.removal.normalized(),
4819            kind: self.kind,
4820        }
4821    }
4822}
4823
4824/// Normalize a linewise capture: newline-TERMINATED, never newline-LED.
4825///
4826/// The removal range and the register capture are two different views of one
4827/// gesture, and the last line of a file with no trailing newline is where they
4828/// come apart. There is no following terminator to take, so `dd` has to
4829/// swallow the PRECEDING one — the right thing to REMOVE, and the wrong thing
4830/// to put back: the raw slice reads `"\nbravo"`, so `yyp` opened a blank line
4831/// and then a `bravo` with no terminator of its own.
4832///
4833/// Stated once, here, where the kind is known. `Register::replayed` handles
4834/// the other half (a capture that ends without a newline).
4835fn as_linewise_capture(slice: &str) -> String {
4836    match slice.strip_prefix('\n') {
4837        Some(rest) => {
4838            let mut s = String::with_capacity(slice.len());
4839            s.push_str(rest);
4840            s.push('\n');
4841            s
4842        }
4843        None => slice.to_owned(),
4844    }
4845}
4846
4847/// How a captured operand's composed action reaches the executor.
4848#[derive(Clone, Copy, PartialEq, Eq, Debug)]
4849enum OperandCount {
4850    /// The capture already applied its own repeats; run the composed action
4851    /// once. Only the object path does this (`2diw` repeats inside it).
4852    SelfCounted,
4853    /// Drain the pending count and hand it to `apply_counted`, so `3fx` /
4854    /// `3ra` / ``3`a`` repeat on the one path every other motion uses.
4855    Drained,
4856}
4857
4858/// One step of the operand-capture chain.
4859struct OperandCapture {
4860    /// Stable label — what `operand_capture_order.rs` asserts against.
4861    name: &'static str,
4862    claim: fn(&mut EditorState, Key) -> Option<ObjectKey>,
4863    count: OperandCount,
4864}
4865
4866/// **The operand-capture chain, in the order that matters.**
4867///
4868/// Every adjacency is a dependency with a named failure:
4869///
4870/// 1. **mark before object** — the object path claims `i`/`a` whenever an
4871///    operator is armed, and a mark LETTER can be either, so ``d`a`` lost its
4872///    `a` to it. They do not fight over the FIRST key (the mark path arms only
4873///    while `pending_object` is clear, so `di'` still reaches the object
4874///    path); they fight over the SECOND, and the gesture already half-typed
4875///    must win.
4876/// 2. **object before find** — `di(` must not read as `d`, then `i` (insert),
4877///    then a literal `(`.
4878/// 3. **find before replace** — no live conflict; `f`/`t` and `r` arm on
4879///    disjoint keys and neither can be pending while the other is. Ordered
4880///    for stability rather than necessity, and said so rather than implying a
4881///    constraint that is not there.
4882/// 4. **all four before the sequence stepper and the keymap** — this is the
4883///    whole point. Each capture also declines while `pending_keys` is
4884///    non-empty, so a LATER key of a gesture (`zt`'s `t`) belongs to the
4885///    sequence rather than arming a till-find.
4886static OPERAND_CHAIN: &[OperandCapture] = &[
4887    OperandCapture {
4888        name: "mark",
4889        claim: EditorState::consume_mark_key,
4890        count: OperandCount::Drained,
4891    },
4892    OperandCapture {
4893        name: "object",
4894        claim: EditorState::consume_object_key,
4895        count: OperandCount::SelfCounted,
4896    },
4897    OperandCapture {
4898        name: "find",
4899        claim: EditorState::consume_find_key,
4900        count: OperandCount::Drained,
4901    },
4902    OperandCapture {
4903        name: "replace",
4904        claim: EditorState::consume_replace_key,
4905        count: OperandCount::Drained,
4906    },
4907];
4908
4909/// The chain's order, for the gate in `tests/operand_capture_order.rs`.
4910#[must_use]
4911pub fn operand_capture_order() -> Vec<&'static str> {
4912    OPERAND_CHAIN.iter().map(|c| c.name).collect()
4913}
4914
4915/// Does this action ABSORB its count into one operation, or REPEAT?
4916///
4917/// A free function rather than a method on `Action` deliberately: the answer
4918/// is a property of THIS EXECUTOR's arms, not of the action's meaning. An arm
4919/// absorbs its count exactly when it takes one, and a name listed here that no
4920/// arm reads is worse than no list — it reads as handled and behaves as
4921/// repeated. Keep the two in step; the tests below pin every member.
4922fn absorbs_count(action: &Action) -> bool {
4923    matches!(
4924        action,
4925        Action::ApplyOperator { .. }
4926            | Action::Put { .. }
4927            // `3ra` is one replace of three characters (and refuses if there
4928            // are not three), `3J` is one join of three lines. Repeating
4929            // either would walk the cursor and do the wrong thing three times.
4930            | Action::ReplaceChar(_)
4931            | Action::JoinLines { .. }
4932            // Only the LINEWISE object can express an `n`-fold extent today.
4933            // `2diw` still repeats, which is the same over-count-a-yank defect
4934            // waiting on a general "resolve this object n times" — named here
4935            // rather than half-fixed.
4936            | Action::ApplyOperatorObject {
4937                object: escriba_core::TextObject::Line,
4938                ..
4939            }
4940    )
4941}
4942
4943/// Where a put leaves the cursor.
4944///
4945/// Decided BEFORE the insert (from the register's kind) and consumed after,
4946/// because the two arms need different information and only one of them
4947/// survives the edit: the linewise arm needs the line it opened, which the
4948/// pre-edit position names, while the charwise arm needs the extent of the
4949/// text it wrote. Computing either from the post-edit buffer alone means
4950/// re-deriving which gesture happened, which is exactly what
4951/// [`escriba_core::RegisterKind`] exists to stop.
4952#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4953enum PutRest {
4954    /// Linewise: the first non-blank of the first line put.
4955    LineStart(u32),
4956    /// Charwise: ON the last character put — vim's rule, and the one that
4957    /// makes a following `p` stack the copies rather than walk rightward.
4958    LastCharPut,
4959}
4960
4961/// vim's three character classes — the whole of what "a word" means to `w`,
4962/// `b`, `e` and `iw`.
4963///
4964/// One classifier, not four. `object_word` grew its own copy while the word
4965/// MOTIONS were still splitting on whitespace alone, so `diw` on `foo.bar`
4966/// took `foo` and `dw` took `foo.bar` — two answers to "where does this word
4967/// end" from one editor, on the same keystroke's worth of text.
4968#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4969enum WordClass {
4970    Word,
4971    Punct,
4972    Space,
4973}
4974
4975fn word_class(c: char) -> WordClass {
4976    if c.is_alphanumeric() || c == '_' {
4977        WordClass::Word
4978    } else if c.is_whitespace() {
4979        WordClass::Space
4980    } else {
4981        WordClass::Punct
4982    }
4983}
4984
4985/// vim's two word WIDTHS. `w` splits on the three [`WordClass`]es; `W` splits
4986/// on whitespace alone, so `foo.bar` is three words and one WORD.
4987///
4988/// A parameter on the scanners rather than a second family of them: `w` and
4989/// `W` differ in exactly one place — how a character is classified — and two
4990/// copies of the cross-line, empty-line and end-of-buffer rules is how they
4991/// would drift.
4992#[derive(PartialEq, Eq, Clone, Copy, Debug)]
4993enum Width {
4994    /// `w` / `e` / `b` / `ge` — alphanumeric, punctuation and space.
4995    Small,
4996    /// `W` / `E` / `B` / `gE` — non-space and space, nothing else.
4997    Big,
4998}
4999
5000fn class_at(c: char, width: Width) -> WordClass {
5001    match (width, word_class(c)) {
5002        (Width::Big, WordClass::Punct) => WordClass::Word,
5003        (_, k) => k,
5004    }
5005}
5006
5007/// A line's characters WITHOUT its terminator.
5008///
5009/// The newline is not a character the cursor can sit on, and every word scan
5010/// wants the line's own text; `line_len_chars` already strips it for exactly
5011/// this reason, so the two agree on where a line ends by construction.
5012fn line_chars(buf: &escriba_buffer::Buffer, line: u32) -> Vec<char> {
5013    let Some(text) = buf.line(line) else {
5014        return Vec::new();
5015    };
5016    let len = buf.line_len_chars(line) as usize;
5017    text.chars().take(len).collect()
5018}
5019
5020/// The last line that HOLDS text.
5021///
5022/// A file ending in `\n` is one line of text plus a terminator, but the rope
5023/// reports two lines, the second empty — so `line_count() - 1` names a line
5024/// that is not there. A forward word motion walking onto it moves the cursor
5025/// off the end of the file onto a row with nothing on it, which is what `w`
5026/// on the last word of an ordinary file did.
5027///
5028/// Scoped to the word motions on purpose. That phantom row is also DRAWN — it
5029/// gets a gutter number in every face — and hiding it is a buffer-model change
5030/// with a much wider blast radius than a motion fix; it is a separate defect,
5031/// named rather than half-fixed here. What is fixed here is the claim these
5032/// motions make: there is no next word after the last character of the text.
5033fn last_text_line(buf: &escriba_buffer::Buffer) -> u32 {
5034    let last = buf.line_count().saturating_sub(1);
5035    if last > 0 && buf.line_len_chars(last) == 0 {
5036        last - 1
5037    } else {
5038        last
5039    }
5040}
5041
5042/// Where a forward word motion runs out of text — the EXCLUSIVE end, so an
5043/// operator reaches the final character. See [`word_next`].
5044fn buffer_end(buf: &escriba_buffer::Buffer) -> Position {
5045    let line = last_text_line(buf);
5046    Position::new(line, buf.line_len_chars(line))
5047}
5048
5049/// `w` — to the start of the next word.
5050///
5051/// Three vim behaviours this had to grow, each of which was a visible wrong
5052/// answer before:
5053///
5054/// - **Punctuation starts a word.** `w` on `foo.bar` stops at `.` and again
5055///   at `b`; the whitespace-only scan sailed past both to the end.
5056/// - **It crosses lines onto the first non-blank**, not onto column 0. Landing
5057///   on the indent means the next `w` is spent walking out of it.
5058/// - **An empty line is a word.** vim stops on one, and that is what makes `w`
5059///   usable for walking paragraphs.
5060///
5061/// When there is no next word it returns the position PAST the last character
5062/// — not the last character itself. That looks like the bug it is next to and
5063/// is the opposite: an operator needs the exclusive end (`dw` on the final
5064/// word must delete the whole word), and it is the Normal-mode cursor that
5065/// must not sit there. So the clamp lives in [`EditorState::set_cursor`],
5066/// which knows the mode, and this stays a pure range endpoint.
5067fn word_next(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5068    let mut line = pos.line;
5069    let mut chars = line_chars(buf, line);
5070    let mut col = (pos.column as usize).min(chars.len());
5071
5072    // Leave the run the cursor is standing in. Starting on a blank skips this
5073    // — there is no run to leave, only blanks to cross.
5074    if col < chars.len() {
5075        let start = class_at(chars[col], width);
5076        if start != WordClass::Space {
5077            while col < chars.len() && class_at(chars[col], width) == start {
5078                col += 1;
5079            }
5080        }
5081    }
5082
5083    loop {
5084        while col < chars.len() && class_at(chars[col], width) == WordClass::Space {
5085            col += 1;
5086        }
5087        if col < chars.len() {
5088            return Position::new(line, u32::try_from(col).unwrap_or(pos.column));
5089        }
5090        if line >= last_text_line(buf) {
5091            // Out of text: the exclusive end of the last word.
5092            return Position::new(line, u32::try_from(chars.len()).unwrap_or(pos.column));
5093        }
5094        line += 1;
5095        col = 0;
5096        chars = line_chars(buf, line);
5097        if chars.is_empty() {
5098            return Position::new(line, 0);
5099        }
5100    }
5101}
5102
5103/// `b` — back to the start of the current or previous word.
5104///
5105/// Class-aware like [`word_next`], so `b` and `w` agree on where a word
5106/// begins; a disagreement between them is felt as `dw` and `db` deleting
5107/// different things from the same spot.
5108///
5109/// Single-line, and that is load-bearing: `<C-w>` reaches back over this
5110/// motion and relies on it returning the cursor UNCHANGED at column 0, which
5111/// is what makes the insert-mode erase fall through to `delete_before_cursor`
5112/// and join with the line above. Teaching this to cross lines would silently
5113/// change that key.
5114fn word_prev(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5115    let chars = line_chars(buf, pos.line);
5116    let mut i = (pos.column as usize).min(chars.len());
5117    while i > 0 && class_at(chars[i - 1], width) == WordClass::Space {
5118        i -= 1;
5119    }
5120    if i > 0 {
5121        let run = class_at(chars[i - 1], width);
5122        while i > 0 && class_at(chars[i - 1], width) == run {
5123            i -= 1;
5124        }
5125    }
5126    Position::new(pos.line, u32::try_from(i).unwrap_or(0))
5127}
5128
5129/// `ge` / `gE` — back to the LAST character of the previous word.
5130///
5131/// The mirror of [`word_end`], and INCLUSIVE like it: `dge` deletes through
5132/// the character it lands on. Single-line for the same reason [`word_prev`]
5133/// is — the backward scanners are what the insert-mode erases stand on, and
5134/// teaching them to cross lines changes those keys silently.
5135fn word_end_prev(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5136    let chars = line_chars(buf, pos.line);
5137    let start = (pos.column as usize).min(chars.len());
5138    // `ge` always retreats at least one character before it starts looking,
5139    // so standing on the last character of a word does not stand still.
5140    let Some(mut i) = start.checked_sub(1) else {
5141        return pos;
5142    };
5143    // Leave the run the cursor is standing in FIRST. Without this, `ge` from
5144    // the middle (or the end) of a word lands one character to its left —
5145    // inside the same word, which is the one place `ge` must never stop.
5146    if let Some(&here) = chars.get(start) {
5147        let run = class_at(here, width);
5148        if run != WordClass::Space {
5149            while i > 0 && class_at(chars[i], width) == run {
5150                i -= 1;
5151            }
5152        }
5153    }
5154    while i > 0 && class_at(chars[i], width) == WordClass::Space {
5155        i -= 1;
5156    }
5157    Position::new(pos.line, u32::try_from(i).unwrap_or(0))
5158}
5159
5160/// `e` — to the LAST character of the current or next word.
5161///
5162/// Always moves, which is what separates it from "the end of this word": on
5163/// the last character of a word, `e` goes to the last character of the NEXT
5164/// one rather than standing still.
5165///
5166/// This motion is INCLUSIVE — it names a character to act on, not a boundary
5167/// to stop before — see [`Motion::is_inclusive`]. `WordEndNext` used to
5168/// resolve through [`word_next`], so `e` and `w` were the same key with two
5169/// names.
5170fn word_end(buf: &escriba_buffer::Buffer, pos: Position, width: Width) -> Position {
5171    let mut line = pos.line;
5172    let mut chars = line_chars(buf, line);
5173    // `e` always advances at least one character before it starts looking.
5174    let mut col = (pos.column as usize).saturating_add(1);
5175
5176    loop {
5177        while col < chars.len() && class_at(chars[col], width) == WordClass::Space {
5178            col += 1;
5179        }
5180        if col < chars.len() {
5181            break;
5182        }
5183        if line >= last_text_line(buf) {
5184            return buffer_end(buf);
5185        }
5186        line += 1;
5187        col = 0;
5188        chars = line_chars(buf, line);
5189    }
5190
5191    let run = class_at(chars[col], width);
5192    while col + 1 < chars.len() && class_at(chars[col + 1], width) == run {
5193        col += 1;
5194    }
5195    Position::new(line, u32::try_from(col).unwrap_or(pos.column))
5196}
5197
5198/// `f` / `F` / `t` / `T` — the character search, resolved on ONE line.
5199///
5200/// vim's character search never crosses a line, which is what makes it safe
5201/// to compose with an operator: `df;` can only ever delete within the line.
5202/// `None` when the character is not there — the motion fails and the operator
5203/// aborts with the buffer untouched, rather than deleting to the line edge.
5204fn find_char(
5205    buf: &escriba_buffer::Buffer,
5206    pos: Position,
5207    ch: char,
5208    backward: bool,
5209    till: bool,
5210) -> Option<Position> {
5211    let chars = line_chars(buf, pos.line);
5212    let cur = (pos.column as usize).min(chars.len());
5213    let hit = if backward {
5214        // `T` stops AFTER the character, so it has to start one further back
5215        // or a repeated `T` would never leave the spot it already reached.
5216        let from = if till { cur.checked_sub(1)? } else { cur };
5217        (0..from).rev().find(|&i| chars[i] == ch)?
5218    } else {
5219        let from = if till { cur.saturating_add(2) } else { cur + 1 };
5220        (from.min(chars.len())..chars.len()).find(|&i| chars[i] == ch)?
5221    };
5222    let col = match (backward, till) {
5223        (false, true) => hit - 1,
5224        (true, true) => hit + 1,
5225        _ => hit,
5226    };
5227    Some(Position::new(pos.line, u32::try_from(col).ok()?))
5228}
5229
5230/// The four bracket pairs `%` knows.
5231const MATCH_PAIRS: [(char, char); 4] = [('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')];
5232
5233/// A language's WORD pairs for `%` — vim's `matchit`, typed.
5234///
5235/// `(open, middles, close)`. A middle (`else`, `elif`, `when`) is a word `%`
5236/// steps THROUGH on its way round the group; without them `%` on a shell `if`
5237/// jumps straight past `elif` to `fi`, which is right for a scanner and wrong
5238/// for a reader.
5239///
5240/// A TABLE keyed by filetype name, not a per-language scanner: every entry is
5241/// the same depth-counting walk over a different word list, so a new language
5242/// is a row. Deliberately small — these are the languages whose blocks are
5243/// words rather than braces, which is exactly the set where bracket-only `%`
5244/// is useless.
5245type WordPairs = &'static [(&'static str, &'static [&'static str], &'static str)];
5246
5247const WORD_PAIRS: &[(&str, WordPairs)] = &[
5248    (
5249        "lua",
5250        &[
5251            ("if", &["elseif", "else"], "end"),
5252            ("for", &[], "end"),
5253            ("while", &[], "end"),
5254            ("function", &[], "end"),
5255            ("do", &[], "end"),
5256            ("repeat", &[], "until"),
5257        ],
5258    ),
5259    (
5260        "ruby",
5261        &[
5262            ("if", &["elsif", "else"], "end"),
5263            ("unless", &["else"], "end"),
5264            ("case", &["when", "else"], "end"),
5265            ("begin", &["rescue", "ensure", "else"], "end"),
5266            ("def", &[], "end"),
5267            ("class", &[], "end"),
5268            ("module", &[], "end"),
5269            ("do", &[], "end"),
5270            ("while", &[], "end"),
5271        ],
5272    ),
5273    (
5274        "sh",
5275        &[
5276            ("if", &["elif", "else"], "fi"),
5277            ("case", &[], "esac"),
5278            ("do", &[], "done"),
5279        ],
5280    ),
5281    (
5282        "bash",
5283        &[
5284            ("if", &["elif", "else"], "fi"),
5285            ("case", &[], "esac"),
5286            ("do", &[], "done"),
5287        ],
5288    ),
5289    (
5290        "elixir",
5291        &[
5292            ("do", &["else", "rescue", "after", "catch"], "end"),
5293            ("fn", &[], "end"),
5294        ],
5295    ),
5296    (
5297        "vim",
5298        &[
5299            ("if", &["elseif", "else"], "endif"),
5300            ("function", &[], "endfunction"),
5301            ("while", &[], "endwhile"),
5302            ("for", &[], "endfor"),
5303            ("try", &["catch", "finally"], "endtry"),
5304        ],
5305    ),
5306];
5307
5308/// A word occurrence: its position, and which group + role it plays.
5309#[derive(Clone, Copy)]
5310struct WordHit {
5311    line: u32,
5312    col: u32,
5313    end: u32,
5314    group: usize,
5315    /// `0` = opener, `1` = middle, `2` = closer.
5316    role: u8,
5317}
5318
5319/// `%` — to the match of the bracket under the cursor, or of the first
5320/// bracket to its right on the same line (vim scans forward to find one).
5321///
5322/// Depth-counting and buffer-wide, because a brace pair that fits on one line
5323/// is the case `%` is least needed for.
5324fn match_pair(buf: &escriba_buffer::Buffer, pos: Position) -> Option<Position> {
5325    let chars = line_chars(buf, pos.line);
5326    let start = (pos.column as usize).min(chars.len());
5327    let (col, open, close, forward) = (start..chars.len()).find_map(|i| {
5328        MATCH_PAIRS.iter().find_map(|&(o, c)| {
5329            if chars[i] == o {
5330                Some((i, o, c, true))
5331            } else if chars[i] == c {
5332                Some((i, o, c, false))
5333            } else {
5334                None
5335            }
5336        })
5337    })?;
5338
5339    let last = buf.line_count().saturating_sub(1);
5340    let mut depth = 0i32;
5341    let (mut line, mut i) = (pos.line, col);
5342    let mut text = chars;
5343    loop {
5344        let c = text[i];
5345        if c == open {
5346            depth += if forward { 1 } else { -1 };
5347        } else if c == close {
5348            depth += if forward { -1 } else { 1 };
5349        }
5350        if depth == 0 {
5351            return Some(Position::new(line, u32::try_from(i).ok()?));
5352        }
5353        if forward {
5354            i += 1;
5355            while i >= text.len() {
5356                if line >= last {
5357                    return None;
5358                }
5359                line += 1;
5360                text = line_chars(buf, line);
5361                i = 0;
5362            }
5363        } else {
5364            while i == 0 {
5365                if line == 0 {
5366                    return None;
5367                }
5368                line -= 1;
5369                text = line_chars(buf, line);
5370                i = text.len();
5371            }
5372            i -= 1;
5373        }
5374    }
5375}
5376
5377/// Every word-pair keyword on `line`, in column order.
5378///
5379/// Word-bounded on both sides, so `endif` is not read as `end`, `define` is
5380/// not read as `def`, and a `do` inside `window` is not a block opener. That
5381/// boundary check is the whole difference between matchit and a substring
5382/// search, and skipping it is worse than having no word pairs at all — a `%`
5383/// that jumps to the middle of an identifier is a silent wrong answer.
5384fn word_hits(buf: &escriba_buffer::Buffer, line: u32, pairs: WordPairs) -> Vec<WordHit> {
5385    let chars = line_chars(buf, line);
5386    let mut out = Vec::new();
5387    let mut i = 0usize;
5388    while i < chars.len() {
5389        if word_class(chars[i]) != WordClass::Word {
5390            i += 1;
5391            continue;
5392        }
5393        let start = i;
5394        while i < chars.len() && word_class(chars[i]) == WordClass::Word {
5395            i += 1;
5396        }
5397        let word: String = chars[start..i].iter().collect();
5398        for (group, (open, middles, close)) in pairs.iter().enumerate() {
5399            let role = if word == *open {
5400                0
5401            } else if word == *close {
5402                2
5403            } else if middles.contains(&word.as_str()) {
5404                1
5405            } else {
5406                continue;
5407            };
5408            out.push(WordHit {
5409                line,
5410                col: u32::try_from(start).unwrap_or(0),
5411                end: u32::try_from(i).unwrap_or(0),
5412                group,
5413                role,
5414            });
5415            break;
5416        }
5417    }
5418    out
5419}
5420
5421/// `%` over WORD pairs — matchit's half of the motion.
5422///
5423/// Finds the keyword at (or right of) the cursor and walks to the next member
5424/// of its group at the same depth: opener → first middle → … → closer →
5425/// opener. Cycling rather than jumping straight to the closer is what makes
5426/// `%` usable for reading an `if`/`elif`/`else`/`fi` chain.
5427fn match_word_pair(
5428    buf: &escriba_buffer::Buffer,
5429    pos: Position,
5430    pairs: WordPairs,
5431) -> Option<Position> {
5432    let here = word_hits(buf, pos.line, pairs)
5433        .into_iter()
5434        .find(|h| h.end > pos.column)?;
5435    let last = last_text_line(buf);
5436    let forward = here.role != 2;
5437    let mut depth = 0i32;
5438    let mut line = here.line;
5439    loop {
5440        let hits = word_hits(buf, line, pairs);
5441        // Only the hits strictly beyond the starting keyword on its own line.
5442        let scan: Vec<WordHit> = if line == here.line {
5443            let mut v: Vec<WordHit> = hits
5444                .into_iter()
5445                .filter(|h| {
5446                    if forward {
5447                        h.col > here.col
5448                    } else {
5449                        h.col < here.col
5450                    }
5451                })
5452                .collect();
5453            if !forward {
5454                v.reverse();
5455            }
5456            v
5457        } else {
5458            let mut v = hits;
5459            if !forward {
5460                v.reverse();
5461            }
5462            v
5463        };
5464        for h in scan {
5465            if h.group != here.group {
5466                continue;
5467            }
5468            match (h.role, forward) {
5469                (0, true) | (2, false) => depth += 1,
5470                (2, true) | (0, false) => {
5471                    if depth == 0 {
5472                        return Some(Position::new(h.line, h.col));
5473                    }
5474                    depth -= 1;
5475                }
5476                // A middle at the SAME depth is the next stop; nested ones are
5477                // somebody else's `else`.
5478                (1, _) if depth == 0 => return Some(Position::new(h.line, h.col)),
5479                _ => {}
5480            }
5481        }
5482        if forward {
5483            if line >= last {
5484                return None;
5485            }
5486            line += 1;
5487        } else {
5488            if line == 0 {
5489                return None;
5490            }
5491            line -= 1;
5492        }
5493    }
5494}
5495
5496/// `{` / `}` — to the nearest blank line in `dir`, or the buffer edge.
5497///
5498/// vim's paragraph boundary is an EMPTY line, not an indentation change; a
5499/// line of spaces is not one. `line_len_chars` already excludes the
5500/// terminator, so "empty" is exactly `len == 0`.
5501fn paragraph(buf: &escriba_buffer::Buffer, pos: Position, forward: bool) -> Position {
5502    let last = last_text_line(buf);
5503    let mut line = pos.line;
5504    loop {
5505        if forward {
5506            if line >= last {
5507                return buffer_end(buf);
5508            }
5509            line += 1;
5510        } else {
5511            if line == 0 {
5512                return Position::ZERO;
5513            }
5514            line -= 1;
5515        }
5516        if buf.line_len_chars(line) == 0 {
5517            return Position::new(line, 0);
5518        }
5519    }
5520}
5521
5522/// `(` / `)` — to the start of the adjacent sentence.
5523///
5524/// A sentence ends at `.`/`!`/`?` followed by whitespace or end-of-line; the
5525/// next one starts at the following non-blank. A paragraph boundary is also a
5526/// sentence boundary, which is what stops `)` at the end of a block of prose
5527/// instead of sailing into the next one.
5528fn sentence(buf: &escriba_buffer::Buffer, pos: Position, forward: bool) -> Position {
5529    let starts = sentence_starts(buf);
5530    let here = (pos.line, pos.column);
5531    if forward {
5532        starts
5533            .iter()
5534            .find(|&&(l, c)| (l, c) > here)
5535            .map_or_else(|| buffer_end(buf), |&(l, c)| Position::new(l, c))
5536    } else {
5537        starts
5538            .iter()
5539            .rev()
5540            .find(|&&(l, c)| (l, c) < here)
5541            .map_or(Position::ZERO, |&(l, c)| Position::new(l, c))
5542    }
5543}
5544
5545/// Every sentence start in the buffer, in order.
5546///
5547/// Computed wholesale rather than scanned directionally: the backward and
5548/// forward cases are then the same list read two ways, so `(` and `)` cannot
5549/// disagree about where a sentence begins.
5550fn sentence_starts(buf: &escriba_buffer::Buffer) -> Vec<(u32, u32)> {
5551    let mut out = vec![(0u32, 0u32)];
5552    let mut ended = false;
5553    for line in 0..=last_text_line(buf) {
5554        let chars = line_chars(buf, line);
5555        if chars.is_empty() {
5556            // A blank line is a paragraph break, and so a sentence break.
5557            out.push((line, 0));
5558            ended = false;
5559            continue;
5560        }
5561        for (i, &c) in chars.iter().enumerate() {
5562            if ended && !c.is_whitespace() {
5563                out.push((line, u32::try_from(i).unwrap_or(0)));
5564                ended = false;
5565            }
5566            if matches!(c, '.' | '!' | '?') {
5567                ended = true;
5568            } else if !matches!(c, ')' | ']' | '"' | '\'') && !c.is_whitespace() {
5569                ended = false;
5570            }
5571        }
5572    }
5573    out.sort_unstable();
5574    out.dedup();
5575    out
5576}
5577
5578#[cfg(test)]
5579mod tests {
5580    use super::*;
5581    use madori::event::{KeyCode, KeyEvent, Modifiers};
5582
5583    // ── search wiring (escriba-search integration) ────────────────────
5584    //
5585    // The engine is proven in escriba-search's own 61 tests. These prove the
5586    // WIRING: that keys reach it, that the cursor lands where it says, and
5587    // that a search prompt and an ex-command can share Command mode without
5588    // being confused for one another.
5589
5590    fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
5591        st.apply(&Action::SearchOpen(dir));
5592        for c in pat.chars() {
5593            st.apply(&Action::InsertChar(c));
5594        }
5595        st.apply(&Action::SubmitCommand);
5596    }
5597
5598    #[test]
5599    fn slash_search_moves_the_cursor_to_the_match() {
5600        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
5601        type_search(&mut st, SearchDirection::Forward, "charlie");
5602        assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
5603        assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
5604        assert_eq!(st.search.matches().len(), 1);
5605    }
5606
5607    #[test]
5608    // `N` is a DIFFERENT vim key from `n` — see escriba-search.
5609    #[allow(non_snake_case)]
5610    fn n_and_N_walk_matches_in_both_directions() {
5611        let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
5612        type_search(&mut st, SearchDirection::Forward, "foo");
5613        let first = st.cursor().line;
5614        st.apply(&Action::SearchRepeat { reverse: false });
5615        let second = st.cursor().line;
5616        assert!(second > first, "n advances ({first} -> {second})");
5617        st.apply(&Action::SearchRepeat { reverse: true });
5618        assert_eq!(st.cursor().line, first, "N comes back");
5619    }
5620
5621    #[test]
5622    fn star_searches_the_word_under_the_cursor() {
5623        let mut st = new_state_with("needle\nhaystack\nneedle\n");
5624        st.apply(&Action::SearchWord { reverse: false });
5625        assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
5626        assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
5627    }
5628
5629    #[test]
5630    fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
5631        let mut st = new_state_with("foo\nbar\nfoo\n");
5632        type_search(&mut st, SearchDirection::Forward, "foo");
5633        let matches_before = st.search.matches().len();
5634
5635        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5636        st.apply(&Action::InsertChar('z'));
5637        st.apply(&Action::ChangeMode(Mode::Normal));
5638
5639        assert!(!st.search.is_prompting(), "prompt gone");
5640        assert_eq!(
5641            st.search.pattern().unwrap().raw(),
5642            "foo",
5643            "old pattern survives"
5644        );
5645        assert_eq!(
5646            st.search.matches().len(),
5647            matches_before,
5648            "old highlights survive"
5649        );
5650    }
5651
5652    #[test]
5653    fn a_search_prompt_and_an_ex_command_are_not_confused() {
5654        let mut st = new_state_with("foo\n");
5655        // No `/` pressed: Command mode belongs to the ex-command line.
5656        st.apply(&Action::ChangeMode(Mode::Command));
5657        assert!(!st.search.is_prompting(), "`:` must not open a search");
5658        st.apply(&Action::InsertChar('w'));
5659        assert!(
5660            st.search.prompt().is_none(),
5661            "typed char went to the ex line"
5662        );
5663    }
5664
5665    #[test]
5666    fn a_missing_pattern_reports_instead_of_failing_silently() {
5667        let mut st = new_state_with("alpha\nbravo\n");
5668        type_search(&mut st, SearchDirection::Forward, "zzz");
5669        assert!(
5670            st.messages.iter().any(|m| m.contains("E486")),
5671            "must report not-found, got {:?}",
5672            st.messages
5673        );
5674    }
5675
5676    #[test]
5677    fn n_without_any_search_reports_rather_than_moving() {
5678        let mut st = new_state_with("alpha\nbravo\n");
5679        let before = st.cursor();
5680        st.apply(&Action::SearchRepeat { reverse: false });
5681        assert_eq!(st.cursor(), before, "cursor must not move");
5682        assert!(
5683            st.messages.iter().any(|m| m.contains("E35")),
5684            "got {:?}",
5685            st.messages
5686        );
5687    }
5688
5689    #[test]
5690    fn search_as_a_motion_composes_with_an_operator() {
5691        // The point of Motion::SearchNext: `d` + search deletes to the match.
5692        let mut st = new_state_with("alpha bravo charlie\n");
5693        type_search(&mut st, SearchDirection::Forward, "charlie");
5694        st.set_cursor(Position::new(0, 0));
5695        let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
5696        assert!(target.is_some(), "search must resolve as a motion");
5697        assert_eq!(target.unwrap().column, 12, "at `charlie`");
5698    }
5699
5700    #[test]
5701    fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
5702        // A silent fallback to offset 0 would make `d` + search delete to the
5703        // start of the file — the worst possible failure for an operator.
5704        let st = new_state_with("alpha bravo\n");
5705        assert!(
5706            st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
5707                .is_none()
5708        );
5709    }
5710
5711    #[test]
5712    fn clear_highlight_keeps_the_pattern_usable() {
5713        let mut st = new_state_with("foo\nbar\nfoo\n");
5714        type_search(&mut st, SearchDirection::Forward, "foo");
5715        st.apply(&Action::ClearSearchHighlight);
5716        assert!(st.search.highlights().is_empty(), "nothing lit");
5717        st.apply(&Action::SearchRepeat { reverse: false });
5718        assert!(st.search.pattern().is_some(), "but n still works");
5719    }
5720
5721    #[test]
5722    fn typing_previews_incrementally_before_commit() {
5723        let mut st = new_state_with("alpha\nbravo\ncharlie\n");
5724        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5725        for c in "charlie".chars() {
5726            st.apply(&Action::InsertChar(c));
5727        }
5728        // incsearch: the cursor has already moved, with nothing committed.
5729        assert_eq!(st.cursor().line, 2, "preview moved the cursor");
5730        assert!(st.search.pattern().is_none(), "but nothing is committed");
5731    }
5732
5733    #[test]
5734    fn backspace_corrects_the_prompt_and_reruns_the_preview() {
5735        let mut st = new_state_with("alpha\nbravo\n");
5736        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5737        for c in "bravox".chars() {
5738            st.apply(&Action::InsertChar(c));
5739        }
5740        assert_eq!(st.search.prompt().unwrap().text(), "bravox");
5741        st.apply(&Action::Backspace);
5742        assert_eq!(
5743            st.search.prompt().unwrap().text(),
5744            "bravo",
5745            "typo corrected"
5746        );
5747        assert_eq!(
5748            st.status_model().prompt_text,
5749            "bravo",
5750            "the model reads the PROMPT — the minibuffer is the ex-line's store",
5751        );
5752        assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
5753    }
5754
5755    #[test]
5756    fn backspacing_past_the_slash_closes_the_prompt() {
5757        let mut st = new_state_with("alpha\n");
5758        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5759        st.apply(&Action::InsertChar('a'));
5760        st.apply(&Action::Backspace);
5761        st.apply(&Action::Backspace);
5762        assert!(!st.search.is_prompting(), "prompt closed");
5763        assert_eq!(st.modal.mode(), Mode::Normal);
5764    }
5765
5766    #[test]
5767    fn noh_clears_highlights_and_keeps_the_pattern() {
5768        let mut st = new_state_with("foo\nbar\nfoo\n");
5769        type_search(&mut st, SearchDirection::Forward, "foo");
5770        assert!(!st.search.highlights().is_empty());
5771        st.run_command("noh", &[]);
5772        assert!(st.search.highlights().is_empty(), ":noh turns them off");
5773        assert!(st.search.pattern().is_some(), "but n still works");
5774    }
5775
5776    #[test]
5777    fn noh_accepts_the_vim_aliases() {
5778        for name in ["noh", "nohl", "nohlsearch"] {
5779            let mut st = new_state_with("foo\nfoo\n");
5780            type_search(&mut st, SearchDirection::Forward, "foo");
5781            st.run_command(name, &[]);
5782            assert!(st.search.highlights().is_empty(), "{name} must clear");
5783        }
5784    }
5785
5786    #[test]
5787    fn backspace_on_the_ex_line_does_not_touch_search_state() {
5788        let mut st = new_state_with("foo\n");
5789        st.apply(&Action::ChangeMode(Mode::Command));
5790        st.apply(&Action::InsertChar('w'));
5791        st.apply(&Action::InsertChar('q'));
5792        st.apply(&Action::Backspace);
5793        assert_eq!(st.status_model().prompt_text, "w");
5794        assert!(st.search.prompt().is_none(), "no search was involved");
5795    }
5796
5797    #[test]
5798    fn up_arrow_recalls_the_previous_search() {
5799        let mut st = new_state_with("alpha\nbravo\n");
5800        type_search(&mut st, SearchDirection::Forward, "bravo");
5801        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5802        st.apply(&Action::PromptHistory { back: true });
5803        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
5804        assert_eq!(
5805            st.status_model().prompt_text,
5806            "bravo",
5807            "display follows the prompt"
5808        );
5809    }
5810
5811    #[test]
5812    fn arrowing_back_down_restores_the_half_typed_pattern() {
5813        let mut st = new_state_with("alpha\nbravo\n");
5814        type_search(&mut st, SearchDirection::Forward, "bravo");
5815        st.apply(&Action::SearchOpen(SearchDirection::Forward));
5816        st.apply(&Action::InsertChar('a'));
5817        st.apply(&Action::PromptHistory { back: true });
5818        assert_eq!(st.search.prompt().unwrap().text(), "bravo");
5819        st.apply(&Action::PromptHistory { back: false });
5820        assert_eq!(
5821            st.search.prompt().unwrap().text(),
5822            "a",
5823            "the draft comes back"
5824        );
5825        assert_eq!(st.status_model().prompt_text, "a");
5826    }
5827
5828    #[test]
5829    fn history_arrows_do_nothing_on_the_ex_line() {
5830        let mut st = new_state_with("alpha\n");
5831        st.apply(&Action::ChangeMode(Mode::Command));
5832        st.apply(&Action::InsertChar('w'));
5833        st.apply(&Action::PromptHistory { back: true });
5834        assert_eq!(st.status_model().prompt_text, "w", "ex line untouched");
5835    }
5836
5837    // ── trouble.* — the findings view ────────────────────────────────
5838    //
5839    // These assert on the ROWS the picker would be built from, not on the
5840    // registry: the registry is already tested, and what could be wrong
5841    // here is the projection — scoping, freshness, and whether a row goes
5842    // anywhere when pressed.
5843
5844    fn finding_at(buffer: BufferId, line: u32, msg: &str) -> escriba_shirube::Finding {
5845        use escriba_core::{Position, Range};
5846        escriba_shirube::Finding::new(
5847            escriba_shirube::Site::in_buffer(
5848                buffer,
5849                Range::new(Position::new(line, 0), Position::new(line, 1)),
5850            ),
5851            escriba_shirube::Severity::Error,
5852            msg.to_string(),
5853            escriba_shirube::Origin::Text("test"),
5854        )
5855    }
5856
5857    #[test]
5858    fn published_findings_become_picker_rows() {
5859        let mut st = new_state_with("a\nb\nc\n");
5860        let world = st.world();
5861        st.results.publish(
5862            "test",
5863            escriba_shirube::ResultList::new(vec![finding_at(st.active, 1, "boom")], world),
5864        );
5865        let rows = st.finding_items(true, None);
5866        assert_eq!(rows.len(), 1, "the published finding produces a row");
5867        // The row must SAY something an operator can act on: severity,
5868        // 1-based line, and the message.
5869        let label = &rows[0].label;
5870        assert!(label.contains("ERROR"), "{label}");
5871        assert!(label.contains(":2"), "lines are 1-based on screen: {label}");
5872        assert!(label.contains("boom"), "{label}");
5873    }
5874
5875    #[test]
5876    fn a_stale_list_contributes_no_rows() {
5877        // THE load-bearing one. A list anchored to a revision the buffer has
5878        // moved past must vanish from the view rather than offer a line that
5879        // has since shifted — which is the whole reason findings carry an
5880        // anchor instead of just a position.
5881        let mut st = new_state_with("a\nb\nc\n");
5882        let world = st.world();
5883        st.results.publish(
5884            "test",
5885            escriba_shirube::ResultList::new(vec![finding_at(st.active, 1, "boom")], world),
5886        );
5887        assert_eq!(st.finding_items(true, None).len(), 1, "fresh to begin with");
5888
5889        st.apply(&Action::InsertChar('x'));
5890        assert!(
5891            st.finding_items(true, None).is_empty(),
5892            "an edit moved the text on; the list is stale and must not be shown"
5893        );
5894    }
5895
5896    #[test]
5897    fn document_scope_excludes_another_buffer() {
5898        // `trouble.document` vs `trouble.workspace` is one bool, so this is
5899        // the only thing that can distinguish them.
5900        let mut st = new_state_with("a\nb\n");
5901        let other = st.buffers.scratch("z\n");
5902        let world = st.world();
5903        st.results.publish(
5904            "test",
5905            escriba_shirube::ResultList::new(
5906                vec![
5907                    finding_at(st.active, 0, "mine"),
5908                    finding_at(other, 0, "theirs"),
5909                ],
5910                world,
5911            ),
5912        );
5913        let ws = st.finding_items(true, None);
5914        assert_eq!(ws.len(), 2, "workspace scope shows both");
5915        let doc = st.finding_items(false, None);
5916        assert_eq!(doc.len(), 1, "document scope shows only the active buffer");
5917        assert!(doc[0].label.contains("mine"), "{}", doc[0].label);
5918    }
5919
5920    #[test]
5921    fn files_under_a_root_produces_rows() {
5922        // `files.open-parent` differs from `files.open` only in the root, so
5923        // what must hold is that a root is actually honoured.
5924        let mut st = new_state_with("");
5925        let rows = st.file_items(std::path::Path::new("."));
5926        assert!(!rows.is_empty(), "the working directory has files");
5927    }
5928
5929    // ── vim text objects ─────────────────────────────────────────────
5930    //
5931    // Asserted through `apply` on real buffer text, so a wrong RANGE shows
5932    // up as wrong text rather than as a range that merely looks plausible.
5933
5934    fn after(text: &str, line: u32, col: u32, act: Action) -> String {
5935        let mut st = new_state_with(text);
5936        st.set_cursor(Position::new(line, col));
5937        st.apply(&act);
5938        st.buffers
5939            .get(st.active)
5940            .map(|b| b.to_string())
5941            .unwrap_or_default()
5942    }
5943
5944    fn del_obj(o: escriba_core::TextObject) -> Action {
5945        Action::ApplyOperatorObject {
5946            op: escriba_core::Operator::Delete,
5947            object: o,
5948        }
5949    }
5950
5951    #[test]
5952    fn dd_removes_the_line_not_just_its_contents() {
5953        // The distinction the newline makes: without it, `dd` blanks a line
5954        // and leaves it behind.
5955        let got = after("a\nb\nc\n", 1, 0, del_obj(escriba_core::TextObject::Line));
5956        assert_eq!(got, "a\nc\n");
5957    }
5958
5959    #[test]
5960    fn dd_on_the_last_line_leaves_no_blank_behind() {
5961        // The case a naive start-of-line..start-of-next range gets wrong:
5962        // there is no following newline to take, so it must take the
5963        // preceding one.
5964        let got = after("a\nb\nc\n", 2, 0, del_obj(escriba_core::TextObject::Line));
5965        assert_eq!(got, "a\nb\n", "no trailing empty line: {got:?}");
5966    }
5967
5968    #[test]
5969    fn dd_on_the_only_line_clears_it_but_keeps_the_line() {
5970        let got = after("solo\n", 0, 2, del_obj(escriba_core::TextObject::Line));
5971        assert!(got.starts_with('\n') || got.is_empty(), "{got:?}");
5972    }
5973
5974    #[test]
5975    fn diw_takes_the_word_and_daw_takes_its_trailing_space() {
5976        let inner = after(
5977            "one two three\n",
5978            0,
5979            5,
5980            del_obj(escriba_core::TextObject::Word { around: false }),
5981        );
5982        assert_eq!(inner, "one  three\n", "iw leaves both spaces");
5983        let around = after(
5984            "one two three\n",
5985            0,
5986            5,
5987            del_obj(escriba_core::TextObject::Word { around: true }),
5988        );
5989        assert_eq!(around, "one three\n", "aw takes the trailing space");
5990    }
5991
5992    #[test]
5993    fn iw_from_any_column_inside_the_word_takes_the_whole_word() {
5994        for col in 4..=6 {
5995            let got = after(
5996                "one two three\n",
5997                0,
5998                col,
5999                del_obj(escriba_core::TextObject::Word { around: false }),
6000            );
6001            assert_eq!(got, "one  three\n", "from column {col}");
6002        }
6003    }
6004
6005    #[test]
6006    fn iw_on_punctuation_takes_the_punctuation_run() {
6007        // vim's three classes: word / punctuation / whitespace. A `::` is a
6008        // run of punctuation, not part of either identifier.
6009        let got = after(
6010            "foo::bar\n",
6011            0,
6012            3,
6013            del_obj(escriba_core::TextObject::Word { around: false }),
6014        );
6015        assert_eq!(got, "foobar\n");
6016    }
6017
6018    #[test]
6019    fn i_paren_takes_the_inside_and_a_paren_takes_the_brackets_too() {
6020        let inner = after(
6021            "f(a, b)\n",
6022            0,
6023            3,
6024            del_obj(escriba_core::TextObject::Delimited {
6025                open: '(',
6026                close: ')',
6027                around: false,
6028            }),
6029        );
6030        assert_eq!(inner, "f()\n");
6031        let around = after(
6032            "f(a, b)\n",
6033            0,
6034            3,
6035            del_obj(escriba_core::TextObject::Delimited {
6036                open: '(',
6037                close: ')',
6038                around: true,
6039            }),
6040        );
6041        assert_eq!(around, "f\n");
6042    }
6043
6044    #[test]
6045    fn nested_brackets_resolve_to_the_enclosing_pair() {
6046        // THE reason the bracket scan counts depth: an inner pair must not
6047        // terminate the search for the one the cursor is actually inside.
6048        let got = after(
6049            "f(g(x), y)\n",
6050            0,
6051            8,
6052            del_obj(escriba_core::TextObject::Delimited {
6053                open: '(',
6054                close: ')',
6055                around: false,
6056            }),
6057        );
6058        assert_eq!(got, "f()\n", "took the outer pair");
6059    }
6060
6061    #[test]
6062    fn quotes_do_not_nest_so_the_nearest_pair_wins() {
6063        let got = after(
6064            r#"say "hi there" ok"#,
6065            0,
6066            7,
6067            del_obj(escriba_core::TextObject::Delimited {
6068                open: '"',
6069                close: '"',
6070                around: false,
6071            }),
6072        );
6073        assert_eq!(got, "say \"\" ok");
6074    }
6075
6076    #[test]
6077    fn an_unmatched_delimiter_resolves_to_nothing_rather_than_guessing() {
6078        let mut st = new_state_with("f(a, b\n");
6079        st.set_cursor(Position::new(0, 3));
6080        let before = st
6081            .buffers
6082            .get(st.active)
6083            .map(|b| b.to_string())
6084            .unwrap_or_default();
6085        st.apply(&del_obj(escriba_core::TextObject::Delimited {
6086            open: '(',
6087            close: ')',
6088            around: false,
6089        }));
6090        let got_after = st
6091            .buffers
6092            .get(st.active)
6093            .map(|b| b.to_string())
6094            .unwrap_or_default();
6095        assert_eq!(got_after, before, "no closing bracket: change nothing");
6096    }
6097
6098    fn new_state_with(text: &str) -> EditorState {
6099        let mut bufs = BufferSet::new();
6100        let id = bufs.scratch(text);
6101        EditorState::new_with_buffer(bufs, id)
6102    }
6103
6104    /// A breakpoint toggle reaches the GPU face's rebuild gate.
6105    ///
6106    /// ## What this does and does not claim
6107    ///
6108    /// The GPU face is the only one that CACHES its gutter: it shapes a
6109    /// glyphon buffer and rebuilds it only when `s.edit_gen() != self.last_gen`
6110    /// (`escriba-render/src/gpu.rs:260`). Both testable faces repaint from
6111    /// scratch every draw, so no rendered-cells test can see this — measured
6112    /// 2026-08-12 by removing the bump and watching all eight breakpoint
6113    /// render tests stay green.
6114    ///
6115    /// The guarantee is STRUCTURAL, not local: [`EditorState::honour`] widens
6116    /// the damage and bumps the generation after every slip, so the property
6117    /// holds for `ToggleBreakpoint` the way it holds for the other thirty.
6118    /// This pins the INSTANCE, and says so rather than pretending to gate a
6119    /// line inside `toggle_breakpoint` — there is no such line, deliberately.
6120    ///
6121    /// RED RUN (2026-08-12): deleting `self.bump_gen()` from `honour` fails
6122    /// this (and much else, which is the honest shape of a structural
6123    /// guarantee). The evidence is the generation counter itself — the exact
6124    /// value the GPU gate compares — not a restatement of "was a method
6125    /// called".
6126    #[test]
6127    fn setting_a_breakpoint_repaints() {
6128        let mut s = new_state_with("alpha\nbravo\ncharlie\n");
6129        let before = s.edit_gen();
6130        s.run_command("dap.toggle-breakpoint", &[]);
6131        assert!(
6132            s.breakpoints().is_set(s.active, 0),
6133            "precondition: the toggle ran",
6134        );
6135        assert_ne!(
6136            s.edit_gen(),
6137            before,
6138            "the GPU face rebuilds its cached gutter ONLY on a generation \
6139             change — without this the mark never reaches that screen",
6140        );
6141        assert!(
6142            !s.damage().is_none(),
6143            "and a scoped-repaint face has to be told the viewport moved",
6144        );
6145    }
6146
6147    #[test]
6148    fn a_breakpoint_toggle_with_no_open_buffer_marks_nothing() {
6149        // A mark on a buffer that does not exist is one no future DAP client
6150        // could ever name, and the honest report is silence rather than a
6151        // confirmation of something that did not happen. `active` names no
6152        // open buffer here, which is the state a `--no-defaults` boot and a
6153        // just-closed buffer both pass through.
6154        let mut s = new_state_with("alpha\n");
6155        s.active = BufferId(9_999);
6156        s.run_command("dap.toggle-breakpoint", &[]);
6157        assert!(!s.breakpoints().is_set(s.active, 0), "nothing was marked");
6158        assert!(
6159            !s.messages.iter().any(|m| m.contains("breakpoint")),
6160            "and nothing was claimed: {:?}",
6161            s.messages,
6162        );
6163    }
6164
6165    /// The refresh-seal driver (theory/ESCRIBA.md §Refresh-Seal): an applied
6166    /// action advances `edit_gen` (so the renderer repaints), and merely
6167    /// reading the generation does not. This is what lets `gpu.rs` gate the
6168    /// re-highlight/re-shape on a generation change — an idle frame observes an
6169    /// unchanged generation and reuses its cached buffer.
6170    #[test]
6171    fn edit_gen_advances_on_applied_action_not_on_read() {
6172        let mut s = new_state_with("hello\nworld\n");
6173        let g0 = s.edit_gen();
6174        s.apply(&Action::InsertChar('X'));
6175        assert_ne!(
6176            s.edit_gen(),
6177            g0,
6178            "an applied action must advance the refresh generation",
6179        );
6180        // Reading the generation is not a mutation — idle frames stay put.
6181        let g1 = s.edit_gen();
6182        assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
6183    }
6184
6185    /// The M1 refresh node (theory/ESCRIBA.md §X): a mutation widens the typed
6186    /// `Damage` to cover exactly what changed — local for an in-place edit,
6187    /// to-end-of-document when the line count shifts — and the renderer drains
6188    /// it per frame. `Damage ⊇ changed` by construction; it never narrows.
6189    #[test]
6190    fn damage_tracks_edit_scope_and_drains() {
6191        let mut s = new_state_with("hello\nworld\n");
6192        assert!(s.damage().is_none(), "a fresh state has no damage");
6193
6194        s.apply(&Action::InsertChar('X')); // in-place edit on line 0
6195        assert_eq!(
6196            s.damage(),
6197            Damage::Lines { from: 0, to: 0 },
6198            "a local edit damages just its line",
6199        );
6200
6201        let drained = s.take_damage();
6202        assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
6203        assert!(s.damage().is_none(), "take_damage drains to None");
6204
6205        s.apply(&Action::InsertChar('\n')); // splits line 0 → line count grows
6206        assert_eq!(
6207            s.damage(),
6208            Damage::Lines {
6209                from: 0,
6210                to: u32::MAX,
6211            },
6212            "a line-count change damages to end-of-document",
6213        );
6214    }
6215
6216    /// A state whose active window is a deliberately tiny viewport
6217    /// (`visible_lines` × `visible_columns`) so the scroll-to-contain
6218    /// invariant is exercised on small inputs.
6219    fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
6220        let mut s = new_state_with(text);
6221        for w in s.layout.windows_mut() {
6222            w.viewport.visible_lines = vis_lines;
6223            w.viewport.visible_columns = vis_cols;
6224        }
6225        s
6226    }
6227
6228    /// The core regression invariant: the active window's viewport CONTAINS
6229    /// the cursor on BOTH axes. This is the operator's exact complaint —
6230    /// "typing past the bottom (or right) leaves the cursor off-screen" —
6231    /// made into a checkable property.
6232    fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
6233        let w = s.layout.active_window().expect("active window");
6234        let v = w.viewport;
6235        let c = s.cursor();
6236        assert!(
6237            v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
6238            "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
6239            c.line,
6240            v.top_line,
6241            v.top_line + v.visible_lines,
6242        );
6243        assert!(
6244            v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
6245            "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
6246            c.column,
6247            v.left_column,
6248            v.left_column + v.visible_columns,
6249        );
6250    }
6251
6252    /// `dd` from the KEYBOARD, not from a synthesized action.
6253    ///
6254    /// The FSM composition is unit-tested, but what an operator actually
6255    /// does is press `d` twice — and that path goes through the keymap and
6256    /// the sequence stepper, either of which could swallow the second `d`.
6257    #[test]
6258    fn pressing_d_twice_deletes_the_line() {
6259        let mut st = new_state_with("alpha\nbeta\ngamma\n");
6260        st.set_cursor(Position::new(1, 0));
6261        st.tick(&press(KeyCode::Char('d')));
6262        st.tick(&press(KeyCode::Char('d')));
6263        let got = st
6264            .buffers
6265            .get(st.active)
6266            .map(|b| b.to_string())
6267            .unwrap_or_default();
6268        assert_eq!(got, "alpha\ngamma\n", "dd from the keyboard");
6269    }
6270
6271    #[test]
6272    fn pressing_2_d_d_deletes_two_lines() {
6273        let mut st = new_state_with("a\nb\nc\nd\n");
6274        st.set_cursor(Position::new(0, 0));
6275        for k in ['2', 'd', 'd'] {
6276            st.tick(&press(KeyCode::Char(k)));
6277        }
6278        let got = st
6279            .buffers
6280            .get(st.active)
6281            .map(|b| b.to_string())
6282            .unwrap_or_default();
6283        assert_eq!(got, "c\nd\n", "count applies to the doubled operator");
6284    }
6285
6286    // ── The insert-entry family: `i` `I` `a` `A` `o` `O` ─────────────────
6287    //
6288    // Measured before the family existed (escriba 0.1.71, live 80×24 TUI):
6289    // pressing `A` moved nothing, changed no mode and printed nothing, because
6290    // an unbound Normal key resolves to `Action::Pending`. Only `i` was bound.
6291
6292    /// Press one key on `text` from `at`, and report (mode, cursor, buffer).
6293    ///
6294    /// The buffer is part of the tuple on purpose: four of the six entries must
6295    /// leave it byte-identical, and a caret-only assertion cannot see a stray
6296    /// edit — which is the exact shape of the phantom-space report that started
6297    /// this work.
6298    fn entry(text: &str, at: Position, key: char) -> (Mode, Position, String) {
6299        let mut st = new_state_with(text);
6300        st.set_cursor(at);
6301        st.tick(&press(KeyCode::Char(key)));
6302        (
6303            st.modal.mode(),
6304            st.cursor(),
6305            st.buffers
6306                .get(st.active)
6307                .map(|b| b.to_string())
6308                .unwrap_or_default(),
6309        )
6310    }
6311
6312    /// The whole family, one row per entry — vim's caret placement exactly.
6313    ///
6314    /// A matrix rather than six tests so the ★★ CLOSED-LOOP MASS-SYNTHESIS
6315    /// rule has something to bite on: `every_insert_entry_has_a_key` below
6316    /// fails the build when a seventh `InsertAt` variant lands without a row.
6317    #[test]
6318    fn the_insert_entry_family_places_the_caret_like_vim() {
6319        // "  hello" — two leading blanks, so `I` and `0` differ, and 7 chars,
6320        // so "one past the end" is column 7.
6321        const TEXT: &str = "  hello\nworld\n";
6322        let from = Position::new(0, 4); // on the first `l`
6323        for (key, want_cursor, want_text, why) in [
6324            (
6325                'i',
6326                Position::new(0, 4),
6327                TEXT,
6328                "`i` inserts before the caret",
6329            ),
6330            (
6331                'I',
6332                Position::new(0, 2),
6333                TEXT,
6334                "`I` goes to the first NON-BLANK, not to column 0",
6335            ),
6336            (
6337                'a',
6338                Position::new(0, 5),
6339                TEXT,
6340                "`a` appends after the caret",
6341            ),
6342            (
6343                'A',
6344                Position::new(0, 7),
6345                TEXT,
6346                "`A` parks one PAST the last char — the whole point of the key",
6347            ),
6348            (
6349                'o',
6350                Position::new(1, 0),
6351                "  hello\n\nworld\n",
6352                "`o` opens below and lands on the new line",
6353            ),
6354            (
6355                'O',
6356                Position::new(0, 0),
6357                "\n  hello\nworld\n",
6358                "`O` opens above; the fresh line takes the caret's line number",
6359            ),
6360        ] {
6361            let (mode, cursor, text) = entry(TEXT, from, key);
6362            assert_eq!(mode, Mode::Insert, "`{key}` must enter Insert");
6363            assert_eq!(cursor, want_cursor, "{why}");
6364            assert_eq!(text, want_text, "`{key}`: {why}");
6365        }
6366    }
6367
6368    /// Every `InsertAt` has a Normal-mode key, and every one of those keys
6369    /// actually resolves to it.
6370    ///
6371    /// The forcing function. Adding a variant to `InsertAt` without binding it
6372    /// fails here rather than shipping a key that silently does nothing — which
6373    /// is precisely how `a`, `A`, `I`, `o` and `O` were missing for so long
6374    /// without any test noticing.
6375    #[test]
6376    fn every_insert_entry_has_a_key() {
6377        let km = escriba_keymap::Keymap::default_vim();
6378        let bound: Vec<InsertAt> = km
6379            .entries_sorted()
6380            .into_iter()
6381            .filter_map(|(mode, _, b)| match (mode, &b.action) {
6382                (Mode::Normal, Action::EnterInsert(at)) => Some(*at),
6383                _ => None,
6384            })
6385            .collect();
6386        for at in InsertAt::ALL {
6387            assert!(
6388                bound.contains(&at),
6389                "InsertAt::{at:?} ({}) has no Normal-mode key",
6390                at.as_str()
6391            );
6392        }
6393        assert_eq!(
6394            bound.len(),
6395            InsertAt::ALL.len(),
6396            "one key per entry, no duplicates: {bound:?}"
6397        );
6398    }
6399
6400    /// `A` then typing appends at the end — the end-to-end gesture, not just
6401    /// the caret placement.
6402    ///
6403    /// The caret assertion above would still pass if Insert mode refused to
6404    /// write at a column past the last character; this is what proves the
6405    /// `CursorRest::AtInsertPoint` rest actually holds through a keystroke.
6406    #[test]
6407    fn shift_a_then_typing_appends_at_the_end_of_the_line() {
6408        let mut st = new_state_with("hello\nworld\n");
6409        st.set_cursor(Position::new(0, 0));
6410        st.tick(&press(KeyCode::Char('A')));
6411        for c in "!!".chars() {
6412            st.tick(&press(KeyCode::Char(c)));
6413        }
6414        assert_eq!(
6415            st.buffers
6416                .get(st.active)
6417                .map(|b| b.to_string())
6418                .unwrap_or_default(),
6419            "hello!!\nworld\n"
6420        );
6421    }
6422
6423    /// `a` on the LAST character still appends, rather than stalling.
6424    ///
6425    /// The case the Normal-mode clamp would break, and the test that measured
6426    /// how. RED RUN 2026-08-12: `place_cursor`'s clamp needs BOTH
6427    /// `CursorRest::OnCharacter` and `Mode::Normal`, so this stays green if
6428    /// either guard is removed and goes red only when both are — reporting
6429    /// `column: 4` (back on the `o`) instead of 5. See `enter_insert_at`, whose
6430    /// doc comment originally over-claimed that the ordering alone carried it.
6431    #[test]
6432    fn a_on_the_last_character_appends_after_it() {
6433        let mut st = new_state_with("hello\n");
6434        st.set_cursor(Position::new(0, 4)); // the `o`
6435        st.tick(&press(KeyCode::Char('a')));
6436        assert_eq!(st.cursor(), Position::new(0, 5), "one past the `o`");
6437        st.tick(&press(KeyCode::Char('?')));
6438        assert_eq!(
6439            st.buffers
6440                .get(st.active)
6441                .map(|b| b.to_string())
6442                .unwrap_or_default(),
6443            "hello?\n"
6444        );
6445    }
6446
6447    /// No insert-entry key touches the buffer except `o`/`O`.
6448    ///
6449    /// The direct gate on the reported symptom: "hitting insert creates a
6450    /// space". It never did — the space was a RENDER defect (see
6451    /// `escriba-tui`'s `entering_insert_does_not_widen_the_rendered_line`) —
6452    /// and this test is what keeps the two explanations from being confused
6453    /// again, by pinning that the text really is untouched.
6454    #[test]
6455    fn entering_insert_types_nothing() {
6456        const TEXT: &str = "  hello\nworld\n";
6457        for key in ['i', 'I', 'a', 'A'] {
6458            let (_, _, text) = entry(TEXT, Position::new(0, 4), key);
6459            assert_eq!(text, TEXT, "`{key}` must not write a character");
6460        }
6461        for key in ['o', 'O'] {
6462            let (_, _, text) = entry(TEXT, Position::new(0, 4), key);
6463            assert_eq!(
6464                text.chars().filter(|c| *c == '\n').count(),
6465                3,
6466                "`{key}` adds exactly one line terminator and no other char"
6467            );
6468            assert!(
6469                text.contains("  hello") && text.contains("world"),
6470                "`{key}` must not disturb the existing lines: {text:?}"
6471            );
6472        }
6473    }
6474
6475    /// Binding bare `a` and `i` must NOT shadow the text objects.
6476    ///
6477    /// The regression this whole family risked. `escriba-keymap`'s rule is that
6478    /// a single binding beats a sequence prefix, so a naive `a` binding would
6479    /// have made `daw` mean "delete, then append". It does not, because
6480    /// `consume_object_key` runs before both and claims `i`/`a` only while an
6481    /// operator is armed — this test is the evidence for that sentence.
6482    #[test]
6483    fn the_insert_entry_keys_do_not_shadow_text_objects() {
6484        assert_eq!(keys("one two three\n", 0, 5, "daw"), "one three\n");
6485        assert_eq!(keys("one two three\n", 0, 5, "diw"), "one  three\n");
6486        assert_eq!(keys("f(a, b)\n", 0, 3, "di("), "f()\n");
6487        // And the operator-free path still reaches the new bindings.
6488        let (mode, cursor, _) = entry("one two\n", Position::new(0, 0), 'a');
6489        assert_eq!(mode, Mode::Insert);
6490        assert_eq!(cursor, Position::new(0, 1), "no operator ⇒ `a` appends");
6491    }
6492
6493    /// Text objects FROM THE KEYBOARD.
6494    ///
6495    /// Every bracket is unbound, and `i`/`a` are claimed by
6496    /// `consume_object_key` only while an operator waits, so all of this is
6497    /// decided on the KEY rather than in the binding table. (Until 2026-08-12
6498    /// this comment read "`i` is `ChangeMode(Insert)` in Normal and `a` … are
6499    /// unbound" — true when written, and made false by the insert-entry family
6500    /// above.)
6501
6502    fn keys(text: &str, line: u32, col: u32, seq: &str) -> String {
6503        let mut st = new_state_with(text);
6504        st.set_cursor(Position::new(line, col));
6505        for c in seq.chars() {
6506            st.tick(&press(KeyCode::Char(c)));
6507        }
6508        st.buffers
6509            .get(st.active)
6510            .map(|b| b.to_string())
6511            .unwrap_or_default()
6512    }
6513
6514    #[test]
6515    fn diw_from_the_keyboard() {
6516        assert_eq!(keys("one two three\n", 0, 5, "diw"), "one  three\n");
6517    }
6518
6519    #[test]
6520    fn daw_from_the_keyboard_takes_the_space() {
6521        assert_eq!(keys("one two three\n", 0, 5, "daw"), "one three\n");
6522    }
6523
6524    #[test]
6525    fn ciw_deletes_and_enters_insert() {
6526        let mut st = new_state_with("one two\n");
6527        st.set_cursor(Position::new(0, 5));
6528        for c in "ciw".chars() {
6529            st.tick(&press(KeyCode::Char(c)));
6530        }
6531        assert_eq!(st.modal.mode(), Mode::Insert, "change leaves you inserting");
6532        let got = st
6533            .buffers
6534            .get(st.active)
6535            .map(|b| b.to_string())
6536            .unwrap_or_default();
6537        assert_eq!(got, "one \n");
6538    }
6539
6540    #[test]
6541    fn di_paren_and_da_paren_from_the_keyboard() {
6542        assert_eq!(keys("f(a, b)\n", 0, 3, "di("), "f()\n");
6543        assert_eq!(keys("f(a, b)\n", 0, 3, "da("), "f\n");
6544    }
6545
6546    #[test]
6547    fn the_closing_bracket_and_b_are_aliases() {
6548        // vim accepts `i(`, `i)` and `ib` for the same object.
6549        for sel in ["di(", "di)", "dib"] {
6550            assert_eq!(keys("f(a, b)\n", 0, 3, sel), "f()\n", "{sel}");
6551        }
6552    }
6553
6554    #[test]
6555    fn di_quote_from_the_keyboard() {
6556        assert_eq!(keys("say \"hi\" ok\n", 0, 6, "di\""), "say \"\" ok\n");
6557    }
6558
6559    #[test]
6560    fn i_alone_still_enters_insert_when_no_operator_is_pending() {
6561        // The load-bearing negative: the object layer must not steal `i`
6562        // from ordinary use.
6563        let mut st = new_state_with("abc\n");
6564        st.tick(&press(KeyCode::Char('i')));
6565        assert_eq!(st.modal.mode(), Mode::Insert);
6566    }
6567
6568    #[test]
6569    fn an_unknown_object_key_cancels_rather_than_staying_armed() {
6570        // `diz` is not an object. The operator must disarm, and the buffer
6571        // must be untouched — not left waiting to eat the next keystroke.
6572        let mut st = new_state_with("one two\n");
6573        st.set_cursor(Position::new(0, 5));
6574        for c in "diz".chars() {
6575            st.tick(&press(KeyCode::Char(c)));
6576        }
6577        let got = st
6578            .buffers
6579            .get(st.active)
6580            .map(|b| b.to_string())
6581            .unwrap_or_default();
6582        assert_eq!(got, "one two\n", "nothing was deleted");
6583        assert_eq!(*st.op_pending.state(), OpState::Resting, "and it disarmed");
6584    }
6585
6586    // ── the register under a count ───────────────────────────────────
6587
6588    #[test]
6589    fn a_counted_delete_puts_all_of_it_in_the_register() {
6590        // `3dw` is one delete of three words as far as the register is
6591        // concerned. Each repetition emits its own Yank, and each used to
6592        // overwrite — so `3dwP` put back only the third word and silently
6593        // lost two.
6594        let mut st = new_state_with("one two three four\n");
6595        st.set_cursor(Position::new(0, 0));
6596        for c in "3dw".chars() {
6597            st.tick(&press(KeyCode::Char(c)));
6598        }
6599        assert_eq!(
6600            st.register_text(),
6601            Some("one two three "),
6602            "all three words, in the order they were deleted"
6603        );
6604    }
6605
6606    #[test]
6607    fn an_uncounted_delete_still_replaces_the_register() {
6608        // The combining flag must not leak: a later single delete replaces.
6609        let mut st = new_state_with("alpha beta\n");
6610        st.set_cursor(Position::new(0, 0));
6611        for c in "3dw".chars() {
6612            st.tick(&press(KeyCode::Char(c)));
6613        }
6614        let mut st2 = new_state_with("gamma delta\n");
6615        st2.set_cursor(Position::new(0, 0));
6616        for c in "dw".chars() {
6617            st2.tick(&press(KeyCode::Char(c)));
6618        }
6619        assert_eq!(st2.register_text(), Some("gamma "));
6620    }
6621
6622    #[test]
6623    fn two_separate_counted_deletes_do_not_accumulate_into_each_other() {
6624        // The flag is cleared after each group, so the second `2dw` starts
6625        // from empty rather than appending to the first.
6626        let mut st = new_state_with("a b c d e f\n");
6627        st.set_cursor(Position::new(0, 0));
6628        for c in "2dw".chars() {
6629            st.tick(&press(KeyCode::Char(c)));
6630        }
6631        let first = st.register_text().map(str::to_owned);
6632        for c in "2dw".chars() {
6633            st.tick(&press(KeyCode::Char(c)));
6634        }
6635        assert_eq!(first.as_deref(), Some("a b "));
6636        assert_eq!(st.register_text(), Some("c d "), "not \"a b c d \"");
6637    }
6638
6639    #[test]
6640    fn a_counted_yank_accumulates_without_changing_the_buffer() {
6641        let mut st = new_state_with("one two three\n");
6642        st.set_cursor(Position::new(0, 0));
6643        let before = st
6644            .buffers
6645            .get(st.active)
6646            .map(|b| b.to_string())
6647            .unwrap_or_default();
6648        for c in "2yw".chars() {
6649            st.tick(&press(KeyCode::Char(c)));
6650        }
6651        assert_eq!(st.register_text(), Some("one two "));
6652        let after = st
6653            .buffers
6654            .get(st.active)
6655            .map(|b| b.to_string())
6656            .unwrap_or_default();
6657        assert_eq!(after, before, "yank does not edit");
6658    }
6659
6660    // ── the anchored reply (Negai::ErrandReply) ──────────────────────
6661    //
6662    // Landed BEFORE the courier that will produce these. The class being
6663    // closed: a reply computed off the tick, applied against a world that
6664    // has since moved, and RESEALED as fresh by the interpreter — which is
6665    // what every synchronous slip correctly does and what an async one must
6666    // never do.
6667
6668    fn a_finding(buffer: BufferId, line: u32) -> escriba_shirube::Finding {
6669        use escriba_core::{Position, Range};
6670        escriba_shirube::Finding::new(
6671            escriba_shirube::Site::in_buffer(
6672                buffer,
6673                Range::new(Position::new(line, 0), Position::new(line, 1)),
6674            ),
6675            escriba_shirube::Severity::Error,
6676            "computed off the tick".to_string(),
6677            escriba_shirube::Origin::Text("test"),
6678        )
6679    }
6680
6681    #[test]
6682    fn a_fresh_errand_reply_is_honoured() {
6683        let mut st = new_state_with("a\nb\nc\n");
6684        let anchor = st.world();
6685        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
6686            anchor,
6687            then: Box::new(escriba_madoguchi::Negai::PublishFindings {
6688                list: "lsp".to_string(),
6689                findings: vec![a_finding(st.active, 1)],
6690            }),
6691        });
6692        assert_eq!(
6693            st.finding_items(true, None).len(),
6694            1,
6695            "the world had not moved"
6696        );
6697    }
6698
6699    /// THE red run. Without the freshness check this passes findings
6700    /// straight through, and `PublishFindings` reseals them with the
6701    /// CURRENT world — so they are reported fresh at columns that moved.
6702    #[test]
6703    fn a_stale_errand_reply_is_dropped_not_resealed() {
6704        let mut st = new_state_with("a\nb\nc\n");
6705        // Capture the world the "server" computed against...
6706        let anchor = st.world();
6707        // ...then let the operator keep typing, which is the whole point.
6708        st.apply(&Action::InsertChar('x'));
6709
6710        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
6711            anchor,
6712            then: Box::new(escriba_madoguchi::Negai::PublishFindings {
6713                list: "lsp".to_string(),
6714                findings: vec![a_finding(st.active, 1)],
6715            }),
6716        });
6717        assert!(
6718            st.finding_items(true, None).is_empty(),
6719            "a reply computed against an older text revision must be DROPPED, \
6720             not resealed against the current one"
6721        );
6722    }
6723
6724    /// The failure the wrapper exists for, and the reason it wraps a slip
6725    /// rather than adding an anchor field to PublishFindings: a stale EDIT
6726    /// corrupts the file, where a stale diagnostic merely mis-decorates it.
6727    #[test]
6728    fn a_stale_errand_reply_cannot_edit_the_buffer() {
6729        let mut st = new_state_with("hello\n");
6730        let anchor = st.world();
6731        st.apply(&Action::InsertChar('!'));
6732        let before = st
6733            .buffers
6734            .get(st.active)
6735            .map(|b| b.to_string())
6736            .unwrap_or_default();
6737
6738        st.honour_one(escriba_madoguchi::Negai::ErrandReply {
6739            anchor,
6740            then: Box::new(escriba_madoguchi::Negai::Edit {
6741                buffer: st.active,
6742                edit: escriba_core::Edit {
6743                    range: Range::new(Position::new(0, 0), Position::new(0, 0)),
6744                    kind: escriba_core::EditKind::Insert {
6745                        text: "FORMATTED".to_string(),
6746                    },
6747                },
6748            }),
6749        });
6750        let after = st
6751            .buffers
6752            .get(st.active)
6753            .map(|b| b.to_string())
6754            .unwrap_or_default();
6755        assert_eq!(
6756            after, before,
6757            "a stale formatter reply must not touch the text"
6758        );
6759    }
6760
6761    fn press(kc: KeyCode) -> AppEvent {
6762        AppEvent::Key(KeyEvent {
6763            key: kc,
6764            pressed: true,
6765            modifiers: Modifiers::default(),
6766            text: None,
6767        })
6768    }
6769
6770    // ── operator-over-motion (the `dw`/`c$`/`y0` verbs) ──────────────
6771
6772    fn line0_len(s: &EditorState) -> u32 {
6773        s.buffers.get(s.active).unwrap().line_len_chars(0)
6774    }
6775
6776    #[test]
6777    fn delete_to_line_end_clears_line_and_fills_register() {
6778        let mut s = new_state_with("hello world");
6779        s.apply(&Action::ApplyOperator {
6780            op: Operator::Delete,
6781            motion: Motion::LineEnd,
6782        });
6783        assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
6784        assert_eq!(
6785            s.register_text(),
6786            Some("hello world"),
6787            "delete fills the register"
6788        );
6789        assert_eq!(
6790            s.cursor(),
6791            Position::ZERO,
6792            "cursor lands at the range start"
6793        );
6794    }
6795
6796    #[test]
6797    fn delete_over_right_motion_removes_one_char() {
6798        let mut s = new_state_with("abc");
6799        s.apply(&Action::ApplyOperator {
6800            op: Operator::Delete,
6801            motion: Motion::Right,
6802        });
6803        assert_eq!(
6804            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6805            Some("bc")
6806        );
6807        assert_eq!(s.register_text(), Some("a"));
6808    }
6809
6810    #[test]
6811    fn change_to_line_end_deletes_and_enters_insert() {
6812        let mut s = new_state_with("hello world");
6813        assert_eq!(s.modal.mode(), Mode::Normal);
6814        s.apply(&Action::ApplyOperator {
6815            op: Operator::Change,
6816            motion: Motion::LineEnd,
6817        });
6818        assert_eq!(line0_len(&s), 0, "c$ deletes the range");
6819        assert_eq!(
6820            s.modal.mode(),
6821            Mode::Insert,
6822            "change enters Insert to type the replacement"
6823        );
6824        assert_eq!(
6825            s.register_text(),
6826            Some("hello world"),
6827            "change fills the register"
6828        );
6829    }
6830
6831    #[test]
6832    fn yank_to_line_end_fills_register_without_mutating() {
6833        let mut s = new_state_with("hello world");
6834        s.apply(&Action::ApplyOperator {
6835            op: Operator::Yank,
6836            motion: Motion::LineEnd,
6837        });
6838        assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
6839        assert_eq!(
6840            s.register_text(),
6841            Some("hello world"),
6842            "yank fills the register"
6843        );
6844        assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
6845    }
6846
6847    #[test]
6848    fn resolve_motion_is_the_shared_target_for_move_and_operator() {
6849        // The encapsulation proof: apply_motion (cursor move) and
6850        // apply_operator (range end) BOTH stand on resolve_motion.
6851        //
6852        // They read its answer differently AT THE BUFFER EDGE, and the
6853        // difference is vim's: `d$` deletes the last character, so the RANGE
6854        // ends after it; `$` puts the cursor ON it, because Normal mode has
6855        // nowhere past the last character to stand. One resolver, one target,
6856        // two readings — the reading is the mode's, not the motion's, which
6857        // is why the rest rule lives in `place_cursor` and not in here.
6858        let mut s = new_state_with("hello world");
6859        let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
6860        assert_eq!(target, Position::new(0, 11), "the exclusive range end");
6861
6862        s.apply_motion(Motion::LineEnd);
6863        assert_eq!(
6864            s.cursor(),
6865            Position::new(0, 10),
6866            "`$` rests on the last character, not past it",
6867        );
6868
6869        let mut d = new_state_with("hello world");
6870        d.apply(&Action::ApplyOperator {
6871            op: Operator::Delete,
6872            motion: Motion::LineEnd,
6873        });
6874        assert_eq!(
6875            line0_len(&d),
6876            0,
6877            "`d$` deletes through the last character — the range ends where \
6878             resolve_motion said, not where the cursor may rest",
6879        );
6880    }
6881
6882    #[test]
6883    fn empty_motion_range_is_a_no_op() {
6884        // An operator over a zero-width motion (cursor already at line start)
6885        // mutates nothing and leaves the register untouched.
6886        let mut s = new_state_with("abc");
6887        s.apply(&Action::ApplyOperator {
6888            op: Operator::Delete,
6889            motion: Motion::LineStart,
6890        });
6891        assert_eq!(
6892            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6893            Some("abc")
6894        );
6895        assert_eq!(s.register_text(), None);
6896    }
6897
6898    #[test]
6899    fn operator_then_motion_composes_through_the_pending_fsm() {
6900        // The full keymap→FSM→engine path: dispatching the `d` operator action
6901        // then a `$` motion composes `d$` via the zenmai operator-pending FSM —
6902        // the operator key alone does nothing until the motion arrives.
6903        let mut s = new_state_with("hello world");
6904        s.apply(&Action::Operator(Operator::Delete));
6905        assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
6906        s.apply(&Action::Move(Motion::LineEnd));
6907        assert_eq!(
6908            line0_len(&s),
6909            0,
6910            "d then $ composes d$ and deletes the line"
6911        );
6912        assert_eq!(s.register_text(), Some("hello world"));
6913    }
6914
6915    #[test]
6916    fn change_operator_through_fsm_enters_insert() {
6917        let mut s = new_state_with("hello world");
6918        s.apply(&Action::Operator(Operator::Change));
6919        s.apply(&Action::Move(Motion::LineEnd));
6920        assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
6921    }
6922
6923    #[test]
6924    fn lone_motion_after_no_operator_just_moves() {
6925        // Without a preceding operator the motion passes through unchanged —
6926        // and comes to rest on the last character, as Normal mode requires.
6927        let mut s = new_state_with("hello world");
6928        s.apply(&Action::Move(Motion::LineEnd));
6929        assert_eq!(s.cursor(), Position::new(0, 10));
6930        assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
6931    }
6932
6933    #[test]
6934    fn counted_operator_deletes_count_times() {
6935        // `3d` + a right-motion = `3dl` = delete 3 chars. The operator's count
6936        // flows through the FSM to the composed motion (the bug fix: previously
6937        // the count repeated the operator key and toggled the FSM).
6938        let mut s = new_state_with("abcdef");
6939        s.apply_counted(&Action::Operator(Operator::Delete), 3);
6940        assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
6941        s.apply(&Action::Move(Motion::Right));
6942        assert_eq!(
6943            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6944            Some("def")
6945        );
6946    }
6947
6948    #[test]
6949    fn operator_and_motion_counts_multiply_end_to_end() {
6950        // `2d3l` = delete 2×3 = 6 chars.
6951        let mut s = new_state_with("abcdefgh");
6952        s.apply_counted(&Action::Operator(Operator::Delete), 2);
6953        s.apply_counted(&Action::Move(Motion::Right), 3);
6954        assert_eq!(
6955            s.buffers.get(s.active).unwrap().line(0).as_deref(),
6956            Some("gh")
6957        );
6958    }
6959
6960    #[test]
6961    fn bare_counted_motion_still_repeats_no_regression() {
6962        // `3j` still moves down 3 lines — the count passes through the FSM
6963        // unchanged when no operator is pending.
6964        let mut s = new_state_with("a\nb\nc\nd\ne");
6965        s.apply_counted(&Action::Move(Motion::Down), 3);
6966        assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
6967    }
6968
6969    /// A monotonic clock for the key-repeat gate in tests — each `next()`
6970    /// jumps a full second past the previous, so every press it stamps is
6971    /// well outside the 80ms debounce window and therefore an INTENTIONAL
6972    /// press (never a storm tick). Used by tests that fire the *same*
6973    /// navigation key twice and assert editor logic, not debounce timing.
6974    struct SpacedClock(std::time::Instant);
6975    impl SpacedClock {
6976        fn new() -> Self {
6977            Self(std::time::Instant::now())
6978        }
6979        fn next(&mut self) -> std::time::Instant {
6980            self.0 += std::time::Duration::from_secs(1);
6981            self.0
6982        }
6983    }
6984
6985    #[test]
6986    fn hjkl_moves_cursor() {
6987        let mut s = new_state_with("hello\nworld");
6988        s.tick(&press(KeyCode::Char('l')));
6989        assert_eq!(s.cursor().column, 1);
6990        s.tick(&press(KeyCode::Char('j')));
6991        assert_eq!(s.cursor().line, 1);
6992        s.tick(&press(KeyCode::Char('h')));
6993        assert_eq!(s.cursor().column, 0);
6994    }
6995
6996    #[test]
6997    fn insert_mode_inserts_chars() {
6998        let mut s = new_state_with("");
6999        s.tick(&press(KeyCode::Char('i')));
7000        assert_eq!(s.modal.mode(), Mode::Insert);
7001        s.tick(&press(KeyCode::Char('h')));
7002        s.tick(&press(KeyCode::Char('i')));
7003        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
7004        assert_eq!(s.cursor().column, 2);
7005    }
7006
7007    #[test]
7008    fn esc_returns_to_normal() {
7009        let mut s = new_state_with("");
7010        s.tick(&press(KeyCode::Char('i')));
7011        s.tick(&press(KeyCode::Escape));
7012        assert_eq!(s.modal.mode(), Mode::Normal);
7013    }
7014
7015    #[test]
7016    fn count_prefix_repeats_motion() {
7017        let mut s = new_state_with("abcdefghij");
7018        s.tick(&press(KeyCode::Char('5')));
7019        s.tick(&press(KeyCode::Char('l')));
7020        assert_eq!(s.cursor().column, 5);
7021    }
7022
7023    #[test]
7024    fn close_event_requests_quit() {
7025        let mut s = new_state_with("");
7026        s.tick(&AppEvent::CloseRequested);
7027        assert!(s.quit_requested);
7028    }
7029
7030    #[test]
7031    fn word_next_jumps_past_whitespace() {
7032        let mut s = new_state_with("foo bar baz");
7033        // Two INTENTIONAL `w` presses, spaced past the key-repeat window so
7034        // the gate passes both (a real user's two taps are ≥80ms apart).
7035        let mut clk = SpacedClock::new();
7036        s.tick_at(&press(KeyCode::Char('w')), clk.next());
7037        assert_eq!(s.cursor().column, 4);
7038        s.tick_at(&press(KeyCode::Char('w')), clk.next());
7039        assert_eq!(s.cursor().column, 8);
7040    }
7041
7042    // ── Multi-key / leader pending-stroke ───────────────────────────
7043
7044    #[test]
7045    fn leader_sequence_holds_then_resolves() {
7046        let mut s = new_state_with("a\nbb\nccc");
7047        s.keymap.bind_sequence(
7048            Mode::Normal,
7049            vec![Key::Char(','), Key::Char('g')],
7050            Action::Move(Motion::DocEnd),
7051            "doc end",
7052        );
7053        // `,` begins the sequence — held pending, nothing applied yet.
7054        s.on_key(&Key::Char(','));
7055        assert_eq!(s.pending_keys, vec![Key::Char(',')]);
7056        assert_eq!(s.cursor(), Position::ZERO);
7057        // `g` completes `<leader>g` → DocEnd; pending clears.
7058        s.on_key(&Key::Char('g'));
7059        assert!(s.pending_keys.is_empty());
7060        assert_eq!(s.cursor().line, 2);
7061    }
7062
7063    #[test]
7064    fn two_key_gg_jumps_doc_start() {
7065        let mut s = new_state_with("a\nbb\nccc");
7066        s.keymap.bind_sequence(
7067            Mode::Normal,
7068            vec![Key::Char('g'), Key::Char('g')],
7069            Action::Move(Motion::DocStart),
7070            "doc start",
7071        );
7072        let mut clk = SpacedClock::new();
7073        s.tick_at(&press(KeyCode::Char('j')), clk.next());
7074        s.tick_at(&press(KeyCode::Char('j')), clk.next());
7075        assert_eq!(s.cursor().line, 2);
7076        s.on_key(&Key::Char('g')); // pending
7077        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7078        s.on_key(&Key::Char('g')); // resolve
7079        assert_eq!(s.cursor(), Position::ZERO);
7080    }
7081
7082    #[test]
7083    fn broken_sequence_aborts_and_clears_pending() {
7084        let mut s = new_state_with("hello");
7085        s.keymap.bind_sequence(
7086            Mode::Normal,
7087            vec![Key::Char('g'), Key::Char('g')],
7088            Action::Move(Motion::DocEnd),
7089            "doc end",
7090        );
7091        s.on_key(&Key::Char('g')); // pending [g]
7092        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7093        s.on_key(&Key::Char('x')); // breaks gg → abort; x is unbound → no-op
7094        assert!(s.pending_keys.is_empty());
7095        assert_eq!(s.cursor(), Position::ZERO);
7096    }
7097
7098    #[test]
7099    fn single_binding_wins_over_sequence_prefix() {
7100        // A key that is BOTH a complete single binding and the start of
7101        // a sequence fires the single binding immediately (no chord
7102        // timeout needed). Here `h` (move-left) also prefixes `hz`.
7103        let mut s = new_state_with("abcde");
7104        let mut clk = SpacedClock::new();
7105        s.tick_at(&press(KeyCode::Char('l')), clk.next());
7106        s.tick_at(&press(KeyCode::Char('l')), clk.next());
7107        assert_eq!(s.cursor().column, 2);
7108        s.keymap.bind_sequence(
7109            Mode::Normal,
7110            vec![Key::Char('h'), Key::Char('z')],
7111            Action::Move(Motion::DocEnd),
7112            "shadowed",
7113        );
7114        s.on_key(&Key::Char('h'));
7115        assert!(s.pending_keys.is_empty(), "single binding should not pend");
7116        assert_eq!(s.cursor().column, 1, "h moved left immediately");
7117    }
7118
7119    // ── tatara-lisp runtime bridge (imperative programmability) ─────
7120
7121    #[test]
7122    fn lisp_set_option_writes_live_options() {
7123        let mut s = new_state_with("");
7124        s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
7125        assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
7126    }
7127
7128    #[test]
7129    fn lisp_insert_modifies_buffer_and_advances_cursor() {
7130        let mut s = new_state_with("");
7131        s.run_lisp(r#"(insert "abc")"#).unwrap();
7132        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
7133        assert_eq!(s.cursor(), Position::new(0, 3));
7134    }
7135
7136    #[test]
7137    fn lisp_message_appends_to_messages() {
7138        let mut s = new_state_with("");
7139        s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
7140        assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
7141    }
7142
7143    #[test]
7144    fn lisp_reads_snapshot_and_branches_to_effect() {
7145        // Genuine programmability: Lisp reads the live cursor line and
7146        // an `if` decides which option to set.
7147        let mut s = new_state_with("one\ntwo\nthree");
7148        // cursor at line 0 → "top" branch
7149        s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
7150            .unwrap();
7151        assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
7152    }
7153
7154    #[test]
7155    fn lisp_run_command_effect_drives_registry() {
7156        // `(run-command "undo")` reaches the live command registry and
7157        // reverts a prior Lisp-driven insert — proving the RunCommand
7158        // effect dispatches through real editor commands.
7159        let mut s = new_state_with("");
7160        s.run_lisp(r#"(insert "abc")"#).unwrap();
7161        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
7162        s.run_lisp(r#"(run-command "undo")"#).unwrap();
7163        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
7164    }
7165
7166    #[test]
7167    fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
7168        // The full imperative-quit path: (run-command "quit") routes
7169        // through the registry's typed `quit_requested` signal — no string
7170        // sentinel, and no minibuffer pollution (the editor stays in a
7171        // clean Normal state, which has no minibuffer at all).
7172        let mut s = new_state_with("");
7173        s.run_lisp(r#"(run-command "quit")"#).unwrap();
7174        assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
7175        assert_eq!(
7176            s.modal.minibuffer(),
7177            "",
7178            "quit must not pollute any command line — Normal mode has no minibuffer",
7179        );
7180    }
7181
7182    // ── Lazy plugin activation (PluginHost) ────────────────────────
7183
7184    #[test]
7185    fn lazy_plugin_activates_on_command_trigger() {
7186        // A user plugin gated on `Command: LazyGo` has its entry applied
7187        // the first time that command runs — proving the lazy.nvim
7188        // `cmd =` model works end-to-end against live editor state.
7189        let mut s = new_state_with("");
7190        s.register_lazy_plugin(
7191            "user-lazy",
7192            vec![LazyTrigger::Command("LazyGo".into())],
7193            r#"(defoption :name "lazy-loaded" :value "yes")
7194               (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
7195        );
7196        assert_eq!(s.plugin_host.pending(), 1);
7197        assert!(
7198            s.options.get("lazy-loaded").is_none(),
7199            "entry not applied yet"
7200        );
7201
7202        // Drive the command through the public imperative path.
7203        s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
7204
7205        assert_eq!(
7206            s.options.get("lazy-loaded").map(String::as_str),
7207            Some("yes"),
7208            "the command trigger applied the plugin's entry",
7209        );
7210        assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
7211    }
7212
7213    #[test]
7214    fn lazy_plugin_activates_on_filetype() {
7215        let mut s = new_state_with("");
7216        s.register_lazy_plugin(
7217            "user-rust",
7218            vec![LazyTrigger::FileType("rust".into())],
7219            r#"(defoption :name "rust-plugin" :value "on")"#,
7220        );
7221        let n = s.activate_filetype_plugins("rust");
7222        assert_eq!(n, 1);
7223        assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
7224        // A second open of the same filetype is a no-op (one-shot).
7225        assert_eq!(s.activate_filetype_plugins("rust"), 0);
7226    }
7227
7228    #[test]
7229    fn cached_vm_serves_multiple_run_lisp_calls() {
7230        let mut s = new_state_with("");
7231        s.run_lisp(r#"(message "one")"#).unwrap();
7232        assert!(
7233            s.lisp_vm.is_some(),
7234            "VM should be cached after first run_lisp"
7235        );
7236        s.run_lisp(r#"(message "two")"#).unwrap();
7237        assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
7238    }
7239
7240    #[test]
7241    fn lisp_define_persists_across_run_lisp_calls() {
7242        // The cached VM's top-level env persists across calls (REPL
7243        // semantics): a `define` in one call is visible in the next.
7244        let mut s = new_state_with("");
7245        s.run_lisp(r#"(define greeting "hi")"#).unwrap();
7246        s.run_lisp(r#"(message greeting)"#).unwrap();
7247        assert_eq!(s.messages, vec!["hi".to_string()]);
7248    }
7249
7250    #[test]
7251    fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
7252        // Within ONE call a program cannot observe its own writes — the
7253        // read snapshot is captured before eval, effects apply after. A
7254        // later call sees the refreshed snapshot.
7255        let mut s = new_state_with("");
7256        s.run_lisp(
7257            r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
7258        )
7259        .unwrap();
7260        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
7261        assert_eq!(
7262            s.options.get("col").map(String::as_str),
7263            Some("stale-zero"),
7264            "cursor-column within the same call reads the pre-eval snapshot",
7265        );
7266        // After the first call the cursor advanced to column 2; the next
7267        // call's snapshot reflects it.
7268        s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
7269            .unwrap();
7270        assert_eq!(
7271            s.options.get("col2").map(String::as_str),
7272            Some("live-two"),
7273            "a later call sees the refreshed snapshot",
7274        );
7275    }
7276
7277    #[test]
7278    fn insert_text_effect_multiline_lands_cursor_on_last_line() {
7279        let mut s = new_state_with("");
7280        s.apply_host_effects(vec![Negai::InsertText("foo\nbar".to_string())]);
7281        assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
7282        assert_eq!(s.cursor(), Position::new(1, 3));
7283    }
7284
7285    #[test]
7286    fn visual_mode_sequence_resolves() {
7287        let mut s = new_state_with("abc");
7288        s.modal.enter(Mode::Visual);
7289        s.keymap.bind_sequence(
7290            Mode::Visual,
7291            vec![Key::Char('g'), Key::Char('e')],
7292            Action::Move(Motion::DocEnd),
7293            "ge",
7294        );
7295        s.on_key(&Key::Char('g'));
7296        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7297        s.on_key(&Key::Char('e'));
7298        assert!(s.pending_keys.is_empty());
7299        assert_eq!(
7300            s.cursor().column,
7301            3,
7302            "ge resolved to doc-end in visual mode"
7303        );
7304    }
7305
7306    #[test]
7307    fn sequence_abort_with_bound_breaking_key_redispatches() {
7308        // gg is a sequence; `l` (move-right) is a bound single key. After
7309        // `g` pends, `l` breaks gg, aborts, and is re-dispatched fresh.
7310        let mut s = new_state_with("abcde");
7311        s.keymap.bind_sequence(
7312            Mode::Normal,
7313            vec![Key::Char('g'), Key::Char('g')],
7314            Action::Move(Motion::DocEnd),
7315            "gg",
7316        );
7317        s.on_key(&Key::Char('g'));
7318        assert_eq!(s.pending_keys, vec![Key::Char('g')]);
7319        s.on_key(&Key::Char('l'));
7320        assert!(s.pending_keys.is_empty());
7321        assert_eq!(
7322            s.cursor().column,
7323            1,
7324            "the breaking key l should re-dispatch as move-right",
7325        );
7326    }
7327
7328    // ── Viewport-follows-cursor invariant (both axes) ───────────────
7329
7330    #[test]
7331    fn viewport_contains_cursor_after_every_op() {
7332        // Tiny window: 5 visible lines × 10 visible columns. Drive a
7333        // representative scripted sequence and assert the viewport contains
7334        // the cursor after EVERY mutating step.
7335        let mut s = new_state_small_viewport("", 5, 10);
7336        assert_cursor_in_viewport(&s, "initial");
7337
7338        // Enter insert mode and type 30 newline-separated lines — this is
7339        // the exact "type past the bottom" complaint.
7340        s.tick(&press(KeyCode::Char('i')));
7341        assert_eq!(s.modal.mode(), Mode::Insert);
7342        for line in 0..30u32 {
7343            for c in "line".chars() {
7344                s.tick(&press(KeyCode::Char(c)));
7345                assert_cursor_in_viewport(&s, "typing chars");
7346            }
7347            s.tick(&press(KeyCode::Enter));
7348            assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
7349        }
7350
7351        // Type a long (200-char) line — the "type past the right edge"
7352        // complaint. The cursor must stay horizontally visible the whole way.
7353        for i in 0..200u32 {
7354            s.tick(&press(KeyCode::Char('x')));
7355            assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
7356        }
7357
7358        // Multi-line insert_text effect (the `(insert …)` Lisp path).
7359        s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
7360        assert_cursor_in_viewport(&s, "insert_text multiline");
7361
7362        // Back to normal mode and move in all directions / to extremes.
7363        s.tick(&press(KeyCode::Escape));
7364        assert_eq!(s.modal.mode(), Mode::Normal);
7365        for m in [
7366            Motion::DocStart,
7367            Motion::DocEnd,
7368            Motion::Down,
7369            Motion::Down,
7370            Motion::Up,
7371            Motion::Right,
7372            Motion::Right,
7373            Motion::Left,
7374            Motion::LineEnd,
7375            Motion::LineStart,
7376            Motion::GotoLine(1),
7377            Motion::GotoLine(40),
7378            Motion::PageDown,
7379            Motion::PageUp,
7380        ] {
7381            s.apply_motion(m);
7382            assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
7383        }
7384
7385        // Undo many times — the buffer shrinks; the viewport must re-follow
7386        // the (now clamped) cursor.
7387        for i in 0..50u32 {
7388            s.apply(&Action::Undo);
7389            assert_cursor_in_viewport(&s, &format!("undo {i}"));
7390        }
7391        // Redo back up.
7392        for i in 0..50u32 {
7393            s.apply(&Action::Redo);
7394            assert_cursor_in_viewport(&s, &format!("redo {i}"));
7395        }
7396    }
7397
7398    #[test]
7399    fn insert_at_eof_keeps_cursor_in_bounds() {
7400        // Inserting at the end of the buffer must leave the cursor clamped
7401        // to a valid position (and inside the viewport).
7402        let mut s = new_state_small_viewport("abc", 5, 10);
7403        s.apply_motion(Motion::DocEnd);
7404        s.tick(&press(KeyCode::Char('i')));
7405        s.tick(&press(KeyCode::Char('d')));
7406        let buf = s.buffers.get(s.active).unwrap();
7407        let clamped = buf.clamp(s.cursor());
7408        assert_eq!(
7409            s.cursor(),
7410            clamped,
7411            "cursor must be clamped in-bounds at EOF"
7412        );
7413        assert_cursor_in_viewport(&s, "insert at eof");
7414    }
7415
7416    #[test]
7417    fn count_prefix_then_sequence_repeats() {
7418        // `2` then `gj` (→ move-down) repeats the resolved action twice.
7419        let mut s = new_state_with("a\nb\nc\nd\ne");
7420        s.keymap.bind_sequence(
7421            Mode::Normal,
7422            vec![Key::Char('g'), Key::Char('j')],
7423            Action::Move(Motion::Down),
7424            "gj",
7425        );
7426        s.on_key(&Key::Char('2'));
7427        s.on_key(&Key::Char('g'));
7428        s.on_key(&Key::Char('j'));
7429        assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
7430    }
7431
7432    // ── Key-repeat gate (awase::KeyRepeatGate) ──────────────────────────
7433
7434    #[test]
7435    fn held_key_repeat_storm_is_debounced_in_normal_mode() {
7436        // The audit's exact complaint: holding `j` floods motion events
7437        // and thrashes the viewport. Simulate an OS key-repeat storm — 20
7438        // identical `j` KeyDowns at 50ms intervals (typical repeat cadence)
7439        // — and assert only the gated subset (one per 80ms window) actually
7440        // moves the cursor.
7441        let mut s = new_state_with(&"x\n".repeat(40));
7442        let t0 = std::time::Instant::now();
7443        let mut delivered = 0u32;
7444        for i in 0..20u32 {
7445            let before = s.cursor().line;
7446            s.tick_at(
7447                &press(KeyCode::Char('j')),
7448                t0 + std::time::Duration::from_millis(u64::from(i) * 50),
7449            );
7450            if s.cursor().line != before {
7451                delivered += 1;
7452            }
7453        }
7454        // 20 events over ~1s at 50ms spacing, 80ms gate ⇒ ~13 pass — far
7455        // fewer than the 20 the ungated path would have applied.
7456        assert!(
7457            (10..=14).contains(&delivered),
7458            "expected the storm debounced to ~13 moves, got {delivered}",
7459        );
7460        assert!(
7461            delivered < 20,
7462            "the gate must drop SOME storm ticks, not pass all 20",
7463        );
7464    }
7465
7466    #[test]
7467    fn spaced_intentional_taps_all_pass() {
7468        // Intentional taps spaced past the debounce window must ALL reach
7469        // the editor — the gate filters storms, never deliberate input.
7470        let mut s = new_state_with(&"x\n".repeat(10));
7471        let t0 = std::time::Instant::now();
7472        for i in 0..5u32 {
7473            s.tick_at(
7474                &press(KeyCode::Char('j')),
7475                // 100ms apart — comfortably past the 80ms window.
7476                t0 + std::time::Duration::from_millis(u64::from(i) * 100),
7477            );
7478        }
7479        assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
7480    }
7481
7482    #[test]
7483    fn distinct_keys_have_independent_clocks() {
7484        // Holding `j` must not block a simultaneous `l` — the gate keys on
7485        // the Key, so independent keys have independent windows.
7486        let mut s = new_state_with("abc\ndef\nghi");
7487        let t = std::time::Instant::now();
7488        s.tick_at(&press(KeyCode::Char('j')), t);
7489        // `j` again within the window is dropped…
7490        s.tick_at(
7491            &press(KeyCode::Char('j')),
7492            t + std::time::Duration::from_millis(10),
7493        );
7494        assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
7495        // …but `l` at the same instant passes (its own clock).
7496        s.tick_at(
7497            &press(KeyCode::Char('l')),
7498            t + std::time::Duration::from_millis(10),
7499        );
7500        assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
7501    }
7502
7503    // ── Cursors newtype is the single cursor home ──────────────────────
7504
7505    #[test]
7506    fn cursor_home_preserves_single_cursor_behavior() {
7507        // The typed `Cursors` wrapper behaves exactly like the old bare
7508        // `Position` field for single-cursor editing: the read accessor
7509        // tracks every mutation routed through `set_cursor`, and there is
7510        // exactly one caret.
7511        let mut s = new_state_with("hello\nworld\nthere");
7512        assert_eq!(s.cursor(), Position::ZERO);
7513        assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
7514
7515        s.apply_motion(Motion::Down);
7516        s.apply_motion(Motion::Right);
7517        s.apply_motion(Motion::Right);
7518        assert_eq!(s.cursor(), Position::new(1, 2));
7519        // Still a single caret after a sequence of motions.
7520        assert_eq!(s.cursors.count(), 1);
7521
7522        // The accessor is the SAME value the viewport-follow path read.
7523        let w = s.layout.active_window().unwrap();
7524        assert!(w.viewport.top_line <= s.cursor().line);
7525    }
7526
7527    #[test]
7528    fn insert_mode_is_ungated_so_repeat_typing_works() {
7529        // Holding a key to repeat-type a character is intended in Insert
7530        // mode — the gate must NOT suppress it. 10 rapid identical `x`
7531        // keystrokes at the same instant must all land as text.
7532        let mut s = new_state_with("");
7533        s.tick(&press(KeyCode::Char('i')));
7534        assert_eq!(s.modal.mode(), Mode::Insert);
7535        let t = std::time::Instant::now();
7536        for _ in 0..10 {
7537            s.tick_at(&press(KeyCode::Char('x')), t);
7538        }
7539        assert_eq!(
7540            s.buffers.get(s.active).unwrap().to_string(),
7541            "xxxxxxxxxx",
7542            "insert-mode repeat typing is ungated",
7543        );
7544    }
7545
7546    // ── the courier seam (denrei) ────────────────────────────────────
7547    //
7548    // What these pin is not "work happens off-thread" — that is the runner's
7549    // business. It is that a reply computed against one world cannot be
7550    // applied against a different one, and that the machinery says so out loud
7551    // when it declines to do something.
7552
7553    mod courier_seam {
7554        use super::new_state_with;
7555        use escriba_madoguchi::Negai;
7556        use escriba_madoguchi::errand::{Crew, Errand, Freight, Parcel, Runner};
7557        use escriba_shirube::{Anchor, Axis, ResultList, SessionKind};
7558        use std::sync::Arc;
7559        use std::sync::atomic::AtomicBool;
7560        use std::sync::mpsc::Sender;
7561
7562        fn a_scan() -> Freight {
7563            Freight::Scan {
7564                raw: "needle".into(),
7565                case: escriba_search::CaseMode::Smart,
7566                root: ".".into(),
7567            }
7568        }
7569
7570        /// Replies with whatever slip it was built with, immediately and on the
7571        /// calling thread — so these tests assert the SEAM, not thread timing.
7572        struct Says(Negai);
7573        impl Runner for Says {
7574            fn start(&self, e: Errand, _c: Arc<AtomicBool>, reply: Sender<Parcel>) {
7575                let _ = reply.send(Parcel {
7576                    id: e.id,
7577                    slip: self.0.clone(),
7578                });
7579            }
7580        }
7581
7582        /// Replies by wrapping its payload in the anchor the DISPATCHER sealed
7583        /// — which is what a real runner does: it echoes back the seal it was
7584        /// handed, because it has no way to mint its own.
7585        struct EchoesSeal(Negai);
7586        impl Runner for EchoesSeal {
7587            fn start(&self, e: Errand, _c: Arc<AtomicBool>, reply: Sender<Parcel>) {
7588                let _ = reply.send(Parcel {
7589                    id: e.id,
7590                    slip: Negai::ErrandReply {
7591                        anchor: e.anchor.into_anchor(),
7592                        then: Box::new(self.0.clone()),
7593                    },
7594                });
7595            }
7596        }
7597
7598        fn crew_with_scan(r: impl Runner + 'static) -> Crew {
7599            Crew {
7600                scan: Box::new(r),
7601                diagnostics: Box::new(escriba_madoguchi::errand::Idle("t")),
7602                format: Box::new(escriba_madoguchi::errand::Idle("t")),
7603            }
7604        }
7605
7606        /// The whole path in one test: a handler names a class of work, the
7607        /// dispatcher seals it, a runner answers, and the reply is applied at a
7608        /// tick boundary.
7609        #[test]
7610        fn an_errand_is_dispatched_sealed_and_its_reply_applied_at_the_drain() {
7611            let mut st = new_state_with("x\n");
7612            st.hire(crew_with_scan(EchoesSeal(Negai::Message("done".into()))));
7613
7614            st.honour_one(Negai::Errand(Box::new(a_scan())));
7615            assert!(
7616                !st.messages.iter().any(|m| m == "done"),
7617                "nothing is applied before the drain"
7618            );
7619
7620            st.deliver();
7621            assert!(
7622                st.messages.iter().any(|m| m == "done"),
7623                "the reply lands at the drain: {:?}",
7624                st.messages
7625            );
7626        }
7627
7628        /// **The reason the whole seam exists.** A reply sealed against the
7629        /// world at dispatch must be discarded once that world has moved.
7630        #[test]
7631        fn a_reply_whose_world_moved_is_dropped() {
7632            let mut st = new_state_with("x\n");
7633            st.hire(crew_with_scan(EchoesSeal(Negai::Message("late".into()))));
7634
7635            st.honour_one(Negai::Errand(Box::new(a_scan())));
7636            // The surface the scan feeds closed while it was running.
7637            st.bump_scan_gen();
7638            st.deliver();
7639
7640            assert!(
7641                !st.messages.iter().any(|m| m == "late"),
7642                "a superseded reply must not be applied: {:?}",
7643                st.messages
7644            );
7645        }
7646
7647        /// The converse, so the test above is not passing because nothing ever
7648        /// applies.
7649        #[test]
7650        fn a_reply_whose_world_held_is_applied() {
7651            let mut st = new_state_with("x\n");
7652            st.hire(crew_with_scan(EchoesSeal(Negai::Message("ok".into()))));
7653            st.honour_one(Negai::Errand(Box::new(a_scan())));
7654            st.deliver();
7655            assert!(st.messages.iter().any(|m| m == "ok"));
7656        }
7657
7658        /// A scan must NOT be staled by typing. It reads the filesystem; no
7659        /// text revision has anything to say about it, and anchoring one on the
7660        /// buffers would kill every result on the next keystroke.
7661        #[test]
7662        fn typing_does_not_stale_a_scan_reply() {
7663            let mut st = new_state_with("x\n");
7664            st.hire(crew_with_scan(EchoesSeal(Negai::Message("rows".into()))));
7665            st.honour_one(Negai::Errand(Box::new(a_scan())));
7666
7667            st.insert_text("hello");
7668            st.deliver();
7669            assert!(
7670                st.messages.iter().any(|m| m == "rows"),
7671                "a scan does not depend on buffer text: {:?}",
7672                st.messages
7673            );
7674        }
7675
7676        /// The seal's OWN anchor becomes the list's seal. Re-sealing at the
7677        /// arrival world would widen a one-axis claim into an every-buffer one,
7678        /// so the findings would die on the next unrelated edit.
7679        #[test]
7680        fn findings_from_an_errand_keep_the_narrow_seal_they_were_computed_with() {
7681            let mut st = new_state_with("x\n");
7682            st.hire(crew_with_scan(EchoesSeal(Negai::PublishFindings {
7683                list: "grep".into(),
7684                findings: vec![],
7685            })));
7686            st.honour_one(Negai::Errand(Box::new(a_scan())));
7687            st.deliver();
7688
7689            let sealed_with = st.results.get("grep").expect("published").anchor().clone();
7690            let axes = sealed_with.axes();
7691            assert_eq!(axes.len(), 1, "narrow, not the whole world: {axes:?}");
7692            assert!(
7693                matches!(axes[0], Axis::Session(SessionKind::Scan, _)),
7694                "sealed on the scan session: {axes:?}"
7695            );
7696
7697            // …and the consequence that makes it worth doing: an edit
7698            // elsewhere does not discard it.
7699            st.insert_text("more");
7700            assert!(
7701                !st.results
7702                    .get("grep")
7703                    .expect("still there")
7704                    .is_stale(&st.world()),
7705                "an unrelated edit must not stale a scan list"
7706            );
7707        }
7708
7709        /// A directly-dispatched `PublishFindings` — an on-tick producer like
7710        /// the marker scan — still seals at the world, which is correct for it.
7711        /// The special case must not have changed that.
7712        #[test]
7713        fn a_direct_publish_still_seals_at_the_world() {
7714            let mut st = new_state_with("x\n");
7715            st.honour_one(Negai::PublishFindings {
7716                list: "todo".into(),
7717                findings: vec![],
7718            });
7719            let axes = st.results.get("todo").expect("published").anchor().axes();
7720            assert!(
7721                axes.len() > 1,
7722                "the on-tick path anchors on the whole world: {axes:?}"
7723            );
7724        }
7725
7726        /// An empty anchor is fresh against every world, so a forged reply
7727        /// carrying one bypasses the gate entirely. The courier cannot produce
7728        /// this — `seal` returns a `NonEmptyAnchor` — and the test exists to
7729        /// document why that type is not decoration.
7730        #[test]
7731        fn an_empty_anchor_would_bypass_the_gate_which_is_why_seal_cannot_mint_one() {
7732            let mut st = new_state_with("x\n");
7733            st.bump_scan_gen();
7734            st.bump_lsp_gen();
7735            st.insert_text("moved a long way");
7736
7737            st.honour_one(Negai::ErrandReply {
7738                anchor: Anchor::new(),
7739                then: Box::new(Negai::Message("forged".into())),
7740            });
7741            assert!(
7742                st.messages.iter().any(|m| m == "forged"),
7743                "an empty anchor passes any world — the hazard NonEmptyAnchor removes"
7744            );
7745        }
7746
7747        /// Closing the picker supersedes the scan feeding it. Both closing
7748        /// paths must do it — choosing a row closes the overlay exactly as Esc
7749        /// does, and only handling Esc leaves a scan running after every pick.
7750        #[test]
7751        fn closing_the_picker_supersedes_the_scan_it_was_feeding() {
7752            let mut st = new_state_with("x\n");
7753            st.hire(crew_with_scan(EchoesSeal(Negai::Message("rows".into()))));
7754            st.honour_one(Negai::Errand(Box::new(a_scan())));
7755
7756            st.close_picker();
7757            st.deliver();
7758            assert!(
7759                !st.messages.iter().any(|m| m == "rows"),
7760                "rows must not reopen a picker the operator closed: {:?}",
7761                st.messages
7762            );
7763        }
7764
7765        /// The default state. An errand with nobody hired must report that it
7766        /// went nowhere — a request that silently does nothing is the exact
7767        /// failure the pre-courier stub had.
7768        #[test]
7769        fn an_errand_with_no_crew_hired_says_so() {
7770            let mut st = new_state_with("x\n");
7771            st.honour_one(Negai::Errand(Box::new(a_scan())));
7772            st.deliver();
7773            assert!(
7774                st.messages.iter().any(|m| m.contains("scan")),
7775                "the inert crew announces: {:?}",
7776                st.messages
7777            );
7778        }
7779
7780        /// A quiet tick must be free — `deliver` is called on every frame.
7781        #[test]
7782        fn delivering_nothing_does_not_repaint() {
7783            let mut st = new_state_with("x\n");
7784            let before = st.edit_gen();
7785            st.deliver();
7786            assert_eq!(st.edit_gen(), before, "an empty drain is not a change");
7787        }
7788
7789        /// …and a tick that DID deliver must repaint, or the result sits in
7790        /// state that nothing draws.
7791        #[test]
7792        fn delivering_something_repaints() {
7793            let mut st = new_state_with("x\n");
7794            st.hire(crew_with_scan(Says(Negai::Message("hi".into()))));
7795            st.honour_one(Negai::Errand(Box::new(a_scan())));
7796            let before = st.edit_gen();
7797            st.deliver();
7798            assert_ne!(st.edit_gen(), before, "a delivered reply repaints");
7799        }
7800
7801        /// The two session kinds must not alias at the runtime level either: an
7802        /// LSP restart must not discard scan results, and vice versa.
7803        #[test]
7804        fn the_two_session_generations_are_independent() {
7805            let mut st = new_state_with("x\n");
7806            let scan_sealed = ResultList::new(
7807                vec![],
7808                Anchor::new().on(Axis::Session(SessionKind::Scan, st.scan_gen)),
7809            );
7810            st.bump_lsp_gen();
7811            assert!(
7812                !scan_sealed.is_stale(&st.world()),
7813                "an LSP restart must not discard scan results"
7814            );
7815            st.bump_scan_gen();
7816            assert!(scan_sealed.is_stale(&st.world()), "…but a scan bump does");
7817        }
7818
7819        #[test]
7820        fn every_freight_class_seals_on_something() {
7821            let mut st = new_state_with("x\n");
7822            let active = st.active;
7823            for freight in [
7824                a_scan(),
7825                Freight::Diagnostics {
7826                    buffer: active,
7827                    path: "a.nix".into(),
7828                    language: None,
7829                    text: String::new(),
7830                },
7831                Freight::Format {
7832                    buffer: active,
7833                    path: "a.nix".into(),
7834                    language: None,
7835                    text: String::new(),
7836                },
7837            ] {
7838                let sealed = st.seal(&freight);
7839                assert!(
7840                    !sealed.as_anchor().is_empty(),
7841                    "{} sealed on nothing",
7842                    freight.label()
7843                );
7844            }
7845            let _ = &mut st;
7846        }
7847    }
7848}